pytest 将所有输出捕获到标准输出

pytest capturing all output to stdout

我测试了这样打印的'current line'

def test_clear(capsys):
    out = capsys.readouterr()
    outputs_more_than_one_line()
    assert out.out == 'last line printed'
    # impossible to check previously printed lines?

但是,我想检查打印的所有内容。我考虑过 monkeypatching builtins.print,但这似乎并不可靠(没有捕获 sys.write.stdout)。无论如何这可能吗?

doc 说:

The readouterr() call snapshots the output so far - and capturing will be continued.

因此您应该在打印行之后调用 readouterr,而不是在:

之前
def test_cap(capsys):
    for _ in range(2):
        print('outputs_more_than_one_line')
    out = capsys.readouterr()
    assert out.out != 'last line printed'