capfd helps you check what your program prints to the screen. It captures output sent to file descriptors like standard output and error.
capfd for file descriptors in PyTest
Introduction
Syntax
PyTest
def test_function(capfd): # run code that prints captured = capfd.readouterr() assert captured.out == 'expected output\n' assert captured.err == ''
capfd is a pytest fixture you add as a test function argument.
Use capfd.readouterr() to get captured output and error as strings.
Examples
PyTest
def test_print_message(capfd): print('Hello world') captured = capfd.readouterr() assert captured.out == 'Hello world\n' assert captured.err == ''
PyTest
def test_error_message(capfd): import sys print('Error happened', file=sys.stderr) captured = capfd.readouterr() assert captured.err == 'Error happened\n' assert captured.out == ''
Sample Program
This test calls a function that prints a greeting. It uses capfd to capture and check the printed output.
PyTest
def greet(name): print(f'Hello, {name}!') def test_greet(capfd): greet('Alice') captured = capfd.readouterr() assert captured.out == 'Hello, Alice!\n' assert captured.err == '' # Running this test with pytest will pass if output matches.
Important Notes
capfd captures output at the file descriptor level, so it works even if code uses low-level print calls.
Always call capfd.readouterr() after the code that prints to capture fresh output.
Summary
capfd is a pytest tool to capture printed output and errors during tests.
Use it to check what your code prints without changing the code.
Remember to assert both standard output and standard error as needed.
Practice
1. What is the main purpose of
capfd in pytest?easy
Solution
Step 1: Understand capfd functionality
capfdis a pytest fixture used to capture output sent to standard output (stdout) and standard error (stderr) during test execution.Step 2: Identify correct purpose
Sincecapfdcaptures printed output, it helps verify what the code prints without changing the code itself.Final Answer:
To capture output printed to the console during tests -> Option AQuick 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
Solution
Step 1: Check pytest fixture usage
To usecapfd, it must be a parameter in the test function so pytest injects it.Step 2: Verify method call
The correct method to get captured output isreadouterr(), notcapture().Final Answer:
def test_func(capfd): output = capfd.readouterr() -> Option BQuick 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
Solution
Step 1: Understand what greet() prints
The functiongreet()prints the string "Hello, world!" followed by a newline.Step 2: Check captured output from capfd
capfd.readouterr()captures stdout including newlines, socaptured.outwill be "Hello, world!\n".Final Answer:
"Hello, world!\n" -> Option AQuick 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
Solution
Step 1: Analyze code flow with exception
Theraise ValueErrorstops execution immediately, socapfd.readouterr()and the assertion never run.Step 2: Identify the problem
Because the capture call is after the exception, the test does not capture output or perform the assertion.Final Answer:
Thecapfd.readouterr()call is after the exception, so it never runs -> Option CQuick 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
Solution
Step 1: Understand output streams
print('Output')writes to standard output with a newline, andprint('Error', file=sys.stderr)writes to standard error with a newline.Step 2: Check captured attributes
captured.outholds stdout, so it should be "Output\n";captured.errholds stderr, so it should be "Error\n".Final Answer:
assert captured.out == 'Output\n' and captured.err == 'Error\n' -> Option DQuick 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
10 questions ~5 mineasy hard
