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

在这里插入图片描述

  • 访问实际的断言内容

在这里插入图片描述

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

在这里插入图片描述

  • 通过xfail指定异常参数

在这里插入图片描述

场景应用

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

相关推荐

  1. 10异常断言

    2023-12-05 19:06:05       28 阅读
  2. pytest断言

    2023-12-05 19:06:05       9 阅读
  3. Python的pytest框架(2)--断言机制

    2023-12-05 19:06:05       14 阅读
  4. pytest中fixture异常处理

    2023-12-05 19:06:05       10 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-05 19:06:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-05 19:06:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-05 19:06:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-05 19:06:05       18 阅读

热门阅读

  1. 数据结构基础(不带头节点的单向非循环链表)

    2023-12-05 19:06:05       36 阅读
  2. 数据结构基础(带头节点的双向循环链表)

    2023-12-05 19:06:05       42 阅读
  3. Python函数(一)

    2023-12-05 19:06:05       42 阅读
  4. JWT 认证机制

    2023-12-05 19:06:05       29 阅读
  5. 【Node.js】笔记整理 1 - 基础知识

    2023-12-05 19:06:05       38 阅读
  6. 学习c#的第二十四天

    2023-12-05 19:06:05       35 阅读
  7. SSH:安全的远程登录和数据传输工具

    2023-12-05 19:06:05       38 阅读