python runtime_error ai_generated true

AttributeError: Mock 对象没有属性 'send'

AttributeError: Mock object has no attribute 'send'

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

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 90% 成功率
    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% 成功率
    Use `autospec=True` in patch so the mock mirrors the real signature:
    
    @patch('mymod.Client', autospec=True)
    def test_client(MockClient):
        ...

无效尝试

常见但无效的做法:

  1. 60% 失败

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

  2. 50% 失败

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