Capture and verify printed output using capsys in pytest
Preconditions (2)
✅ Expected Result: The test passes confirming the printed output is correctly captured and matches the expected string
import pytest def greet(): print("Hello, world!") def test_greet_output(capsys): greet() captured = capsys.readouterr() assert captured.out == "Hello, world!\n"
The greet function prints the string 'Hello, world!'.
The test function test_greet_output uses the capsys fixture provided by pytest to capture output printed to the console.
Inside the test, we call greet() which prints the message. Then capsys.readouterr() captures the output streams.
We assert that captured.out (standard output) exactly matches the expected string including the newline character.
This confirms the printed output is correctly captured and verified.
Now add data-driven testing to capture and verify output for three different greetings: 'Hello, world!', 'Hi there!', and 'Good morning!'
capsys in pytest tests?capsys.readouterr().capture(), getoutput(), or print() do not exist on capsys.def greet():
print('Hello, Tester!')
def test_greet(capsys):
greet()
captured = capsys.readouterr()
assert captured.out == 'Hello, Tester!\n'def test_error(capsys):
print('Start')
captured = capsys.readouterr
assert captured.out == 'Start\n'Pass the test and this pattern moves unknown