python runtime_error ai_generated true

AttributeError: Mock object has no attribute 'send'

ID: python/unittest-mock-autospec-missing-attr

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-09-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active — — —
3.12 active — — —

Root Cause

A bare `Mock()` returns child mocks for any attribute access, but `MagicMock`/`Mock` with `spec=` restricts attributes. If a test uses `spec=` and the code calls a method not in the spec, this error appears.

generic

中文

裸 `Mock()` 对任意属性访问都会返回子 mock,但带 `spec=` 的 `MagicMock`/`Mock` 会限制属性。若测试使用了 `spec=`,而代码调用了 spec 中不存在的方法,就会出现此错误。

Workarounds

  1. 90% success
    Add the missing method to the spec's source class, or use `spec=` on the real class:
    
    from unittest.mock import MagicMock
    from mylib import Client
    m = MagicMock(spec=Client)
    # ensure Client actually defines .send()
  2. 90% success
    Use `autospec=True` in patch so the mock mirrors the real signature:
    
    @patch('mymod.Client', autospec=True)
    def test_client(MockClient):
        ...

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Disables safety checks; typos in method calls are no longer caught and tests may pass silently.

  2. 50% fail

    With `spec_set=True` you cannot add new attributes; with plain `spec` this works but defeats the purpose.