python
module_error
ai_generated
true
AssertionError: 预期 'send_email' 被调用一次。实际调用 0 次。
AssertionError: Expected 'send_email' to have been called once. Called 0 times.
ID: python/unittest-mock-method-not-called
80%修复率
89%置信度
0证据数
2024-03-29首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
被测函数调用的是导入到其自身模块中的名称(`from myapp.mail import send_email`),但测试补丁了 `myapp.mail.send_email`。本地绑定仍指向原始函数。
English
The function under test calls a name that was imported into its own module (`from myapp.mail import send_email`), but the test patched `myapp.mail.send_email`. The local binding still points to the original function.
解决方案
-
95% 成功率
from unittest import mock # services.py does: from myapp.mail import send_email def test_signup(): with mock.patch("myapp.services.send_email") as fake_send: signup("[email protected]") fake_send.assert_called_once_with("[email protected]") -
88% 成功率
# services.py import myapp.mail as mail def signup(email): mail.send_email(email) # test with mock.patch("myapp.mail.send_email") as fake_send: signup("[email protected]")
无效尝试
常见但无效的做法:
-
85% 失败
The mock was never invoked; changing args doesn't help.
-
60% 失败
Works only if you patch the correct binding; patching the definition module alone is a no-op for the caller.