0
0
PytestHow-ToBeginner ยท 4 min read

How to Use tmpdir Fixture in pytest for Temporary Directories

In pytest, the tmpdir fixture provides a temporary directory unique to each test function. You can use it by adding tmpdir as a parameter to your test, then create files or folders inside it safely without affecting your real file system.
๐Ÿ“

Syntax

The tmpdir fixture is used by declaring it as a parameter in your test function. It provides a py.path.local object representing a temporary directory.

  • tmpdir.mkdir("subfolder"): creates a subdirectory.
  • tmpdir.join("file.txt"): creates a file path inside the temp directory.
  • .write("text"): writes text to a file.
python
def test_example(tmpdir):
    sub = tmpdir.mkdir("subfolder")
    file = sub.join("testfile.txt")
    file.write("hello")
    assert file.read() == "hello"
๐Ÿ’ป

Example

This example shows how to use tmpdir to create a temporary file, write data, and verify its contents. The temporary directory and files are removed automatically after the test finishes.

python
def test_write_and_read(tmpdir):
    temp_file = tmpdir.join("sample.txt")
    temp_file.write("pytest tmpdir example")
    content = temp_file.read()
    assert content == "pytest tmpdir example"
Output
============================= test session starts ============================== collected 1 item test_tmpdir_example.py . [100%] ============================== 1 passed in 0.03s ===============================
โš ๏ธ

Common Pitfalls

Common mistakes when using tmpdir include:

  • Not using tmpdir as a test function parameter, so pytest won't inject it.
  • Trying to use tmpdir outside test functions or fixtures.
  • Confusing tmpdir with tmp_path (the newer pathlib-based fixture).

Always use tmpdir inside test functions and avoid hardcoding paths.

python
import os

def test_wrong_usage():
    # Wrong: tmpdir not passed as parameter
    temp_dir = tmpdir  # NameError: tmpdir is not defined

# Correct usage:
def test_right_usage(tmpdir):
    file = tmpdir.join("file.txt")
    file.write("data")
    assert file.read() == "data"
๐Ÿ“Š

Quick Reference

ActionMethodDescription
Create subdirectorytmpdir.mkdir("name")Creates a new folder inside the temp directory
Create file pathtmpdir.join("filename")Returns a file path object inside temp directory
Write to filefile.write("text")Writes text content to the file
Read from filefile.read()Reads text content from the file
Get path stringstr(tmpdir)Returns the string path of the temp directory
โœ…

Key Takeaways

Use tmpdir by adding it as a parameter to your test function to get a temporary directory.
tmpdir allows safe creation of files and folders that are deleted after tests run.
Always write and read files using tmpdir.join() and its methods to avoid path errors.
Do not use tmpdir outside test functions or without declaring it as a parameter.
Consider tmp_path fixture for pathlib-based temporary directories in newer pytest versions.