python runtime_error ai_generated true

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

AttributeError: Mock object has no attribute 'some_method'

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

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

版本兼容性

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

根因分析

使用 `create_autospec` 将 mock 限制为真实对象的属性;如果 `some_method` 是动态添加的或拼写错误,访问会失败。

English

Using `create_autospec` restricts the mock to the real object's attributes; if `some_method` is dynamically added or misspelled, access fails.

generic

解决方案

  1. 95% 成功率
    class MyClass:
        def some_method(self): ...
    
    mock = create_autospec(MyClass)
    mock.some_method()
  2. 80% 成功率
    mock = Mock(spec_set=['some_method', 'other_method'])

无效尝试

常见但无效的做法:

  1. 60% 失败

    Loses the safety of autospec and may hide typos in method names.

  2. 70% 失败

    Defeats the purpose of autospec and may not match the real signature.