如何在运行单元测试时摆脱第三方库警告?

Sky*_*ker 2 python unit-testing pytest

我使用 PyScaffold 设置我的项目,并在使用 pytest 运行单元测试时收到以下第三方警告,我想摆脱它,但不知道如何:

==================================== warnings summary ====================================
c:\dev\pyrepo\lib\site-packages\patsy\constraint.py:13
  c:\dev\pyrepo\lib\site-packages\patsy\constraint.py:13: DeprecationWarning: Using or importing
 the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in
 3.9 it will stop working
    from collections import Mapping

-- Docs: https://docs.pytest.org/en/latest/warnings.html
Run Code Online (Sandbox Code Playgroud)

避免像这样的第三方库发出警告而不是我自己的项目代码警告的最佳方法是什么?

hur*_*nko 5

有多种方法可以抑制警告:

  • 使用命令行参数

要完全隐藏警告,请使用

pytest . -W ignore::DeprecationWarning
Run Code Online (Sandbox Code Playgroud)

该命令将隐藏warnings summary但会显示1 passed, 1 warning消息

pytest . --disable-warnings
Run Code Online (Sandbox Code Playgroud)
  • pytest.ini使用以下内容创建
[pytest]
filterwarnings =
    ignore::DeprecationWarning
Run Code Online (Sandbox Code Playgroud)

您还可以使用正则表达式模式:

ignore:.*U.*mode is deprecated:DeprecationWarning
Run Code Online (Sandbox Code Playgroud)

来自文档:

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

  • 标记你的test_函数@pytest.mark.filterwarnings("ignore::DeprecationWarning")

  • 使用PYTHONWARNINGS环境变量

PYTHONWARNINGS="ignore::DeprecationWarning" pytest .

Run Code Online (Sandbox Code Playgroud)

-W它与命令行参数具有相同的语法。更多这里

更多详细信息可以在pytest 文档中找到