Test Overview
This test captures output sent to standard output (stdout) and standard error (stderr) using pytest's capfd fixture. It verifies that the printed messages appear correctly in the captured output.
This test captures output sent to standard output (stdout) and standard error (stderr) using pytest's capfd fixture. It verifies that the printed messages appear correctly in the captured output.
import sys def greet(): print("Hello, stdout!") print("Warning on stderr!", file=sys.stderr) def test_greet_output(capfd): greet() out, err = capfd.readouterr() assert out == "Hello, stdout!\n" assert err == "Warning on stderr!\n"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and pytest initializes the capfd fixture to capture stdout and stderr. | Test environment ready with capfd capturing file descriptors. | — | PASS |
| 2 | Calls the greet() function which prints to stdout and stderr. | Output "Hello, stdout!" sent to stdout and "Warning on stderr!" sent to stderr. | — | PASS |
| 3 | Reads captured output and error using capfd.readouterr(). | Captured stdout contains "Hello, stdout!\n" and stderr contains "Warning on stderr!\n". | — | PASS |
| 4 | Asserts that captured stdout matches expected string. | Captured stdout is "Hello, stdout!\n". | assert out == "Hello, stdout!\n" | PASS |
| 5 | Asserts that captured stderr matches expected string. | Captured stderr is "Warning on stderr!\n". | assert err == "Warning on stderr!\n" | PASS |
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