一、测试用例用excel管理,存放地址:C:\Users\wangli\PycharmProjects\Test\test\files\apiCase.xls
二、代码实现如下:
1、封装读取excel用例数据
2、Pytest装饰器@pytest.mark.parametrize('参数名',list)实现登录模块2条测试用例数据驱动
import pytest,xlrd,os,requests,json#获取excel用例数据
def get_case_data():case_path = os.path.join(os.path.dirname(__file__), r'files\apiCase.xls')book = xlrd.open_workbook(case_path)sheet = book.sheet_by_name('sheet1名字')case = []for i in range(0, sheet.nrows):if sheet.row_values(i)[0] == 'C端登录' and sheet.row_values(i)[3]=='YES':case.append(sheet.row_values(i))return caseclass Test(object):def setup_class(self):passdef teardown_class(self):pass#调用获取测试用例数据case_data=get_case_data()#使用装饰器参数化用例数据@pytest.mark.parametrize('Function,TestCase,Type,Run,URL,Headers,Parameter,SQL1,SQL2,SQL3,AssertType,Expect1,Expect2,Expect3', case_data)def test_login1(self,Function,TestCase,Type,Run,URL,Headers,Parameter,SQL1,SQL2,SQL3,AssertType,Expect1,Expect2,Expect3):r=requests.post(url=URL,headers=eval(Headers),json=eval(Parameter))response=r.json()print(response)assert eval(Expect1)['code']==response['code']assert eval(Expect1)['msg'] == response['msg']if __name__=="__main__":pytest.main(["-s","test02.py"])"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/test/test02.py
============================= test session starts =============================
platform win32 -- Python 3.5.2, pytest-5.1.2, py-1.8.0, pluggy-0.12.0
rootdir: C:\Users\wangli\PycharmProjects\Test\test
plugins: allure-pytest-2.8.5, html-1.22.0, metadata-1.8.0
collected 2 itemstest02.py {'msg': '成功', 'code': 0, 'data': {'token': 'bearereyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9tZW1iZXItYXBpLnN0Mi50ZXN0LmxhbnhpbmthLmNvbVwvMi4wXC91c2Vyc1wvbG9naW4iLCJpYXQiOjE1NzI3NTE4MDUsImV4cCI6MTU3NDA0NzgwNSwibmJmIjoxNTcyNzUxODA1LCJqdGkiOiJpS2ZKZGdBam0xQWoyRmc1Iiwic3ViIjo1ODQ5MDIsInBydiI6IjNhN2IwNmU5NTBkMDhlMjMzMjkyMjdjN2E2YTUyMzQyYWJiNGYxOWIiLCJidXNpbmVzc190eXBlIjoiNiJ9.1bYj4VslhNMU3yjBtxccCG6fAWNwH8jhAacC6cl-f_A'}}
.{'msg': '验证码错误', 'code': 220002, 'data': {}}
.============================== 2 passed in 0.75s ==============================Process finished with exit code 0
通过以上实验,我们可以看出如果模块有100条测试用例,同样用以上代码可以实现测试并断言出结果,是不是很简单呢。