python
type_error
ai_generated
true
TypeError: 不支持的操作数类型 +: 'Mock' 和 'int'
TypeError: unsupported operand type(s) for +: 'Mock' and 'int'
ID: python/unittest-mock-magic-method-not-supported
80%修复率
89%置信度
0证据数
2024-02-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
普通的 unittest.mock.Mock 不实现 __add__、__len__、__iter__ 等魔法方法。当被测代码依赖 dunder 方法时,应使用 MagicMock(或 AsyncMock)。
English
A plain unittest.mock.Mock does not implement magic methods like __add__, __len__, __iter__. Use MagicMock (or AsyncMock) when the code under test relies on dunder methods.
解决方案
-
98% 成功率
from unittest.mock import MagicMock m = MagicMock() m.__add__.return_value = 42 assert m + 1 == 42
-
90% 成功率
from unittest.mock import AsyncMock m = AsyncMock() m.__aenter__.return_value = resource
无效尝试
常见但无效的做法:
-
90% 失败
Plain Mock ignores magic method assignments; you must use MagicMock for them to take effect.
-
95% 失败
int(Mock()) raises TypeError because Mock has no __int__; converting does not help.