Excel 測試用例的讀取
安裝 python 操作Excel 的庫
pip install xlrd/xlwt/xlutils (安裝三個操作庫)
接口請求代碼構建
import requests
from random import randint
import xlrd
import json
class My_request(object):
# 對返回值進行處理
def __str__(self):
# return "%r"%self.connect()
return str("%r"%self.connect())
# 獲取表格數據
def connect(self):
excelDir = '../data/動畫繪本館測試用例.xls'
# 打開Excel文件 formatting_info=True :保持原樣式
self.workBook = xlrd.open_workbook(excelDir,formatting_info=True)
# 獲取所有表名
sheets = self.workBook.sheet_names()
# 需要執行的sheet
workSheet = self.workBook.sheet_by_name('測試用例2')
# 獲取一行
# cellData = workSheet.row_values(1)
# 獲取單元格 獲取的不是字符串 而是excel 格式參數
cellData = workSheet.cell(1, 0)
return cellData.value
# token函數 調用函數就可獲取token值 再用到新增接口
def get_token(self):
# 獲取token
token_urls = 'http://47.96.181.17:9090/rest/toController'
payload = {'userName': 'J201903070064', 'password': '362387359'}
# 發送請求 json 請求體
res = requests.post(token_urls, json=payload)
return res.json()['token']
# 新增用戶接口
def add_user(self,bodyData):
"""
:param bodyData: request body
:return: res data
"""
self.addUsr_url = 'http://47.96.181.17:9090/rest/ac01CrmController'
# 對字符串轉換字典 json 串
self.payload = json.loads(bodyData)
# 對手機號進行參數化
self.payload['aac030'] = f'134{randint(11111111,99999999)}'
self.header_addusr = {'Content-Type': 'application/json', 'X-AUTH-TOKEN': self.get_token()}
# # 發送請求 url 請求體
res = requests.post(self.addUsr_url,json=self.payload,headers = self.header_addusr)
self.rest = res.json()
# 打印輸出結果 是否注冊成功
print(res.json())
return res.json()
def write_index(self,datas):
from xlutils.copy import copy
# 對表復制 原始的測試用例不會改變
newWoekBook = copy(self.workBook)
# 取拷貝的excel的sheet 下標
newSheet = newWoekBook.get_sheet(1)
# 寫入數據 第一行第一列
newSheet.write(1, 1, datas)
# 保存新生成的 excel對象
newWoekBook.save('../data/res.xls')
def write_in(self):
# 如果已經有數據了 就需要對原表進行復制
if self.rest['message'] == '成功':
info = 'pass'
self.write_index(info)
else:
info = 'fail'
self.write_index(info)
if __name__ == '__main__':
re = My_request()
re.add_user(re.connect())
re.write_in()
測試結果寫入到Excel
文件不存在 -- 新建excel -- 寫 -- xlwt
文件本身存在--另存為寫入excel--xlutils
def write_index(self,datas):
from xlutils.copy import copy
# 對表復制 原始的測試用例不會改變
newWoekBook = copy(self.workBook)
# 取拷貝的excel的sheet 下標
newSheet = newWoekBook.get_sheet(1)
# 寫入數據 第一行第一列
newSheet.write(1, 1, datas)
# 保存新生成的 excel對象
newWoekBook.save('../data/res.xls')
def write_in(self):
# 如果已經有數據了 就需要對原表進行復制
if self.rest['message'] == '成功':
info = 'pass'
self.write_index(info)
else:
info = 'fail'
self.write_index(info)