Challenge - 5 Problems
Capsys Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output captured by capsys?
Consider this pytest test function using capsys to capture printed output. What will be the value of captured.out after the test runs?
PyTest
def test_print_output(capsys): print('Hello, world!') captured = capsys.readouterr() assert captured.out == 'Hello, world!\n'
Attempts:
2 left
💡 Hint
Remember that print adds a newline character at the end.
✗ Incorrect
The print function adds a newline character '\n' after the string. capsys.readouterr().out captures exactly what was printed, including the newline.
❓ assertion
intermediate2:00remaining
Which assertion correctly checks captured stderr output?
Given this test code snippet, which assertion correctly verifies that the error message 'Error occurred' was printed to standard error?
PyTest
def test_error_output(capsys): import sys print('Error occurred', file=sys.stderr) captured = capsys.readouterr()
Attempts:
2 left
💡 Hint
Standard error output is captured in captured.err, not captured.out.
✗ Incorrect
The error message is printed to sys.stderr, so capsys.readouterr().err contains the output. The exact string includes a newline.
🔧 Debug
advanced2:00remaining
Why does this test fail to capture output?
This test tries to capture printed output but fails. What is the reason?
PyTest
def test_no_capture(capsys): captured = capsys.readouterr() print('Test output') assert captured.out == 'Test output\n'
Attempts:
2 left
💡 Hint
Think about when capsys.readouterr() is called relative to print.
✗ Incorrect
capsys.readouterr() captures output up to the point it is called. Since it is called before print, it captures nothing. The print output is not captured in captured.
❓ framework
advanced2:00remaining
How to capture output from a function called multiple times?
You want to test a function that prints output multiple times. How do you capture all output using capsys?
PyTest
def greet(): print('Hello') print('World') def test_greet(capsys): greet() captured = capsys.readouterr()
Attempts:
2 left
💡 Hint
capsys accumulates output until readouterr() is called.
✗ Incorrect
capsys captures all output printed until readouterr() is called. Calling it after greet() captures all prints combined.
🧠 Conceptual
expert2:00remaining
What happens if you call capsys.readouterr() multiple times?
In a pytest test, what is the effect of calling capsys.readouterr() multiple times during the test?
Attempts:
2 left
💡 Hint
Think of capsys.readouterr() like reading and emptying a mailbox.
✗ Incorrect
Each call to capsys.readouterr() returns the output printed since the last call and clears the internal buffer, so subsequent calls only get new output.