@pytest.mark.filterwarnings 如何工作?

Lon*_*Rob 7 python pytest

根据文档,您可以忽略这样的警告:

@pytest.mark.filterwarnings("ignore:api v1")
def test_foo():
Run Code Online (Sandbox Code Playgroud)

这使:

但是似乎没有关于这种迷你语言的任何文档(它甚至迷你语言吗?)

比赛是如何进行的?

我问这个是因为以下测试不会忽略DeprecationWarning通过导入引发的boto3

@pytest.mark.filterwarnings("ignore:DeprecationWarning")
def test_ignore_warnings():
    import boto3
Run Code Online (Sandbox Code Playgroud)

pytest 输出:

============================================================================================================================== warnings summary ===============================================================================================================================
/home/rob/dev/time-series/.venv/lib/python3.7/site-packages/botocore/awsrequest.py:624
  /home/rob/dev/time-series/.venv/lib/python3.7/site-packages/botocore/awsrequest.py:624: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
    class HeadersDict(collections.MutableMapping):

-- Docs: https://docs.pytest.org/en/latest/warnings.html
==================================================================================================================== 1 passed, 1 warnings in 0.36 seconds =====================================================================================================================
Run Code Online (Sandbox Code Playgroud)

tmt*_*tmt 7

过滤器的工作方式与将-W参数与python命令一起使用时的工作方式相同(请参阅 参考资料python --help)。该格式在warnings模块的文档中进行了描述。总之这action:message:category:module:line其中action可能是强制性的,但也可以省略其他部分。

"ignore:api v1"将尝试message通过定义“包含警告消息开头必须匹配的正则表达式的字符串”来匹配。由于您实际上想要匹配category,因此可以跳过message. 这意味着您似乎只是缺少一个冒号,ignore所以这是正确的格式:

@pytest.mark.filterwarnings("ignore::DeprecationWarning")
def test_ignore_warnings():
    import boto3
Run Code Online (Sandbox Code Playgroud)

但是,如果它发生在测试函数之外的包的导入期间您显然仍然会收到警告。在这种情况下,您可能需要将过滤器全局指定为 pytest 的参数:

pytest -W "ignore::DeprecationWarning" ./tests/

...或将其添加到pytest.ini

[pytest]
filterwarnings =
    ignore::DeprecationWarning
Run Code Online (Sandbox Code Playgroud)

如果不希望这样的全局排除,您可以尝试将其限制为特定模块:

ignore::DeprecationWarning:boto3

测试

出于测试目的,您可以使用以下代码:

[pytest]
filterwarnings =
    ignore::DeprecationWarning
Run Code Online (Sandbox Code Playgroud)

  • 这根本不是标准@CecilCurry。AFAIK,没有大的 python 包在做这个。仍然是一个有趣的想法。 (4认同)
  • @LondonRob:出于这个原因和类似的原因,在测试中导入某些内容是**您应该始终做的事情**。这并没有什么不寻常的。这是标准做法。导入测试“外部”的东西是不寻常的。除“pytest”本身之外的所有导入都应被视为可疑,并仅限于需要这些导入的特定测试。 (2认同)