safe_tempdir.mojo (1272B)
1 """Non-swallowing temporary-directory context manager for tests. 2 3 On this toolchain, using the standard library's temporary-directory helper as a 4 `with` context manager suppresses an exception raised inside the body, silently 5 masking failing assertions. This wrapper delegates enter/exit to the standard 6 implementation but does not reproduce that suppression, so body exceptions 7 propagate normally. 8 9 This describes observed behavior only; the standard library's exact internal 10 mechanism is not asserted here. Use `SafeTempDir` anywhere a test currently 11 uses the standard helper as a `with` context manager. The interface is 12 identical: `__enter__` returns the temporary directory path as a `String`. 13 """ 14 15 from std.tempfile import TemporaryDirectory as _StdTemporaryDirectory 16 17 18 struct SafeTempDir: 19 var _inner: _StdTemporaryDirectory 20 21 def __init__(out self) raises: 22 self._inner = _StdTemporaryDirectory() 23 24 def __enter__(mut self) raises -> String: 25 return self._inner.__enter__() 26 27 def __exit__(mut self) raises: 28 # Delegate cleanup. The observed standard behavior suppresses a body 29 # exception at this point; this wrapper's non-suppressing exit lets the 30 # body exception propagate instead. 31 self._inner.__exit__()