I added a pytest_fixture_setup function to my conftest.py, and it works correctly for function- and module-scoped fixtures. However, it doesn’t seem to run for session-scoped fixtures. Is this expected behavior, and how can I trigger pytest_fixture_setup for session-scoped fixtures?
Yes, this is expected. The pytest_fixture_setup hook does get called for session-scoped fixtures, but only when the fixture is first requested. If no test actually uses the session fixture, the hook won’t run.
For example:
# conftest.py
def pytest_fixture_setup(fixturedef, request):
print(f"Setting up fixture {fixturedef.name}")
# test_sample.py
import pytest
@pytest.fixture(scope="session")
def my_fixture():
return 42
def test_dummy(my_fixture):
assert my_fixture == 42
If you don’t reference my_fixture in any test, the setup hook won’t fire. I usually make sure session fixtures are actually used or explicitly requested in pytest_sessionstart.
If you want the pytest_fixture_setup hook to trigger even before any test uses a session fixture, you can request it manually in a session-scoped autouse fixture:
@pytest.fixture(scope="session", autouse=True)
def ensure_session_fixture(request):
request.getfixturevalue("my_fixture")
This forces pytest to initialize the session fixture at session start, which in turn triggers your pytest_fixture_setup hook. I’ve used this pattern for logging or metrics on session fixtures.
Session-scoped fixtures are cached for the entire test session. That means pytest_fixture_setup runs only once per fixture, no matter how many times it’s requested. For function- or module-scoped fixtures, the hook runs multiple times, which might make it feel like session fixtures are skipped.
To verify, try printing the fixture name in pytest_fixture_setup—you’ll see it fires exactly once when the session fixture is first used. This caching behavior is why hooks seem “silent” for session fixtures if you’re not paying attention.Preformatted text