python
config_error
ai_generated
true
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
80%Fix Rate
87%Confidence
0Evidence
2024-04-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
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中文
模块或会话作用域的 fixture 依赖函数作用域的 fixture(mocker),pytest 禁止此做法,因为作用域更广的 fixture 生命周期长于更窄的 fixture。
Workarounds
-
95% success
@pytest.fixture def module_mock(mocker): # function scope return mocker.patch('myapp.client') # or use @pytest.fixture(scope='function') -
85% success
@pytest.fixture(scope='module') def module_mock(): from unittest.mock import patch with patch('myapp.client') as m: yield m
Dead Ends
Common approaches that don't work:
-
95% fail
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.
-
60% fail
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.