0
0
PyTesttesting~5 mins

capsys for capturing output in PyTest

Choose your learning style9 modes available
Introduction

capsys helps you catch what your program prints so you can check if it shows the right messages.

You want to test if a function prints the correct greeting message.
You need to check error messages printed to the console during a test.
You want to verify output from a script without changing the code.
You want to capture print output to avoid cluttering test results.
Syntax
PyTest
def test_function(capsys):
    print("Hello")
    captured = capsys.readouterr()
    assert captured.out == "Hello\n"

capsys is a special pytest argument that captures print output.

Use capsys.readouterr() to get the captured output as an object with out and err strings.

Examples
Checks if the printed message matches exactly.
PyTest
def test_print_message(capsys):
    print("Test message")
    captured = capsys.readouterr()
    assert captured.out == "Test message\n"
Captures multiple print lines and checks combined output.
PyTest
def test_multiple_prints(capsys):
    print("Line 1")
    print("Line 2")
    captured = capsys.readouterr()
    assert captured.out == "Line 1\nLine 2\n"
Captures error messages printed to standard error.
PyTest
def test_error_output(capsys):
    import sys
    print("Error happened", file=sys.stderr)
    captured = capsys.readouterr()
    assert captured.err == "Error happened\n"
Sample Program

This test calls greet which prints a message. capsys captures the output and the test checks if it is correct.

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

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

# Running test_greet will pass if output matches
OutputSuccess
Important Notes

capsys captures output only during the test function where it is used.

After calling capsys.readouterr(), the captured output is cleared.

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

Summary

capsys lets you catch and check printed messages in tests.

Use capsys.readouterr() to get output and error streams.

This helps verify your program talks to users correctly.