pytest常用断言

image

如上官网所说,pytest使用python中的assert来比较实际值与预期值,实现断言功能

1 常用的断言方式 assert xxx

assert a == b
assert a!=b
assert a > b
assert a <b
assert a in b
assert a not in b
assert instance(a,int)
assert a >b and a >c 同时断言多个条件
assert a > b or a> c

2 断言异常 pytest.raise(xxx)

如果test代码出现了预期中的异常则断言成功,否则断言失败
image

执行结果
image

b为0 时,py会抛出ZeroDivisionError,b为1 时,情况正常,不会抛出异常。所以
预期会抛出ZeroDivisionError,断言成功
预期会抛出ValueError,实际是抛出ZeroDivisionError或者不抛出异常,断言失败

注意
1 这里没有用我们常见的assert的方式
2 注意with语句后的代码是否执行的问题
image

断言异常并断言异常信息中的文本与预期是否一致

image
执行结果
image

注意
1 assert的缩进位置
2 异常与预期不一致、未发生异常也会导致断言失败
3 异常有3个属性 traceback type value

也可以用正则匹配的方式来判断异常中的文本信息

image

不用with语句方式断言异常

image

断言未抛出指定异常

image

执行结果
image

3断言警告信息pytest_warning()

用法与异常断言一样
warning 的类型参照python的warning部分 https://docs.python.org/3/library/warnings.html
image

posted @   工作手记  阅读(317)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示