python type_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-05-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.11 active — — —
3.12 active — — —

Root Cause

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

generic

中文

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

Workarounds

  1. 96% success
    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% success
    with patch('myapp.container', autospec=True) as m:
        m.__len__.return_value = 3
        assert len(container) == 3

Dead Ends

Common approaches that don't work:

  1. 80% fail

    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% fail

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