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.

Pavol Kutaj
2 min readMay 24, 2023

NOTE FOR VSCODE CODERS: Passing a capsysfixture 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 :)

where is my output ??? captured by pytest capsys fixture :)

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 to stdout and stderr.
  • inside the function, we call my_function(), which presumably prints multiple outputs.
  • use the readouterr() method of the capsys fixture to capture the outputs.
  • this method returns a named tuple with two attributes: out and err, which contain the captured output to stdout and stderr, 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

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com