python module_error ai_generated true

AssertionError: Expected 'send_email' to have been called once. Called 0 times.

ID: python/unittest-mock-method-not-called

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-03-29First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

The function under test calls a name that was imported into its own module (`from myapp.mail import send_email`), but the test patched `myapp.mail.send_email`. The local binding still points to the original function.

generic

中文

被测函数调用的是导入到其自身模块中的名称(`from myapp.mail import send_email`),但测试补丁了 `myapp.mail.send_email`。本地绑定仍指向原始函数。

Workarounds

  1. 95% success
    from unittest import mock
    
    # services.py does: from myapp.mail import send_email
    def test_signup():
        with mock.patch("myapp.services.send_email") as fake_send:
            signup("[email protected]")
            fake_send.assert_called_once_with("[email protected]")
  2. 88% success
    # services.py
    import myapp.mail as mail
    
    def signup(email):
        mail.send_email(email)
    
    # test
    with mock.patch("myapp.mail.send_email") as fake_send:
        signup("[email protected]")

Dead Ends

Common approaches that don't work:

  1. 85% fail

    The mock was never invoked; changing args doesn't help.

  2. 60% fail

    Works only if you patch the correct binding; patching the definition module alone is a no-op for the caller.