tmp_path.rst

Overview

This documentation describes the usage and behavior of the `tmp_path` and related fixtures provided by `pytest` for managing temporary directories and files during test execution. These fixtures simplify the creation and handling of isolated file-system resources that are unique per test function, facilitating safe and clean testing of code involving file operations.

The file explains the purpose, usage, and retention policies of the `tmp_path` fixture, its session-scoped counterpart `tmp_path_factory`, as well as the legacy `tmpdir` and `tmpdir_factory` fixtures. It also details the location and lifecycle management of temporary directories created by these fixtures.

Key functionalities covered:

Detailed Descriptions

The tmp_path Fixture

**Purpose:** The `tmp_path` fixture provides a temporary directory unique to each test function. It is a convenient and modern way to handle temporary file-system resources using Python's standard `pathlib.Path` API.

**Type:** `pathlib.Path` object

**Usage Example:**

CONTENT = "content"

def test_create_file(tmp_path):
    d = tmp_path / "sub"
    d.mkdir()
    p = d / "hello.txt"
    p.write_text(CONTENT, encoding="utf-8")
    assert p.read_text(encoding="utf-8") == CONTENT
    assert len(list(tmp_path.iterdir())) == 1

Here, `tmp_path` is a directory provided by `pytest`. The test creates a subdirectory and a file within it, writes content, and verifies the expected results.

**Important Details:**


The tmp_path_factory Fixture

**Purpose:** `tmp_path_factory` is a session-scoped fixture that allows creation of arbitrary temporary directories from any fixture or test. This is useful when generating expensive or large data once per test session rather than per test function.

**Usage Example:**

# conftest.py
import pytest

@pytest.fixture(scope="session")
def image_file(tmp_path_factory):
    img = compute_expensive_image()
    fn = tmp_path_factory.mktemp("data") / "img.png"
    img.save(fn)
    return fn

# test_image.py
def test_histogram(image_file):
    img = load_image(image_file)
    # compute and test histogram

**Important Details:**


The tmpdir and tmpdir_factory Fixtures (Legacy)

**Purpose:** Legacy fixtures similar to `tmp_path` and `tmp_path_factory`, but return `py.path.local` objects instead of `pathlib.Path`.

**Notes:**


Temporary Directory Location and Retention

**Default Location Template:**

{temproot}/pytest-of-{user}/pytest-{num}/{testname}/

**Retention:**

**Using `--basetemp` option:**

{basetemp}/{testname}/

**Interaction with `pytest-xdist`:**


Implementation and Algorithms


Interactions with Other Parts of the System


Visual Diagram: Mermaid Class and Fixture Interaction Diagram

classDiagram
    class tmp_path {
        +pathlib.Path directory
        +create_subdir(name)
        +write_text(file, content)
        +read_text(file)
    }

    class tmp_path_factory {
        +mktemp(name): pathlib.Path
    }

    class tmpdir {
        +py.path.local directory
    }

    class tmpdir_factory {
        +mktemp(name): py.path.local
    }

    tmp_path_factory --|> tmp_path : creates
    tmpdir_factory --|> tmpdir : creates
    tmp_path ..|> pathlib.Path
    tmpdir ..|> py.path.local

This diagram shows the relationship between the primary fixtures, their types, and their factory counterparts. `tmp_path` and `tmp_path_factory` use the modern `pathlib.Path`, while `tmpdir` and `tmpdir_factory` use the legacy `py.path.local` objects.


Summary

The [tmp_path.rst](/projects/286/67363) file serves as an authoritative guide on how pytest manages temporary directories and files for testing. It advocates the use of `tmp_path` and `tmp_path_factory` fixtures for modern, pathlib-based temporary file handling, explains legacy alternatives, and clarifies the configuration, retention, and lifecycle of these temporary resources. By using these fixtures, test authors can write cleaner, safer tests involving filesystem operations with automatic cleanup and isolation.


**End of Documentation**