diff --git a/Lib/tempfile.py b/Lib/tempfile.py index b7439a2..e79c61b 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -661,6 +661,7 @@ class TemporaryDirectory(object): _listdir = staticmethod(_os.listdir) _path_join = staticmethod(_os.path.join) _isdir = staticmethod(_os.path.isdir) + _islink = staticmethod(_os.path.islink) _remove = staticmethod(_os.remove) _rmdir = staticmethod(_os.rmdir) _os_error = _os.error @@ -672,7 +673,8 @@ class TemporaryDirectory(object): for name in self._listdir(path): fullname = self._path_join(path, name) try: - isdir = self._isdir(fullname) + # Don't recurse to symlinked directories (issue #12464) + isdir = self._isdir(fullname) and not self._islink(fullname) except self._os_error: isdir = False if isdir: diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 2d29885..68a45d5 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -964,6 +964,23 @@ class test_TemporaryDirectory(TC): finally: os.rmdir(dir) + def test_cleanup_with_symlink_to_a_directory(self): + # cleanup() should not follow symlinks to directories (issue #12464) + d1 = self.do_create() + d2 = self.do_create() + + # Symlink d1/foo -> d2 + os.symlink(d2.name, os.path.join(d1.name, "foo")) + + d1.cleanup() + + self.assertFalse(os.path.exists(d1.name), + "TemporaryDirectory %s exists after cleanup" % d1.name) + self.assertTrue(os.path.exists(d2.name), + "Directory pointed to by a symlink was deleted") + + d2.cleanup() + @support.cpython_only def test_del_on_collection(self): # A TemporaryDirectory is deleted when garbage collected