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

- **ID:** `python/unittest-mock-magic-method`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.12 | active | — | — |

## 解决方案

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})
   ```

## 无效尝试

- **** — Dunder lookups bypass instance attributes; assigning __getitem__ on an instance does not make it subscriptable. (90% 失败率)
- **** — This changes production code to accommodate the test, masking the real interface. (85% 失败率)
