From e400cb399f60f2c3386290d971bffdbf02e2e262 Mon Sep 17 00:00:00 2001 From: liruiluo Date: Sat, 14 Mar 2026 09:16:22 +0800 Subject: [PATCH] docs: prefer cache fixture in cache examples --- doc/en/how-to/cache.rst | 10 +++++++--- doc/en/reference/reference.rst | 6 ++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/doc/en/how-to/cache.rst b/doc/en/how-to/cache.rst index ca345916fc5..5070d30bd97 100644 --- a/doc/en/how-to/cache.rst +++ b/doc/en/how-to/cache.rst @@ -29,6 +29,10 @@ Other plugins may access the `config.cache`_ object to set/get :ref:`cmdunregister` (the internal name for this plugin is ``cacheprovider``). + In fixtures and tests, prefer the built-in :fixture:`cache` fixture. If + you need to access ``pytestconfig.cache`` directly, first guard it with + ``hasattr(pytestconfig, "cache")`` because the plugin may be disabled. + Rerunning only failures or failures first ----------------------------------------------- @@ -213,12 +217,12 @@ across pytest invocations: @pytest.fixture - def mydata(pytestconfig): - val = pytestconfig.cache.get("example/value", None) + def mydata(cache): + val = cache.get("example/value", None) if val is None: expensive_computation() val = 42 - pytestconfig.cache.set("example/value", val) + cache.set("example/value", val) return val diff --git a/doc/en/reference/reference.rst b/doc/en/reference/reference.rst index 644a687af53..8ff4fb55948 100644 --- a/doc/en/reference/reference.rst +++ b/doc/en/reference/reference.rst @@ -441,8 +441,10 @@ config.cache **Tutorial**: :ref:`cache` The ``config.cache`` object allows other plugins and fixtures -to store and retrieve values across test runs. To access it from fixtures -request ``pytestconfig`` into your fixture and get it with ``pytestconfig.cache``. +to store and retrieve values across test runs. In fixtures, prefer the built-in +:fixture:`cache` fixture. If you need ``pytestconfig.cache`` directly, guard the +attribute with ``hasattr(pytestconfig, "cache")`` because users may disable the +``cacheprovider`` plugin. Under the hood, the cache plugin uses the simple ``dumps``/``loads`` API of the :py:mod:`json` stdlib module.