pytest
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:
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::
with capsys.disabled():
print("This will be shown immediately.")
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.cache
The cache fixture provides a persistent key/value store to save and retrieve data across test runs. It exposes simple get and set methods for writing and reading values and internally stores them using JSON serialization (json.dumps / json.loads).
caplog
pytest also captures log records emitted via the standard logging module. By default:
