如何使用pytest在回溯中查找特定异常并验证嵌套RuntimeError
在pytest中验证被捕获并重新抛出的原始异常
要验证bar()中确实抛出过RuntimeError("Foo"),可以利用Python的异常链机制——当你在except块中隐式重新抛出异常时,原始异常会被保存在新异常的__context__属性里。结合pytest.raises返回的ExceptionInfo对象,就能拿到并验证原始异常。
修改后的测试代码如下:
import pytest def foo(): raise RuntimeError("Foo") def bar(): try: foo() except RuntimeError: raise ValueError("Bar") def test_raises(): with pytest.raises(ValueError, match="Bar") as exc_info: bar() # 从异常链中获取原始的RuntimeError original_exception = exc_info.value.__context__ # 验证原始异常的类型和消息 assert isinstance(original_exception, RuntimeError) assert str(original_exception) == "Foo"
补充说明
- 如果你的代码是显式指定异常链(比如用
raise ValueError("Bar") from e),那么原始异常会被存在新异常的__cause__属性中,此时需要把代码里的__context__换成__cause__来获取。 exc_info.value就是被捕获的ValueError实例,通过它的异常链属性就能追溯到之前抛出的RuntimeError。
内容的提问来源于stack exchange,提问作者Peque
相关产品推荐
相关产品推荐

