python type_error ai_generated true

TypeError: 'Mock' 对象不可下标访问

TypeError: 'Mock' object is not subscriptable

ID: python/unittest-mock-magic-method

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-11-26首次发现

版本兼容性

版本状态引入弃用备注
3.8 active — — —
3.12 active — — —

根因分析

被测代码对 Mock 进行下标访问(如 mock_obj['key']),但普通 Mock 不支持 __getitem__;需要 MagicMock 来支持魔术方法。

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 85% 失败

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