Bird
Raised Fist0
PyTesttesting~20 mins

capfd for file descriptors in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Capfd Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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 == ''
A''
B'Hello World\n'
C'HelloWorld'
D'Hello\nWorld\n'
Attempts:
2 left
💡 Hint
Remember that print adds a newline after each call.
❓ assertion
intermediate
2: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()
Aassert err == 'Error occurred'
Bassert err == 'Error occurred\n'
Cassert out == 'Error occurred\n'
Dassert out == ''
Attempts:
2 left
💡 Hint
Error messages printed to stderr are captured in err.
🔧 Debug
advanced
2: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 == ''
ABecause readouterr() clears the captured output after reading
BBecause print only outputs once and capfd caches it
CBecause capfd only captures stderr, not stdout
DBecause the second print statement is missing
Attempts:
2 left
💡 Hint
Think about what happens to the buffer after reading.
🧠 Conceptual
advanced
2: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.
Acapfd captures output only from Python print, capsys captures all system output
Bcapfd captures only stdout, capsys captures both stdout and stderr
Ccapfd captures output at the file descriptor level, capsys captures at the Python sys module level
Dcapfd is slower than capsys because it uses subprocesses
Attempts:
2 left
💡 Hint
Think about how low-level the capture happens.
❓ framework
expert
3: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)
A
def test_log(capfd):
    log_messages()
    out, err = capfd.readouterr()
    assert out == 'Info\n'
    assert err == 'Warning\n'
B
def test_log(capfd):
    log_messages()
    out, err = capfd.readouterr()
    assert out == 'Warning\n'
    assert err == 'Info\n'
C
def test_log(capfd):
    log_messages()
    out, err = capfd.readouterr()
    assert out == 'InfoWarning\n'
    assert err == ''
D
def test_log(capfd):
    log_messages()
    out, err = capfd.readouterr()
    assert out == ''
    assert err == 'Info\nWarning\n'
Attempts:
2 left
💡 Hint
Remember which stream each print writes to.

Practice

(1/5)
1. What is the main purpose of capfd in pytest?
easy
A. To capture output printed to the console during tests
B. To mock database connections in tests
C. To measure test execution time
D. To generate test reports automatically

Solution

  1. Step 1: Understand capfd functionality

    capfd is a pytest fixture used to capture output sent to standard output (stdout) and standard error (stderr) during test execution.
  2. Step 2: Identify correct purpose

    Since capfd captures printed output, it helps verify what the code prints without changing the code itself.
  3. Final Answer:

    To capture output printed to the console during tests -> Option A
  4. Quick Check:

    capfd captures printed output = B [OK]
Hint: Remember capfd captures print output and errors [OK]
Common Mistakes:
  • Confusing capfd with mocking tools
  • Thinking capfd measures time
  • Assuming capfd generates reports
2. Which of the following is the correct way to use capfd in a pytest test function?
easy
A. def test_func(capsys): output = capfd.readouterr()
B. def test_func(capfd): output = capfd.readouterr()
C. def test_func(): output = capfd.readouterr()
D. def test_func(capfd): output = capfd.capture()

Solution

  1. Step 1: Check pytest fixture usage

    To use capfd, it must be a parameter in the test function so pytest injects it.
  2. Step 2: Verify method call

    The correct method to get captured output is readouterr(), not capture().
  3. Final Answer:

    def test_func(capfd): output = capfd.readouterr() -> Option B
  4. Quick Check:

    Use capfd parameter and readouterr() method = D [OK]
Hint: Use capfd as function argument and call readouterr() [OK]
Common Mistakes:
  • Using capsys instead of capfd
  • Calling non-existent capture() method
  • Not passing capfd as parameter
3. Given the following test code, what will be the value of captured.out after capfd.readouterr() is called?
def greet():
    print('Hello, world!')

def test_greet(capfd):
    greet()
    captured = capfd.readouterr()
medium
A. "Hello, world!\n"
B. "Hello, world!"
C. "" (empty string)
D. An exception is raised

Solution

  1. Step 1: Understand what greet() prints

    The function greet() prints the string "Hello, world!" followed by a newline.
  2. Step 2: Check captured output from capfd

    capfd.readouterr() captures stdout including newlines, so captured.out will be "Hello, world!\n".
  3. Final Answer:

    "Hello, world!\n" -> Option A
  4. Quick Check:

    Printed string plus newline = C [OK]
Hint: Print adds newline, capfd captures it too [OK]
Common Mistakes:
  • Forgetting the newline character
  • Expecting empty string if not returned
  • Thinking an exception occurs
4. What is wrong with this test code using capfd?
def test_error(capfd):
    print('Start')
    raise ValueError('Oops')
    captured = capfd.readouterr()
    assert captured.out == 'Start\n'
medium
A. The assertion should check captured.err instead of captured.out
B. The print statement does not produce output
C. The capfd.readouterr() call is after the exception, so it never runs
D. capfd cannot capture output if exceptions occur

Solution

  1. Step 1: Analyze code flow with exception

    The raise ValueError stops execution immediately, so capfd.readouterr() and the assertion never run.
  2. Step 2: Identify the problem

    Because the capture call is after the exception, the test does not capture output or perform the assertion.
  3. Final Answer:

    The capfd.readouterr() call is after the exception, so it never runs -> Option C
  4. Quick Check:

    Exception stops code before capture call = A [OK]
Hint: Place capture before exceptions to avoid skipping [OK]
Common Mistakes:
  • Assuming print output is lost
  • Thinking capfd fails on exceptions
  • Checking wrong captured attribute
5. You want to test a function that prints to both standard output and standard error. How do you correctly assert both outputs using capfd?
def test_both_outputs(capfd):
    print('Output')
    import sys
    print('Error', file=sys.stderr)
    captured = capfd.readouterr()
    # What assertions should you write?
hard
A. assert captured.out == '' and captured.err == 'Output\nError\n'
B. assert captured.out == 'Output' and captured.err == 'Error'
C. assert captured.out == 'Output\nError\n' and captured.err == ''
D. assert captured.out == 'Output\n' and captured.err == 'Error\n'

Solution

  1. Step 1: Understand output streams

    print('Output') writes to standard output with a newline, and print('Error', file=sys.stderr) writes to standard error with a newline.
  2. Step 2: Check captured attributes

    captured.out holds stdout, so it should be "Output\n"; captured.err holds stderr, so it should be "Error\n".
  3. Final Answer:

    assert captured.out == 'Output\n' and captured.err == 'Error\n' -> Option D
  4. Quick Check:

    Separate stdout and stderr captured correctly = A [OK]
Hint: Assert captured.out and captured.err separately with newlines [OK]
Common Mistakes:
  • Mixing stdout and stderr in one assertion
  • Forgetting newline characters
  • Checking wrong captured attribute
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard