python
config_error
ai_generated
true
ScopeMismatch: You tried to access the function scoped fixture 'tmp_path' with a session scoped request object
ID: python/pytest-scope-mismatch-session-in-function
80%Fix Rate
88%Confidence
0Evidence
2024-04-08First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
A session/module-scoped fixture depends on a narrower-scoped fixture. pytest forbids a wider scope from consuming a narrower one because the narrower fixture would be torn down before the wider one.
generic中文
session/module 作用域的 fixture 依赖了更窄作用域的 fixture。pytest 禁止宽作用域消费窄作用域,因为窄 fixture 会在宽 fixture 之前被拆除。
Workarounds
-
93% success
@pytest.fixture(scope='session') def tmp_root(tmp_path_factory): return tmp_path_factory.mktemp('root') @pytest.fixture(scope='session') def settings(tmp_root): return load(tmp_root) -
90% success
@pytest.fixture(scope='session') def db(tmp_path_factory): path = tmp_path_factory.mktemp('db') return init_db(path)
Dead Ends
Common approaches that don't work:
-
80% fail
autouse doesn't change scope; the mismatch remains and pytest still raises ScopeMismatch.
-
85% fail
The lambda still references the same fixture object; pytest resolves dependencies before invocation.