Skip to content

Commit 7869a22

Browse files
committed
Issue #26385: Cleanup NamedTemporaryFile if open() fails, by SilentGhost
1 parent 96421d6 commit 7869a22

3 files changed

Lines changed: 14 additions & 2 deletions

File tree

Lib/tempfile.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -552,7 +552,8 @@ def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None,
552552
newline=newline, encoding=encoding)
553553

554554
return _TemporaryFileWrapper(file, name, delete)
555-
except Exception:
555+
except BaseException:
556+
_os.unlink(name)
556557
_os.close(fd)
557558
raise
558559

Lib/test/test_tempfile.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -948,8 +948,16 @@ def close(fd):
948948
self.assertRaises(ValueError, tempfile.NamedTemporaryFile)
949949
self.assertEqual(len(closed), 1)
950950

951-
# How to test the mode and bufsize parameters?
951+
def test_bad_mode(self):
952+
dir = tempfile.mkdtemp()
953+
self.addCleanup(support.rmtree, dir)
954+
with self.assertRaises(ValueError):
955+
tempfile.NamedTemporaryFile(mode='wr', dir=dir)
956+
with self.assertRaises(TypeError):
957+
tempfile.NamedTemporaryFile(mode=2, dir=dir)
958+
self.assertEqual(os.listdir(dir), [])
952959

960+
# How to test the mode and bufsize parameters?
953961

954962
class TestSpooledTemporaryFile(BaseTestCase):
955963
"""Test SpooledTemporaryFile()."""

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,9 @@ Core and Builtins
8484
Library
8585
-------
8686

87+
- Issue #26385: Remove the file if the internal open() call in
88+
NamedTemporaryFile() fails. Patch by Silent Ghost.
89+
8790
- Issue #26402: Fix XML-RPC client to retry when the server shuts down a
8891
persistent connection. This was a regression related to the new
8992
http.client.RemoteDisconnected exception in 3.5.0a4.

0 commit comments

Comments
 (0)