Pytest capture STDOUT and STDERR with capsys
The capsys fixture captures everything that is printed to STDOUT and STDERR so we can compare that to the expected output and error.
- We need to include
capsysas the parameter of the test function. - The first call to
readouterrwill return whatever was printed to STDOUT and STDERR respectively from the start of the test function. - The subsequent calls to
readouterrwill return the output that was generated since the previous call toreadouterr.
from greet import welcome
def test_myoutput(capsys):
welcome("hello", "world")
out, err = capsys.readouterr()
assert out == "STDOUT: hello\n"
assert err == "STDERR: world\n"
welcome("next")
out, err = capsys.readouterr()
assert out == "STDOUT: next\n"
assert err == ""
pytest test_greet.py
Note, however, using -s won’t print anything extra in this case as the ourput was captured by capsys.
pytest -s test_greet.py