0
0
PyTesttesting~15 mins

capsys for stdout/stderr in PyTest - Build an Automation Script

Choose your learning style9 modes available
Capture and verify printed output using capsys in pytest
Preconditions (2)
Step 1: Write a test function that calls the target function which prints to stdout and stderr
Step 2: Use the capsys fixture to capture the output
Step 3: After calling the function, use capsys.readouterr() to get the captured stdout and stderr
Step 4: Assert that the captured stdout contains the expected printed text
Step 5: Assert that the captured stderr contains the expected error text
✅ Expected Result: The test passes if the captured stdout and stderr match the expected printed messages
Automation Requirements - pytest
Assertions Needed:
Assert captured stdout equals expected string
Assert captured stderr equals expected string
Best Practices:
Use the capsys fixture parameter in the test function
Call capsys.readouterr() only once after the function call
Avoid printing inside the test except for debugging
Keep assertions clear and specific
Automated Solution
PyTest
import sys

def greet():
    print("Hello, world!")
    print("Warning: something minor happened", file=sys.stderr)


def test_greet_output(capsys):
    greet()
    captured = capsys.readouterr()
    assert captured.out == "Hello, world!\n"
    assert captured.err == "Warning: something minor happened\n"

The greet function prints a message to standard output and another to standard error.

The test function test_greet_output uses the capsys fixture to capture these outputs.

After calling greet(), capsys.readouterr() returns an object with out and err strings.

Assertions check that the captured output matches exactly what greet printed, including newline characters.

This ensures the printed messages are correctly captured and verified.

Common Mistakes - 3 Pitfalls
Calling capsys.readouterr() multiple times after the function call
Not including newline characters in expected strings
Printing inside the test function for debugging without disabling
Bonus Challenge

Now add tests for a function that prints different messages based on input, capturing and asserting stdout and stderr for three different inputs.

Show Hint