python config_error ai_generated true

ScopeMismatch: 你尝试用 session 作用域的请求对象访问 function 作用域的 fixture 'tmp_path'

ScopeMismatch: You tried to access the function scoped fixture 'tmp_path' with a session scoped request object

ID: python/pytest-scope-mismatch-session-function

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-05-22首次发现

版本兼容性

版本状态引入弃用备注
7.x active
8.x active

根因分析

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

English

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

解决方案

  1. 92% 成功率
    # 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% 成功率
    @pytest.fixture(scope="session")
    def heavy(request):
        def get_tmp():
            return request.getfixturevalue("tmp_path")
        yield get_tmp

无效尝试

常见但无效的做法:

  1. 98% 失败

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

  2. 90% 失败

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

  3. 95% 失败

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