fixture作为参数传入
定义测试固件fixture就是在函数上加个装饰器@pytest.fixture(),fixture命名不要用test_开头,跟用例区分开。用例才是test_开头的命名。
fixture是可以有返回值的,如果没return默认返回None。用例调用fixture的返回值,直接就是把fixture装饰的函数名称当成变量名称,如下案例
import pytest @pytest.fixture() def user(): print("获取用户名") a = "tom" return a # 用例调用fixture的返回值,直接就是把fixture装饰的函数名称当成变量名称 def test_1(user): assert user == "tom" if __name__ == "__main__": pytest.main(["-s", "-v", "test_01.py"])
执行结果:
rootdir: /Users/shimo/PycharmProjects/lovetest/testDemo
plugins: allure-pytest-2.8.29
collecting ... collected 1 item
test_01.py::test_1 获取用户名
PASSED
============================== 1 passed in 0.01s ===============================
Process finished with exit code 0
1、分开定义成多个fixture,然后test_用例传多个fixture参数
2、fixture与fixture之间互相调用
import pytest
@pytest.fixture()
def user():
print("获取用户名")
a = "tom"
b = "jerry"
# 返回一个元组数据
return a, b
@pytest.fixture()
def psw():
print("获取用户密码")
c = '123456'
d = '123456'
return c, d
''' fixture与fixture互相调用 '''
@pytest.fixture()
def zhanghao(user,psw):
print("调用user,psw的fixture")
name=user[0]
password=psw[1]
return name, password
# 用例传一个fixture参数
def test_1(user):
print(user, type(user))
assert user == ('tom', 'jerry')
# 定义成多个fixture,然后test_2用例传多个fixture参数
def test_2(user, psw):
print("用户{}登录,密码为{}".format(user, psw))
def test_3(zhanghao):
print("账号密码是{}".format(zhanghao))
if __name__ == "__main__":
pytest.main(["-s", "-v", "test_01.py"])
执行结果:
collecting ... collected 3 items
test_01.py::test_1 获取用户名
('tom', 'jerry') <class 'tuple'>
PASSED
test_01.py::test_2 获取用户名
获取用户密码
用户('tom', 'jerry')登录,密码为('123456', '123456')
PASSED
test_01.py::test_3 获取用户名
获取用户密码
调用user,psw的fixture
账号密码是('tom', '123456')
PASSED
============================== 3 passed in 0.02s ===============================