【问题标题】:How to run fixture once for each run of other fixture如何为其他夹具的每次运行运行一次夹具
【发布时间】:2019-01-04 17:22:52
【问题描述】:

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

test_file.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 组),但是对于所有 3 组测试,fixture2 只运行一次(至少这是我的理解)。我不确定如何让它在每次运行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

【问题讨论】:

    标签: python pytest fixtures


    【解决方案1】:

    @pytest.fixture(scope="module") 更改为@pytest.fixture(scope="class")@pytest.fixture(scope="function") 之类的其他名称。 模块范围意味着每个模块运行一次。

    来自夹具参数文档:

    scope – 共享此夹具的范围,“功能”之一 (默认)、“类”、“模块”、“包”或“会话”。

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

    Pytest documentation on scopes

    使fixture1 依赖于fixture2 并使用相同的范围,如果您希望每次调用另一个fixture 时调用一次。

    【讨论】:

    • module和session、class有什么区别?
    • @4c74356b41 在链接的文档中有描述
    • @4c74356b41 来自文档:我们可以将 scope="module" 添加到我们的夹具函数中,每个测试模块只调用一次(默认是每个测试函数调用一次)。因此,测试模块中的多个测试函数将接收相同的夹具实例,从而节省时间。如果您决定更愿意拥有一个会话范围的夹具实例,您可以简单地声明它:scope="session"。最后,类作用域将为每个测试类调用一次夹具。
    • @4c74356b41 该模块是基于每个文件的,会话是每个测试会话的,就像您运行的所有测试一样。
    • 然后让fixture1依赖fixture2并使用相同的作用域
    猜你喜欢
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多