python type_error ai_generated true

AttributeError: 'dict' 对象没有属性 'items'

AttributeError: 'dict' object has no attribute 'items'

ID: python/pytest-mock-patch-dict

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2026-01-20首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

字典被 Mock 替换,但代码期望一个真实的字典并调用了 .items() 等字典方法。

English

A dictionary was patched with a Mock, but the code expects a real dictionary and calls dict methods like .items().

generic

解决方案

  1. 95% 成功率
    patch.dict('module.my_dict', {'key': 'value'}) or use a simple class that implements the required methods.
  2. 85% 成功率
    mock_dict = Mock()
    mock_dict.items.return_value = [('key', 'value')]
    patch('module.my_dict', mock_dict)

无效尝试

常见但无效的做法:

  1. 70% 失败

    MagicMock supports magic methods but not dict-specific methods like .items() unless configured.

  2. 90% 失败

    This defeats the purpose of the test and may cause other failures.