【阅读目录】
-
1 使用场景
-
2 传单个参数
-
3 传多个参数
-
4 多个fixtrue
1 使用场景
-
当我们为了提高用例的复用性,会用到不同的
fixture
,比如登陆场景; -
但是如果登陆场景,我们使用不同的账号进行测试,那如何来做?
-
此时不能使用
fixture
把账号直接写死
,需要通过传参的方式来实现。
2 传单个参数
-
import pytest
-
# 传一个参数
-
@pytest.fixture()
-
def user_login(request):
-
user_name = request.param
-
return user_name
-
data = ["user_name01", "user_name02"]
-
@pytest.mark.parametrize("user_login", data, indirect=True)
-
def test_login(user_login):
-
print(f"登陆用户的名称为:{user_login}")
-
if __name__ == '__main__':
-
pytest.main(["-s", "test_request.py"])
-
test_request.py::test_login[user_name01] PASSED
-
[ 50%]登陆用户的名称为:user_name01
-
test_request.py::test_login[user_name02] PASSED
-
[100%]登陆用户的名称为:user_name02
-
============================== 2 passed in0.03s ==============================
-
其中
indirect=True
参数是为了把user_login
当成一个函数去执行,而不是一个参数,并且将data
当做参数传入函数。
3 传多个参数
-
传多个参数,需要通过字典去传。
-
import pytest
-
# 传多个参数
-
@pytest.fixture()
-
def user_login(request):
-
user_name = request.param
-
return user_name
-
data = [{"user_name": "user_name01", "passwd": "passwd01"},
-
{"user_name": "user_name02", "passwd": "passwd02"}
-
]
-
@pytest.mark.parametrize("user_login", data, indirect=True)
-
def test_login(user_login):
-
print(f"登陆用户的名称为:{user_login['user_name']},登陆的密码: {user_login['passwd']}")
-
if __name__ == '__main__':
-
pytest.main(["-s", "test_request01.py"])
-
test_request01.py::test_login[user_login0] PASSED
-
[ 50%]登陆用户的名称为:user_name01,登陆的密码: passwd01
-
test_request01.py::test_login[user_login1] PASSED
-
[100%]登陆用户的名称为:user_name02,登陆的密码: passwd02
-
============================== 2 passed in0.04s ==============================
4 多个fixtrue
-
import pytest
-
# 传多个fixture
-
@pytest.fixture()
-
def user_name(request):
-
name = request.param
-
return name
-
@pytest.fixture()
-
def user_pwd(request):
-
pwd = request.param
-
return pwd
-
data = [("user_name01", "pwd01"), ("user_name02", "pwd02")]
-
@pytest.mark.parametrize("user_name, user_pwd", data, indirect=True)
-
def test_login(user_name, user_pwd):
-
print(f"登陆信息为{user_name}, {user_pwd}")
-
if __name__ == '__main__':
-
pytest.main(["-s", "test_request02.py"])
-
test_request02.py::test_login[user_name01-pwd01] PASSED
-
[ 50%]登陆信息为user_name01, pwd01
-
test_request02.py::test_login[user_name02-pwd02] PASSED
-
[100%]登陆信息为user_name02, pwd02
-
============================== 2 passed in0.03s ==============================
感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:
这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!有需要的小伙伴可以点击下方小卡片领取