python
runtime_error
ai_generated
true
AssertionError: 未找到期望的调用。 期望: fetch('https://api.example.com') 实际: fetch()
AssertionError: expected call not found. Expected: fetch('https://api.example.com') Actual: fetch()
ID: python/unittest-mock-magicmock-assertion
80%修复率
86%置信度
0证据数
2024-08-03首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
assert_called_with 比较精确的位置参数和关键字参数。实际调用传入了不同的参数(例如 URL 对象而非字符串),或者 mock 在调用和断言之间被重置/重新配置。
English
assert_called_with compares exact positional and keyword arguments. The actual call passed different arguments (e.g., a URL object instead of a string) or the mock was reset/reconfigured between the call and the assertion.
解决方案
-
90% 成功率
mock_fetch.assert_called_once() args, kwargs = mock_fetch.call_args assert str(args[0]) == 'https://api.example.com'
-
82% 成功率
from unittest.mock import call, ANY mock_fetch.assert_called_with(ANY) assert mock_fetch.call_args.args[0].__str__().endswith('/api.example.com')
无效尝试
常见但无效的做法:
-
80% 失败
Only checks call count, not arguments; the bug (wrong URL) goes undetected.
-
85% 失败
matching.ANY makes the assertion always pass and hides the real argument mismatch.