python type_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-09-17First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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

中文

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

Workarounds

  1. 93% success
    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% success
    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()

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 80% fail

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