python runtime_error ai_generated true

AssertionError: 未引发 ValueError

AssertionError: ValueError not raised

ID: python/unittest-assertraises-no-exception

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

版本兼容性

版本状态引入弃用备注
3.10 active
3.11 active
3.12 active

根因分析

self.assertRaises(ValueError) 作为上下文管理器使用,但被测代码未引发异常,或异常在函数内部被捕获并吞掉。

English

self.assertRaises(ValueError) was used as a context manager but the code under test did not raise, or the exception was caught and swallowed inside the function.

generic

解决方案

  1. 90% 成功率
    with self.assertRaises(ValueError) as ctx:
        parse('bad-input')
    self.assertIn('bad-input', str(ctx.exception))
  2. 92% 成功率
    import pytest
    
    def test_parse_raises():
        with pytest.raises(ValueError, match=r'bad-input'):
            parse('bad-input')

无效尝试

常见但无效的做法:

  1. 85% 失败

    Inverts the logic: except catches the expected exception and calls fail, so a correct raise now fails the test.

  2. 75% 失败

    Broadens the assertion so much that any unrelated error (e.g. TypeError) passes the test, masking real bugs.