Capturing output helps check if a program shows the right messages or results. It proves the program works as expected by looking at what it prints.
Why capturing output validates behavior in PyTest
def test_function(capsys): # Run code that prints output print('Hello') # Capture output captured = capsys.readouterr() # Assert output is as expected assert captured.out == 'Hello\n'
capsys is a pytest fixture that captures printed output.
Use captured.out for standard output and captured.err for error output.
def test_print_message(capsys): print('Test passed') captured = capsys.readouterr() assert captured.out == 'Test passed\n'
def test_error_message(capsys): import sys print('Error occurred', file=sys.stderr) captured = capsys.readouterr() assert captured.err == 'Error occurred\n'
This test calls a function that prints a greeting. It captures the output and checks if it matches the expected greeting message.
def greet(name): print(f'Hello, {name}!') def test_greet(capsys): greet('Alice') captured = capsys.readouterr() assert captured.out == 'Hello, Alice!\n' # Running test_greet will pass if output matches
Always include the newline character \n when asserting printed output because print() adds it automatically.
Use output capturing to test user-facing messages without changing the original code.
Captured output helps find bugs in what the program shows, not just what it returns.
Capturing output lets you check printed messages to confirm correct behavior.
Use pytest's capsys fixture to capture and test output easily.
Validating output is useful for testing messages, errors, and logs.
Practice
Solution
Step 1: Understand output capturing purpose
Capturing output allows tests to see what the function prints, which is important to verify expected messages.Step 2: Relate to behavior validation
By checking printed messages, we confirm the function behaves as intended, not just runs without errors.Final Answer:
It lets you check the printed messages to confirm correct behavior. -> Option CQuick Check:
Output capture = verify printed messages [OK]
- Thinking output capture speeds tests
- Believing it fixes errors automatically
- Assuming it stops function execution
Solution
Step 1: Recall pytest output capture fixtures
pytest provides the fixture namedcapsysto capture stdout and stderr output during tests.Step 2: Eliminate incorrect options
Other options likecapout,capprint, andcaptureare not valid pytest fixtures.Final Answer:
capsys -> Option AQuick Check:
Output capture fixture = capsys [OK]
- Using non-existent fixture names
- Confusing capsys with capture
- Misspelling the fixture name
def greet():
print('Hello, Tester!')
def test_greet(capsys):
greet()
captured = capsys.readouterr()
assert captured.out == 'Hello, Tester!\n'Solution
Step 1: Analyze printed output from greet()
The function prints 'Hello, Tester!' followed by a newline automatically from print().Step 2: Check captured output and assertion
capsys.readouterr() captures stdout including the newline, so captured.out equals 'Hello, Tester!\n', matching the assertion.Final Answer:
The assertion passes because output matches exactly. -> Option BQuick Check:
Printed output with newline = assertion match [OK]
- Forgetting print adds newline
- Comparing without newline in assertion
- Misusing capsys.readouterr()
def say_hi():
print('Hi!')
def test_say_hi(capsys):
say_hi()
captured = capsys.readouterr()
assert captured.out == 'Hi!'Solution
Step 1: Understand print output format
print('Hi!') outputs 'Hi!' plus a newline character '\n' at the end.Step 2: Check assertion string against captured output
The assertion compares captured.out to 'Hi!' without the newline, causing it to fail.Final Answer:
The assertion misses the newline character at the end of output. -> Option AQuick Check:
Print adds newline; assertion must include it [OK]
- Ignoring newline added by print
- Calling capsys.readouterr() too early
- Not passing capsys fixture to test
def respond(answer):
if answer == 'yes':
print('Confirmed')
else:
print('Denied')Solution
Step 1: Understand output capture per call
Each call to respond prints a message; capturing output after each call separately lets us check exact printed text.Step 2: Validate output for each input
Calling respond('yes') should print 'Confirmed\n', and respond('no') should print 'Denied\n'. Separate captures and assertions confirm correct behavior.Final Answer:
Call respond('yes'), capture output with capsys, assert output is 'Confirmed\n', then repeat for 'no' with 'Denied\n'. -> Option DQuick Check:
Separate capture/assert per call = correct validation [OK]
- Capturing output once for multiple calls
- Asserting combined output without newlines
- Ignoring output capture and checking return values
Ready to prove it?
Pass the test and this pattern moves unknown
