pytest tmp_path: Test Files Without Project Clutter addresses a recurring problem in Python projects: Create a unique directory per test and use it as a pathlib.Path object. This guide explains the mechanism, provides an executable example, and identifies the boundaries that keep an implementation reliable.

Concept and use case

tmp_path provides an isolated temporary Path. It removes global naming collisions, supports parallel execution, and lets pytest handle cleanup.

For the related fundamentals, also read the pytest guide. Integration stays simpler when functions receive dependencies and data explicitly instead of relying on global state.

Practical example

from pathlib import Path


def save_report(path: Path, rows: list[str]) -> None:
    path.write_text("\n".join(rows), encoding="utf-8")


def test_save_report(tmp_path: Path):
    output = tmp_path / "report.txt"
    save_report(output, ["alpha", "beta"])
    assert output.read_text(encoding="utf-8") == "alpha\nbeta"

Pass paths into production functions instead of discovering a global folder. Create only the required fixture files and assert content, encoding, and layout.

Important decisions

The correct choice depends on the public contract, expected volume, and failure behavior.

Consider concurrency, empty inputs, and partial failures. Document every limit that affects consumers and choose names that express intent.

Common mistakes

A minimal example does not replace bounds, error handling, and observability. Writing into the repository leaves debris and introduces order dependence. Mocking the complete file API can hide real integration mistakes.

Avoid catching exceptions without context or returning partial output as if it were complete. An explicit failure is usually safer than silently incorrect data.

How to validate

Validate behavior, not only the happy path. Run repeatedly and in parallel, include spaces and non-ASCII names, and verify behavior when an input file is absent.

The official documentation, accessed July 28, 2026, details the API and should remain the reference for future changes.