python runtime_error ai_generated true

AssertionError: ValueError not raised by my_function

ID: python/unittest-assert-raises-not-caught

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —
3.12 active — — —

Root Cause

The function under test does not raise the expected exception, or the exception is caught inside the function and not re-raised.

generic

中文

被测函数未引发预期的异常,或者异常在函数内部被捕获且未重新引发。

Workarounds

  1. 95% success
    def my_function(x):
        if x < 0:
            raise ValueError('negative')
        return x
    
    with self.assertRaises(ValueError):
        my_function(-1)
  2. 90% success
    with pytest.raises(ValueError, match='negative'):
        my_function(-1)

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Tests the test, not the function; false positive.

  2. 70% fail

    Too broad; may pass for unrelated exceptions and hide bugs.