Conftest.py
@pytest.fixture(scope="module")
def fixture2(request):
do something
@pytest.fixture(scope="session", params=[ 1, 2, 3 ])
def fixture1(request):
do something else
测试文件.py
@pytest.mark.usefixtures('fixture2', 'fixture1')
class TestSomething1(object):
def test_1(self):
pass
def test_2(self):
pass
@pytest.mark.usefixtures('fixture1')
class TestSomething2(object):
def test_3(self):
pass
def test_4(self):
pass
发生的情况是我得到了 3 组测试(每次调用 Fixture1 各一组),但 Fixture2 仅针对所有 3 组测试运行一次(至少这是我的理解)。我不确定如何让它在每次运行fixture1时运行一次(而不是每次测试运行一次)。
我最终做了什么:
@pytest.fixture(scope="module")
def fixture2(request, fixture1):
do something
@pytest.fixture(scope="session", params=[ 1, 2, 3 ])
def fixture1(request):
do something else
最佳答案
将 @pytest.fixture(scope="module")
更改为其他内容,例如 @pytest.fixture(scope="class")
或 @pytest .fixture(范围=“函数”)
。
模块范围意味着每个模块运行一次。
来自 fixture 参数文档:
scope – the scope for which this fixture is shared, one of "function" (default), "class", "module", "package" or "session".
"package" is considered experimental at this time.
Pytest documentation on scopes
如果您希望每次调用一个固定装置时调用另一个固定装置一次,请使固定装置 1 依赖于固定装置 2 并使用相同的作用域。
关于python - 如何为其他 fixture 的每次运行运行一次 fixture ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54043472/