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-function-vs-session

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-22First 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 function-scoped fixture is torn down after each test while the session fixture lives longer.

generic

中文

session 作用域的 fixture 依赖了 function 作用域的 fixture,这是不允许的,因为 function 作用域的 fixture 在每个测试后就会销毁,而 session fixture 存活更久。

Workarounds

  1. 90% success
    @pytest.fixture(scope='session')
    def db():
        conn = connect()
        yield conn
        conn.close()
    
    @pytest.fixture(scope='session')
    def seeded_db(db):
        seed(db)
        return db
  2. 92% success
    @pytest.fixture(scope='session')
    def db():
        conn = connect()
        yield conn
        conn.close()
    
    @pytest.fixture
    def user(db):
        u = create_user(db)
        yield u
        db.delete(u)

Dead Ends

Common approaches that don't work:

  1. 30% fail

    Fixes the error but destroys the performance benefit; the expensive setup runs for every test.

  2. 50% fail

    Defaults to function scope, same performance regression, and may not match other fixtures that already use session.