capsys helps you catch what a program prints on the screen during tests. This way, you can check if the right messages appear without seeing them in real time.
capsys for stdout/stderr in PyTest
Introduction
Syntax
PyTest
def test_function(capsys): print("Hello") captured = capsys.readouterr() assert captured.out == "Hello\n"
capsys is a pytest fixture that captures output automatically.
Use capsys.readouterr() to get what was printed to stdout and stderr.
Examples
PyTest
def test_print_stdout(capsys): print("Hello stdout") captured = capsys.readouterr() assert captured.out == "Hello stdout\n"
PyTest
import sys def test_print_stderr(capsys): print("Error message", file=sys.stderr) captured = capsys.readouterr() assert captured.err == "Error message\n"
PyTest
def test_multiple_prints(capsys): print("First line") print("Second line") captured = capsys.readouterr() assert captured.out == "First line\nSecond line\n"
Sample Program
This test calls a function that prints a greeting. It uses capsys to capture and check the printed output.
PyTest
def greet(name): print(f"Hello, {name}!") def test_greet(capsys): greet("Alice") captured = capsys.readouterr() assert captured.out == "Hello, Alice!\n"
Important Notes
capsys captures output only during the test function's execution.
Calling capsys.readouterr() clears the captured output, so call it once per check.
Use captured.out for standard output and captured.err for error output.
Summary
capsys helps test printed output without showing it on screen.
Use capsys.readouterr() to get what was printed.
Check captured.out for normal prints and captured.err for errors.
Practice
1. What is the main purpose of using
capsys in pytest tests?easy
Solution
Step 1: Understand what
capsysdoescapsysis a pytest feature that captures output sent to the console, including both stdout and stderr.Step 2: Identify its main use in tests
It allows tests to check what was printed, so you can verify messages or errors your code produces.Final Answer:
To capture and check printed output sent to stdout and stderr -> Option AQuick Check:
capsys captures output = C [OK]
Hint: capsys catches print output for verification [OK]
Common Mistakes:
- Thinking capsys speeds up tests
- Believing capsys fixes code errors
- Confusing capsys with test data generation
2. Which of the following is the correct way to use
capsys to capture printed output in a pytest test function?easy
Solution
Step 1: Check how
In pytest,capsysis passed and usedcapsysis passed as a function argument and used after printing to capture output.Step 2: Verify correct method to read output
The method to get output iscapsys.readouterr(), which returns captured stdout and stderr.Final Answer:
def test_func(capsys): print('Hello'); captured = capsys.readouterr() -> Option CQuick Check:
capsys as argument + readouterr() = A [OK]
Hint: Pass capsys as argument and call readouterr() after print [OK]
Common Mistakes:
- Not passing capsys as a test function argument
- Calling non-existent capture() method
- Calling readouterr() before printing
3. What will be the output of the following pytest test code snippet?
def test_output(capsys):
print('Test message')
captured = capsys.readouterr()
assert captured.out == 'Test message\n'
medium
Solution
Step 1: Understand output capture timing
The print statement runs first, sending 'Test message' plus a newline to stdout.Step 2: Check captured output and assertion
capsys.readouterr() captures the output including the newline. The assertion checks for 'Test message\n', which matches exactly.Final Answer:
Test passes because printed output matches assertion -> Option AQuick Check:
Printed output includes newline = B [OK]
Hint: Remember print adds newline; assert with '\n' [OK]
Common Mistakes:
- Forgetting newline in assertion string
- Calling readouterr() before print
- Assuming captured.out excludes newlines
4. Identify the error in this pytest test using
capsys:
def test_error(capsys):
captured = capsys.readouterr()
print('Hello')
assert captured.out == 'Hello\n'
medium
Solution
Step 1: Check order of output capture and print
capsys.readouterr() is called before the print statement, so it captures output up to that point, which is empty.Step 2: Understand assertion failure reason
The assertion expects 'Hello\n' but captured.out is empty, causing test failure.Final Answer:
Calling capsys.readouterr() before printing captures nothing -> Option BQuick Check:
Read output after print, not before = A [OK]
Hint: Always call readouterr() after print to capture output [OK]
Common Mistakes:
- Calling readouterr() before print
- Forgetting newline in assertion
- Assuming capsys needs import
5. You want to test a function that prints error messages to stderr using pytest and
capsys. Which code snippet correctly captures and asserts the stderr output?hard
Solution
Step 1: Identify how to print to stderr
Useprint(..., file=sys.stderr)to send output to stderr stream.Step 2: Check correct use of capsys and assertion
capsys.readouterr() captures both stdout and stderr. To check stderr, assertcaptured.errmatches expected string including newline.Final Answer:
def test_error_message(capsys): print('Error occurred', file=sys.stderr) captured = capsys.readouterr() assert captured.err == 'Error occurred\n' -> Option DQuick Check:
Print to stderr + assert captured.err = D [OK]
Hint: Print with file=sys.stderr and assert captured.err [OK]
Common Mistakes:
- Not passing capsys as argument
- Printing to stdout instead of stderr
- Asserting captured.out instead of captured.err
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
