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.
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.
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"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | pytest test runner initialized | — | PASS |
| 2 | Calls greet() function | greet() prints 'Hello, world!' to stdout and 'Error happened' to stderr | — | PASS |
| 3 | capsys reads captured stdout and stderr | captured.out contains 'Hello, world!\n', captured.err contains 'Error happened\n' | — | PASS |
| 4 | Assert captured.out equals 'Hello, world!\n' | captured.out is 'Hello, world!\n' | assert captured.out == 'Hello, world!\n' | PASS |
| 5 | Assert captured.err equals 'Error happened\n' | captured.err is 'Error happened\n' | assert captured.err == 'Error happened\n' | PASS |
| 6 | Test ends successfully | All assertions passed | — | PASS |
capsys in pytest tests?capsys doescapsys is a pytest feature that captures output sent to the console, including both stdout and stderr.capsys to capture printed output in a pytest test function?capsys is passed and usedcapsys is passed as a function argument and used after printing to capture output.capsys.readouterr(), which returns captured stdout and stderr.def test_output(capsys):
print('Test message')
captured = capsys.readouterr()
assert captured.out == 'Test message\n'
capsys:
def test_error(capsys):
captured = capsys.readouterr()
print('Hello')
assert captured.out == 'Hello\n'
capsys. Which code snippet correctly captures and asserts the stderr output?print(..., file=sys.stderr) to send output to stderr stream.captured.err matches expected string including newline.Pass the test and this pattern moves unknown