Challenge - 5 Problems
Output Capture Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this pytest capture example?
Consider this pytest test function that captures printed output. What will be the value of
captured after running this test?PyTest
def greet(): print("Hello, Tester!") def test_greet_output(capsys): greet() captured = capsys.readouterr().out assert captured == "Hello, Tester!\n"
Attempts:
2 left
💡 Hint
Remember that print adds a newline character at the end.
✗ Incorrect
The print function adds a newline character '\n' at the end of the output. The capsys fixture captures this exact output including the newline.
❓ assertion
intermediate2:00remaining
Which assertion correctly checks captured stderr output?
You want to test that a function prints an error message to standard error. Which assertion correctly verifies this using pytest's capsys?
PyTest
def error_func(): import sys print("Error occurred", file=sys.stderr) def test_error_output(capsys): error_func() captured = capsys.readouterr()
Attempts:
2 left
💡 Hint
Standard error output is stored in
captured.err.✗ Incorrect
The error message is printed to standard error, so it is captured in
captured.err including the newline.🔧 Debug
advanced2:00remaining
Why does this pytest output capture test fail?
This test is supposed to check printed output but fails. What is the reason?
PyTest
def test_print_fail(capsys): print("Test output") captured = capsys.readouterr().out assert captured == "Test output"
Attempts:
2 left
💡 Hint
Check what print adds at the end of the string.
✗ Incorrect
Print adds a newline '\n' at the end, so captured output is "Test output\n" not "Test output".
🧠 Conceptual
advanced2:00remaining
Why is capturing output important in testing behavior?
Why does capturing printed output help validate the behavior of a function in tests?
Attempts:
2 left
💡 Hint
Think about how users interact with programs.
✗ Incorrect
Capturing output lets tests verify that the program shows the right messages, which is part of correct behavior.
❓ framework
expert3:00remaining
How to capture output from a subprocess in pytest?
You want to test a command-line tool run as a subprocess and capture its output in pytest. Which approach correctly captures both stdout and stderr?
PyTest
import subprocess def test_subprocess_output(): result = subprocess.run(['echo', 'hello'], capture_output=True, text=True) # What assertion below correctly checks the output?
Attempts:
2 left
💡 Hint
Check the attributes of subprocess.CompletedProcess for output.
✗ Incorrect
The subprocess.run with capture_output=True stores stdout in result.stdout including newline, stderr in result.stderr.