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
80%Fix Rate
88%Confidence
0Evidence
2024-04-22First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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 -
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:
-
30% fail
Fixes the error but destroys the performance benefit; the expensive setup runs for every test.
-
50% fail
Defaults to function scope, same performance regression, and may not match other fixtures that already use session.