Ignore/catch 针对单元测试特定行的警告 - pytest

Ignore/catch a warning for a specific line of a unit test - pytest

我正在尝试编写一个重复调用函数的单元测试,并测试如果使用相同的输入多次 运行 会发生什么情况。该函数的一个副产品是当它为 运行 时会发出一些警告。这导致代码如下:

with pytest.warns(RuntimeWarning, match='depends on the pytest parametrization'):
    output = func(**kwargs)

当我使用 pytest.mark.parametrize 时,这变得非常冗长,现在会导致多个 if pytest.warns(...) 类型代码。

我可以指定只忽略单元测试中特定行发出的所有警告吗?例如。像这样

with pytest.ignore_all_warnings():
    output = func(**kwargs)

其他忽略警告的方法

我知道 can pytest ignore a specific warning? 以及忽略警告的一般方法,但这些方法会跨文件和函数忽略。我只想忽略单元测试特定行中的警告。

Python documentation 中所述,您可以使用 catch_warnings 上下文管理器将警告过滤器中的更改限制为代码块。如果将它与忽略所有警告的非特定过滤器一起使用,则可以在一行中抑制所有警告:

import warnings
...

with warnings.catch_warnings():
    # ignore all warnings
    warnings.filterwarnings('ignore')
    do_stuff()

这不是特定于 pytest,但可以在任何代码中使用。