Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 948
Pythonisto Avatar asked Sep 06 '25 03:09

Pythonisto


1 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
like image 127
hoefling Avatar answered Sep 07 '25 20:09

hoefling