python
config_error
ai_generated
true
ScopeMismatch: 你尝试用 session 作用域的请求对象访问 function 作用域的 fixture db
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%修复率
88%置信度
0证据数
2024-04-22首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
session 作用域的 fixture 依赖了 function 作用域的 fixture,这是不允许的,因为 function 作用域的 fixture 在每个测试后就会销毁,而 session fixture 存活更久。
English
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.
解决方案
-
90% 成功率
@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% 成功率
@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)
无效尝试
常见但无效的做法:
-
30% 失败
Fixes the error but destroys the performance benefit; the expensive setup runs for every test.
-
50% 失败
Defaults to function scope, same performance regression, and may not match other fixtures that already use session.