python type_error ai_generated true

AttributeError: 'function' object has no attribute 'assert_called_once'

ID: python/pytest-mock-not-found

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

The test attempts to use mock assertion methods on a regular function instead of a Mock object. This happens when a function is patched incorrectly (e.g., using @patch without creating a Mock) or when the mock is not properly injected.

generic

中文

测试尝试在普通函数上使用mock断言方法,而不是在Mock对象上。这通常发生在函数被错误地打补丁时(例如,使用 @patch 但没有创建 Mock),或者mock没有被正确注入。

Workarounds

  1. 98% success
    from unittest.mock import patch
    
    @patch('mymodule.my_function')
    def test_my_function(mock_func):
        my_function()
        mock_func.assert_called_once()
  2. 95% success
    def test_my_function(mocker):
        mock_func = mocker.patch('mymodule.my_function')
        my_function()
        mock_func.assert_called_once()
  3. 90% success
    If you have a reference to a Mock, ensure you're calling the mock, not the original:
    
    mock = Mock()
    mymodule.my_function = mock
    mymodule.my_function()
    mock.assert_called_once()

Dead Ends

Common approaches that don't work:

  1. 98% fail

    Functions do not have mock assertion methods; this is a fundamental misunderstanding of the mock API.

  2. 90% fail

    Creating a Mock object does not replace the real function; the test still calls the original function.

  3. 85% fail

    mocker.patch requires a target string; omitting it raises a TypeError or patches the wrong object.