python config_error ai_generated true

ScopeMismatch: You tried to access the function scoped fixture db_session with a session scoped request object

ID: python/pytest-session-fixture-scope-mismatch

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-09-27First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

A session-scoped fixture depends on a function-scoped fixture, which pytest forbids because the shorter-lived fixture cannot outlive its scope.

generic

中文

会话作用域的 fixture 依赖函数作用域的 fixture,pytest 禁止这样做,因为生命周期较短的 fixture 无法存活于其作用域之外。

Workarounds

  1. 90% success
    Align the dependent fixture's scope to session, or restructure so the session fixture does not depend on a function fixture:
    
    @pytest.fixture(scope='session')
    def engine():
        ...
    
    @pytest.fixture
    def db_session(engine):
        ...
  2. 85% success
    Use a factory fixture to create per-test objects from a session resource.

Dead Ends

Common approaches that don't work:

  1. 85% fail

    The error is about the fixture dependency graph, not the test; the mismatch persists.

  2. 80% fail

    Autouse does not change scope; the ScopeMismatch still occurs.