How to Use capsys in pytest for Capturing Output
In pytest, use the
capsys fixture to capture output sent to stdout and stderr. Call capsys.readouterr() inside your test to get the captured output as a namedtuple with out and err strings, which you can then assert against.Syntax
The capsys fixture is passed as a parameter to your test function. Use capsys.readouterr() to capture the current output streams.
capsys: pytest fixture to capture output.capsys.readouterr(): returns a namedtuple without(stdout) anderr(stderr) strings.
python
def test_example(capsys): print("Hello stdout") import sys print("Hello stderr", file=sys.stderr) captured = capsys.readouterr() assert captured.out == "Hello stdout\n" assert captured.err == "Hello stderr\n"
Example
This example shows how to capture and assert printed output to both stdout and stderr using capsys. It demonstrates capturing output after printing and then checking the captured strings.
python
def test_print_output(capsys): print("Output to stdout") import sys print("Output to stderr", file=sys.stderr) captured = capsys.readouterr() assert captured.out == "Output to stdout\n" assert captured.err == "Output to stderr\n"
Output
============================= test session starts =============================
collected 1 item
test_sample.py . [100%]
============================== 1 passed in 0.01s ==============================
Common Pitfalls
Common mistakes when using capsys include:
- Calling
capsys.readouterr()before the output is generated, resulting in empty capture. - Not calling
readouterr()after output, so assertions check empty strings. - Expecting output without a newline character when
print()adds one by default.
Always call capsys.readouterr() after the output you want to capture.
python
def test_wrong_usage(capsys): captured = capsys.readouterr() # Called too early, no output captured print("Hello") assert captured.out == "Hello\n" # This will fail # Correct usage: def test_correct_usage(capsys): print("Hello") captured = capsys.readouterr() # Called after output assert captured.out == "Hello\n"
Quick Reference
| Action | Usage | Description |
|---|---|---|
| Use capsys fixture | def test_func(capsys): | Injects the output capturing fixture into your test |
| Capture output | captured = capsys.readouterr() | Reads and returns captured stdout and stderr |
| Access stdout | captured.out | String of captured standard output |
| Access stderr | captured.err | String of captured error output |
| Assert output | assert captured.out == 'expected\n' | Check if output matches expected string |
Key Takeaways
Use the capsys fixture parameter in your pytest test to capture output.
Call capsys.readouterr() after output is generated to get stdout and stderr.
Captured output includes newline characters added by print().
Always assert against captured.out for stdout and captured.err for stderr.
Avoid calling readouterr() before the output you want to test.