TypeError: assertRaises() 缺少 1 个必需的位置参数:'callable'
TypeError: assertRaises() missing 1 required positional argument: 'callable'
ID: python/unittest-assertraises-not-called
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.10 | active | — | — | — |
| 3.12 | active | — | — | — |
根因分析
unittest.TestCase.assertRaises 既可用作上下文管理器,也可传入可调用对象和参数。仅传入异常类而不传可调用对象(或未使用 `with`)会引发 TypeError。
English
unittest.TestCase.assertRaises can be used as a context manager or called with a callable plus args. Calling it with only an exception class and no callable (or not using `with`) raises TypeError.
解决方案
-
98% 成功率
with self.assertRaises(ValueError): int('not-a-number') -
95% 成功率
self.assertRaises(ValueError, int, 'not-a-number') # or with keyword args: self.assertRaises(ValueError, int, base=2, x='zz')
无效尝试
常见但无效的做法:
-
95% 失败
assertRaises expects an exception class or tuple of classes, not a string; passing a string causes a different TypeError about the expected type.
-
80% 失败
This actually works, but if the user forgets the second argument entirely (the common mistake), it still raises the same TypeError; the dead-end is the mental model of 'just add the exception class'.