What if your tests could handle files safely without any messy cleanup or errors?
Why tmp_path and tmp_path_factory in PyTest? - Purpose & Use Cases
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.
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.
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.
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')
def test_file(tmp_path): file = tmp_path / 'data.txt' file.write_text('hello') # test code
You can write safe, fast tests that use real files without worrying about cleanup or conflicts.
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.
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.