python type_error ai_generated true

类型错误:assertRaises() 参数 1 必须是异常类型或异常类型的元组

TypeError: assertRaises() arg 1 must be an exception type or tuple of exception types

ID: python/unittest-assertraises-invalid-exception

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

版本兼容性

版本状态引入弃用备注
3.x active

根因分析

将非异常对象(如字符串或函数)作为 assertRaises 的第一个参数传递。

English

Passing a non-exception object (e.g., a string or function) as the first argument to assertRaises.

generic

解决方案

  1. 99% 成功率
    with self.assertRaises(ValueError):
        function_that_raises()
  2. 99% 成功率
    with self.assertRaises((ValueError, TypeError)):
        function_that_raises()

无效尝试

常见但无效的做法:

  1. 90% 失败

    assertRaises expects the exception class, not an instance.

  2. 95% 失败

    Strings are not valid exception types.