python
runtime_error
ai_generated
true
AttributeError: Mock object has no attribute 'send'
ID: python/unittest-mock-autospec-missing-attr
80%Fix Rate
85%Confidence
0Evidence
2024-09-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
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()
-
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:
-
60% fail
Disables safety checks; typos in method calls are no longer caught and tests may pass silently.
-
50% fail
With `spec_set=True` you cannot add new attributes; with plain `spec` this works but defeats the purpose.