pytest实现参数化单个参数实现参数化多个参数实现参数化修改测试名称使用yaml文件实现参数化1. 实现一个登录功能2. 实现参数化3. 使用yaml文件实现参数化
pytest实现参数化
在unittest需要第三方库ddt进行配合实现参数化但是在Pytest中不需要第三方库的配合,使用装饰器@pytest.mark.parametrize()就可以实现
单个参数实现参数化
importpytest
###第一种写法
@pytest.mark.parametrize('a',[1,2,3])
deftest_de(a):
asserta==3
if__name__=='__main__':
pytest.main(['test_dd.py'])
###第二种写法
@pytest.mark.parametrize('a',(1,2,3))
deftest_de(a):
asserta==3
if__name__=='__main__':
pytest.main(['test_dd.py'])
参数化中第一个参数形参,第二个传入列表或者元组,当然列表中的数据就是被测对象,可以是列表字典,或者是字符串等,被测函数传入的参数为参数化的形参
多个参数实现参数化
importpytest
###第一种
@pytest.mark.parametrize('a,b',((1,3),(4,5),(5,5)))
deftest_de(a,b):
asserta==b
if__name__=='__main__':
pytest.main(['test_dd.py'])
###第二种
@pytest.mark.parametrize('a,b',[(1,3),(4,5),(5,5)])
deftest_de(a,b):
asserta==b
if__name__=='__main__':
pytest.main(['test_dd.py'])
###第三种
@pytest.mark.parametrize('a,b',[[1,3],[4,5],[5,5]])
deftest_de(a,b):
asserta==b
if__name__=='__main__':
pytest.main(['test_dd.py'])
参数化中第一个参数形参传入形式可以是字符串,第二个传入的被测对象可以为列表或者元组 1,被测函数传入的参数为参数化的形参
修改测试名称
参数化除了支持传递两个参数还支持传递第三个参数ids来自定义显示结果的名称
data= [1,2,3]
id= [f"case{i}"foriinrange(len(data))]
@pytest.mark.parametrize(('a'),data,ids=id)
deftest_de(a):
asserta==3
if__name__=='__main__':
pytest.main(['test_dd.py'])
使用yaml文件实现参数化
上面我们说明了参数化的使用方法,当然如果被测用例2比较多,我们可以把它写在一个文件中,当然文件不只是局限于yaml也可以是json或者xld文件
1. 实现一个登录功能
url='http://www.shopxo.com/shopxo/index.php?s=/index/user/login.html'
data={'accounts':'test2','pwd':123456}
param= {'X-Requested-With': 'XMLHttpRequest'}
deftest_login():
res=requests.post(url=url,headers=param,json=data)
assertres.status_code==200
if__name__=='__main__':
pytest.main(['test_dd.py'])
2. 实现参数化
url='http://www.shopxo.com/shopxo/index.php?s=/index/user/login.html'
data=[{'accounts':'test2','pwd':123456},{'accounts':'test3','pwd':123456}]
param= {'X-Requested-With': 'XMLHttpRequest'}
@pytest.mark.parametrize('a',data)
deftest_login(a):
res=requests.post(url=url,headers=param,json=a)
print (res.text)
assertres.status_code==200
if__name__=='__main__':
pytest.main(['test_dd.py'])
3. 使用yaml文件实现参数化
yaml文件
-
data:
accounts: test2
pwd: 123456
excepted:
code: 200
message: 登录成功
-
data:
accounts: test3
pwd: 123456
excepted:
code: 200
message: 帐号不存在
python文件读取yaml
importyaml
deftd():
withopen('t.yml',encoding='utf-8') asf:
hf=yaml.load(f,Loader=yaml.FullLoader)
returnhf
参数化
importpytest
importrequests
fromparserymlimporttd
###数据驱动,ddt:1.装饰器是哪一种 2.unittest框架是哪一个
url='http://www.shopxo.com/shopxo/index.php?s=/index/user/login.html'
param= {'X-Requested-With': 'XMLHttpRequest'}
@pytest.mark.parametrize('a',td())
deftest_login(a):
data=a['data']
excepted=a['excepted']
res=requests.post(url=url,headers=param,json=data)
print ("响应文本::",res.text)
print ("a的值::",a)
assert excepted['code']==res.status_code
assertexcepted['message'] ==res.json()['msg']
if__name__=='__main__':
pytest.main(['test_dd.py'])
[1] 若多个参数,参数的数量对应元组中被测对象的数量要保持一致
[2] 被测用例也就是指的我们的第二个参数