python
type_error
ai_generated
true
TypeError: 'MagicMock' 类型的对象没有 len() 在处理上述异常时,又发生了一个异常: TypeError: 不支持 'MagicMock' 与 'MagicMock' 之间的 + 运算
TypeError: object of type 'MagicMock' has no len() During handling of the above exception, another exception occurred: TypeError: unsupported operand type(s) for +: 'MagicMock' and 'MagicMock'
ID: python/pytest-mock-magic-method-not-mocked
80%修复率
89%置信度
0证据数
2024-05-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
在需要 MagicMock 的地方使用了普通的 mock.Mock;只有 MagicMock 支持 __len__、__add__、__iter__ 等魔术方法。
English
A regular mock.Mock was used where a MagicMock is required; only MagicMock supports magic methods like __len__, __add__, and __iter__.
解决方案
-
96% 成功率
from unittest.mock import MagicMock, patch with patch('myapp.container', new=MagicMock()) as m: m.__len__.return_value = 3 assert len(container) == 3 -
93% 成功率
with patch('myapp.container', autospec=True) as m: m.__len__.return_value = 3 assert len(container) == 3
无效尝试
常见但无效的做法:
-
80% 失败
Works for one magic method but breaks as soon as another (e.g., __iter__) is used; the mock is still not a full MagicMock.
-
90% 失败
configure_mock only sets named attributes; it does not add magic method support to a plain Mock.