Bird
Raised Fist0
PyTesttesting~5 mins

Temporary directory management in PyTest

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using the tmp_path fixture in pytest?
easy
A. To create a temporary directory for test files that is cleaned up automatically
B. To permanently store test results on disk
C. To speed up test execution by caching files
D. To replace the need for writing assertions in tests

Solution

  1. Step 1: Understand the role of tmp_path in pytest

    The tmp_path fixture provides a temporary directory unique to each test run.
  2. Step 2: Recognize the cleanup behavior

    Files created in this directory are removed after the test finishes, keeping tests clean and isolated.
  3. Final Answer:

    To create a temporary directory for test files that is cleaned up automatically -> Option A
  4. Quick Check:

    Temporary directory = safe test files [OK]
Hint: Remember tmp_path auto-cleans test files after each test [OK]
Common Mistakes:
  • Thinking tmp_path stores files permanently
  • Confusing tmp_path with caching mechanisms
  • Believing tmp_path replaces assertions
2. Which of the following is the correct way to use the tmp_path fixture in a pytest test function?
easy
A. def test_example():\n file = tmp_path / 'test.txt'\n file.write_text('hello')
B. def test_example(tmp_path):\n file = tmp_path / 'test.txt'\n file.write_text('hello')
C. def test_example(tmp_path):\n file = open('test.txt', 'w')\n file.write('hello')
D. def test_example():\n tmp_path = '/tmp/test'\n file = tmp_path + '/test.txt'\n write(file, 'hello')

Solution

  1. Step 1: Identify correct fixture usage

    pytest injects tmp_path as a function argument automatically.
  2. Step 2: Check file creation syntax

    Using tmp_path / 'filename' creates a Path object; write_text() writes content correctly.
  3. Final Answer:

    def test_example(tmp_path):\n file = tmp_path / 'test.txt'\n file.write_text('hello') -> Option B
  4. Quick Check:

    Fixture as argument + Path write = correct [OK]
Hint: Always accept tmp_path as a test function argument [OK]
Common Mistakes:
  • Assigning tmp_path manually instead of using fixture
  • Using open() without tmp_path directory
  • Not passing tmp_path as a parameter
3. What will be the output of the following pytest test code snippet?
def test_write_read(tmp_path):
    file = tmp_path / 'data.txt'
    file.write_text('pytest')
    content = file.read_text()
    assert content == 'pytest'
medium
A. Runtime error because file is not created
B. Test fails due to assertion error
C. Syntax error in test code
D. Test passes successfully

Solution

  1. Step 1: Analyze file writing and reading

    The code writes 'pytest' to a file in tmp_path, then reads it back correctly.
  2. Step 2: Check assertion correctness

    The read content matches the written string 'pytest', so assertion passes.
  3. Final Answer:

    Test passes successfully -> Option D
  4. Quick Check:

    Write then read same text = pass [OK]
Hint: Write and read text in tmp_path matches, so assert passes [OK]
Common Mistakes:
  • Assuming file is not created automatically
  • Confusing assertion logic
  • Thinking tmp_path is a string path, not Path object
4. Identify the error in this pytest test using tmp_path:
def test_error(tmp_path):
    file = tmp_path + '/file.txt'
    file.write_text('error')
medium
A. File write_text method does not exist
B. Missing assertion statement causes test failure
C. Using + operator to join paths causes a TypeError
D. tmp_path fixture is not passed as argument

Solution

  1. Step 1: Check path joining method

    tmp_path is a Path object; using + with string causes TypeError.
  2. Step 2: Correct path joining

    Use tmp_path / 'file.txt' to join paths properly.
  3. Final Answer:

    Using + operator to join paths causes a TypeError -> Option C
  4. Quick Check:

    Path + string = error; use / operator [OK]
Hint: Join paths with / operator, not + [OK]
Common Mistakes:
  • Using + to join Path and string
  • Forgetting to pass tmp_path as parameter
  • Assuming write_text is invalid method
5. You want to create a nested directory structure inside tmp_path and write a file in the deepest folder. Which code snippet correctly does this in pytest?
hard
A. 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')
B. 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')
C. def test_nested(tmp_path):\n nested_dir = tmp_path / 'a' / 'b' / 'c'\n file = nested_dir / 'file.txt'\n file.write_text('nested')
D. 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')

Solution

  1. Step 1: Understand nested directory creation

    To create nested folders, mkdir(parents=True) is needed to create all missing parents.
  2. Step 2: Check path joining and file writing

    Using / operator joins paths correctly; writing text to file is valid.
  3. 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') misses parents=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.
  4. 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 A
  5. Quick Check:

    mkdir(parents=True) + / operator = correct [OK]
Hint: Use mkdir(parents=True) to create nested folders [OK]
Common Mistakes:
  • Not using parents=True for nested mkdir
  • Using + operator to join paths
  • Writing file before creating directories
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard