python config_error ai_generated true

ScopeMismatch: 您试图用 session 作用域的 request 对象访问 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-in-function

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

版本兼容性

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

根因分析

session/module 作用域的 fixture 依赖了更窄作用域的 fixture。pytest 禁止宽作用域消费窄作用域,因为窄 fixture 会在宽 fixture 之前被拆除。

English

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

解决方案

  1. 93% 成功率
    @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)
  2. 90% 成功率
    @pytest.fixture(scope='session')
    def db(tmp_path_factory):
        path = tmp_path_factory.mktemp('db')
        return init_db(path)

无效尝试

常见但无效的做法:

  1. 80% 失败

    autouse doesn't change scope; the mismatch remains and pytest still raises ScopeMismatch.

  2. 85% 失败

    The lambda still references the same fixture object; pytest resolves dependencies before invocation.