0
0
PytestHow-ToBeginner ยท 3 min read

How to Capture Output in pytest: Simple Guide

In pytest, you can capture output printed to the console using the capsys fixture. This fixture lets you access the standard output and error streams during a test, allowing you to assert on what was printed.
๐Ÿ“

Syntax

The capsys fixture is passed as a parameter to your test function. Use capsys.readouterr() to capture the output printed to stdout and stderr. It returns a namedtuple with out and err strings.

  • capsys: pytest fixture to capture output
  • readouterr(): method to get captured output
  • out: captured standard output (print statements)
  • err: captured standard error output
python
def test_example(capsys):
    print("Hello, pytest!")
    captured = capsys.readouterr()
    assert captured.out == "Hello, pytest!\n"
    assert captured.err == ""
๐Ÿ’ป

Example

This example shows how to capture and assert printed output in a pytest test using capsys. The test prints a message, captures it, and checks that the output matches the expected string.

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

def test_greet(capsys):
    greet("Alice")
    captured = capsys.readouterr()
    assert captured.out == "Hello, Alice!\n"
    assert captured.err == ""
Output
============================= test session starts ============================= collected 1 item test_capture.py . [100%] ============================== 1 passed in 0.01s ==============================
โš ๏ธ

Common Pitfalls

One common mistake is calling capsys.readouterr() before the output is generated, which results in empty captured output. Another is forgetting that print() adds a newline, so assertions must include \n. Also, do not call readouterr() multiple times expecting cumulative output; it resets after each call.

python
def test_wrong_usage(capsys):
    captured = capsys.readouterr()  # Captures nothing yet
    print("Hello")
    # This assertion will fail because captured.out is empty
    assert captured.out == "Hello\n"


def test_correct_usage(capsys):
    print("Hello")
    captured = capsys.readouterr()  # Capture after print
    assert captured.out == "Hello\n"
๐Ÿ“Š

Quick Reference

  • capsys fixture: Inject into test to capture output
  • readouterr(): Call after output to get out and err
  • Output includes newlines: Remember print() adds \n
  • One read per capture: Each readouterr() resets capture buffers
โœ…

Key Takeaways

Use the capsys fixture to capture printed output in pytest tests.
Call capsys.readouterr() after output is generated to get stdout and stderr.
Remember that print adds a newline, so include \n in assertions.
Do not call readouterr() before output or expect cumulative output after multiple calls.
Captured output helps verify console messages and logging in tests.