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

标签 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

避免来自此类第三方库的警告而不是我自己的项目代码警告的最佳方法是什么?

最佳答案

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

  • 使用命令行参数

要完全隐藏警告,请使用

pytest . -W ignore::DeprecationWarning

此命令将隐藏警告摘要,但会显示1 个已通过,1 个警告消息

pytest . --disable-warnings
  • 使用以下内容创建pytest.ini
[pytest]
filterwarnings =
    ignore::DeprecationWarning

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

ignore:.*U.*mode is deprecated:DeprecationWarning

来自文档:

This will ignore all warnings of type DeprecationWarning where the start of the message matches the regular expression .*U.*mode is deprecated.

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

  • 使用PYTHONWARNINGS环境变量

PYTHONWARNINGS="ignore::DeprecationWarning" pytest .

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

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

关于python - 如何在运行单元测试时摆脱第三方库警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60853213/

相关文章:

python - Pytest:模拟具有不同 side_effect 的相同方法的多次调用

python - 在 XML 节点中设置自增属性

python - Django 在关系模型属性的特定值上注释查询集

python - 应用程序应如何向现有拨款添加/删除范围?

ruby-on-rails - 如何使用 RSpec 测试 `rand()`?

unit-testing - 如何在 Golang 测试文件中构建导入

python - 使用嵌套分隔符号拆分 Python 字符串

javascript - react-addon-test-utils createElement 问题

python-3.x - 在 Pytest fixture 中使用时,Python 日志记录不会记录

python - 使用多个接受参数的 fixture 进行参数化测试