Complete worked example
python
def greet(name):
print(f"Hello, {name}")
return 0
def test_greeting_output(capsys):
assert greet("Ada") == 0
captured = capsys.readouterr()
assert captured.out == "Hello, Ada\n"
assert captured.err == ""- Reasoning
- The complete example prints a greeting to stdout and returns a success code. capsys.readouterr gives the captured output so far and resets the capture buffer. The test asserts the return code, exact newline-terminated stdout and empty stderr. A later read observes output since the previous read, not the full session repeatedly. If a test uses capsys.disabled, output during that block bypasses capture intentionally. Keep such blocks for interactive debugging rather than using them to avoid an assertion.