当前位置: 首页 > news >正文

11、pytest断言预期异常

官方用例

# content of test_exception_zero.py
import pytestdef test_zero_division():with pytest.raises(ZeroDivisionError):1/0
# content of test_exception_runtimeerror.py
import pytestdef 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 pytestdef myfunc():raise ValueError("Exception 123 raised")def test_match():with pytest.raises(ValueError, match=r".* 123 .*"):myfunc()
# content of test_exception_indexerror.py
import pytestdef f():a = []a[1]=2@pytest.mark.xfail(raises=IndexError)
def test_f():f()

解读与实操

  • 使用pytest.raises作为断言的上下文管理器

在这里插入图片描述

  • 访问实际的断言内容

在这里插入图片描述

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

在这里插入图片描述

  • 通过xfail指定异常参数

在这里插入图片描述

场景应用

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

http://www.lryc.cn/news/257024.html

相关文章:

  • Vue之数据绑定
  • druid在没有web的项目中如何查看监控
  • 游戏被攻击该怎么办?游戏盾该如何使用,游戏盾如何防护攻击
  • 【基于openGauss5.0.0简单使用DBMind】
  • [递归回溯]连接卡片最短路径
  • 初识人工智能,一文读懂强化学习的知识文集(5)
  • 视频封面提取:精准截图,如何从指定时长中提取某一帧图片
  • Shopify 开源 WebAssembly 工具链 Ruvy
  • zxjy008- 项目集成Swagger
  • 使用linux CentOS本地部署SQL Server数据库
  • 理解基于 Hadoop 生态的大数据技术架构
  • 【Go】Go语言基础内容
  • HP-UNIX 系统安全基线 安全加固操作
  • 第九天:信息打点-CDN绕过篇amp;漏洞回链amp;接口探针amp;全网扫描amp;反向邮件
  • 【利用二手车数据进行可视化分析】
  • 快速测试 3节点的redis sentinel集群宕机2个节点以后是否仍能正常使用
  • echarts词云图echarts-wordcloud使用方法
  • 二叉树的OJ练习(二)
  • uni-app 微信小程序之自定义navigationBar顶部导航栏
  • 前端入门:HTML初级指南,网页的简单实现!
  • 低多边形3D建模石头材质纹理贴图
  • 【华为OD题库-081】最长的元音子串长度-Java
  • 第9节:Vue3 指令
  • B028-JDBC基础
  • ngixn 准备
  • 生活小记录
  • Diary22-全网最全的CSS3.0讲解
  • LAMP和分离式LNMP部署
  • 基于Java房屋租赁管理系统
  • windows安装protoc、protoc-gen-go、protoc-gen-go-grpc