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.
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
https://cloudoverflow.com/a/56300627/11082684 How to capture stdout/stderr output — pytest documentation