How to Test Printed Output in Python with Pytest and its Capsys Fixture
The aim of this page📝 is to investigate methods for succesfully testing a print statement output in pytest.
NOTE FOR VSCODE CODERS: passing a
capsysfixture into a test signature will cause you won’t be able to see any
print(“foo”)output to debug console. Don’t be surprised :)
Testing a simple statement is simple: use capsys fixture and
To test the last out of multiple printed commands, split captured string and select via expected position
- the function
test_my_functiontakes one argument,
capsys, which is a built-in pytest fixture that captures the output to
- inside the function, we call
my_function(), which presumably prints multiple outputs.
- use the
readouterr()method of the
capsysfixture to capture the outputs.
- this method returns a named tuple with two attributes:
err, which contain the captured output to
- split the captured output by newline characters to get a list of all individual outputs.
- get the last output by indexing the list with
- finally, use an assertion to check if the last output is equal to the expected value.
If I don’t know the exact position of the printed command, I am using the
- the following also uses a
monkeypatchfixture for simulating three inputs that the script takes
- the script is a command composer of a Hashicorp Vault wrapper setting a secret