Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python testing: assert temporary cleanup after a failure

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A temporary-directory test verifies that owned filesystem state is removed when a context exits, even if work inside it raises.

Download Python source kit

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

python
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

Output
cleaned: True

Costs 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.

python
tempdir-cleanup-tests
Storage details