Temporary directories help tests create files without messing up your real folders. They clean up automatically after tests run.
Temporary directory management in 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.
def test_write_file(tmp_path): file = tmp_path / "data.txt" file.write_text("data") assert file.read_text() == "data"
def test_create_subdir(tmp_path): subdir = tmp_path / "sub" subdir.mkdir() file = subdir / "info.txt" file.write_text("info") assert file.exists()
def test_temp_dir_is_empty(tmp_path): assert list(tmp_path.iterdir()) == []
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.
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()
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.
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.
Practice
tmp_path fixture in pytest?Solution
Step 1: Understand the role of
Thetmp_pathin pytesttmp_pathfixture provides a temporary directory unique to each test run.Step 2: Recognize the cleanup behavior
Files created in this directory are removed after the test finishes, keeping tests clean and isolated.Final Answer:
To create a temporary directory for test files that is cleaned up automatically -> Option AQuick Check:
Temporary directory = safe test files [OK]
- Thinking tmp_path stores files permanently
- Confusing tmp_path with caching mechanisms
- Believing tmp_path replaces assertions
tmp_path fixture in a pytest test function?Solution
Step 1: Identify correct fixture usage
pytest injectstmp_pathas a function argument automatically.Step 2: Check file creation syntax
Usingtmp_path / 'filename'creates a Path object;write_text()writes content correctly.Final Answer:
def test_example(tmp_path):\n file = tmp_path / 'test.txt'\n file.write_text('hello') -> Option BQuick Check:
Fixture as argument + Path write = correct [OK]
- Assigning tmp_path manually instead of using fixture
- Using open() without tmp_path directory
- Not passing tmp_path as a parameter
def test_write_read(tmp_path):
file = tmp_path / 'data.txt'
file.write_text('pytest')
content = file.read_text()
assert content == 'pytest'Solution
Step 1: Analyze file writing and reading
The code writes 'pytest' to a file in tmp_path, then reads it back correctly.Step 2: Check assertion correctness
The read content matches the written string 'pytest', so assertion passes.Final Answer:
Test passes successfully -> Option DQuick Check:
Write then read same text = pass [OK]
- Assuming file is not created automatically
- Confusing assertion logic
- Thinking tmp_path is a string path, not Path object
tmp_path:def test_error(tmp_path):
file = tmp_path + '/file.txt'
file.write_text('error')Solution
Step 1: Check path joining method
tmp_pathis a Path object; using + with string causes TypeError.Step 2: Correct path joining
Usetmp_path / 'file.txt'to join paths properly.Final Answer:
Using + operator to join paths causes a TypeError -> Option CQuick Check:
Path + string = error; use / operator [OK]
- Using + to join Path and string
- Forgetting to pass tmp_path as parameter
- Assuming write_text is invalid method
tmp_path and write a file in the deepest folder. Which code snippet correctly does this in pytest?Solution
Step 1: Understand nested directory creation
To create nested folders,mkdir(parents=True)is needed to create all missing parents.Step 2: Check path joining and file writing
Using/operator joins paths correctly; writing text to file is valid.Step 3: Identify errors in other options
def test_nested(tmp_path):\n nested_dir = tmp_path / 'a' / 'b' / 'c'\n nested_dir.mkdir()\n file = nested_dir / 'file.txt'\n file.write_text('nested') missesparents=True, so mkdir fails if parents missing. def test_nested(tmp_path):\n nested_dir = tmp_path / 'a' / 'b' / 'c'\n file = nested_dir / 'file.txt'\n file.write_text('nested') does not create directories before writing file. def test_nested(tmp_path):\n nested_dir = tmp_path + '/a/b/c'\n nested_dir.mkdir(parents=True)\n file = nested_dir / 'file.txt'\n file.write_text('nested') uses + operator incorrectly for paths.Final Answer:
def test_nested(tmp_path):\n nested_dir = tmp_path / 'a' / 'b' / 'c'\n nested_dir.mkdir(parents=True)\n file = nested_dir / 'file.txt'\n file.write_text('nested') -> Option AQuick Check:
mkdir(parents=True) + / operator = correct [OK]
- Not using parents=True for nested mkdir
- Using + operator to join paths
- Writing file before creating directories
Ready to prove it?
Pass the test and this pattern moves unknown
