python type_error ai_generated true

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

ID: python/unittest-assertraises-not-called

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-01-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.10 active — — —
3.12 active — — —

Root Cause

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

中文

unittest.TestCase.assertRaises 既可用作上下文管理器,也可传入可调用对象和参数。仅传入异常类而不传可调用对象(或未使用 `with`)会引发 TypeError。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 95% fail

    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% fail

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