python
type_error
ai_generated
true
AttributeError: 'function' 对象没有属性 'assert_called_once'
RuntimeError: Mock object has no attribute 'assert_called_once_with' after test body? No — actually: AttributeError: 'function' object has no attribute 'assert_called_once'
ID: python/pytest-mock-mocker-scope
80%修复率
83%置信度
0证据数
2024-09-17首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
mocker.patch 替换了错误的对象,或在被测代码捕获引用之后才应用补丁,导致断言针对真实函数而非 Mock 对象。
English
The mocker.patch target replaced the wrong object or the patch was applied after the code under test captured a reference, so the assertion runs against the real function, not a Mock.
解决方案
-
93% 成功率
def test_send(mocker): m = mocker.patch('app.mailer.smtplib.SMTP') send_email('[email protected]') m.assert_called_once() m.return_value.sendmail.assert_called_once() -
85% 成功率
def test_send(mocker): m = mocker.patch('app.mailer.smtplib.SMTP') from app.mailer import send_email # import after patch send_email('[email protected]') m.assert_called_once()
无效尝试
常见但无效的做法:
-
90% 失败
The real function has no such method; you must assert on the returned mock object.
-
80% 失败
Patches a different attribute path, so the code under test still uses the real function.