0
0
PyTesttesting~5 mins

capsys for stdout/stderr in PyTest

Choose your learning style9 modes available
Introduction

capsys helps you catch what a program prints on the screen during tests. This way, you can check if the right messages appear without seeing them in real time.

You want to check if a function prints a welcome message.
You need to verify error messages printed to the screen.
You want to test that debug information is shown during a process.
You want to make sure no unexpected output appears during a test.
Syntax
PyTest
def test_function(capsys):
    print("Hello")
    captured = capsys.readouterr()
    assert captured.out == "Hello\n"

capsys is a pytest fixture that captures output automatically.

Use capsys.readouterr() to get what was printed to stdout and stderr.

Examples
This test checks standard output (stdout) for the printed message.
PyTest
def test_print_stdout(capsys):
    print("Hello stdout")
    captured = capsys.readouterr()
    assert captured.out == "Hello stdout\n"
This test checks standard error (stderr) for the printed error message.
PyTest
import sys

def test_print_stderr(capsys):
    print("Error message", file=sys.stderr)
    captured = capsys.readouterr()
    assert captured.err == "Error message\n"
This test captures multiple lines printed to stdout.
PyTest
def test_multiple_prints(capsys):
    print("First line")
    print("Second line")
    captured = capsys.readouterr()
    assert captured.out == "First line\nSecond line\n"
Sample Program

This test calls a function that prints a greeting. It uses capsys to capture and check the printed output.

PyTest
def greet(name):
    print(f"Hello, {name}!")

def test_greet(capsys):
    greet("Alice")
    captured = capsys.readouterr()
    assert captured.out == "Hello, Alice!\n"
OutputSuccess
Important Notes

capsys captures output only during the test function's execution.

Calling capsys.readouterr() clears the captured output, so call it once per check.

Use captured.out for standard output and captured.err for error output.

Summary

capsys helps test printed output without showing it on screen.

Use capsys.readouterr() to get what was printed.

Check captured.out for normal prints and captured.err for errors.