python type_error ai_generated true

AttributeError: Mock object has no attribute 'fetch_user'

ID: python/unittest-mock-autospec-missing

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.10 active
3.11 active
3.12 active

Root Cause

A plain MagicMock was used instead of create_autospec, so typos in method names are silently accepted until the mock is used as the real object and the attribute is looked up.

generic

中文

使用了普通 MagicMock 而非 create_autospec,方法名拼写错误被静默接受,直到 mock 被当作真实对象使用并查找属性时才暴露。

Workarounds

  1. 95% success
    from unittest.mock import create_autospec
    mock_svc = create_autospec(UserService, instance=True)
    # mock_svc.fetch_user now exists and typo'd names raise AttributeError
  2. 90% success
    from unittest.mock import Mock
    mock_svc = Mock(spec=UserService)

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Fixes one symptom but the mock still accepts any typo, so the next misspelling fails the same way.

  2. 75% fail

    Loses the ability to assert calls and may trigger real I/O or DB access.