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"] == 42Cache 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 entirelyThe 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.
NOTE
The 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
...