如何在pytest中通过回溯找到特定异常

1 投票
1 回答
30 浏览
提问于 2025-04-14 15:25

有一个叫做 test_raises 的测试,它的作用是检查是否抛出了 ValueError,这个测试是通过 pytest.raises 来实现的:

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"):
        bar()

我想知道在这个测试中,怎么检查是否也抛出了 RuntimeError,并且这个错误的提示信息是 "Foo"

看起来 pytest 允许你使用 with pytest.raises(ValueError) as exc_info: 这样的方式,但我不太确定怎么才能找到 ExceptionInfo,以便查看 RuntimeError

1 个回答

1

你可以通过 getrepr 这个方法来获取它。

def test_raises():
    with pytest.raises(ValueError, match="Bar") as exc_info:
        bar()

    found = False
    for lst in exc_info.getrepr(style="short").chain:
        for tup in lst:
            if hasattr(tup, "reprentries") and "RuntimeErrors" in str(tup.reprentries):
                found = True
    assert found, "RuntimeError not found in stacktrace"

如果你确定错误发生的位置,可以去掉循环,直接写死那个位置,像这样:

assert "RuntimeError" in str(exc_info.getrepr(style="short").chain[0][1]), "RuntimeError not found in stacktrace"

撰写回答