python config_error ai_generated true

ScopeMismatch: 你试图在模块作用域的 request 对象中访问函数作用域的 fixture mocker,涉及的工厂: module: conftest.py:15: def module_mock(request) function: pytest_mock/plugin.py:40: def mocker()

ScopeMismatch: You tried to access the function scoped fixture mocker with a module scoped request object, involved factories: module: conftest.py:15: def module_mock(request) function: pytest_mock/plugin.py:40: def mocker()

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

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

版本兼容性

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

根因分析

模块或会话作用域的 fixture 依赖函数作用域的 fixture(mocker),pytest 禁止此做法,因为作用域更广的 fixture 生命周期长于更窄的 fixture。

English

A module- or session-scoped fixture depends on a function-scoped fixture (mocker), which pytest forbids because the broader-scoped fixture outlives the narrower one.

generic

解决方案

  1. 95% 成功率
    @pytest.fixture
    def module_mock(mocker):  # function scope
        return mocker.patch('myapp.client')
    
    # or use @pytest.fixture(scope='function')
  2. 85% 成功率
    @pytest.fixture(scope='module')
    def module_mock():
        from unittest.mock import patch
        with patch('myapp.client') as m:
            yield m

无效尝试

常见但无效的做法:

  1. 95% 失败

    mocker is provided by pytest-mock and its scope is not configurable via pytest.ini; attempting to override it in conftest raises the same ScopeMismatch.

  2. 60% 失败

    Decorator patching applies per-function, not per-module; it doesn't solve the need for a module-scoped mock and can conflict with other patches.