如何有条件地跳过pytest中夹具的实例化?

How to conditionally skip instantiation of fixture in pytest?

问题:

我有一个需要大约 5 分钟来实例化的夹具。这个夹具依赖于另一个我无法触摸的包中的夹具。根据不同(必须更快实例化)夹具的状态,可以大大加快夹具的时间。例如,这是我要执行的操作的伪代码:

@pytest.fixture()
def everyday_fixture(slow_fixture, fast_fixture):
    if fast_fixture.is_usable():
        yield fast_fixture
    else:
        slow_fixture.instantiate()
        yield slow_fixture

这是pytest的一个特性吗?我试过直接调用 fixtures 但这也是不允许的。

您可以使用 “factory as fixture” pattern:

@pytest.fixture()
def fast_fixture():
    def _fast_fixture():
        return fast_fixture_data

    return _fast_fixture


@pytest.fixture()
def slow_fixture():
    def _slow_fixture():
        return slow_fixture_data

    return _slow_fixture


@pytest.fixture()
def everyday_fixture(slow_fixture, fast_fixture):
    if fast_fixture():
        yield fast_fixture()
    else:
        yield slow_fixture()

我会为此使用 request 夹具。

@pytest.fixture
def everyday_fixture(request, fast_fixture):
    if fast_fixture.is_usable():
        yield fast_fixture
    else:
        slow_fixture = request.getfixturevalue("slow_fixture")
        slow_fixture.instantiate()
        yield slow_fixture