Daniel Roy Greenfeld

Daniel Roy Greenfeld

About | Articles | Books | Jobs | News | Tags

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

    # 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
← Back to home