TIL: Capture stdout & stderr with pytest
I wish I knew this earlier, but I know it now thanks to Cody Antunez. Here it is:
import sys def test_myoutput(capsys): # or use "capfd" for fd-level # Write some text print("hello") sys.stderr.write("world\n") # Capture the text captured = capsys.readouterr() # Test the captured output, both std and err assert captured.out == "hello\n" assert captured.err == "world\n"
In the pytest docs it describes the fixtures to capture binary and more.
Tags: python TIL