Python 3.4.1, pytest 2.6.2.
When a test fails, pytest
will routinely report what was printed to stdout by the test.
For instance this code:
Asides using "startswith".You can also use the "in" keyword, for example:
assert "Hello" in output
This is great if you have a huge amount of data being passed to stdout, you can use "in" to check for different lines in your stdout.
def test_result_and_stdout(capsys):
result = method_under_test()
out, err = capsys.readouterr()
sys.stdout.write(out)
sys.stderr.write(err)
assert "Hello" in out
assert result == 42
You can also assert what's passed into stderr instead of stdout by using:
assert "What you are expecting" in err
Also note that line:
out, err = capsys.readouterr()
creates a snapshot of the output to both stdout and stderr so far so you can assert what you are expecting for that test.
You're seeing the correct behaviour, when using capsys.readouterr()
you're consuming the captured output. Hence any output to stdout and stderr will no longer show up in the test report. But any new output which you create after this and do not consume will still be reported, so you can get the full output back in the report by simply writing it to the output streams once more:
def test_result_and_stdout(capsys):
result = method_under_test()
out, err = capsys.readouterr()
sys.stdout.write(out)
sys.stderr.write(err)
assert out.startswith("Hello")
assert result == 42
From the documentation the behavior seems correct: only after the test function (test_result_and_stdout
) finishes the output streams will be restored, not after each readouterr
call. I don't think that currently capsys supports also redirecting to the original streams besides capturing them, which seems to be what you want.
I would suggest to create an issue in the official repository and see what people have to say.