定义fixture跟定义普通函数差不多,唯一区别就是在函数上加个装饰器@pytest.fixture(),fixture命名不要以test开头,跟用例区分开。fixture是有返回值的,没有返回值默认为None。用例调用fixture的返回值,直接就是把fixture的函数名称当做变量名称。
import pytest
@pytest.fixture()
def test1():
a = 'leo'
return a
def test2(test1):
assert test1 == 'leo'
if __name__ == '__main__':
pytest.main(['-q','test_fixture.py'])
# test1函数的返回值为a,在test2函数中将test1作为参数传入
如果用例需要用到多个fixture的返回数据,fixture也可以返回一个元祖,list或字典,然后从里面取出对应数据。
import pytest
@pytest.fixture()
def test1():
a = 1
b = 2
return (a, b)
def test2(test1):
c = test1[0]
d = test1[1]
assert c == 1
assert d == 2
print('元祖形式正确')
if __name__ == '__main__':
pytest.main('-q test_fixture.py')
当然也可以分成多个fixture,然后在用例中传多个fixture参数
import pytest
@pytest.fixture()
def test1():
a = 1
return a
@pytest.fixture()
def test2():
b = 2
return b
def test3(test1, test2):
c = test1
d = test2
assert c == 1
assert d == 2
print('传入多个fixture参数正确')
if __name__ == '__main__':
pytest.main(['-q' ,'test_fixture.py'])
# test3函数中传入test1和test2作为参数
先简单介绍一下,后续pytest实现前置后置的时候会说明这个pytest的具体应用场景