Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fieldse/e22820e52f85d74e6ea6ac94852e34c5 to your computer and use it in GitHub Desktop.
Save fieldse/e22820e52f85d74e6ea6ac94852e34c5 to your computer and use it in GitHub Desktop.
Python pytest + stdout: Capture messages sent to stdout / stderr from your functions with pytest capsys
# test.py
# Print statements to pytest
# Capture messages sent to stdout / stderr from your functions,
# and test the output with a pytest unit test.
# tl;dr - use the capsys parameter in your test arguments
# extract the messages sent to stdout/stderr with capsys.readouterr()
import sys
import pytest
message = 'The meaning of life is not actually 42\n'
def print_greeting():
"""print 42 to stdout"""
print(message)
# write to stdout
def message_to_stdout():
"""print message directly to stdout"""
# print to stdout
sys.stdout.write(message)
def message_to_stderr():
"""print error message to stderr"""
# print error message to stderr
sys.stderr.write('An error has happened!')
def return_greeting():
""" return 42 """
return message
class TestClass():
def setup_method(self, function):
""" Setup before each function """
print('\n\n[+] Test: "{}"'.format( function.__name__))
print(' ' + function.__doc__ )
def test_messagetostdout(self, capsys):
"""assert '42' was printed to stdout"""
# Run my function
message_to_stdout()
# catch what was set to stdout, stderr
out, err = capsys.readouterr()
assert '42' in out
def test_messagetosterr(self, capsys):
"""assert 'error' was printed to stderr"""
# Run my function
message_to_stderr()
# catch what was set to stdout, stderr
out, err = capsys.readouterr()
assert 'error' in err
def test_printgreeting(self, capsys):
"""assert '42' was printed to console"""
# capture stdout / stderr
# Run my function
print_greeting()
out, err = capsys.readouterr()
# 42 not in stdout from sys.stdout.write
assert '42' in out
def test_returngreeting(self):
"""assert '42' returned from function"""
# Run my function
greeting = return_greeting()
# 42 is in returned from function
assert '42' in greeting
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment