How to Test Printed Output in Python with Pytest and its Capsys Fixture
The aim of this page📝 is to investigate methods for successfully testing a print statement output in pytest.
2 min readMay 24, 2023
NOTE FOR VSCODE CODERS: Passing a capsys
fixture into a test signature will cause you to not be able to see any print(“foo”)
output to the debug console. Don’t be surprised :)
Testing a simple statement is simple: use capsys fixture and readouterr().out
To test the last out of multiple printed commands, split the captured string and select via the expected position
- the function
test_my_function
takes one argument,capsys
, which is a built-in pytest fixture that captures the output tostdout
andstderr
. - inside the function, we call
my_function()
, which presumably prints multiple outputs. - use the
readouterr()
method of thecapsys
fixture to capture the outputs. - this method returns a named tuple with two attributes:
out
anderr
, which contain the captured output tostdout
andstderr
, respectively. - split the captured output by newline characters to get a list of all individual outputs.
- get the last output by indexing the list with
-1
. - 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 in
operator
- the following also uses a
monkeypatch
fixture for simulating three inputs that the script takes - the script is a command composer of a Hashicorp Vault wrapper setting a secret
LINKS
https://cloudoverflow.com/a/56300627/11082684 How to capture stdout/stderr output — pytest documentation