A temporary-directory test verifies that owned filesystem state is removed when a context exits, even if work inside it raises.
Python testing: assert temporary cleanup after a failure
Operation contract
The fixture creates one marker, captures only its owned path, then raises a validation error. After the exception is caught outside the context, the path no longer exists. This checks a cleanup boundary rather than the content of the file. It uses a generated temporary location but prints only a Boolean, so the displayed output is stable.
Failure and ownership boundary
This does not establish how cleanup behaves after process termination or power loss. On some platforms, open handles can prevent removal; tests that keep a file open should close it first. Python pathlib files: specify encoding and close the resource owner, Python pathlib reference: distinguish a path name from validated file content and Pytest fixtures: isolated files and parameterized rejection tests cover related behavior.
Working program
from pathlib import Path
from tempfile import TemporaryDirectory
owned_path = None
try:
with TemporaryDirectory() as directory:
owned_path = Path(directory) / "receipt.marker"
owned_path.write_text("pending", encoding="utf-8")
raise ValueError("invalid receipt")
except ValueError:
print("cleaned:", not owned_path.exists())Output
cleaned: TrueCosts and limits
The fixture writes and removes a tiny file. Real temporary trees cost work proportional to entry count and file size, and cleanup can fail for reasons this owned test does not exercise.
Common Mistakes
- Catch the intended error after the ownership context exits.
- Do not infer crash recovery from normal context-manager cleanup.
Connected lessons
Python pathlib files: specify encoding and close the resource owner, Python pathlib reference: distinguish a path name from validated file content, Pytest fixtures: isolated files and parameterized rejection tests.
