python
runtime_error
ai_generated
true
AssertionError: 期望 'mock_method' 被调用一次。实际调用 0 次。
AssertionError: Expected 'mock_method' to have been called once. Called 0 times.
ID: python/pytest-mock-patch-not-applied
80%修复率
87%置信度
0证据数
2024-07-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
mock 应用到了错误的命名空间,或被测代码直接导入函数,绕过了 patch。
English
The mock was applied to the wrong namespace or the code under test imports the function directly, bypassing the patch.
解决方案
-
95% 成功率
If my_module.py does 'from other_module import my_func', patch 'my_module.my_func' instead of 'other_module.my_func'.
-
90% 成功率
def test_my_func(monkeypatch): monkeypatch.setattr('my_module.my_func', lambda: None) # test code -
85% 成功率
import my_module; print(my_module.my_func.__module__) to see where it's defined, then patch accordingly.
无效尝试
常见但无效的做法:
-
95% 失败
The test then passes but does not verify the intended behavior; the mock is still not applied.
-
90% 失败
If the target is incorrect, patch.object fails similarly.