如何使用 pytest 在回溯中查找特定异常

问题描述 投票:0回答:1

进行像这样的

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
是否在某个时刻也被提出?

似乎 pytest 允许您

with pytest.raises(ValueError) as exc_info:
,但不确定哪种是遍历
ExceptionInfo
以便找到
RuntimeError
的最佳方式。

python pytest
1个回答
0
投票

可以通过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"
© www.soinside.com 2019 - 2024. All rights reserved.