0
0
PytestHow-ToBeginner ยท 4 min read

How to Use tmp_path Fixture in pytest for Temporary Files

In pytest, the tmp_path fixture provides a temporary directory as a pathlib.Path object for your tests. Use it by adding tmp_path as a test function argument, then create files or folders inside it. This directory is unique per test and is removed after the test finishes.
๐Ÿ“

Syntax

The tmp_path fixture is used by adding it as a parameter to your test function. It gives you a pathlib.Path object pointing to a temporary directory.

You can then use standard pathlib methods to create files or directories inside this temporary folder.

python
def test_example(tmp_path):
    # tmp_path is a pathlib.Path object
    file = tmp_path / "testfile.txt"
    file.write_text("Hello, pytest!")
    assert file.read_text() == "Hello, pytest!"
๐Ÿ’ป

Example

This example shows how to create a temporary file inside the tmp_path directory, write text to it, and then read it back to verify the content.

python
import pytest

def test_write_and_read(tmp_path):
    temp_file = tmp_path / "sample.txt"
    temp_file.write_text("pytest tmp_path example")
    content = temp_file.read_text()
    assert content == "pytest tmp_path example"
Output
============================= test session starts ============================== collected 1 item test_tmp_path_example.py . [100%] ============================== 1 passed in 0.01s ===============================
โš ๏ธ

Common Pitfalls

  • Not using tmp_path as a test argument: The fixture only works if you declare it as a parameter in your test function.
  • Assuming the path is a string: tmp_path is a pathlib.Path object, so use pathlib methods instead of string operations.
  • Not cleaning up files manually: You don't need to delete files or directories created inside tmp_path because pytest removes them automatically after the test.
python
def test_wrong_usage():
    # Wrong: tmp_path not declared as parameter
    # tmp_path is undefined here and will cause an error
    pass


def test_string_usage(tmp_path):
    # Wrong: treating tmp_path as string
    # This will raise AttributeError
    try:
        tmp_path.write_text("text")
    except AttributeError:
        pass  # Correct way is to use tmp_path / 'filename' to write files


def test_correct_usage(tmp_path):
    file = tmp_path / "file.txt"
    file.write_text("correct usage")
    assert file.read_text() == "correct usage"
๐Ÿ“Š

Quick Reference

tmp_path fixture key points:

  • Provides a pathlib.Path object to a unique temporary directory.
  • Directory and contents are deleted after the test finishes.
  • Use tmp_path / 'filename' to create files.
  • Works only when declared as a test function argument.
FeatureDescription
Typepathlib.Path object
ScopeUnique temporary directory per test
CleanupAutomatic after test ends
UsageDeclare as test function parameter
File creationUse / operator to join paths
โœ…

Key Takeaways

Always declare tmp_path as a parameter in your test function to use it.
tmp_path gives a pathlib.Path object pointing to a temporary directory unique to each test.
Create files inside tmp_path using pathlib methods like / operator and write_text().
pytest automatically cleans up the tmp_path directory after the test finishes.
Avoid treating tmp_path as a string; use pathlib.Path methods for file operations.