python
type_error
ai_generated
true
AttributeError: 'function' 对象没有属性 'assert_called_once'
AttributeError: 'function' object has no attribute 'assert_called_once'
ID: python/pytest-mock-not-found
80%修复率
88%置信度
0证据数
2024-08-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
测试尝试在普通函数上使用mock断言方法,而不是在Mock对象上。这通常发生在函数被错误地打补丁时(例如,使用 @patch 但没有创建 Mock),或者mock没有被正确注入。
English
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.
解决方案
-
98% 成功率
from unittest.mock import patch @patch('mymodule.my_function') def test_my_function(mock_func): my_function() mock_func.assert_called_once() -
95% 成功率
def test_my_function(mocker): mock_func = mocker.patch('mymodule.my_function') my_function() mock_func.assert_called_once() -
90% 成功率
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()
无效尝试
常见但无效的做法:
-
98% 失败
Functions do not have mock assertion methods; this is a fundamental misunderstanding of the mock API.
-
90% 失败
Creating a Mock object does not replace the real function; the test still calls the original function.
-
85% 失败
mocker.patch requires a target string; omitting it raises a TypeError or patches the wrong object.