python runtime_error ai_generated true

AssertionError: <class 'ValueError'> not raised

ID: python/unittest-assertraises-wrong-exception

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

The code under test did not raise the expected exception. This could be because the code path was not triggered, the exception type is different, or the code silently handles the error.

generic

中文

被测代码未引发预期的异常。这可能是因为代码路径未触发、异常类型不同,或代码静默处理了错误。

Workarounds

  1. 92% success
    with self.assertRaises(ValueError) as cm:
        my_function(invalid_input)
    self.assertEqual(str(cm.exception), 'expected message')
  2. 95% success
    import pytest
    
    with pytest.raises(ValueError, match='expected message'):
        my_function(invalid_input)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    This broadens the assertion and may pass even when the wrong exception is raised, hiding bugs.

  2. 85% fail

    This bypasses assertRaises entirely and does not verify the exception type correctly.