首页 > 解决方案 > 如何为其他夹具的每次运行运行一次夹具

问题描述

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 1 组),但是 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

标签: pythonpytestfixtures

解决方案


更改@pytest.fixture(scope="module")为其他内容,例如@pytest.fixture(scope="class")or @pytest.fixture(scope="function")。模块范围是指每个模块运行一次。

从夹具参数文档中:

scope – 共享此夹具的范围,“function”(默认)、“class”、“module”、“package”或“session”之一。

“package”此时被认为是实验性的。

关于范围的 Pytest 文档

如果您希望一个夹具在每次调用另一个夹具时调用一次,则使夹具 1 依赖夹具 2 并使用相同的范围。


推荐阅读