Verify function output by capturing printed output
Preconditions (2)
✅ Expected Result: The test passes if the captured output exactly matches the expected printed message
import pytest def greet(): print("Hello, friend!") def test_greet_output(capsys): greet() captured = capsys.readouterr() assert captured.out == "Hello, friend!\n", f"Expected 'Hello, friend!\n' but got {captured.out!r}"
The greet function prints a message to the console.
The test function test_greet_output uses pytest's capsys fixture to capture anything printed to standard output during the test.
After calling greet(), capsys.readouterr() returns an object with out containing the printed text.
The assertion checks that the captured output exactly matches the expected string including the newline character.
This method validates behavior by confirming what the user would see on the screen, ensuring the function works as intended.
Now add data-driven testing with 3 different greeting messages
capsys to capture stdout and stderr output during tests.capout, capprint, and capture are not valid pytest fixtures.def greet():
print('Hello, Tester!')
def test_greet(capsys):
greet()
captured = capsys.readouterr()
assert captured.out == 'Hello, Tester!\n'def say_hi():
print('Hi!')
def test_say_hi(capsys):
say_hi()
captured = capsys.readouterr()
assert captured.out == 'Hi!'def respond(answer):
if answer == 'yes':
print('Confirmed')
else:
print('Denied')Pass the test and this pattern moves unknown