0
0
PyTesttesting~5 mins

Temporary directory management in PyTest

Choose your learning style9 modes available
Introduction

Temporary directories help tests create files without messing up your real folders. They clean up automatically after tests run.

When you need to test file creation or modification without affecting real files.
When your test needs a clean folder to work in each time it runs.
When you want to avoid manual cleanup of test files after tests finish.
When testing code that reads or writes files in a directory.
When you want to isolate test data to prevent interference between tests.
Syntax
PyTest
def test_example(tmp_path):
    # tmp_path is a pathlib.Path object for a temp directory
    file = tmp_path / "testfile.txt"
    file.write_text("hello")
    assert file.read_text() == "hello"

tmp_path is a built-in pytest fixture that gives a temporary directory as a pathlib.Path object.

The temporary directory is unique for each test and is deleted after the test finishes.

Examples
Create and write a file inside the temporary directory, then check its content.
PyTest
def test_write_file(tmp_path):
    file = tmp_path / "data.txt"
    file.write_text("data")
    assert file.read_text() == "data"
Create a subfolder inside the temp directory and add a file there.
PyTest
def test_create_subdir(tmp_path):
    subdir = tmp_path / "sub"
    subdir.mkdir()
    file = subdir / "info.txt"
    file.write_text("info")
    assert file.exists()
Check that the temporary directory starts empty for each test.
PyTest
def test_temp_dir_is_empty(tmp_path):
    assert list(tmp_path.iterdir()) == []
Sample Program

This test uses pytest's tmp_path fixture to create a temporary directory. It writes a file, reads it back, and checks the content and existence. The temp directory and file are removed after the test.

PyTest
import pytest

def test_temp_directory(tmp_path):
    # Create a new file in the temp directory
    file_path = tmp_path / "sample.txt"
    file_path.write_text("pytest temp dir test")

    # Read the file content
    content = file_path.read_text()

    # Assert the content is correct
    assert content == "pytest temp dir test"

    # Assert the file exists
    assert file_path.exists()
OutputSuccess
Important Notes

Use tmp_path for pathlib.Path objects or tmpdir for older py.path objects.

Temporary directories are unique per test, so tests won't interfere with each other's files.

Always use these fixtures instead of hardcoding temp paths to avoid leftover files.

Summary

Temporary directories keep test files isolated and clean up automatically.

Use pytest's tmp_path fixture to get a temp directory as a pathlib.Path object.

Write and read files inside this directory to test file-related code safely.