0
0
PyTesttesting~10 mins

capsys for stdout/stderr in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test captures output printed to the console (stdout) and error messages (stderr) using pytest's capsys fixture. It verifies that the printed messages match expected text.

Test Code - pytest
PyTest
import sys

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

def test_greet_output(capsys):
    greet()
    captured = capsys.readouterr()
    assert captured.out == "Hello, world!\n"
    assert captured.err == "Error happened\n"
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2Calls greet() functiongreet() prints 'Hello, world!' to stdout and 'Error happened' to stderr-PASS
3capsys reads captured stdout and stderrcaptured.out contains 'Hello, world!\n', captured.err contains 'Error happened\n'-PASS
4Assert captured.out equals 'Hello, world!\n'captured.out is 'Hello, world!\n'assert captured.out == 'Hello, world!\n'PASS
5Assert captured.err equals 'Error happened\n'captured.err is 'Error happened\n'assert captured.err == 'Error happened\n'PASS
6Test ends successfullyAll assertions passed-PASS
Failure Scenario
Failing Condition: The printed output does not match the expected strings
Execution Trace Quiz - 3 Questions
Test your understanding
What does capsys.readouterr() return?
AAn object with captured stdout and stderr strings
BA boolean indicating if output was captured
CThe original print function
DA file handle to stdout
Key Result
Use pytest's capsys fixture to capture and verify console output and error messages, ensuring your code prints exactly what you expect.