python type_error ai_generated true

AttributeError: 'function' 对象没有属性 'assert_called_once'

RuntimeError: Mock object has no attribute 'assert_called_once_with' after test body? No — actually: AttributeError: 'function' object has no attribute 'assert_called_once'

ID: python/pytest-mock-mocker-scope

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

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

mocker.patch 替换了错误的对象,或在被测代码捕获引用之后才应用补丁,导致断言针对真实函数而非 Mock 对象。

English

The mocker.patch target replaced the wrong object or the patch was applied after the code under test captured a reference, so the assertion runs against the real function, not a Mock.

generic

解决方案

  1. 93% 成功率
    def test_send(mocker):
        m = mocker.patch('app.mailer.smtplib.SMTP')
        send_email('[email protected]')
        m.assert_called_once()
        m.return_value.sendmail.assert_called_once()
  2. 85% 成功率
    def test_send(mocker):
        m = mocker.patch('app.mailer.smtplib.SMTP')
        from app.mailer import send_email  # import after patch
        send_email('[email protected]')
        m.assert_called_once()

无效尝试

常见但无效的做法:

  1. 90% 失败

    The real function has no such method; you must assert on the returned mock object.

  2. 80% 失败

    Patches a different attribute path, so the code under test still uses the real function.