Skip to content

Commit

Permalink
Ensure we exit from copytree() when copying directory over itself.
Browse files Browse the repository at this point in the history
  • Loading branch information
barneygale committed Jul 27, 2024
1 parent f9219ee commit 5ad2c1d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions Lib/pathlib/_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,6 +851,7 @@ def on_error(err):
raise OSError(f"Cannot copy {self!r} inside itself: {target!r}")
except OSError as err:
on_error(err)
return
stack = [(self, target)]
while stack:
source_dir, target_dir = stack.pop()
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/test_pathlib/test_pathlib_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1825,6 +1825,12 @@ def test_copy_empty(self):
self.assertTrue(target.exists())
self.assertEqual(target.read_bytes(), b'')

def test_copy_to_itself(self):
base = self.cls(self.base)
source = base / 'empty'
source.write_bytes(b'')
self.assertRaises(OSError, source.copy, source)

def test_copytree_simple(self):
base = self.cls(self.base)
source = base / 'dirC'
Expand Down Expand Up @@ -1908,6 +1914,19 @@ def test_copytree_to_existing_directory_dirs_exist_ok(self):
self.assertTrue(target.joinpath('fileC').read_text(),
"this is file C\n")

def test_copytree_to_itself(self):
base = self.cls(self.base)
source = base / 'dirC'
self.assertRaises(OSError, source.copytree, source)

def test_copytree_to_itself_on_error(self):
base = self.cls(self.base)
source = base / 'dirC'
errors = []
source.copytree(source, on_error=errors.append)
self.assertEqual(len(errors), 1)
self.assertIsInstance(errors[0], OSError)

def test_copytree_file(self):
base = self.cls(self.base)
source = base / 'fileA'
Expand Down

0 comments on commit 5ad2c1d

Please sign in to comment.