brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python pytest's tmp_path gives every test its own empty folder

Python
~/tips/tip-python-pytest-tmp-path

def save_report(folder, text):

Test code that writes files without touching real folders or cleaning up yourself.

Tests for code that writes files easily leave junk behind on disk. Asking pytest for the tmp_path fixture solved that.

def save_report(folder, text):
    (folder / "report.txt").write_text(text)

def test_save_report(tmp_path):
    save_report(tmp_path, "ok")
    assert (tmp_path / "report.txt").read_text() == "ok"

Put tmp_path in the test’s arguments and pytest passes in a fresh, empty pathlib.Path that’s unique to that test. Your code writes there, you check the result, and no two tests ever see each other’s files.

It works best when the code under test takes the folder as an argument instead of using a hard coded path like /var/lib/myapp. Making that change is good for the code anyway, and the test becomes trivial.

One thing I find surprising: pytest doesn’t delete the folder right after the test. It keeps the folders of the last three runs under a base temp directory so you can look at the files of a failing test afterwards, and cleans up older ones. If you want to know where they are, print tmp_path in the test and run with -s. Don’t rely on the folder still being there later, though, since the next runs will rotate it away.

Further reading: pytest: tmp_path

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link