Challenge - 5 Problems
Capfd 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 capfd?
Consider this pytest test function using capfd to capture output from print statements. What will be the value of captured output after running this test?
PyTest
def test_capture_output(capfd): print('Hello') print('World') out, err = capfd.readouterr() assert out == 'Hello\nWorld\n' assert err == ''
Attempts:
2 left
💡 Hint
Remember that print adds a newline after each call.
✗ Incorrect
The capfd fixture captures output sent to stdout and stderr. Each print adds a newline, so the captured stdout is 'Hello\nWorld\n'.
❓ assertion
intermediate2:00remaining
Which assertion correctly checks stderr captured by capfd?
Given a function that writes an error message to stderr, which assertion correctly verifies the captured error output using capfd?
PyTest
def test_error_message(capfd): import sys print('Error occurred', file=sys.stderr) out, err = capfd.readouterr()
Attempts:
2 left
💡 Hint
Error messages printed to stderr are captured in err.
✗ Incorrect
The error message is printed to stderr, so capfd captures it in err with a newline added by print.
🔧 Debug
advanced2:00remaining
Why does capfd.readouterr() return empty strings after first call?
In this test, capfd.readouterr() is called twice. Why does the second call return empty strings?
PyTest
def test_double_read(capfd): print('Test') out1, err1 = capfd.readouterr() out2, err2 = capfd.readouterr() assert out1 == 'Test\n' assert out2 == ''
Attempts:
2 left
💡 Hint
Think about what happens to the buffer after reading.
✗ Incorrect
capfd.readouterr() returns the current captured output and then clears the buffer. So the second call returns empty strings.
🧠 Conceptual
advanced2:00remaining
What is the main difference between capfd and capsys in pytest?
Choose the correct statement about the difference between capfd and capsys fixtures in pytest.
Attempts:
2 left
💡 Hint
Think about how low-level the capture happens.
✗ Incorrect
capfd captures output by redirecting the OS file descriptors (low-level), while capsys captures output by replacing sys.stdout and sys.stderr (Python-level).
❓ framework
expert3:00remaining
How to test a function that writes to both stdout and stderr using capfd?
You have a function that prints 'Info' to stdout and 'Warning' to stderr. Which test code correctly asserts both outputs using capfd?
PyTest
def log_messages(): import sys print('Info') print('Warning', file=sys.stderr)
Attempts:
2 left
💡 Hint
Remember which stream each print writes to.
✗ Incorrect
The function prints 'Info' to stdout and 'Warning' to stderr. capfd captures both separately in out and err.