pytest 测试框架学习(14):pytest.warns

时间:2022-07-24
本文章向大家介绍pytest 测试框架学习(14):pytest.warns,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

pytest.warns

含义

warns: 使用 pytest.warns 可以检查代码是否发出特定的警告信息,使用方法与 raises 类似。 源码:

使用

  1. 简单使用
import warnings
import pytest

def test_warning():
    with pytest.warns(UserWarning):
        warnings.warn("my warning", UserWarning)
  1. 匹配正则表达式
# 1、 完全匹配
def test_match():
    with pytest.warns(UserWarning, match='must be 0 or None'):
        warnings.warn("value must be 0 or None", UserWarning)
# 2、部分匹配
def test_match():
    with pytest.warns(UserWarning, match=r'must be d+$'):
        warnings.warn("value must be 44", UserWarning)
# 3、不匹配
def test_match():
	with pytest.warns(UserWarning, match=r'must be d+$'):
        warnings.warn("this is not here", UserWarning)

# 不匹配时,执行测试就会失败。
# Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...
  1. 参数可以传入函数和参数
def sub(a, b):
    if a < b:
        warnings.warn("a must greater b", UserWarning)
    return a - b

# 1、调用函数
def test_sub1():
    pytest.warns(UserWarning, sub, 1, 2)

# 2、字符串传入函数,官网上这样写,但是我尝试是失败的,提示类型错误。
def test_sub2():
    pytest.warns(UserWarning, "sub(a=1, b=2)")
  1. 可以获取返回的警告
def test_sub3():
    with pytest.warns(UserWarning) as record:
        sub(1, 2)
        
    # check that only one warning was raised
    assert len(record) == 1
    # check that the message matches
    assert record[0].message.args[0] == "a must greater b"
  1. pytest.warns 不做断言,使用None进行标记,后可使用 assert 对 record 进行断言处理
with pytest.warns(None) as record:
    warnings.warn("user", UserWarning)
    warnings.warn("runtime", RuntimeWarning)

assert len(record) == 2
assert str(record[0].message) == "user"
assert str(record[1].message) == "runtime"
  1. 使用 recwarn 配置
import warnings

# 解析
# 使用 recwarn 会自动记录现在已有的 warning 类型。我们可以对其进行遍历,也可以获取特定的 warning 类型里的内容进行断言。

# 遍历
def test_recwarn(recwarn):
     warnings.warn("hello", UserWarning)
    warnings.warn("hello", BytesWarning)
    warnings.warn("hello", SyntaxWarning)
    print(len(recwarn))
    for r in recwarn:
        print(r)
        assert str(r.message) == "hello"
# 遍历时我们可以看到每条 recwarn 记录中的数据内容,包括:
# {message: UserWarning('hello'), category: 'UserWarning', filename: 'path\warns.py', lineno: 48, line: None}
# 我们需要断言什么时,就可以对应去获取这些值。

# 获取特定的类型记录 进行断言
def test_hello(recwarn):
    warnings.warn("hello", UserWarning)
    assert len(recwarn) == 1
    w = recwarn.pop(UserWarning)
    assert issubclass(w.category, UserWarning)
    assert str(w.message) == "hello"
    assert w.filename
    assert w.lineno

说明:本篇参考官网并加入自己些许理解翻译而来,觉得有用,可以点赞和赞赏哦(^ v ^),谢谢支持;如果有不足地方,可留言评论。后续将继续更新。