python config_error ai_generated true

ScopeMismatch: 你试图在会话作用域的请求对象中访问函数作用域的 fixture db_session

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

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

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

版本兼容性

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

根因分析

会话作用域的 fixture 依赖函数作用域的 fixture,pytest 禁止这样做,因为生命周期较短的 fixture 无法存活于其作用域之外。

English

A session-scoped fixture depends on a function-scoped fixture, which pytest forbids because the shorter-lived fixture cannot outlive its scope.

generic

解决方案

  1. 90% 成功率
    Align the dependent fixture's scope to session, or restructure so the session fixture does not depend on a function fixture:
    
    @pytest.fixture(scope='session')
    def engine():
        ...
    
    @pytest.fixture
    def db_session(engine):
        ...
  2. 85% 成功率
    Use a factory fixture to create per-test objects from a session resource.

无效尝试

常见但无效的做法:

  1. 85% 失败

    The error is about the fixture dependency graph, not the test; the mismatch persists.

  2. 80% 失败

    Autouse does not change scope; the ScopeMismatch still occurs.