python type_error ai_generated true

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

AttributeError: Mock object has no attribute 'commit'

ID: python/unittest-mock-spec-missing-attribute

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

版本兼容性

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

根因分析

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

English

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

解决方案

  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

无效尝试

常见但无效的做法:

  1. 70% 失败

    Disables typo detection and signature validation; tests pass with wrong method names, hiding real bugs.

  2. 60% 失败

    Violates spec contract; the mock no longer reflects the real interface and future signature changes go unnoticed.