Last-Failed and New-First Caching

Purpose

This subtopic addresses the need to optimize test execution by prioritizing tests based on their previous run outcomes or novelty. Specifically, it enables rerunning only tests that failed in the last session (`--lf` / `--last-failed`) or running tests from new or recently modified files first (`--nf` / `--new-first`). This targeted rerun approach saves time and resources by avoiding redundant execution of passing tests and focusing on areas likely to contain regressions or new code changes.

Functionality

Core Features

Key Workflows and Methods

Illustrative Code Snippets

Integration

This caching mechanism is tightly integrated with the pytest test collection and execution phases:

This subtopic introduces the concrete caching layer and logic for "last-failed" and "new-first" test prioritization, which is not covered at a high level in the parent topic, providing the essential mechanism for persistent state and targeted test reruns.

Diagram

flowchart TD
    A[Start Test Run]
    B[Test Collection]
    C{Caching Mode?}
    C -->|--lf (Last-Failed)| D[Filter collected tests to last failed only]
    C -->|--ff (Failed-First)| E[Reorder tests: failed first, then others]
    C -->|--nf (New-First)| F[Reorder tests: new files first]
    C -->|None| G[Run tests as collected]
    D --> H[Run filtered tests]
    E --> H
    F --> H
    G --> H
    H --> I[Test Execution & Reporting]
    I --> J[Update cache with failures and passes]
    J --> K[Save cache to disk]
    K --> L[End Test Run]

This flowchart visualizes how the last-failed and new-first caching influences test collection and execution, and how test outcomes update the cache for future runs.