官方用例
# content of test_exception_zero.py
import pytest
def test_zero_division():
    with pytest.raises(ZeroDivisionError):
        1/0
# content of test_exception_runtimeerror.py
import pytest
def 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 pytest
def myfunc():
    raise ValueError("Exception 123 raised")
    
def test_match():
    with pytest.raises(ValueError, match=r".* 123 .*"):
        myfunc()
# content of test_exception_indexerror.py
import pytest
def f():
    a = []
    a[1]=2
@pytest.mark.xfail(raises=IndexError)
def test_f():
    f()
解读与实操
- 使用pytest.raises作为断言的上下文管理器

- 访问实际的断言内容

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

- 通过xfail指定异常参数

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



















