python
type_error
ai_generated
true
AssertionError: 未抛出 ValueError 在处理上述异常时,又发生了一个异常: TypeError: 'ValueError' 对象不可调用
AssertionError: ValueError not raised During handling of the above exception, another exception occurred: TypeError: 'ValueError' object is not callable
ID: python/unittest-mock-side-effect-not-raised
80%修复率
90%置信度
0证据数
2024-02-28首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
mock.side_effect 被设置为异常实例而不是异常类;mock 尝试调用该实例并抛出 TypeError,而非预期的异常。
English
mock.side_effect was set to an exception instance instead of the exception class; mock tries to call the instance and raises TypeError instead of the intended exception.
解决方案
-
96% 成功率
from unittest import mock with mock.patch('myapp.fetch') as m: m.side_effect = ValueError # class, not ValueError() with pytest.raises(ValueError): call_sut() -
94% 成功率
def boom(*args, **kwargs): raise ValueError('bad input') with mock.patch('myapp.fetch', side_effect=boom): with pytest.raises(ValueError, match='bad input'): call_sut()
无效尝试
常见但无效的做法:
-
90% 失败
return_value returns the exception object as the call result; it is never raised, so the test still fails.
-
85% 失败
Masks the mock misconfiguration and makes the test pass for the wrong reason; the SUT never actually raised.