python config_error ai_generated true

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

ID: python/pytest-scope-mismatch

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

Version Compatibility

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

Root Cause

A session-scoped fixture depends on a function-scoped fixture, which is not allowed because the session fixture outlives the function fixture.

generic

中文

session 作用域的 fixture 依赖了 function 作用域的 fixture,这是不允许的,因为 session fixture 的生命周期长于 function fixture。

Workarounds

  1. 90% success
    Promote the dependency to a compatible scope:
    @pytest.fixture(scope='session')
    def db():
        ...
  2. 88% success
    Or demote the dependent fixture to function scope:
    @pytest.fixture(scope='function')
    def client(db):
        ...

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Defaults to function scope, which is the same problem.

  2. 70% fail

    Does not change scope compatibility.