python type_error ai_generated true

AttributeError: Mock object has no attribute 'non_existent_method' when using autospec

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2026-07-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active

Root Cause

Using autospec=True in patch or create_autospec restricts the mock to only have attributes that exist on the original object, and accessing a non-existent attribute raises an AttributeError.

generic

中文

在 patch 或 create_autospec 中使用 autospec=True 会将模拟限制为仅具有原始对象上存在的属性,访问不存在的属性会引发 AttributeError。

Workarounds

  1. 85% success
    Ensure the attribute exists on the original object, or use autospec with a spec object that includes the attribute: create_autospec(MyClass, instance=True)
  2. 75% success
    Use spec_set instead of autospec to allow additional attributes while still checking existing ones.

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Disabling autospec (autospec=False) may allow the test to pass but hides potential mismatches between the mock and the real API.

  2. 40% fail

    Adding the missing attribute to the original object may not be feasible if it's a third-party library.