Skip to content

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.

python
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:

shell
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.

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.

python
@pytest.fixture(scope="session")
def heavy_data(pytestconfig):
    cache = pytestconfig.cache  # same persistent store
    ...