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

2024-05-23 17:59:25 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法抑制pytest的内部否决警告?

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

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

使用pytest 3.0.4运行$ pytest path-to-test-folder完全由

WC1 ~repos/numpy/numpy/lib/tests/test_twodim_base.py yield tests are deprecated, and scheduled to be removed in pytest 4.0

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


Tags: topathtestnumpy警告套件pytesttests
3条回答

pytest -p no:warnings,或者在pytest.ini或tox.ini中添加以下内容:

[pytest]
addopts = -p no:warnings

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

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

请注意,总是隐藏所有警告可能会导致您错过重要警告。If you want to hide only specific warnings, look at Cloc's answer

我认为你不想隐藏所有的警告,只想隐藏那些不相关的警告。在本例中,来自导入的python模块的deprectation警告。

阅读关于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完全删除了过滤器,因为它在运行时显示了所有那些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 --help

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

相关问题 更多 >