首页/开发/软件测试速查/pytest 异常断言
自动化测试66 条

pytest 异常断言

pytest.raises 上下文断言异常类型,match 参数用正则匹配消息;也可通过 excinfo 取异常对象继续检查属性,覆盖异常分支的验证。

软件测试速查开发更新于 2026-10-12

异常断言

异常断言
import pytest


def test_divide():
    with pytest.raises(ZeroDivisionError, match="division by zero"):
        1 / 0


def test_value():
    with pytest.raises(ValueError) as excinfo:
        int("abc")
    assert "invalid literal" in str(excinfo.value)
只断言「抛了异常」时建议同时校验消息或错误码,避免其他异常被误判通过。

易错点

  • 捕获宽泛的 Exception,其他异常也被算作通过
  • match 按正则解析,消息里的括号、点号等特殊字符需要转义

数据来源与参考

  • pytest 官方文档:Assertions about expected exceptions
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