Pytest 如何断言代码抛出了指定异常?
用 pytest.raises 上下文管理器:with pytest.raises(ValueError): 调用代码。可配合 match 参数校验异常消息文本。本文给出完整示例与进阶用法。
用 pytest.raises 上下文:with pytest.raises(ValueError): 包裹被测代码——块内抛出该异常则测试通过,没抛或抛错类型则失败。
基本用法
import pytest
def divide(a, b):
if b == 0:
raise ValueError("除数不能为零")
return a / b
def test_divide_by_zero():
with pytest.raises(ValueError):
divide(10, 0)
校验异常消息
def test_error_message():
with pytest.raises(ValueError, match="除数不能为零"):
divide(10, 0)
match 是正则匹配(re.search 语义),部分匹配即可。
获取异常对象进一步断言
def test_exception_detail():
with pytest.raises(ValueError) as exc_info:
divide(10, 0)
assert "零" in str(exc_info.value)
断言多个异常类型之一
with pytest.raises((ValueError, TypeError)):
risky()
常见问题(FAQ)
Q:with 块里异常之后的代码还会执行吗? 不会——被测调用要放块内最后一行。
Q:想断言"不抛异常"怎么写? 直接调用即可,不抛就通过;无需特殊语法。