Capture and verify printed output using capsys in pytest
Preconditions (2)
✅ Expected Result: The test passes if the captured stdout and stderr match the expected printed messages
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.
Now add tests for a function that prints different messages based on input, capturing and asserting stdout and stderr for three different inputs.
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