Python Friday #45: Show the Print() Output in the Test Summary

While trying to get a better understanding of pytest fixtures, I noticed a little problem: I could not see the output of the print() statements in my code. Let’s look why this happens and how we can change it.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

No output

When I try something new, I like to use the print() function to keep track of what is going on. This simple debugging practice does not resonate well with pytest. I created this little test method with a print() statement as a minimalistic example:

When I run pytest, the test passes (no wonder without an assert statement), but I cannot see the expected output:

the output 'Hello World' is missing

 

What does pytest with the stdout/stderr output?

By default, pytest captures the output to sys.stdout/stderr and redirects it to a temporary file. This is great to get a clean and understandable test summary, but rather bad when you want to debug your code with print() statements.

 

Turn the capturing off when you need the output

To change the default behaviour, we can run pytest with the -s flag and our output is back:

the output 'Hello World' is back

 

Next

Now that this obstacle is removed, I am back on track to learn more about test fixtures. Until I know enough to blog about it, I will look at other interesting parts of pytest.

1 thought on “Python Friday #45: Show the Print() Output in the Test Summary”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.