python
type_error
ai_generated
true
TypeError: unsupported operand type(s) for +: 'Mock' and 'int'
ID: python/unittest-mock-magic-method-not-supported
80%Fix Rate
89%Confidence
0Evidence
2024-02-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
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.
generic中文
普通的 unittest.mock.Mock 不实现 __add__、__len__、__iter__ 等魔法方法。当被测代码依赖 dunder 方法时,应使用 MagicMock(或 AsyncMock)。
Workarounds
-
98% success
from unittest.mock import MagicMock m = MagicMock() m.__add__.return_value = 42 assert m + 1 == 42
-
90% success
from unittest.mock import AsyncMock m = AsyncMock() m.__aenter__.return_value = resource
Dead Ends
Common approaches that don't work:
-
90% fail
Plain Mock ignores magic method assignments; you must use MagicMock for them to take effect.
-
95% fail
int(Mock()) raises TypeError because Mock has no __int__; converting does not help.