ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

11、pytest断言预期异常

2026/8/16 6:29:44 拓冰建站 浏览量
11、pytest断言预期异常

官方用例

# content of test_exception_zero.py
import pytestdef test_zero_division():with pytest.raises(ZeroDivisionError):1/0
# content of test_exception_runtimeerror.py
import pytestdef test_recursion_depth():with pytest.raises(RuntimeError) as excinfo:def f():f()f()assert "maximum recursion" in str(excinfo.value)
# content of test_exception_valueerror.py
import pytestdef myfunc():raise ValueError("Exception 123 raised")def test_match():with pytest.raises(ValueError, match=r".* 123 .*"):myfunc()
# content of test_exception_indexerror.py
import pytestdef f():a = []a[1]=2@pytest.mark.xfail(raises=IndexError)
def test_f():f()

解读与实操

  • 使用pytest.raises作为断言的上下文管理器

在这里插入图片描述

  • 访问实际的断言内容

在这里插入图片描述

  • 通过正则表达式匹配异常的字符串

在这里插入图片描述

  • 通过xfail指定异常参数

在这里插入图片描述

场景应用

使用pytest.raises()在测试自己的代码有意引发的异常的情况下会更好;带有检查函数的@pytest.mark.xfail更适合记录未修复的Bug或依赖项中的Bug。