We use tmp_path and tmp_path_factory to create temporary folders during tests. This helps keep tests clean and avoids messing with real files.
0
0
tmp_path and tmp_path_factory in PyTest
Introduction
When you need a fresh folder to save files during a test.
When you want to test file creation or modification without affecting real data.
When multiple tests need separate temporary folders to avoid conflicts.
When you want to clean up files automatically after tests finish.
Syntax
PyTest
def test_example(tmp_path): # tmp_path is a pathlib.Path object for a temp directory file = tmp_path / "test.txt" file.write_text("hello") def test_factory(tmp_path_factory): # tmp_path_factory creates multiple temp directories dir1 = tmp_path_factory.mktemp("data1") dir2 = tmp_path_factory.mktemp("data2")
tmp_path gives a unique temporary directory for each test function.
tmp_path_factory lets you create multiple temporary directories if needed.
Examples
This test writes and reads a file inside a temporary folder.
PyTest
def test_write_file(tmp_path): file = tmp_path / "file.txt" file.write_text("hello world") assert file.read_text() == "hello world"
This test creates two separate temp folders and writes files in each.
PyTest
def test_multiple_dirs(tmp_path_factory): dir_a = tmp_path_factory.mktemp("a") dir_b = tmp_path_factory.mktemp("b") (dir_a / "a.txt").write_text("A") (dir_b / "b.txt").write_text("B") assert (dir_a / "a.txt").read_text() == "A" assert (dir_b / "b.txt").read_text() == "B"
Sample Program
This script has two tests. The first uses tmp_path to create and check a file. The second uses tmp_path_factory to create two folders and files inside them, then checks their contents.
PyTest
import pytest def test_tmp_path_creates_file(tmp_path): file_path = tmp_path / "sample.txt" file_path.write_text("pytest temp file") content = file_path.read_text() assert content == "pytest temp file" def test_tmp_path_factory_creates_dirs(tmp_path_factory): dir1 = tmp_path_factory.mktemp("dir1") dir2 = tmp_path_factory.mktemp("dir2") (dir1 / "file1.txt").write_text("data1") (dir2 / "file2.txt").write_text("data2") assert (dir1 / "file1.txt").read_text() == "data1" assert (dir2 / "file2.txt").read_text() == "data2"
OutputSuccess
Important Notes
Temporary folders are deleted automatically after tests finish.
Use tmp_path for simple cases needing one temp folder per test.
Use tmp_path_factory when you need multiple temp folders in one test.
Summary
tmp_path gives a fresh temp folder for each test.
tmp_path_factory lets you create many temp folders as needed.
Both help keep tests clean and avoid changing real files.