11、pytest断言预期异常

官方用例

# 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作为断言的上下文管理器

11、pytest断言预期异常_第1张图片

  • 访问实际的断言内容

在这里插入图片描述

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

11、pytest断言预期异常_第2张图片

  • 通过xfail指定异常参数

在这里插入图片描述

场景应用

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

你可能感兴趣的:(pytest入门30讲,pytest)