Capture and verify output printed to stdout and stderr using capfd
Preconditions (2)
✅ Expected Result: The test passes if the captured stdout and stderr match the expected messages
import sys import pytest def print_messages(): print("Hello stdout") print("Error message", file=sys.stderr) def test_capture_output(capfd): print_messages() out, err = capfd.readouterr() assert "Hello stdout" in out assert "Error message" in err
The print_messages function prints a message to standard output and another to standard error.
The test function test_capture_output uses the capfd fixture to capture these outputs.
After calling print_messages(), it calls capfd.readouterr() once to get both stdout and stderr.
Assertions check that the expected messages appear in the captured output streams.
This approach ensures the test verifies exactly what the function prints, without showing output during test runs.
Now add data-driven testing with 3 different functions that print different messages to stdout and stderr, and verify each output using capfd.
capfd in pytest?capfd is a pytest fixture used to capture output sent to standard output (stdout) and standard error (stderr) during test execution.capfd captures printed output, it helps verify what the code prints without changing the code itself.capfd in a pytest test function?capfd, it must be a parameter in the test function so pytest injects it.readouterr(), not capture().captured.out after capfd.readouterr() is called?def greet():
print('Hello, world!')
def test_greet(capfd):
greet()
captured = capfd.readouterr()greet() prints the string "Hello, world!" followed by a newline.capfd.readouterr() captures stdout including newlines, so captured.out will be "Hello, world!\n".capfd? def test_error(capfd):
print('Start')
raise ValueError('Oops')
captured = capfd.readouterr()
assert captured.out == 'Start\n'raise ValueError stops execution immediately, so capfd.readouterr() and the assertion never run.capfd.readouterr() call is after the exception, so it never runs -> Option Ccapfd?def test_both_outputs(capfd):
print('Output')
import sys
print('Error', file=sys.stderr)
captured = capfd.readouterr()
# What assertions should you write?print('Output') writes to standard output with a newline, and print('Error', file=sys.stderr) writes to standard error with a newline.captured.out holds stdout, so it should be "Output\n"; captured.err holds stderr, so it should be "Error\n".Pass the test and this pattern moves unknown