Skip to content

bpo-43153: Don't mask PermissionError with NotADirectoryError during tempdirectory cleanup #29940

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Dec 5, 2023
Merged
9 changes: 8 additions & 1 deletion Lib/tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -822,8 +822,15 @@ def resetperms(path):

try:
_os.unlink(path)
except IsADirectoryError:
cls._rmtree(path, ignore_errors=ignore_errors)
# PermissionError is raised on FreeBSD for directories
except (IsADirectoryError, PermissionError):
except PermissionError:
# On Windows, _rmtree will cause IsADirectoryError
if _os.name == 'nt' and _os.path.isfile(path):
if ignore_errors:
return
raise
cls._rmtree(path, ignore_errors=ignore_errors)
except FileNotFoundError:
pass
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_tempfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1460,6 +1460,16 @@ def test_explict_cleanup_ignore_errors(self):
temp_path.exists(),
f"TemporaryDirectory {temp_path!s} exists after cleanup")

@unittest.skipUnless(os.name == "nt", "Only on Windows.")
def test_explicit_cleanup_correct_error(self):
with tempfile.TemporaryDirectory() as working_dir:
temp_dir = self.do_create(dir=working_dir)
with open(os.path.join(temp_dir.name, "example.txt"), 'wb'):
# Used to raise IsADirectoryError on Windows.
with self.assertRaises(PermissionError):
temp_dir.cleanup()


@os_helper.skip_unless_symlink
def test_cleanup_with_symlink_to_a_directory(self):
# cleanup() should not follow symlinks to directories (issue #12464)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
On Windows, ``tempfile.TemporaryDirectory`` previously masked a
``PermissionError`` with ``NotADirectoryError`` during directory cleanup. It
now correctly raises ``PermissionError`` if errors are not ignored. Patch by
Andrei Kulakov and Ken Jin.