python runtime_error ai_generated true

AssertionError: ValueError not raised by parse_input

ID: python/unittest-assert-raises-no-exception

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active — — —

Root Cause

assertRaises expects the callable to raise the specified exception. If the function returns normally (e.g., it was fixed, or the input is valid), the context manager's __exit__ receives no exception and the test fails.

generic

中文

assertRaises 期望可调用对象引发指定的异常。如果函数正常返回(例如它已被修复,或者输入有效),上下文管理器的 __exit__ 不会收到异常,测试就会失败。

Workarounds

  1. 97% success
    def parse_input(s):
        if not s:
            raise ValueError('empty input')
        return int(s)
    
    # test
    with self.assertRaises(ValueError):
        parse_input('')
  2. 96% success
    import pytest
    
    def test_parse_input_empty():
        with pytest.raises(ValueError, match='empty input'):
            parse_input('')

Dead Ends

Common approaches that don't work:

  1. 90% fail

    assertRaisesRegex still requires the exception to be raised; an empty pattern matches anything but the exception absence still fails.

  2. 70% fail

    Reimplements assertRaises worse; loses the informative 'ValueError not raised' message and complicates the test.