0
0
PyTesttesting~3 mins

Why tmp_path and tmp_path_factory in PyTest? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your tests could handle files safely without any messy cleanup or errors?

The Scenario

Imagine you are testing a program that creates and modifies files. You try to do this manually by creating folders and files on your computer before each test, then deleting them after. It feels like a lot of work and you worry about accidentally deleting important files or leaving junk behind.

The Problem

Doing file setup and cleanup by hand is slow and easy to mess up. You might forget to delete files, causing clutter. Or tests might interfere with each other if they use the same file names. This makes your tests unreliable and your computer messy.

The Solution

pytest's tmp_path and tmp_path_factory give you fresh temporary folders automatically for each test. They handle creation and cleanup safely, so you never worry about leftover files or conflicts. Your tests stay clean and isolated.

Before vs After
Before
import os
import shutil
def test_file():
    os.mkdir('temp')
    with open('temp/data.txt', 'w') as f:
        f.write('hello')
    # test code
    shutil.rmtree('temp')
After
def test_file(tmp_path):
    file = tmp_path / 'data.txt'
    file.write_text('hello')
    # test code
What It Enables

You can write safe, fast tests that use real files without worrying about cleanup or conflicts.

Real Life Example

Testing a photo app that saves images: each test gets its own folder to save pictures, so tests don't overwrite each other's files or leave junk behind.

Key Takeaways

Automatic temporary folders: pytest creates and cleans them for you.

Isolated tests: Each test gets a fresh space to avoid conflicts.

Less manual work: No need to write setup or cleanup code for files.