似乎
warnings.filterwarnings
不尊重使用pytest
忽略警告。例如:
$ cat test.py
import warnings
warnings.filterwarnings('ignore', category=UserWarning)
def test_warnings_filter():
warnings.warn("This is a warning", category=UserWarning)
当我运行此命令时,我预计我明确忽略的警告将被
pytest
忽略。相反,我得到了这个:
$ pytest test.py
=============================================================================== test session starts ===============================================================================
platform darwin -- Python 3.10.8, pytest-7.2.1, pluggy-1.0.0
rootdir: /Users/aldcroft/tmp/pytest
plugins: anyio-3.6.2
collected 1 item
test.py . [100%]
================================================================================ warnings summary =================================================================================
test.py::test_warnings_filter
/Users/aldcroft/tmp/pytest/test.py:7: UserWarning: This is a warning
warnings.warn("This is a warning", category=UserWarning)
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
========================================================================== 1 passed, 1 warning in 0.01s ===========================================================================
我知道
pytest.ini
配置文件和 -W
标志和 @pytest.mark.filterwarnings
,但这些效果不佳
对于我通过 <pkg_name>.test()
集成测试大量已安装软件包的用例,其中有
至少有十几个第三方警告需要被忽略以获得干净的输出。
关于如何实现这项工作有什么想法吗?
您可以使用@pytest.mark.filterwarnings注释来忽略来自特定测试函数或整个测试类的警告。
import warnings
import pytest
@pytest.mark.filterwarnings("ignore:warning")
def test_warnings_filter():
warnings.warn("This is a warning", category=UserWarning)
https://docs.pytest.org/en/7.1.x/how-to/capture-warnings.html#pytest-mark-filterwarnings
这可能是由于 pytest 用于捕获警告的内置插件:
从版本 3.1 开始,pytest 现在会在测试执行期间自动捕获警告并在会话结束时显示它们
将 in-python
warnings.filterwarnings()
视为 application 警告配置,pytest 将“忽略”该配置,以便可以独立进行 test 警告配置并考虑到测试隔离。
您提到了
@pytest.mark.filterwarnings
,但 pytest 也有顶级 filterwarnings
配置,例如在我的pyproject.toml
:
[tool.pytest.ini_options]
filterwarnings = [
"ignore:::flask_appbuilder",
"ignore:::flask_sqlalchemy",
"ignore:::marshmallow_sqlalchemy",
"ignore:::pydantic",
]
我忽略了来自每个第三方模块的所有警告。警告过滤器规范和机制来自 Python 核心:https://docs.python.org/3/library/warnings.html#describing-warning-filters
pytest --disable-warnings
——禁用所有警告,即使是在你的代码中
pytest -p no:warnings
-- 完全禁用 pytest 的警告插件,使您的测试警告配置与应用程序警告配置相同。如果您只想消除第三方警告并且永远不会发出您自己的警告,那么这可能没问题。但是,如果您正在编写库并想要警告用户(因为您想要测试该行为),您可能需要使用警告插件。