python config_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-21First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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.

generic

中文

会话级 fixture 依赖函数级 fixture(如 tmp_path 或 monkeypatch),pytest 禁止此行为,因为窄作用域 fixture 无法比宽作用域 fixture 存活更久。

Workarounds

  1. 95% success
    @pytest.fixture(scope='session')
    def data_dir(tmp_path_factory):
        d = tmp_path_factory.mktemp('data')
        (d / 'file.txt').write_text('hi')
        return d
  2. 85% success
    @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']

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Defeats the purpose of sharing expensive setup; tests slow down dramatically.

  2. 85% fail

    Raises the same ScopeMismatch at runtime; getfixturevalue does not change scopes.