diff --git a/Lib/pathlib/_abc.py b/Lib/pathlib/_abc.py index b83d616f097284..2668a5ed903cd2 100644 --- a/Lib/pathlib/_abc.py +++ b/Lib/pathlib/_abc.py @@ -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() diff --git a/Lib/test/test_pathlib/test_pathlib_abc.py b/Lib/test/test_pathlib/test_pathlib_abc.py index e4fd0fd9339c4f..882368ab868c73 100644 --- a/Lib/test/test_pathlib/test_pathlib_abc.py +++ b/Lib/test/test_pathlib/test_pathlib_abc.py @@ -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' @@ -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'