Retention and Cleanup

Purpose

Temporary directories created during test runs can accumulate quickly, consuming disk space and potentially cluttering the environment. The **Retention and Cleanup** subtopic addresses this by providing configurable policies that determine when these temporary directories should be preserved or removed. This feature allows developers to retain directories selectively—for example, keeping only those from failed test runs for troubleshooting—while cleaning up others automatically to maintain a tidy workspace.

Functionality

This subtopic introduces a retention policy mechanism that governs the lifecycle of temporary directories under the `tmp_path` fixture. The core functionality includes:

Key Code Interactions

class TempPathFactory:
    def __init__(self, *, retention_count: int, retention_policy: RetentionType, ...):
        self._retention_count = retention_count
        self._retention_policy = retention_policy
    ...
    def mktemp(self, basename: str, numbered: bool = True) -> Path:
        # Creates a uniquely numbered temp directory.
@fixture
def tmp_path(request, tmp_path_factory):
    path = tmp_path_factory.mktemp(...)
    yield path
    if tmp_path_factory._retention_policy == "failed" and test_passed:
        rmtree(path, ignore_errors=True)
@hookimpl(wrapper=True, tryfirst=True)
def pytest_runtest_makereport(item, call):
    rep = yield
    item.stash.setdefault(tmppath_result_key, {})[rep.when] = rep.passed
    return rep
def pytest_sessionfinish(session, exitstatus):
    if exitstatus == 0 and policy == "failed" and no_given_basetemp:
        rmtree(basetemp, ignore_errors=True)
    cleanup_dead_symlinks(basetemp)

Integration

Retention and Cleanup tightly integrate with the **Temporary Directory Management** parent topic by extending the lifecycle management of temporary directories beyond simple creation and deletion. While the parent topic focuses on providing unique temporary directories per test, this subtopic adds intelligent policies that conditionally preserve or remove these directories based on test outcomes and user preferences.

This subtopic also interacts with:

Together, these integrations ensure that temporary directories are managed efficiently, aiding both debugging (by retaining relevant dirs) and resource hygiene (by cleaning up unnecessary data).

Diagram

flowchart TD
    Start[Test Starts]
    MkTmp[Create Temp Dir (mktemp)]
    RunTest[Test Execution]
    CaptureResult[Capture Test Result]
    CheckPolicy{Retention Policy}
    Passed?{Test Passed?}
    CleanupDir[Delete Temp Dir]
    KeepDir[Keep Temp Dir]
    End[Test Ends]

    Start --> MkTmp --> RunTest --> CaptureResult --> CheckPolicy
    CheckPolicy -->|none| CleanupDir
    CheckPolicy -->|all| KeepDir
    CheckPolicy -->|failed| Passed?
    Passed? -->|Yes| CleanupDir
    Passed? -->|No| KeepDir
    CleanupDir --> End
    KeepDir --> End

This flowchart visualizes the decision process for retaining or cleaning up temporary directories based on the configured retention policy and the outcome of each test.