python runtime_error ai_generated true

AttributeError: Mock object has no attribute 'some_method'

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

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.12 active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 60% fail

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

  2. 70% fail

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