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-function

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

A higher-scoped fixture (session/module) depends on a lower-scoped fixture (function), which pytest forbids because the lower-scoped fixture would need to be recreated per test.

generic

中文

较高作用域的 fixture(session/module)依赖较低作用域的 fixture(function),pytest 禁止此行为,因为低作用域 fixture 需要为每个测试重新创建。

Workarounds

  1. 92% success
    # Instead of session-scoped fixture depending on tmp_path:
    @pytest.fixture
    def db(tmp_path):
        ...
    
    @pytest.fixture(scope="session")
    def db_session():
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            yield make_db(d)
  2. 75% success
    @pytest.fixture(scope="session")
    def heavy(request):
        def get_tmp():
            return request.getfixturevalue("tmp_path")
        yield get_tmp

Dead Ends

Common approaches that don't work:

  1. 98% fail

    The error is raised by pytest during fixture resolution before the body runs; catching it inside the fixture never executes.

  2. 90% fail

    autouse changes when fixtures are requested, not their scope, so the ScopeMismatch persists.

  3. 95% fail

    No such option exists; pytest ignores unknown ini keys and the error remains.