0.fixture就是跑测试之前或者之后跑的一些功能,也可以往test case中传入参数
fixture功能可以看成一个普通函数
return 和 yield之前的部分在跑测试用例前面执行,一般可以看作case setup行为
yield之后的部分在跑测试用例之后执行,一般可以看作 case teardown行为
返回值可以传入到case中使用
1.创建fixture,普通函数被装饰器pytest.fixture()装饰后,就可以被声明成一个fixture
pytest.fixture()装饰器可以有参数,用于setup当前fixture功能的执行范围,执行方式,传入到fixture的参数
fixture功能可以看成一个普通的函数
2.调用fixture,测试用例通过fixture名字调用fixture,fixture在运行test之前启用
使用下面三种方法调用:
test case或者test class使用pytest.mark.usefixtures(fixturename)
test case可以把fixture当作参数,fixture被提前执行一遍
自动调用,前提是pytest.fixture(autouse=True)
import pytest
@pytest.fixture()
def before():
print("====start====")
@pytest.fixture()
def before_after(request):
print("running case %s setup"%request.node.name)
yield
print("finish case %s teardown"%request.node.name)
@pytest.fixture(params=[(10,10),(11,9)])
def test_data(request):
yield request.param
print("-------clear test_data-------")
@pytest.fixture(params=[(10,10),(11,9)])
def test_data_r(request):
print("before return data")
return request.param
@pytest.mark.slow
@pytest.mark.usefixtures("before")
@pytest.mark.usefixtures("before_after")
@pytest.mark.parametrize(argnames="a,b",argvalues=[(1,2),(3,4)])
def test_a(a,b,before_after):
print(a+b)
print(before_after)
@pytest.mark.quick
@pytest.mark.usefixtures("before_after")
@pytest.mark.parametrize(argnames="a,b",argvalues=[(3,4),(3,4)])
def test_b(a,b):
print(a+b)
@pytest.mark.slow
@pytest.mark.usefixtures("before_after")
@pytest.mark.skipif(condition=False,reason="test skip")
def test_c(test_data):
assert test_data[0]+test_data[1]==20
@pytest.mark.slow
@pytest.mark.usefixtures("before_after")
def test_d(test_data_r):
assert test_data_r[0]+test_data_r[1]==20
运行结果
ttt.py running case test_a[1-2] setup
====start====
3
None
.finish case test_a[1-2] teardown
running case test_a[3-4] setup
====start====
7
None
.finish case test_a[3-4] teardown
running case test_b[3-40] setup
7
.finish case test_b[3-40] teardown
running case test_b[3-41] setup
7
.finish case test_b[3-41] teardown
running case test_c[test_data0] setup
.-------clear test_data-------
finish case test_c[test_data0] teardown
running case test_c[test_data1] setup
.-------clear test_data-------
finish case test_c[test_data1] teardown
running case test_d[test_data_r0] setup
before return data
.finish case test_d[test_data_r0] teardown
running case test_d[test_data_r1] setup
before return data
.finish case test_d[test_data_r1] teardown