Pytest官方教程-10-捕获警告信息

目录:

  1. 安装及入门
  2. 使用和调用方法
  3. 原有TestSuite使用方法
  4. 断言的编写和报告
  5. Pytest fixtures:清晰 模块化 易扩展
  6. 使用Marks标记测试用例
  7. Monkeypatching/对模块和环境进行Mock
  8. 使用tmp目录和文件
  9. 捕获stdout及stderr输出
  10. 捕获警告信息
  11. 模块及测试文件中集成doctest测试
  12. skip及xfail: 处理不能成功的测试用例
  13. Fixture方法及测试用例的参数化
  14. 缓存: 使用跨执行状态
  15. unittest.TestCase支持
  16. 运行Nose用例
  17. 经典xUnit风格的setup/teardown
  18. 安装和使用插件
  19. 插件编写
  20. 编写钩子(hook)方法
  21. 运行日志
  22. API参考
    1. 方法(Functions)
    2. 标记(Marks)
    3. 钩子(Hooks)
    4. 装置(Fixtures)
    5. 对象(Objects)
    6. 特殊变量(Special Variables)
    7. 环境变量(Environment Variables)
    8. 配置选项(Configuration Options)
  23. 优质集成实践
  24. 片状测试
  25. Pytest导入机制及sys.path/PYTHONPATH
  26. 配置选项
  27. 示例及自定义技巧
  28. Bash自动补全设置

捕获警告信息

3.1版中的新功能。

从版本开始3.1,pytest现在会在测试执行期间自动捕获警告并在会话结束时显示它们:

# content of test_show_warnings.py
import warnings

def api_v1():
    warnings.warn(UserWarning("api v1, should use functions from v2"))
    return 1

def test_one():
    assert api_v1() == 1

运行pytest现在产生这个输出:

$ pytest test_show_warnings.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-4.x.y, py-1.x.y, pluggy-0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR
collected 1 item

test_show_warnings.py .                                              [100%]

============================= warnings summary =============================
test_show_warnings.py::test_one
  $REGENDOC_TMPDIR/test_show_warnings.py:5: UserWarning: api v1, should use functions from v2
    warnings.warn(UserWarning("api v1, should use functions from v2"))

-- Docs: https://docs.pytest.org/en/latest/warnings.html
=================== 1 passed, 1 warnings in 0.12 seconds ===================

-W可以传递该标志以控制将显示哪些警告,甚至将其转换为错误:

$ pytest -q test_show_warnings.py -W error::UserWarning
F                                                                    [100%]
================================= FAILURES =================================
_________________________________ test_one _________________________________

 def test_one():
>       assert api_v1() == 1

test_show_warnings.py:10:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

 def api_v1():
>       warnings.warn(UserWarning("api v1, should use functions from v2"))
E       UserWarning: api v1, should use functions from v2

test_show_warnings.py:5: UserWarning
1 failed in 0.12 seconds

可以pytest.ini使用filterwarningsini选项在文件中设置相同的选项。例如,以下配置将忽略所有用户警告,但会将所有其他警告转换为错误。

[pytest]
filterwarnings =
 error
 ignore::UserWarning

当警告与列表中的多个选项匹配时,将执行最后一个匹配选项的操作。

这两个-W命令行选项和filterwarningsINI选项是基于Python的 -W选项warnings.simplefilter,所以请参考这些部分Python文档的其他例子和高级的用法英寸

@pytest.mark.filterwarnings

版本3.2中的新功能。

您可以使用@pytest.mark.filterwarnings向特定测试项添加警告过滤器,以便更好地控制应在测试,类甚至模块级别捕获哪些警告:

import warnings

def api_v1():
    warnings.warn(UserWarning("api v1, should use functions from v2"))
    return 1

@pytest.mark.filterwarnings("ignore:api v1")
def test_one():
    assert api_v1() == 1

使用标记应用的过滤器优先于在命令行上传递或由filterwarningsini选项配置的过滤器。

您可以通过使用filterwarnings标记作为类装饰器或通过设置pytestmark变量将模块中的所有测试应用于类的所有测试:

# turns all warnings into errors for this module
pytestmark = pytest.mark.filterwarnings("error")

积分转到Florian Schulze获取 pytest-warnings 插件中的参考实现

禁用警告摘要

虽然不推荐,但您可以使用--disable-warnings命令行选项从测试运行输出中完全禁止警告摘要。

完全禁用警告捕获

此插件默认启用,但可以在您的pytest.ini文件中完全禁用:

[pytest]
addopts = -p no:warnings

或者传入命令行。如果测试套件使用外部系统处理警告,这可能很有用。-p no:warnings

弃用警告和待命记录警告

版本3.8中的新功能。

在3.9版中更改。

默认情况下,pytest将显示DeprecationWarningPendingDeprecationWarning从用户代码和第三方库警告,建议PEP-0565。这有助于用户保持代码现代化,并在有效删除已弃用的警告时避免破坏。

有时隐藏在您无法控制的代码(例如第三方库)中发生的某些特定弃用警告很有用,在这种情况下,您可以使用警告过滤器选项(ini或标记)来忽略这些警告。

例如:

[pytest]
filterwarnings =
 ignore:.*U.*mode is deprecated:DeprecationWarning

这将忽略DeprecationWarning消息开头与正则表达式匹配的所有类型的警告。".*U.*mode isdeprecated"

