更改一次测试的 pytest 捕获

Change pytest capturing for one test

是否可以仅针对一个测试更改 pytest 中的捕获行为——即在测试脚本中?

我有一堆测试与往常一样与 pytest. There are several useful quantities that I like to print during some tests, so I use the -s flag to show them in the pytest output. But I also test for warnings, which also get printed, and look ugly and distracting. I've tried using the warnings.simplefilter 一起使用,只是为了不显示警告,但这似乎没有任何作用。 (也许 pytest 破解它???)无论如何,我想要一些方法来消除警告,但仍然检查它们是否被引发,同时还能够看到从我的其他打印语句中捕获的输出。有没有什么办法可以做到这一点——例如,只更改一个测试函数的捕获?

我已经通过手动重定向完成了 stderr:

import os
import sys
import warnings
import pytest

def test():
    stderr = sys.stderr
    sys.stderr = open(os.devnull, 'w')
    with pytest.warns(UserWarning):
        warnings.warn("Warning!", UserWarning)
    sys.stderr = stderr

如果不需要其他打印语句,我可以类似地将 stdout 重定向到 devnull。

使用 pytest 3.x 有一个 easy way 可以暂时禁用捕获(请参阅有关 capsys.disabled().

的部分

还有 pytest-warnings 插件,它在专门的报告部分显示警告。