Temp Path Factories
Purpose
The Temp Path Factories subtopic addresses the need for creating and managing temporary directories during test runs, ensuring each test function can safely work with isolated filesystem locations. Unlike the broader temporary directory management topic, which covers retention policies and cleanup strategies, this subtopic focuses specifically on the factory objects responsible for generating these directories, managing their lifecycle, and providing consistent, unique paths scoped per test or session.
This feature solves challenges such as:
Providing unique temporary directory paths for each test invocation to avoid conflicts.
Ensuring directories are created under a common base temporary directory that respects user configuration and platform constraints.
Supporting configurable naming conventions and numbering schemes to guarantee uniqueness.
Integrating retention policies at the directory creation level to influence cleanup behavior downstream.
Functionality
Core Factory Class: TempPathFactory
The `TempPathFactory` class encapsulates all logic related to creating and managing temporary directory paths under a shared base directory. Its key responsibilities include:
Initialization from Configuration
Usingfrom_config(), the factory reads pytest’s ini options (tmp_path_retention_countandtmp_path_retention_policy) and CLI options to configure retention and location behavior.Base Directory Management
The factory lazily determines the base temporary directory (getbasetemp()), which may be user-specified or automatically generated under system temp directories. It ensures ownership and permission correctness, creating a secure and isolated directory tree for temporary paths.Unique Directory Creation
The mktemp() method creates new temporary directories with a specified base name. Whennumbered=True, it generates unique directory names by appending incremental suffixes (e.g.,foo-0,foo-1), ensuring no collisions even when multiple tests run concurrently.Path Normalization & Safety
It validates that requested directory names are normalized relative paths within the base temp directory to avoid security or path traversal issues.
Integration with Fixtures
The tmp_path_factory fixture exposes a session-scoped instance of
TempPathFactoryfor tests or other fixtures to request temporary directories.The
tmp_pathfixture leverages tmp_path_factory to provide each test function with a fresh temporary directory, guaranteeing isolation and cleanup according to retention policies.
Lifecycle Hooks
During the test session, the factory tracks test results and retention policies to decide when to remove temporary directories (e.g., removing directories from tests that passed if the policy is
failed).At session finish, it performs cleanup of the base temporary directory if conditions meet retention criteria, also removing stale symlinks.
Code Snippet Illustrating Directory Creation
def mktemp(self, basename: str, numbered: bool = True) -> Path:
basename = self._ensure_relative_to_basetemp(basename)
if not numbered:
p = self.getbasetemp().joinpath(basename)
p.mkdir(mode=0o700)
else:
p = make_numbered_dir(root=self.getbasetemp(), prefix=basename, mode=0o700)
self._trace("mktemp", p)
return p
This snippet shows how the factory creates a new temporary directory, optionally adding a numeric suffix to ensure uniqueness.
Integration
The Temp Path Factories subtopic is tightly integrated with the overall Temporary Directory Management parent topic by serving as the concrete mechanism for generating temporary paths that other utilities manage and clean up. It complements related subtopics by:
Providing the path infrastructure that retention and cleanup policies rely on.
Connecting with pytest’s fixture system to offer temporary directories scoped per test or session.
Enabling plugins and internal components to request temporary directories in a consistent, configurable manner.
While the parent topic handles the policy and lifecycle, Temp Path Factories handle the actual directory creation, naming, and base directory management, thus ensuring a clean separation of concerns.
Diagram
flowchart TD
A[Start Test Session] --> B[Initialize TempPathFactory from Config]
B --> C[Determine Base Temporary Directory]
C --> D[Create Unique Temp Directories per Test]
D --> E[Provide Temp Path via tmp_path Fixture]
E --> F[Test Execution Using Temp Directory]
F --> G[Track Test Outcome in Stash]
G --> H{Retention Policy?}
H -->|Failed| I[Keep Temp Directory]
H -->|Passed / None| J[Remove Temp Directory]
I --> K[Continue Testing]
J --> K
K --> L[Session Finish]
L --> M{Cleanup Base Directory if Needed}
M --> N[Remove Dead Symlinks]
N --> O[End Test Session]
This flowchart visualizes the lifecycle of temporary path creation and management per test and session, highlighting configuration, usage, retention decisions, and cleanup steps.