Junior — Middle
How to implement generator functions inside fixtures in pytest to control their execution order?
sobes.tech AI
Answer from AI
Generator functions inside fixtures in pytest are deprecated, but if we talk about the order of fixture execution using generators, it can be managed through fixture dependencies.
Example of a generator fixture (old style):
import pytest
@pytest.fixture
def resource():
# setup
print("Setup resource")
yield
# teardown
print("Teardown resource")
To control the execution order, fixtures can be chained through parameters:
@pytest.fixture
def first():
print("Setup first")
yield
print("Teardown first")
@pytest.fixture
def second(first):
print("Setup second")
yield
print("Teardown second")
Here, second depends on first, so first will run earlier.
Thus, the order of fixture execution with generator functions is controlled through their dependencies, not directly within the generator.