python runtime_error ai_generated true

AssertionError: my_function 未引发 ValueError

AssertionError: ValueError not raised by my_function

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

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 95% 失败

    Tests the test, not the function; false positive.

  2. 70% 失败

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