From b6b1ab4fa83c000f14bd63c92d9182fbd507d0be Mon Sep 17 00:00:00 2001 From: Martin Panter Date: Mon, 29 Feb 2016 00:31:38 +0000 Subject: [PATCH] Issue #26385: Cleanup NamedTemporaryFile if fdopen() fails, by SilentGhost --- Lib/tempfile.py | 3 ++- Lib/test/test_tempfile.py | 7 +++++++ Misc/NEWS | 3 +++ 3 files changed, 12 insertions(+), 1 deletion(-) diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 8a2e9cd8756..7e3b25a0702 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -476,7 +476,8 @@ def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="", try: file = _os.fdopen(fd, mode, bufsize) return _TemporaryFileWrapper(file, name, delete) - except: + except BaseException: + _os.unlink(name) _os.close(fd) raise diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 3d0ac57a5b0..078e4a9a2d0 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -827,6 +827,13 @@ class test_NamedTemporaryFile(TC): os.close = old_close os.fdopen = old_fdopen + def test_bad_mode(self): + dir = tempfile.mkdtemp() + self.addCleanup(support.rmtree, dir) + with self.assertRaises(TypeError): + tempfile.NamedTemporaryFile(mode=(), dir=dir) + self.assertEqual(os.listdir(dir), []) + # How to test the mode and bufsize parameters? test_classes.append(test_NamedTemporaryFile) diff --git a/Misc/NEWS b/Misc/NEWS index 012f7d70adf..ac564b77179 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -55,6 +55,9 @@ Core and Builtins Library ------- +- Issue #26385: Remove the file if the internal fdopen() call in + NamedTemporaryFile() fails. Based on patch by Silent Ghost. + - Issue #26309: In the "socketserver" module, shut down the request (closing the connected socket) when verify_request() returns false. Based on patch by Aviv Palivoda.