python runtime_error ai_generated true

AssertionError: 期望 'send_email' 被调用一次。实际调用 0 次。

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

ID: python/unittest-mock-assertion-failure

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

版本兼容性

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

根因分析

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

English

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

解决方案

  1. 92% 成功率
    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% 成功率
    Debug by printing the mock's call list:
    
    print(m.mock_calls)
    print(m.call_args_list)

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 85% 失败

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