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).
All cached data lives under the .pytest_cache/ directory by default.
def test_cache_example(cache):
# store a value
cache.set("myplugin/last_result", {"count": 42})
# read it back
value = cache.get("myplugin/last_result")
assert value["count"] == 42
Cache keys should follow a namespaced convention to avoid collisions. A common pattern is "plugin_or_app/key", such as myplugin/heavy_dataset_v1.
You can inspect cached values using pytest’s command-line options:
pytest --cache-show # show everything
pytest --cache-show myprefix/* # show values matching glob
pytest --cache-clear # clear the cache entirely
The underlying cache storage object is accessed via pytestconfig.cache (or request.config.cache). This is how fixtures, especially session-scoped ones, interact with the persistent cache, because the cache fixture behaves like a function-scoped fixture while the cache object it exposes persists across the entire test session.
cache fixture behaves like a function-scoped fixture, but the underlying cache store (config.cache) is persistent across the entire test session and survives between pytest runs.@pytest.fixture(scope="session")
def heavy_data(pytestconfig):
cache = pytestconfig.cache # same persistent store
...
pytestconfig
pytestconfig is a session-scoped fixture provides access to pytest’s global configuration object. It allows tests and fixtures to read command-line options, configuration values from pytest.ini and other runtime settings. This is useful when test behavior needs to change based on how pytest was invoked.
capsys
By default, pytest runs with output capturing enabled (to keep test results clean), meaning:
