python type_error ai_generated true

TypeError: assertRaises() 缺少 1 个必需的位置参数:'callable'

TypeError: assertRaises() missing 1 required positional argument: 'callable'

ID: python/unittest-assertraises-not-called

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-01-30首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

解决方案

  1. 98% 成功率
    with self.assertRaises(ValueError):
        int('not-a-number')
  2. 95% 成功率
    self.assertRaises(ValueError, int, 'not-a-number')
    # or with keyword args:
    self.assertRaises(ValueError, int, base=2, x='zz')

无效尝试

常见但无效的做法:

  1. 95% 失败

    assertRaises expects an exception class or tuple of classes, not a string; passing a string causes a different TypeError about the expected type.

  2. 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'.