32
社区成员
发帖
与我相关
我的任务
分享假如想为一个测试类中的每个测试函数都去调用一个fixture,则此时可以在类上通过使用@pytest.mark.usefixtures()来指定
test_demo.py代码如下:
import pytest
@pytest.fixture(scope="function")
def f1():
print("in f1 fixture setup...")
yield
print("in f1 fixture teardown...")
@pytest.mark.usefixtures("f1")
class TestDemo(object):
def test_01(self):
print("in test_01...")
assert 1==1
def test_02(self):
print("in test_02...")
assert 1==1
def test_03(self):
print("in test_03...")
assert 1==1
执行结果如下:
$ pytest -s
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-1.0.0
rootdir: G:\src\blog\tests
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 3 items
test_demo.py in f1 fixture setup...
in test_01...
.in f1 fixture teardown...
in f1 fixture setup...
in test_02...
.in f1 fixture teardown...
in f1 fixture setup...
in test_03...
.in f1 fixture teardown...
========================================================================== 3 passed in 0.04s ===========================================================================