python runtime_error ai_generated true

AssertionError:parse_input 未引发 ValueError

AssertionError: ValueError not raised by parse_input

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

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-01-30首次发现

版本兼容性

版本状态引入弃用备注
3.8 active

根因分析

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

English

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

解决方案

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

无效尝试

常见但无效的做法:

  1. 90% 失败

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

  2. 70% 失败

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