python runtime_error ai_generated true

AttributeError: Mock object has no attribute 'fetch' # with autospec=True AttributeError: Mock object has no attribute 'fetch'

ID: python/unittest-mock-autospec-attribute

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-10-28First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active — — —
3.12 active — — —

Root Cause

autospec=True builds a spec from the target object. If the target is a module or class where 'fetch' is defined dynamically (e.g., added in __init__ or via setattr), autospec cannot see it and the mock lacks the attribute.

generic

中文

autospec=True 根据目标对象构建规范。如果目标是模块或类,而 'fetch' 是在 __init__ 中或通过 setattr 动态添加的,autospec 无法识别,mock 缺少该属性。

Workarounds

  1. 90% success
    Autospec the instance instead of the class:
    
    instance = MyClient()
    with patch.object(instance, 'fetch', autospec=True) as m:
        ...
  2. 88% success
    Use create_autospec on an instance with spec_set for stricter checks:
    
    from unittest.mock import create_autospec
    m = create_autospec(MyClient(), spec_set=True)

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Loses signature validation and lets typos in call arguments pass silently.

  2. 60% fail

    Works but bypasses autospec and does not validate the signature of fetch.