python runtime_error ai_generated true

AttributeError: Mock 对象没有属性 'fetch' # 使用 autospec=True 时 AttributeError: Mock 对象没有属性 'fetch'

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

ID: python/unittest-mock-autospec-attribute

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 90% 成功率
    Autospec the instance instead of the class:
    
    instance = MyClient()
    with patch.object(instance, 'fetch', autospec=True) as m:
        ...
  2. 88% 成功率
    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)

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 60% 失败

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