python
type_error
ai_generated
true
AttributeError: Mock object has no attribute 'commit'
ID: python/unittest-mock-spec-missing-attribute
80%Fix Rate
87%Confidence
0Evidence
2024-12-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
A Mock created with spec= or autospec= restricts attributes to the spec target. The code under test accesses an attribute not present on the spec, raising AttributeError.
generic中文
使用 spec= 或 autospec= 创建的 Mock 将属性限制为 spec 目标上的属性。被测代码访问 spec 上不存在的属性时抛出 AttributeError。
Workarounds
-
90% success
from unittest.mock import patch @patch('app.repo.Connection', autospec=True) def test_save(mock_conn_cls): inst = mock_conn_cls.return_value inst.commit.return_value = None save() inst.commit.assert_called_once() -
88% success
from unittest.mock import create_autospec mock_conn = create_autospec(Connection, instance=True) mock_conn.commit() # allowed because Connection.commit exists
Dead Ends
Common approaches that don't work:
-
70% fail
Disables typo detection and signature validation; tests pass with wrong method names, hiding real bugs.
-
60% fail
Violates spec contract; the mock no longer reflects the real interface and future signature changes go unnoticed.