Capture STDOUT and STDERR - capsys

Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Fixtures and Mocking in Python

Capture STDOUT and STDERR - capsys

  • capsys
import sys

def greet(to_out, to_err=None):
    print(to_out)
    if to_err:
        print(to_err, file=sys.stderr)


import app

def test_myoutput(capsys):
    app.greet("hello", "world")
    out, err = capsys.readouterr()
    assert out == "hello\n"
    assert err == "world\n"

    app.greet("next")
    out, err = capsys.readouterr()
    assert out == "next\n"
    assert err == ""