python
runtime_error
ai_generated
true
AttributeError: Mock object has no attribute 'some_method'
ID: python/unittest-mock-autospec-missing-attribute
80%Fix Rate
90%Confidence
0Evidence
2024-07-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
95% success
class MyClass: def some_method(self): ... mock = create_autospec(MyClass) mock.some_method() -
80% success
mock = Mock(spec_set=['some_method', 'other_method'])
Dead Ends
Common approaches that don't work:
-
60% fail
Loses the safety of autospec and may hide typos in method names.
-
70% fail
Defeats the purpose of autospec and may not match the real signature.