python runtime_error ai_generated true

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

ID: python/unittest-mock-assertion-failure

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-04-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.12 active — — —

Root Cause

A mock's assert_called_once() failed because the patched function was never invoked, usually due to patching the wrong module reference, an early return in the code under test, or the call happening in a different thread.

generic

中文

mock 的 assert_called_once() 失败,因为被补丁的函数从未被调用,通常由于补丁指向了错误的模块引用、被测代码提前返回或调用发生在不同线程。

Workarounds

  1. 92% success
    Patch the name where it is used and assert against the same object:
    
    with patch('app.orders.send_email') as m:
        place_order(order)
        m.assert_called_once_with('[email protected]')
  2. 88% success
    Debug by printing the mock's call list:
    
    print(m.mock_calls)
    print(m.call_args_list)

Dead Ends

Common approaches that don't work:

  1. 90% fail

    This only checks that it was called at least once, but the count is 0, so it still fails.

  2. 85% fail

    create=True creates a mock attribute but does not make the real code call it.