python
type_error
ai_generated
true
AttributeError: Mock object has no attribute 'some_method'
ID: python/attributeerror-mock-object-has-no-attribute
80%Fix Rate
86%Confidence
0Evidence
2024-10-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
Root Cause
A mock object is created without specifying the attribute, and the code tries to access an undefined attribute.
generic中文
创建模拟对象时未指定属性,代码尝试访问未定义的属性。
Workarounds
-
95% success Configure mock with spec or autospec
mock = Mock(spec=MyClass); mock.some_method.return_value = 42
-
90% success Set attribute directly on mock
mock = Mock(); mock.some_method = MagicMock(return_value=42)
Dead Ends
Common approaches that don't work:
-
Adding attribute via mock.attach_mock
60% fail
attach_mock is for attaching additional mocks, not simple attributes.
-
Using mock.reset_mock()
80% fail
Reset clears call history but does not add missing attributes.