如何抑制 py.test 内部弃用警告

How to suppress py.test internal deprecation warnings

有没有办法抑制 pytest 的内部弃用警告?

上下文:我正在评估将测试套件从 nose 移植到 pytest 的难度。该套件相当大,并且大量使用基于 nose 风格 yield 的测试生成器。

我想首先确保 现有 测试通过 pytest,然后可能将测试生成器更改为 parameterized.

只是运行 $ pytest path-to-test-folder用pytest 3.0.4完全被

的页面和页面所支配
WC1 ~repos/numpy/numpy/lib/tests/test_twodim_base.py yield tests are deprecated, and scheduled to be removed in pytest 4.0

有没有办法关闭这些警告?

来自pytest --help

--disable-pytest-warnings
                      disable warnings summary, overrides -r w flag

pytest -p no:warnings,或将以下内容添加到您的 pytest.ini 或 tox.ini:

[pytest]
addopts = -p no:warnings

结果将是绿色的,没有任何警告指示。请参阅 https://docs.pytest.org/en/latest/warnings.html#disabling-warnings-summary 处的文档。

对于需要干净输出的测试套件,这可能是一个有效的用例。

请注意,始终隐藏所有警告可能会导致您错过重要警告。 .

我认为您不想隐藏所有警告,而只是隐藏不相关的警告。在这种情况下,来自导入 python 模块的弃用警告。

正在阅读有关 Warnings Capture 的 pytest 文档:

Both -W command-line option and filterwarnings ini option are based on Python’s own -W option and warnings.simplefilter, so please refer to those sections in the Python documentation for other examples and advanced usage.

因此您可以使用 python 的 -W 选项过滤警告!

似乎 pytest 完全删除了过滤器,因为它在 运行ning 时显示了所有那些 DeprecationWarning,以及 Python 关于 Default Warning Filters 的文档清楚地说:

In regular release builds, the default warning filter has the following entries (in order of precedence):

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning

所以在你的情况下,如果你想过滤你想忽略的警告类型,比如那些 DeprecationWarning,只需 运行 带有 -W 选项的 pytest 命令:

$ pytest path-to-test-folder -W ignore::DeprecationWarning

编辑:根据colini的评论,可以按模块过滤。忽略来自所有 sqlalchemy 的弃用警告的示例:

ignore::DeprecationWarning:sqlalchemy.*:

然后您可以列出在 pytest

的输出中产生过多噪音的已安装模块

与文件一起使用而不是在命令行中使用:

您可能更喜欢在 pytest.ini 文件中列出这些过滤器:

[pytest]
filterwarnings =
    ignore::DeprecationWarning

我不想隐藏所有警告,所以我把它放在 pytest.ini

[pytest]
filterwarnings =
    ignore::DeprecationWarning

在 pytest.ini 文件中您可以添加:

[pytest]
addopts = -p no:warnings

OR 在命令行中传递以下行。如果您的测试套件使用外部系统处理警告,这可能会有用。

-p no:warnings

OR 如果您只想隐藏一些特定的弃用警告,请在 pytest.ini 文件

中添加以下语句
[pytest]
filterwarnings =
    ignore:.*U.*mode is deprecated:DeprecationWarning

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

或虽然不推荐,但您可以使用

--disable-warnings

命令行选项可完全抑制测试 运行 输出中的警告摘要。

这里有一个 说明如何在您使用 pyproject.toml 文件作为配置时抑制警告。

[tool.pytest.ini_options]
testpaths = ["./tests/unit"]
filterwarnings = ["ignore:::.*third_party_package.module:123", "ignore:::.*another_module*"]

123 在这种情况下是要抑制的行号

如果您使用 setup.cfg 文件,请将其放入:

[tool:pytest]
addopts = -p no:warnings

你需要 tool:pytest 而不仅仅是 pytest,但它会告诉你:

Failed: [pytest] section in setup.cfg files is no longer supported, change to [tool:pytest] instead.