python type_error ai_generated true

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

ID: python/unittest-assertraises-invalid-exception

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-05-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

  1. 99% success
    with self.assertRaises(ValueError):
        function_that_raises()
  2. 99% success
    with self.assertRaises((ValueError, TypeError)):
        function_that_raises()

Dead Ends

Common approaches that don't work:

  1. 90% fail

    assertRaises expects the exception class, not an instance.

  2. 95% fail

    Strings are not valid exception types.