Novice学Pytest(10)-fixture 传参数 request的详细使用
一、前言
- 为了提高代码复用性,我们在写测试用例时,会用到不同的fixture,比如:最常见的登录操作,大部分用例的前置条件都是登录
- 假设不同的用例想登录不同的测试账号,比如登录已配置音乐品类的账号,那么登录fixture就不能把账号写死,需要通过传参的方式来完成登录操作
二、小试牛刀
(1)传单个参数
1 import pytest 2 3 @pytest.fixture() 4 def login(request): 5 user = request.param 6 print(f"\n===账号是{user}===") 7 return user 8 9 data = ["liyebin01","Isaymore"] 10 ids = [f"login_user is :{user}" for user in data] 11 12 @pytest.mark.parametrize("login",data,ids=ids,indirect=True) 13 def test_user(login): 14 print(f"===测试用例登录的账号是:{login}===")
执行结果:
Notes:
添加indirect=True参数是为了把login当成一个函数去执行,而不是一个参数,并且把data当做参数输入函数
def test_user(login),这里的login是获取fixture返回的值
(2)传多个参数
1 import pytest 2 3 @pytest.fixture() 4 def login(request): 5 user = request.param 6 print(f"账号是:{user['username']},密码是:{user['pwd']}") 7 return user 8 9 data = [ 10 {"username":"liyebin01","pwd":"xiaobin1234"}, 11 {"username":"Isaymore","pwd":"yy123"} 12 ] 13 @pytest.mark.parametrize("login",data,indirect=True) 14 def test_user(login): 15 print(f"测试用例登录的账号是{login['username']},密码是{login['pwd']}")
执行结果:
Notes:如果需要传多个参数,需要通过字典去传
(3)多个fixture(只加一个装饰器) -- 更常用
1 import pytest 2 3 # 多个fixture 4 @pytest.fixture(scope="module") 5 def input_user(request): 6 user = request.param 7 print(f"登录账号:{user}") 8 return user 9 10 @pytest.fixture(scope="module") 11 def input_pwd(request): 12 pwd = request.param 13 print(f"登录密码:{pwd}") 14 return pwd 15 16 data = [ 17 ("liyebin01","xiaobin1234"), 18 ("Isaymore","yy123") 19 ] 20 @pytest.mark.parametrize("input_user,input_pwd",data,indirect=True) 21 def test_more_fixture(input_user,input_pwd): 22 print(f"账号是{input_user},密码是{input_pwd}")
执行结果:
(4)多个fixture(叠加装饰器)
import pytest
# 多个fixture
@pytest.fixture(scope="function")
def input_user(request):
user = request.param
print(f"登录账号:{user}")
return user
@pytest.fixture(scope="function")
def input_pwd(request):
pwd = request.param
print(f"登录密码:{pwd}")
return pwd
user = ["liyebin01","Isaymore"]
pwd = ["xiaobin1234","yy123"]
@pytest.mark.parametrize("input_user",user,indirect=True)
@pytest.mark.parametrize("input_pwd",pwd,indirect=True)
def test_more_fixture(input_user,input_pwd):
print(f"\n账号是{input_user},密码是{input_pwd}")
执行结果:
Notes:测试用例数为n*m=4条,其中n和m都为2
参考链接:https://www.cnblogs.com/poloyy/p/12685948.html
一行代码一行诗