Batu Lab NotesPractical developer guides

Test filesystem failure paths without changing permissions

By Batu ยท English technical notes

Also published in our Blogger archive.

Trigger a write failure using a temporary directory

Path.write_text tries to open its target for text output. A directory made in TemporaryDirectory supplies a controlled failure without changing permissions or touching a user path. The handler catches OSError and prints a stable kind.

It intentionally does not claim a particular subclass such as IsADirectoryError: filesystem implementations can report the directory condition through OSError subclasses differently. This one failure does not simulate full storage, quotas, ACLs, or network filesystem behavior.

Example

from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
    target = Path(d) / 'directory'
    target.mkdir()
    try:
        target.write_text('x')
    except OSError:
        result = 'kind=write-failed'
    print(result)

Expected stdout:

kind=write-failed

Sources

- pathlib.Path.write_text

- OSError

Prepared with AI assistance. The example uses synthetic data; its stated limits apply.