# AttributeError: Mock 对象没有属性 'commit'

- **ID:** `python/unittest-mock-spec-missing-attribute`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

使用 spec= 或 autospec= 创建的 Mock 将属性限制为 spec 目标上的属性。被测代码访问 spec 上不存在的属性时抛出 AttributeError。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.11 | active | — | — |
| 3.12 | active | — | — |

## 解决方案

1. **** (90% 成功率)
   ```
   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()
   ```
2. **** (88% 成功率)
   ```
   from unittest.mock import create_autospec
mock_conn = create_autospec(Connection, instance=True)
mock_conn.commit()  # allowed because Connection.commit exists
   ```

## 无效尝试

- **** — Disables typo detection and signature validation; tests pass with wrong method names, hiding real bugs. (70% 失败率)
- **** — Violates spec contract; the mock no longer reflects the real interface and future signature changes go unnoticed. (60% 失败率)
