capsys
By default, pytest runs with output capturing enabled (to keep test results clean), meaning:
print()output does not appear on the terminal.- pytest captures both
stdoutandstderrinternally. - failed tests show the captured output in the traceback.
The capsys fixture lets you read captured output during a test:
python
def test_output_capture(capsys):
print("hello world")
out, err = capsys.readouterr()
assert out.strip() == "hello world"
assert err == ""You can temporarily disable capture for a block of code::
python
with capsys.disabled():
print("This will be shown immediately.")WARNING
When pytest is run with the -s option, all output capturing is disabled. As a result, capsys.readouterr() will always return empty strings for both stdout and stderr, and capsys.disabled() has no additional effect since capturing is already turned off.
