python type_error ai_generated true

TypeError: 'MagicMock' 类型的对象没有 len() 在处理上述异常时,又发生了一个异常: TypeError: 不支持 'MagicMock' 与 'MagicMock' 之间的 + 运算

TypeError: object of type 'MagicMock' has no len() During handling of the above exception, another exception occurred: TypeError: unsupported operand type(s) for +: 'MagicMock' and 'MagicMock'

ID: python/pytest-mock-magic-method-not-mocked

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

版本兼容性

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

根因分析

在需要 MagicMock 的地方使用了普通的 mock.Mock;只有 MagicMock 支持 __len__、__add__、__iter__ 等魔术方法。

English

A regular mock.Mock was used where a MagicMock is required; only MagicMock supports magic methods like __len__, __add__, and __iter__.

generic

解决方案

  1. 96% 成功率
    from unittest.mock import MagicMock, patch
    
    with patch('myapp.container', new=MagicMock()) as m:
        m.__len__.return_value = 3
        assert len(container) == 3
  2. 93% 成功率
    with patch('myapp.container', autospec=True) as m:
        m.__len__.return_value = 3
        assert len(container) == 3

无效尝试

常见但无效的做法:

  1. 80% 失败

    Works for one magic method but breaks as soon as another (e.g., __iter__) is used; the mock is still not a full MagicMock.

  2. 90% 失败

    configure_mock only sets named attributes; it does not add magic method support to a plain Mock.