Skip to content
Advertisement

How to conditionally skip instantiation of fixture in pytest?

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.

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement