python type_error ai_generated true

TypeError: 'Mock' object is not subscriptable

ID: python/unittest-mock-magic-method

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-11-26First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 93% success
    Use MagicMock, which implements __getitem__:
    
    from unittest.mock import MagicMock
    m = MagicMock()
    m.__getitem__.return_value = 'value'
    assert m['key'] == 'value'
  2. 85% success
    Configure the subscript return value:
    
    m = MagicMock()
    m.configure_mock(**{'__getitem__.return_value': 42})

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Dunder lookups bypass instance attributes; assigning __getitem__ on an instance does not make it subscriptable.

  2. 85% fail

    This changes production code to accommodate the test, masking the real interface.