注意

如果在解释器级别配置警告,使用PYTHONWARNINGS环境变量或 -W命令行选项,pytest将默认不配置任何过滤器。

此外,pytest不遵循PEP-0506重置所有警告过滤器的建议,因为它可能会破坏通过调用自行配置警告过滤器的测试套件warnings.simplefilter(请参阅问题#2430 以获取该示例)。

确保代码触发弃用警告

您还可以调用全局帮助程序来检查某个函数调用是否触发a DeprecationWarningPendingDeprecationWarning

import pytest

def test_global():
    pytest.deprecated_call(myfunction, 17)

默认情况下,DeprecationWarningPendingDeprecationWarning不会被使用时,捕捉pytest.warnsrecwarn因为默认的Python警告过滤器隐藏起来。如果您希望在自己的代码中记录它们,请使用以下命令warnings.simplefilter('always')

import warnings
import pytest

def test_deprecation(recwarn):
    warnings.simplefilter("always")
    warnings.warn("deprecated", DeprecationWarning)
    assert len(recwarn) == 1
    assert recwarn.pop(DeprecationWarning)

您还可以将其用作上下文管理器:

def test_global():
    with pytest.deprecated_call():
        myobject.deprecated_method()

用警告功能断言警告

版本2.8中的新功能。

您可以检查代码是否引发了特定警告pytest.warns,其工作方式类似于引发

import warnings
import pytest

def test_warning():
    with pytest.warns(UserWarning):
        warnings.warn("my warning", UserWarning)

如果未提出相关警告,测试将失败。match断言异常与文本或正则表达式匹配的关键字参数:

>>> with warns(UserWarning, match='must be 0 or None'):
...     warnings.warn("value must be 0 or None", UserWarning)

>>> with warns(UserWarning, match=r'must be \d+/pre>):
...     warnings.warn("value must be 42", UserWarning)

>>> with warns(UserWarning, match=r'must be \d+/pre>):
...     warnings.warn("this is not here", UserWarning)
Traceback (most recent call last):
  ...
Failed: DID NOT WARN. No warnings of type ...UserWarning... was emitted...

您还可以调用pytest.warns函数或代码字符串:

pytest.warns(expected_warning, func, *args, **kwargs)
pytest.warns(expected_warning, "func(*args, **kwargs)")

该函数还返回所有引发警告(作为warnings.WarningMessage对象)的列表 ,您可以查询其他信息:

with pytest.warns(RuntimeWarning) as record:
    warnings.warn("another warning", RuntimeWarning)

# check that only one warning was raised
assert len(record) == 1
# check that the message matches
assert record[0].message.args[0] == "another warning"

或者,您可以使用recwarn夹具详细检查凸起的警告 (见下文)。

注意

DeprecationWarning并且PendingDeprecationWarning区别对待; 请参阅确保代码触发弃用警告

录制警告

您可以使用夹具pytest.warns或使用recwarn夹具记录凸起的警告。

要在pytest.warns不声明任何有关警告的情况下进行记录,请传递None为预期的警告类型:

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"

recwarn夹具将记录整个函数的警告:

import warnings

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

双方recwarnpytest.warns返回相同的接口,用于记录警告:一个WarningsRecorder实例。要查看记录的警告,您可以迭代此实例,调用len它以获取已记录警告的数量,或将其编入索引以获取特定记录的警告。

完整的API : WarningsRecorder.

自定义失败消息

记录警告提供了在未发出警告或满足其他条件时生成自定义测试失败消息的机会。

def test():
    with pytest.warns(Warning) as record:
        f()
        if not record:
            pytest.fail("Expected a warning!")

如果在呼叫时没有发出警告f,那么将评估为。然后,您可以使用自定义错误消息进行调用。notrecord``True``pytest.fail

内部pytest警告

版本3.8中的新功能。

pytest可能会在某些情况下生成自己的警告,例如使用不当或不推荐使用的功能。

例如,如果遇到匹配python_classes但也定义__init__构造函数的类,pytest将发出警告,因为这会阻止实例化类:

# content of test_pytest_warnings.py
class Test:
    def __init__(self):
        pass

    def test_foo(self):
        assert 1 == 1
$ pytest test_pytest_warnings.py -q

============================= warnings summary =============================
test_pytest_warnings.py:1
  $REGENDOC_TMPDIR/test_pytest_warnings.py:1: PytestWarning: cannot collect test class 'Test' because it has a __init__ constructor
    class Test:

-- Docs: https://docs.pytest.org/en/latest/warnings.html
1 warnings in 0.12 seconds

可以使用用于过滤其他类型警告的相同内置机制来过滤这些警告。

请阅读我们的向后兼容性政策,了解我们如何继续弃用并最终删除功能。

pytest使用以下警告类型,它们是公共API的一部分:

classPytestWarning
基类:UserWarning pytest发出的所有警告的基类。

classPytestDeprecationWarning
基类:pytest.PytestWarning 将来版本中将删除的功能的警告类。

classRemovedInPytest4Warning
基类:pytest.PytestDeprecationWarning 计划在pytest 4.0中删除的功能的警告类。

classPytestExperimentalApiWarning
基类:pytest.PytestWarning 警告类别用于表示pytest中的实验。谨慎使用,因为API可能会在未来版本中更改甚至完全删除

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容