python
runtime_error
ai_generated
true
AssertionError: 未找到预期调用。 预期: send(1) 实际: 未被调用。
AssertionError: expected call not found. Expected: send(1) Actual: not called.
ID: python/pytest-mock-mocker-scope-mismatch
80%修复率
83%置信度
0证据数
2024-07-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.14.x | active | — | — | — |
根因分析
mocker.patch 在函数作用域的 fixture 中应用,但被 patch 的调用发生在会话作用域 setup 中,该 setup 在 patch 安装之前已执行。
English
mocker.patch was applied inside a fixture with function scope, but the patched call happens in a session-scoped setup that ran before the patch was installed.
解决方案
-
90% 成功率
@pytest.fixture(scope='session') def patched_send(): with mock.patch('myapp.notify.send') as m: yield m def test_x(patched_send): run_setup() patched_send.assert_called_with(1) -
93% 成功率
def test_x(mocker): m = mocker.patch('myapp.notify.send') run_setup() # called here, not in a fixture m.assert_called_with(1)
无效尝试
常见但无效的做法:
-
90% 失败
The mock was never called in the first place; resetting does not retroactively capture calls that happened before patching.
-
85% 失败
create=True only bypasses AttributeError; the timing problem (patch applied after the call) is unchanged.