Mattwmaster58
Mattwmaster58

Reputation: 2585

pytest capturing all output to stdout

I test the 'current line' that's printed like this

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

However, I would like to check everything that was printed. I've considered monkeypatching builtins.print, but that doesn't seem robust (doesn't capture sys.write.stdout). Is there anyway this would be possible?

Upvotes: 3

Views: 2390

Answers (1)

georgexsh
georgexsh

Reputation: 16634

The doc says:

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

therefore you should call readouterr after print lines, not before:

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

Upvotes: 4

Related Questions