How to conditionally skip instantiation of fixture in pytest?

Viewed 352

Problem:

I have a fixture that takes about 5 minutes to instantiate. This fixture relies on a fixture from another package that I cannot touch. The time of the fixture can be drastically sped up depending on the state of a different (must faster instantiating) fixture. For example, this is the psuedo code of what I am looking to do:

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

Is this a feature of pytest? I have tried calling fixtures directly but this is also not allowed.

2 Answers

I would use the request fixture for that.

@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

You can use the “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()
Related