Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 309836c

Browse files
committed
Issue #18849: Fixed a Windows-specific tempfile bug where collision with an
existing directory caused mkstemp and related APIs to fail instead of retrying. Report and fix by Vlad Shcherbina.
2 parents f7b436c + f315df3 commit 309836c

4 files changed

Lines changed: 38 additions & 0 deletions

File tree

Lib/tempfile.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,13 @@ def _mkstemp_inner(dir, pre, suf, flags):
199199
return (fd, _os.path.abspath(file))
200200
except FileExistsError:
201201
continue # try again
202+
except PermissionError:
203+
# This exception is thrown when a directory with the chosen name
204+
# already exists on windows.
205+
if _os.name == 'nt':
206+
continue
207+
else:
208+
raise
202209

203210
raise FileExistsError(_errno.EEXIST,
204211
"No usable temporary file name found")

Lib/test/test_tempfile.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,32 @@ def test_textmode(self):
373373
os.lseek(f.fd, 0, os.SEEK_SET)
374374
self.assertEqual(os.read(f.fd, 20), b"blat")
375375

376+
def test_collision_with_existing_directory(self):
377+
# _mkstemp_inner tries another name when a directory with
378+
# the chosen name already exists
379+
container_dir = tempfile.mkdtemp()
380+
try:
381+
def mock_get_candidate_names():
382+
return iter(['aaa', 'aaa', 'bbb'])
383+
with support.swap_attr(tempfile,
384+
'_get_candidate_names',
385+
mock_get_candidate_names):
386+
dir = tempfile.mkdtemp(dir=container_dir)
387+
self.assertTrue(dir.endswith('aaa'))
388+
389+
flags = tempfile._bin_openflags
390+
(fd, name) = tempfile._mkstemp_inner(container_dir,
391+
tempfile.template,
392+
'',
393+
flags)
394+
try:
395+
self.assertTrue(name.endswith('bbb'))
396+
finally:
397+
os.close(fd)
398+
os.unlink(name)
399+
finally:
400+
support.rmtree(container_dir)
401+
376402

377403
class TestGetTempPrefix(BaseTestCase):
378404
"""Test gettempprefix()."""

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,6 +1157,7 @@ Daniel Shahaf
11571157
Ha Shao
11581158
Mark Shannon
11591159
Richard Shapiro
1160+
Vlad Shcherbina
11601161
Justin Sheehy
11611162
Charlie Shepherd
11621163
Bruce Sherwood

Misc/NEWS

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,10 @@ Library
189189

190190
- Issue #8860: Fixed rounding in timedelta constructor.
191191

192+
- Issue #18849: Fixed a Windows-specific tempfile bug where collision with an
193+
existing directory caused mkstemp and related APIs to fail instead of
194+
retrying. Report and fix by Vlad Shcherbina.
195+
192196
Tests
193197
-----
194198

0 commit comments

Comments
 (0)