python runtime_error ai_generated true

AssertionError: expected call not found. Expected: fetch('https://api.example.com') Actual: fetch()

ID: python/unittest-mock-magicmock-assertion

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.12 active — — —

Root Cause

assert_called_with compares exact positional and keyword arguments. The actual call passed different arguments (e.g., a URL object instead of a string) or the mock was reset/reconfigured between the call and the assertion.

generic

中文

assert_called_with 比较精确的位置参数和关键字参数。实际调用传入了不同的参数(例如 URL 对象而非字符串),或者 mock 在调用和断言之间被重置/重新配置。

Workarounds

  1. 90% success
    mock_fetch.assert_called_once()
    args, kwargs = mock_fetch.call_args
    assert str(args[0]) == 'https://api.example.com'
  2. 82% success
    from unittest.mock import call, ANY
    mock_fetch.assert_called_with(ANY)
    assert mock_fetch.call_args.args[0].__str__().endswith('/api.example.com')

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Only checks call count, not arguments; the bug (wrong URL) goes undetected.

  2. 85% fail

    matching.ANY makes the assertion always pass and hides the real argument mismatch.