首先安装ddt,unitest,data
1、读取Excel测试数据类
from openpyxl import load_workbook
class DoExcel :
def __init__(self,filename,sheet_name):
self.filename=filename
self.sheet_name=sheet_name
def get_data(self):
wb=load_workbook(self.filename)
sheet=wb[self.sheet_name]
test_data=[]
for i in range(2,sheet.max_row+1):
sub_data={}
sub_data['url']=sheet.cell(i,1).value
sub_data['data']=sheet.cell(i,2).value
sub_data['except']=sheet.cell(i,3).value
sub_data['method'] = sheet.cell(i, 4).value
test_data.append(sub_data)
return test_data
if __name__ == '__main__':
res= DoExcel('../class_01/test.xlsx','tet').get_data()
print(res)
2、测试类
import unittest,json
from ddt import ddt,data
from class_01.HttpRequest import HttpRequest
from pool.method_1 import DoExcel
test_data=DoExcel('../class_01/test.xlsx','tet').get_data()
@ddt
class TestLogin(unittest.TestCase):
def setUp(self) -> None:
pass
@data (*test_data)
def test_login_api(self,item):
print('取值:',item)
res = HttpRequest().http_request(url=item['url'], data=json.dumps(eval(item['data'])), method='post')
#print(res.json())
try:
self.assertEqual(int(item['except']),res.json()['tid'])
except Exception as e:
print("正常登录报错:{}".format(e))
raise e
def tearDown(self) -> None:
pass
if __name__ == '__main__':
unittest.main()
3、执行
import unittest,HTMLTestReportCN
from class_01.test_HttpRequest import TestLogin
from pool.method_3 import DoExcel
suite=unittest.TestSuite()
#通过loader方式来加载用例,ddt方式只能通过loader方式加载
loader=unittest.TestLoader()
suite.addTest(loader.loadTestsFromTestCase(TestLogin))
with open('test_report.html','w',encoding='utf-8') as fp:
runner=HTMLTestReportCN.HTMLTestRunner(stream=fp, verbosity=2,title='2020-01-15测试报告',description=None,tester=None)
runner.run(suite)