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