python
config_error
ai_generated
true
ScopeMismatch: 你尝试以会话级请求对象访问函数级 fixture 'tmp_path',涉及的工厂
ScopeMismatch: You tried to access the function scoped fixture 'tmp_path' with a session scoped request object, involved factories
ID: python/pytest-session-scoped-fixture-with-function-scope
80%修复率
88%置信度
0证据数
2024-05-21首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
会话级 fixture 依赖函数级 fixture(如 tmp_path 或 monkeypatch),pytest 禁止此行为,因为窄作用域 fixture 无法比宽作用域 fixture 存活更久。
English
A session-scoped fixture depends on a function-scoped fixture (like tmp_path or monkeypatch), which pytest forbids because the narrower fixture cannot outlive the wider one.
解决方案
-
95% 成功率
@pytest.fixture(scope='session') def data_dir(tmp_path_factory): d = tmp_path_factory.mktemp('data') (d / 'file.txt').write_text('hi') return d -
85% 成功率
@pytest.fixture(scope='session') def cache(): return {} @pytest.fixture def resource(cache, tmp_path): if 'r' not in cache: cache['r'] = build(tmp_path) yield cache['r']
无效尝试
常见但无效的做法:
-
50% 失败
Defeats the purpose of sharing expensive setup; tests slow down dramatically.
-
85% 失败
Raises the same ScopeMismatch at runtime; getfixturevalue does not change scopes.