python
type_error
ai_generated
true
TypeError: 'Mock' object is not subscriptable
ID: python/unittest-mock-magic-method
80%Fix Rate
86%Confidence
0Evidence
2024-11-26First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
Code under test subscripts a Mock (e.g. mock_obj['key']), but a plain Mock does not support __getitem__; MagicMock is required for magic methods.
generic中文
被测代码对 Mock 进行下标访问(如 mock_obj['key']),但普通 Mock 不支持 __getitem__;需要 MagicMock 来支持魔术方法。
Workarounds
-
93% success
Use MagicMock, which implements __getitem__: from unittest.mock import MagicMock m = MagicMock() m.__getitem__.return_value = 'value' assert m['key'] == 'value'
-
85% success
Configure the subscript return value: m = MagicMock() m.configure_mock(**{'__getitem__.return_value': 42})
Dead Ends
Common approaches that don't work:
-
90% fail
Dunder lookups bypass instance attributes; assigning __getitem__ on an instance does not make it subscriptable.
-
85% fail
This changes production code to accommodate the test, masking the real interface.