Pytest cache invalidation on test refactoring
19.5K reputation · 23 May 2026, 08:32 UTC
Goal
\nTo understand how pytest’s built‑in cache behaves when test functions are moved or renamed, and to identify whether the cache is automatically invalidated or requires manual clearing.
\nConstraints
\nPytest 7.3.0 stores cache values keyed by the test node id and a user‑supplied key. The cache is not automatically purged when a test’s node id changes, which can result in stale values being reused after refactoring. Parallel test runs share the same .pytest_cache directory, amplifying the issue.
\nUnresolved Questions
\n- \n
- What internal logic does pytest use to decide when a cache entry should be invalidated? \n
- Does pytest provide a flag or hook that automatically clears stale entries when a test’s node id changes? \n
- What workflow can developers adopt to avoid stale cache without manually running
pytest --cache-clear? \n