From 5a3908d003dcf08ab2c5e5e29e3aae8dcff0fe58 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:21:24 -0800 Subject: [PATCH 1/7] Remove a folder in one request, and only an empty one without recursive - fs.rm(path, recursive=True) on a folder lists what is in it once and then trashes or deletes the folder with one request, instead of one request per file and folder. It raises PermissionError and removes nothing when this account cannot remove some of the contents. - fs.rm(folder) and fs.rm_file(folder) without recursive removed the folder and everything in it. They now remove it only when it is empty, like rmdir, and raise OSError(ENOTEMPTY) otherwise. - A Drive root alias cannot be removed. - The live test tree is deleted for good at teardown, not trashed. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 8 ++ pydrive2/fs/spec.py | 95 ++++++++++++++++++-- pydrive2/test/test_fs.py | 119 +++++++++++++++++++++++++- pydrive2/test/test_fs_registration.py | 7 +- pydrive2/test/test_fs_unit.py | 111 ++++++++++++++++-------- 5 files changed, 294 insertions(+), 46 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..b058e4b2 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -58,6 +58,14 @@ the granted scopes alongside the token. Drive checks emptiness and performs the removal in separate requests, so coordinate concurrent writers when using this operation. +``fs.rm(path)`` and ``fs.rm_file(path)`` remove a folder the same way: only +when it is empty. ``fs.rm(path, recursive=True)`` removes a folder and +everything in it with one request, moving it to the trash or deleting it +for good as ``trash_only`` says. It first lists the folder's contents and +raises ``PermissionError``, removing nothing, if this account cannot remove +some of them, such as files that other people own. A Drive root cannot be +removed. + One root per filesystem ----------------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac47994b..07511638 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1495,13 +1495,96 @@ def _check_empty_folder(self, item_id, path): path, ) - def rm_file(self, path): - _, base = self._split_mounted_path(path) - match, _ = self._lookup_path(base) - item_id = _select_item_id(path, match.ids) - known_folder = item_id in match.folders + def rm(self, path, recursive=False, maxdepth=None): + """Remove files, and with recursive=True whole folders. + + A folder is removed with one request, after a listing checks that + this account can remove everything in it. + """ + if not recursive or maxdepth is not None: + super().rm(path, recursive=recursive, maxdepth=maxdepth) + return + removed: list[str] = [] + # A folder sorts before what is in it, which goes with the folder. + for item in sorted(self.expand_path(path)): + if any(item.startswith(folder + "/") for folder in removed): + continue + self._refuse_root_alias(item) + item_id, is_folder = self._lookup_item(item) + if is_folder: + self._remove_folder(item_id, item) + removed.append(item.rstrip("/")) + else: + self._gdrive_delete_file(item_id) + self._invalidate_folder(item_id, item, known_folder=False) + + def _refuse_root_alias(self, path): + root, base = self._split_mounted_path(path) + if not base and root in _ROOT_ALIASES: + raise PermissionError( + errno.EPERM, "Cannot remove a Drive root", path + ) + + def _remove_folder(self, item_id, path): + capability = "canTrash" if self._trash_only else "canDelete" + action = "moved to the trash" if self._trash_only else "deleted" + folder = self.client.CreateFile({"id": item_id}) + with _translate_not_found(path): + _gdrive_retry_repeatable(folder.FetchMetadata)( + fields=f"driveId,capabilities/{capability}" + ) + if folder.get("driveId") == item_id: + raise PermissionError( + errno.EPERM, "Cannot remove a Drive root", path + ) + if not folder.get("capabilities", {}).get(capability): + raise PermissionError( + errno.EACCES, f"This account cannot have it {action}", path + ) + stays = self._items_that_would_stay(item_id, path, capability) + if stays: + raise PermissionError( + errno.EACCES, + f"Nothing was removed: {len(stays)} item(s) in the folder " + f"cannot be {action} by this account, such as {stays[0]}", + path, + ) self._gdrive_delete_file(item_id) - self._invalidate_folder(item_id, path, known_folder=known_folder) + self._invalidate_folder(item_id, path, known_folder=True) + + def _items_that_would_stay(self, folder_id, path, capability): + """Paths below a folder that removing the folder would not remove.""" + fields = ( + "nextPageToken,incompleteSearch," + f"files(id,name,mimeType,parents,capabilities/{capability})" + ) + stays = [] + frontier = {folder_id: path.rstrip("/")} + visited = set(frontier) + while frontier: + batch = dict(islice(frontier.items(), _MAX_QUERY_TERMS)) + for parent in batch: + del frontier[parent] + for item in self._query_children(batch, fields=fields): + parents = [p for p in item.get("parents", ()) if p in batch] + parent_path = batch[parents[0]] if parents else path + item_path = posixpath.join(parent_path, item["name"]) + if not item.get("capabilities", {}).get(capability): + stays.append(item_path) + is_folder = item["mimeType"] == FOLDER_MIME_TYPE + if is_folder and item["id"] not in visited: + visited.add(item["id"]) + frontier[item["id"]] = item_path + return stays + + def rm_file(self, path): + self._refuse_root_alias(path) + item_id, is_folder = self._lookup_item(path) + # Like rmdir, a folder is removed only when it is empty. + self._gdrive_delete_file( + item_id, empty_directory=path if is_folder else None + ) + self._invalidate_folder(item_id, path, known_folder=is_folder) def _gdrive_delete_file(self, item_id, *, empty_directory=None): attempts = count() diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..745a6f21 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -13,6 +13,7 @@ from googleapiclient.http import HttpRequest from pydrive2.drive import GoogleDrive +from pydrive2.files import ApiRequestError from pydrive2.fs import GDriveFileSystem from pydrive2.test.test_util import ( GDRIVE_USER_CREDENTIALS_DATA, @@ -53,8 +54,9 @@ def _create_fs(): yield _create_fs GDriveFileSystem.cachable = True - fs = GDriveFileSystem(base_remote_dir, service_auth) - fs.rm_file(base_remote_dir) + # Delete for good, so test runs do not fill the trash. + fs = GDriveFileSystem(base_remote_dir, service_auth, trash_only=False) + fs.rm(base_remote_dir, recursive=True) @pytest.fixture @@ -734,3 +736,116 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( fs.cp_file(f"root/{workspace_files}-link", remote_dir + "/copy") assert len(lost) == 1 assert items_below(fs_factory()[0], remote_dir) == ["copy"] + + +@pytest.fixture +def sent_requests(service_auth, monkeypatch): + """The method and path of every request this thread sends to Drive.""" + http = service_auth.Get_Http_Object() + send = http.request + sent = [] + + def request(uri, method="GET", **kwargs): + sent.append((method, urlsplit(uri).path)) + return send(uri, method, **kwargs) + + monkeypatch.setattr(http, "request", request) + monkeypatch.setattr(service_auth.thread_local, "http", http, raising=False) + return sent + + +def make_tree(fs, path): + fs.pipe_file(path + "/a.txt", b"a") + fs.pipe_file(path + "/b.txt", b"b") + fs.pipe_file(path + "/sub/c.txt", b"c") + + +@pytest.fixture +def tree_in_my_drive(service_auth, request): + """A folder in the root of My Drive with a.txt and sub/c.txt. + + Returns its path and the IDs of everything in it. + """ + drive = GoogleDrive(service_auth) + ids = {} + + def create(name, parent, folder=False): + metadata = {"name": name, "parents": [parent]} + if folder: + metadata["mimeType"] = "application/vnd.google-apps.folder" + item = drive.CreateFile(metadata) + if not folder: + item.SetContentString(name) + pydrive_retry(item.Upload) + ids[name] = item["id"] + return item["id"] + + name = uuid.uuid4().hex + top = create(name, "root", folder=True) + create("a.txt", top) + create("c.txt", create("sub", top, folder=True)) + + def delete_what_is_left(): + try: + pydrive_retry(drive.CreateFile({"id": top}).Delete) + except ApiRequestError as error: + if error.error["code"] != 404: + raise + + request.addfinalizer(delete_what_is_left) + return "root/" + name, ids + + +@pytest.mark.parametrize( + ("trash_only", "removed_file"), + [(True, "is in the trash"), (False, "is gone")], + ids=["trash", "delete"], +) +def test_rm_recursive_removes_a_folder_tree_with_one_write( + service_auth, tree_in_my_drive, sent_requests, trash_only, removed_file +): + path, ids = tree_in_my_drive + fs = GDriveFileSystem("root", service_auth, trash_only=trash_only) + + fs.rm(path, recursive=True) + + writes = [request for request in sent_requests if request[0] != "GET"] + assert len(writes) == 1 + assert len(sent_requests) <= 5 + assert not GDriveFileSystem("root", service_auth).exists(path) + for file_id in ids.values(): + assert state_on_drive(service_auth, file_id) == removed_file + + +def state_on_drive(service_auth, file_id): + item = GoogleDrive(service_auth).CreateFile({"id": file_id}) + try: + pydrive_retry(item.FetchMetadata, fields="trashed") + except ApiRequestError as error: + if error.error["code"] == 404: + return "is gone" + raise + return "is in the trash" if item["trashed"] else "is in place" + + +def test_rm_without_recursive_of_a_folder_with_files_raises_and_keeps_them( + fs, fs_factory, remote_dir +): + make_tree(fs, remote_dir + "/tree") + with pytest.raises(OSError) as error: + fs.rm(remote_dir + "/tree") + assert error.value.errno == errno.ENOTEMPTY + kept = fs_factory()[0].find(remote_dir + "/tree") + assert [path.removeprefix(remote_dir) for path in kept] == [ + "/tree/a.txt", + "/tree/b.txt", + "/tree/sub/c.txt", + ] + + +def test_rm_without_recursive_of_an_empty_folder_removes_it( + fs, fs_factory, remote_dir +): + fs.makedirs(remote_dir + "/empty") + fs.rm(remote_dir + "/empty") + assert not fs_factory()[0].exists(remote_dir + "/empty") diff --git a/pydrive2/test/test_fs_registration.py b/pydrive2/test/test_fs_registration.py index 342ff2ea..65040c15 100644 --- a/pydrive2/test/test_fs_registration.py +++ b/pydrive2/test/test_fs_registration.py @@ -213,7 +213,10 @@ def test_file_id_errors(mock_drive, tmp_path, method, status, reason): def test_trashed_file_id_is_absent_from_metadata(mock_drive): trashed = {"mimeType": "text/plain", "trashed": True} drive, requests = mock_drive( - response({"trashed": True}), response(trashed), response(trashed) + response({"mimeType": "text/plain"}), + response({"trashed": True}), + response(trashed), + response(trashed), ) fs, path = fsspec.core.url_to_fs("gdrive://FiLe", google_auth=drive.auth) fs.rm_file(path) @@ -221,7 +224,7 @@ def test_trashed_file_id_is_absent_from_metadata(mock_drive): with pytest.raises(FileNotFoundError) as error: fs.info(path) assert error.value.filename == path - trash, *metadata = requests + _, trash, *metadata = requests assert trash[1] == "PATCH" assert json.loads(trash[2]) == {"trashed": True} assert all( diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..ee19d9b0 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -470,6 +470,8 @@ def test_folder_mutations_release_old_names_under_duplicate_parents( replies.append(listing()) # The destination does not exist. item_id = "D" if operation == "rename" else f"D{i}" replies.append(listing(dict(folder(old, item_id), parents=["A"]))) + if operation == "remove": + replies.append(listing()) # The folder is empty. replies.append( response(folder(new, item_id) if operation == "rename" else {}) ) @@ -587,32 +589,6 @@ def test_find_missing_path_uses_one_lookup(mock_drive, bare): assert ("q" in query(lookup)) == (not bare) -def test_recursive_remove_does_not_relist_each_directory(mock_drive): - sub = dict(folder("sub", "S"), parents=["D"]) - file = { - "name": "file", - "id": "F", - "mimeType": "text/plain", - "parents": ["S"], - } - drive, requests = mock_drive( - listing(folder("dir", "D")), - listing(sub), - listing(file), - listing(file), - response({}), - response({}), - response({}), - ) - fs = filesystem(drive, trash_only=False) - fs.rm("root/dir", recursive=True) - assert [req[1] for req in requests] == ["GET"] * 4 + ["DELETE"] * 3 - assert [ - urlsplit(req[0]).path.rsplit("/", 1)[-1] for req in requests[-3:] - ] == ["F", "S", "D"] - assert all("q" in query(req) for req in requests[:4]) - - def batch_child(parent): return { "id": f"file-{parent}", @@ -1545,10 +1521,20 @@ def test_ambiguous_parent_row_cannot_hide_a_file_at_the_root_alias(mock_drive): @pytest.mark.parametrize("operation", ["trash", "rename"]) def test_directory_mutation_evicts_descendants_only(mock_drive, operation): moved = folder("renamed", "dir-id") + child = dict( + folder("child", "child-id"), + parents=["dir-id"], + capabilities={"canTrash": True}, + ) mutation = ( [listing(), response(moved)] if operation == "rename" - else [response({})] + else [ + response({"capabilities": {"canTrash": True}}), + listing(child), + listing(), + response({}), + ] ) drive, requests = mock_drive( listing(folder("dir", "dir-id")), @@ -1566,8 +1552,9 @@ def test_directory_mutation_evicts_descendants_only(mock_drive, operation): assert [r[1] for r in requests[before:]] == ["GET", "PATCH"] assert "name='renamed'" in query(requests[before])["q"][0] else: - fs.rm_file("root/dir") - assert [r[1] for r in requests[before:]] == ["PATCH"] + fs.rm("root/dir", recursive=True) + methods = [r[1] for r in requests[before:]] + assert methods == ["GET", "GET", "GET", "PATCH"] assert not fs.exists("root/dir/child") assert "name='dir'" in query(requests[-1])["q"][0] @@ -1610,6 +1597,7 @@ def test_move_rechecks_the_physical_destination_when_its_path_was_uncached( listing(dict(q, parents=["P"])), listing(t), listing(cached, arriving), + listing(), # x is an empty folder. response({}), ) fs = filesystem(drive) @@ -1619,7 +1607,7 @@ def test_move_rechecks_the_physical_destination_when_its_path_was_uncached( fs.mv("root/dup/q/x", "root/dup/q/t") fs.rm_file("root/dup/q/t/x") assert urlsplit(requests[-1][0]).path.endswith("/files/N") - assert query(requests[-2])["q"] == [ + assert query(requests[-3])["q"] == [ "('T' in parents) and trashed=false and name='x'" ] @@ -1756,6 +1744,8 @@ def test_delayed_lookup_cannot_restore_a_removed_folder( path = "root/dir" def pause_removal(request): + if request[1] == "GET": + return # The emptiness check. removing.set() assert lookup_started.wait(5) @@ -1768,7 +1758,9 @@ def delay_listing(request): drive, lookups = mock_drive( found, found, listing(), on_request=delay_listing ) - writer, mutations = mock_drive(response({}), on_request=pause_removal) + writer, mutations = mock_drive( + listing(), response({}), on_request=pause_removal + ) fs = filesystem(drive, trash_only=trash_only) assert fs.exists(path) @@ -1783,7 +1775,10 @@ def remove(http): assert fs.exists(path) # The in-flight listing still sees the folder. assert not fs.exists(path) assert [r[1] for r in lookups] == ["GET"] * 3 - assert [r[1] for r in mutations] == ["PATCH" if trash_only else "DELETE"] + assert [r[1] for r in mutations] == [ + "GET", + "PATCH" if trash_only else "DELETE", + ] def test_copy_into_parent_invalidated_during_lookup(mock_drive): @@ -2563,7 +2558,8 @@ def rediscover(request): drive, requests = mock_drive( listing(folder("old", "D")), - *([listing()] if operation == "move" else []), + # The destination lookup of a move, or the emptiness check. + listing(), listing(folder("other", "D")), listing(folder("child", "C")), response(folder("new", "D")), @@ -2728,13 +2724,14 @@ def test_shared_drive_delete_permission_error(mock_drive, trash_only): drive, requests = mock_drive( response({"driveId": "shared"}), listing(folder("dir", "folder-id")), + listing(), # The folder is empty. error_response(403, "insufficientFilePermissions"), ) fs = filesystem(drive, "shared", trash_only=trash_only) with pytest.raises(PermissionError, match="Manager"): fs.rm_file("shared/dir") assert fs.exists("shared/dir") - assert len(requests) == 3 + assert len(requests) == 4 def test_copy_creates_missing_directories_and_copies_on_drive(mock_drive): @@ -3398,18 +3395,59 @@ def test_missing_mount_discards_cached_children( assert all("q" not in query(req) for req in requests[2:]) -def test_exists_rechecks_a_removed_mount_before_using_a_cached_folder( +@pytest.mark.parametrize("trash_only", [True, False], ids=["trash", "delete"]) +def test_rm_of_a_folder_with_an_item_this_account_cannot_remove_removes_nothing( + mock_drive, trash_only +): + capability = "canTrash" if trash_only else "canDelete" + sub = dict( + folder("sub", "S"), parents=["D"], capabilities={capability: True} + ) + theirs = { + "id": "T", + "name": "theirs.txt", + "mimeType": "text/plain", + "parents": ["S"], + "capabilities": {capability: False}, + } + drive, requests = mock_drive( + listing(folder("dir", "D")), + response({"capabilities": {capability: True}}), + listing(sub), + listing(theirs), + ) + fs = filesystem(drive, trash_only=trash_only) + with pytest.raises(PermissionError, match="root/dir/sub/theirs.txt"): + fs.rm("root/dir", recursive=True) + assert [r[1] for r in requests] == ["GET"] * 4 + + +@pytest.mark.parametrize("root", ["root", "appDataFolder"]) +def test_rm_of_a_drive_root_raises_before_any_request(mock_drive, root): + drive, requests = mock_drive() + fs = filesystem(drive, root) + with pytest.raises(PermissionError, match="Drive root"): + fs.rm(root, recursive=True) + with pytest.raises(PermissionError, match="Drive root"): + fs.rm_file(root) + assert requests == [] + + +def test_exists_rechecks_a_trashed_mount_before_using_a_cached_folder( mock_drive, ): drive, requests = mock_drive( listing(folder("mount", "M")), listing(folder("other", "O")), + response({"capabilities": {"canTrash": True}}), + listing(dict(folder("other", "O"), capabilities={"canTrash": True})), + listing(), response({"trashed": True}), listing(), ) fs = filesystem(drive, "root/mount") assert fs.exists("root/other") - fs.rm_file("root/mount") + fs.rm("root/mount", recursive=True) assert not fs.exists("root/other") assert "name='mount'" in query(requests[-1])["q"][0] @@ -3418,6 +3456,7 @@ def test_makedirs_after_trashing_and_restoring_the_mount(mock_drive): root = {"mimeType": FOLDER_MIME_TYPE} drive, _ = mock_drive( response(root), + listing(), # The folder is empty. response({"trashed": True}), response(dict(root, trashed=True)), response(root), From b039a0e117a2b9b88397abd70baccbe357b8e03b Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:22:12 -0800 Subject: [PATCH 2/7] Test a folder this account cannot trash Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs_unit.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index ee19d9b0..77e24afd 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -3422,6 +3422,16 @@ def test_rm_of_a_folder_with_an_item_this_account_cannot_remove_removes_nothing( assert [r[1] for r in requests] == ["GET"] * 4 +def test_rm_of_a_folder_this_account_cannot_trash_lists_nothing(mock_drive): + drive, requests = mock_drive( + listing(folder("dir", "D")), + response({"capabilities": {"canTrash": False}}), + ) + with pytest.raises(PermissionError, match="moved to the trash"): + filesystem(drive).rm("root/dir", recursive=True) + assert [r[1] for r in requests] == ["GET", "GET"] + + @pytest.mark.parametrize("root", ["root", "appDataFolder"]) def test_rm_of_a_drive_root_raises_before_any_request(mock_drive, root): drive, requests = mock_drive() From 983dba79e8e726f247b240aee85eeecbc3161c09 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:37:15 -0800 Subject: [PATCH 3/7] Wait for Drive to remove what was in a removed folder On real Drive the files in a trashed or deleted folder are trashed or deleted in the background, a few seconds after the folder. Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 745a6f21..d1344f1b 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -2,6 +2,7 @@ import os import posixpath import secrets +import time import uuid from concurrent import futures from io import StringIO @@ -813,8 +814,18 @@ def test_rm_recursive_removes_a_folder_tree_with_one_write( assert len(writes) == 1 assert len(sent_requests) <= 5 assert not GDriveFileSystem("root", service_auth).exists(path) + # Drive removes what is in a folder in the background. for file_id in ids.values(): - assert state_on_drive(service_auth, file_id) == removed_file + assert state_once_settled(service_auth, file_id) == removed_file + + +def state_once_settled(service_auth, file_id, timeout=180): + deadline = time.monotonic() + timeout + while True: + state = state_on_drive(service_auth, file_id) + if state != "is in place" or time.monotonic() > deadline: + return state + time.sleep(5) def state_on_drive(service_auth, file_id): From a384729d4898867e270819267ffaa6e724a5834a Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 20:27:07 -0800 Subject: [PATCH 4/7] Count requests that Drive did, not ones it refused Under a rate limit the filesystem repeats a refused request, which made the request count of the folder removal test one too high. Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index d1344f1b..4a2f4c27 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -741,14 +741,20 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( @pytest.fixture def sent_requests(service_auth, monkeypatch): - """The method and path of every request this thread sends to Drive.""" + """The method and path of every request of this thread that Drive did. + + A request that Drive refused, for example with a rate limit, and that + the filesystem then repeated, counts once. + """ http = service_auth.Get_Http_Object() send = http.request sent = [] def request(uri, method="GET", **kwargs): - sent.append((method, urlsplit(uri).path)) - return send(uri, method, **kwargs) + response, content = send(uri, method, **kwargs) + if response.status < 400: + sent.append((method, urlsplit(uri).path)) + return response, content monkeypatch.setattr(http, "request", request) monkeypatch.setattr(service_auth.thread_local, "http", http, raising=False) From 9c394bcae327e149705bd8151b7b5962af553ce2 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:06:59 -0800 Subject: [PATCH 5/7] Check roots, scopes and trashed items before a recursive rm - Refuse a Drive root operand before fsspec's rm with maxdepth removes its children, and refuse a Shared Drive root in rm_file too. - Refuse a recursive rm when the scopes can hide children, as rmdir does. - With trash_only=False, also check items already in the trash. - Stop at the first item that would stay and name it. - Raise FileNotFoundError and forget the item when another client removed it, in rm_file and rm as in rmdir. - Skip items inside removed folders with a set, not a scan. - Live test: build the tree under the module folder, include a trashed file, and wait for all files under one deadline. Delete the module folder by ID. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 8 ++- pydrive2/fs/spec.py | 125 ++++++++++++++++++++-------------- pydrive2/test/test_fs.py | 66 +++++++++--------- pydrive2/test/test_fs_unit.py | 84 ++++++++++++++++++++++- 4 files changed, 196 insertions(+), 87 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index b058e4b2..50c10737 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -63,8 +63,12 @@ when it is empty. ``fs.rm(path, recursive=True)`` removes a folder and everything in it with one request, moving it to the trash or deleting it for good as ``trash_only`` says. It first lists the folder's contents and raises ``PermissionError``, removing nothing, if this account cannot remove -some of them, such as files that other people own. A Drive root cannot be -removed. +some of them, such as files that other people own. With +``trash_only=False`` the listing includes files already in the trash, +which the removal deletes too. Like ``rmdir``, it needs credentials that +can list everything in the folder. Drive checks and removes in separate +requests, so coordinate concurrent writers here too. A Drive root cannot +be removed. One root per filesystem ----------------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 07511638..91239a05 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -271,6 +271,13 @@ def _quote_query_value(value): return f"'{escaped}'" +def _ancestors(path): + path = path.rstrip("/") + while "/" in path: + path = path.rsplit("/", 1)[0] + yield path + + def _batches(items, size): iterator = iter(items) while batch := list(islice(iterator, size)): @@ -760,11 +767,17 @@ def _get_root_metadata( } return item.metadata - def _query_children(self, parents, names=(), *, fields=_LIST_FIELDS): + def _query_children( + self, parents, names=(), *, fields=_LIST_FIELDS, trashed=False + ): parent_query = " or ".join( f"{_quote_query_value(p)} in parents" for p in parents ) - query = f"({parent_query}) and trashed=false" + query = ( + f"({parent_query})" + if trashed + else f"({parent_query}) and trashed=false" + ) if names: terms = " or ".join(f"name={_quote_query_value(n)}" for n in names) query += f" and {terms}" if len(names) == 1 else f" and ({terms})" @@ -1428,11 +1441,7 @@ def rmdir(self, path): ) item_id = match.folders[0] else: - if root in _ROOT_ALIASES: - raise PermissionError( - errno.EPERM, "Cannot remove a Drive root", path - ) - item = self._get_root_metadata(fresh=True) + item = self._refuse_drive_root(path, fresh=True) if item.get("trashed"): raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), path @@ -1441,19 +1450,9 @@ def rmdir(self, path): raise NotADirectoryError( errno.ENOTDIR, os.strerror(errno.ENOTDIR), path ) - if item.get("driveId") == root: - raise PermissionError( - errno.EPERM, "Cannot remove a Drive root", path - ) item_id = root - try: - with _translate_not_found(path): - self._gdrive_delete_file(item_id, empty_directory=path) - except FileNotFoundError: - self._invalidate_folder(item_id, path, known_folder=True) - raise - self._invalidate_folder(item_id, path, known_folder=True) + self._remove(item_id, path, is_folder=True, empty_directory=path) def _check_empty_folder(self, item_id, path): query = f"{_quote_query_value(item_id)} in parents" @@ -1476,7 +1475,9 @@ def _check_empty_folder(self, item_id, path): ) if pages.metadata.get("incompleteSearch"): raise OSError(errno.EIO, "Incomplete Drive listing", path) + self._require_scopes_that_list_everything(path) + def _require_scopes_that_list_everything(self, path): # drive.file can return an empty, complete page while hiding children. credentials = self.client.auth.credentials if isinstance(credentials, service_account.Credentials): @@ -1485,7 +1486,7 @@ def _check_empty_folder(self, item_id, path): scopes = getattr(credentials, "granted_scopes", None) required = ( _APP_DATA_SCOPES - if params.get("spaces") == "appDataFolder" + if self._list_params.get("spaces") == "appDataFolder" else _LIST_ALL_SCOPES ) if required.isdisjoint(scopes or ()): @@ -1501,91 +1502,111 @@ def rm(self, path, recursive=False, maxdepth=None): A folder is removed with one request, after a listing checks that this account can remove everything in it. """ + for operand in [path] if isinstance(path, str) else path: + self._refuse_drive_root(self._strip_protocol(operand)) if not recursive or maxdepth is not None: super().rm(path, recursive=recursive, maxdepth=maxdepth) return - removed: list[str] = [] + removed = set() # A folder sorts before what is in it, which goes with the folder. for item in sorted(self.expand_path(path)): - if any(item.startswith(folder + "/") for folder in removed): + if not removed.isdisjoint(_ancestors(item)): continue - self._refuse_root_alias(item) item_id, is_folder = self._lookup_item(item) if is_folder: self._remove_folder(item_id, item) - removed.append(item.rstrip("/")) + removed.add(item.rstrip("/")) else: - self._gdrive_delete_file(item_id) - self._invalidate_folder(item_id, item, known_folder=False) + self._remove(item_id, item, is_folder=False) - def _refuse_root_alias(self, path): + def _refuse_drive_root(self, path, *, fresh=False): + """Raise for a Drive root, else return the metadata of a mount root.""" root, base = self._split_mounted_path(path) - if not base and root in _ROOT_ALIASES: - raise PermissionError( - errno.EPERM, "Cannot remove a Drive root", path - ) + if base: + return None + if root not in _ROOT_ALIASES: + metadata = self._get_root_metadata(fresh=fresh) + if metadata.get("driveId") != root: + return metadata + raise PermissionError(errno.EPERM, "Cannot remove a Drive root", path) def _remove_folder(self, item_id, path): capability = "canTrash" if self._trash_only else "canDelete" action = "moved to the trash" if self._trash_only else "deleted" + self._require_scopes_that_list_everything(path) folder = self.client.CreateFile({"id": item_id}) - with _translate_not_found(path): - _gdrive_retry_repeatable(folder.FetchMetadata)( - fields=f"driveId,capabilities/{capability}" - ) - if folder.get("driveId") == item_id: - raise PermissionError( - errno.EPERM, "Cannot remove a Drive root", path + with self._forget_if_gone(item_id, path, is_folder=True): + _gdrive_retry_read(folder.FetchMetadata)( + fields=f"capabilities/{capability}" ) if not folder.get("capabilities", {}).get(capability): raise PermissionError( errno.EACCES, f"This account cannot have it {action}", path ) - stays = self._items_that_would_stay(item_id, path, capability) - if stays: + stays = self._item_that_would_stay(item_id, path, capability) + if stays is not None: raise PermissionError( errno.EACCES, - f"Nothing was removed: {len(stays)} item(s) in the folder " - f"cannot be {action} by this account, such as {stays[0]}", + f"Nothing was removed: this account cannot have {stays} " + f"{action}", path, ) - self._gdrive_delete_file(item_id) - self._invalidate_folder(item_id, path, known_folder=True) + self._remove(item_id, path, is_folder=True) - def _items_that_would_stay(self, folder_id, path, capability): - """Paths below a folder that removing the folder would not remove.""" + def _item_that_would_stay(self, folder_id, path, capability): + """The first path below a folder that removing it would leave.""" fields = ( "nextPageToken,incompleteSearch," f"files(id,name,mimeType,parents,capabilities/{capability})" ) - stays = [] frontier = {folder_id: path.rstrip("/")} visited = set(frontier) while frontier: batch = dict(islice(frontier.items(), _MAX_QUERY_TERMS)) for parent in batch: del frontier[parent] - for item in self._query_children(batch, fields=fields): + # A permanent removal also deletes what is already in the trash. + children = self._query_children( + batch, fields=fields, trashed=not self._trash_only + ) + for item in children: parents = [p for p in item.get("parents", ()) if p in batch] parent_path = batch[parents[0]] if parents else path item_path = posixpath.join(parent_path, item["name"]) if not item.get("capabilities", {}).get(capability): - stays.append(item_path) + return item_path is_folder = item["mimeType"] == FOLDER_MIME_TYPE if is_folder and item["id"] not in visited: visited.add(item["id"]) frontier[item["id"]] = item_path - return stays + return None def rm_file(self, path): - self._refuse_root_alias(path) + self._refuse_drive_root(path) item_id, is_folder = self._lookup_item(path) # Like rmdir, a folder is removed only when it is empty. - self._gdrive_delete_file( - item_id, empty_directory=path if is_folder else None + self._remove( + item_id, + path, + is_folder=is_folder, + empty_directory=path if is_folder else None, ) + + def _remove(self, item_id, path, *, is_folder, empty_directory=None): + with self._forget_if_gone(item_id, path, is_folder=is_folder): + self._gdrive_delete_file(item_id, empty_directory=empty_directory) self._invalidate_folder(item_id, path, known_folder=is_folder) + @contextmanager + def _forget_if_gone(self, item_id, path, *, is_folder): + """Raise FileNotFoundError for an item another client removed.""" + try: + with _translate_not_found(path): + yield + except FileNotFoundError: + self._invalidate_folder(item_id, path, known_folder=is_folder) + raise + def _gdrive_delete_file(self, item_id, *, empty_directory=None): attempts = count() with _unwrap_not_retried(): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 4a2f4c27..c2a63c86 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -56,8 +56,8 @@ def _create_fs(): GDriveFileSystem.cachable = True # Delete for good, so test runs do not fill the trash. - fs = GDriveFileSystem(base_remote_dir, service_auth, trash_only=False) - fs.rm(base_remote_dir, recursive=True) + base_folder = GoogleDrive(service_auth).CreateFile({"id": base_item["id"]}) + pydrive_retry(base_folder.Delete) @pytest.fixture @@ -768,11 +768,13 @@ def make_tree(fs, path): @pytest.fixture -def tree_in_my_drive(service_auth, request): - """A folder in the root of My Drive with a.txt and sub/c.txt. +def tree(service_auth, fs_factory): + """A folder with a.txt, sub/c.txt and a file in the trash. - Returns its path and the IDs of everything in it. + Returns the module folder's ID, the folder's path under that ID, and + the IDs of everything in the folder. """ + _, base_item = fs_factory() drive = GoogleDrive(service_auth) ids = {} @@ -785,22 +787,14 @@ def create(name, parent, folder=False): item.SetContentString(name) pydrive_retry(item.Upload) ids[name] = item["id"] - return item["id"] + return item name = uuid.uuid4().hex - top = create(name, "root", folder=True) + top = create(name, base_item["id"], folder=True)["id"] create("a.txt", top) - create("c.txt", create("sub", top, folder=True)) - - def delete_what_is_left(): - try: - pydrive_retry(drive.CreateFile({"id": top}).Delete) - except ApiRequestError as error: - if error.error["code"] != 404: - raise - - request.addfinalizer(delete_what_is_left) - return "root/" + name, ids + create("c.txt", create("sub", top, folder=True)["id"]) + pydrive_retry(create("trashed.txt", top).Trash) + return base_item["id"], f"{base_item['id']}/{name}", ids @pytest.mark.parametrize( @@ -809,29 +803,37 @@ def delete_what_is_left(): ids=["trash", "delete"], ) def test_rm_recursive_removes_a_folder_tree_with_one_write( - service_auth, tree_in_my_drive, sent_requests, trash_only, removed_file + service_auth, tree, sent_requests, trash_only, removed_file ): - path, ids = tree_in_my_drive - fs = GDriveFileSystem("root", service_auth, trash_only=trash_only) + root, path, ids = tree + fs = GDriveFileSystem(root, service_auth, trash_only=trash_only) fs.rm(path, recursive=True) - writes = [request for request in sent_requests if request[0] != "GET"] - assert len(writes) == 1 - assert len(sent_requests) <= 5 - assert not GDriveFileSystem("root", service_auth).exists(path) + reads = [request for request in sent_requests if request[0] == "GET"] + assert len(sent_requests) - len(reads) == 1 + assert len(reads) <= 5 + assert not GDriveFileSystem(root, service_auth).exists(path) # Drive removes what is in a folder in the background. - for file_id in ids.values(): - assert state_once_settled(service_auth, file_id) == removed_file + states = states_after_waiting(service_auth, ids.values(), removed_file) + assert states == dict.fromkeys(ids.values(), removed_file) -def state_once_settled(service_auth, file_id, timeout=180): +def states_after_waiting(service_auth, file_ids, expected, timeout=180): + """The state of each file once all are as expected, or at the deadline.""" deadline = time.monotonic() + timeout + pause = 1 + states = {} while True: - state = state_on_drive(service_auth, file_id) - if state != "is in place" or time.monotonic() > deadline: - return state - time.sleep(5) + for file_id in file_ids: + if states.get(file_id) != expected: + states[file_id] = state_on_drive(service_auth, file_id) + if set(states.values()) == {expected}: + return states + if time.monotonic() > deadline: + return states + time.sleep(pause) + pause = min(2 * pause, 10) def state_on_drive(service_auth, file_id): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 77e24afd..47338719 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -3414,12 +3414,15 @@ def test_rm_of_a_folder_with_an_item_this_account_cannot_remove_removes_nothing( listing(folder("dir", "D")), response({"capabilities": {capability: True}}), listing(sub), - listing(theirs), + response({"files": [theirs], "nextPageToken": "more"}), ) fs = filesystem(drive, trash_only=trash_only) with pytest.raises(PermissionError, match="root/dir/sub/theirs.txt"): fs.rm("root/dir", recursive=True) assert [r[1] for r in requests] == ["GET"] * 4 + # Deleting for good also deletes what is already in the trash. + child_queries = [query(r)["q"][0] for r in requests[2:]] + assert ["trashed=false" in q for q in child_queries] == [trash_only] * 2 def test_rm_of_a_folder_this_account_cannot_trash_lists_nothing(mock_drive): @@ -3438,11 +3441,90 @@ def test_rm_of_a_drive_root_raises_before_any_request(mock_drive, root): fs = filesystem(drive, root) with pytest.raises(PermissionError, match="Drive root"): fs.rm(root, recursive=True) + with pytest.raises(PermissionError, match="Drive root"): + fs.rm(root, recursive=True, maxdepth=1) + with pytest.raises(PermissionError, match="Drive root"): + fs.rm([f"{root}/x", root], recursive=True) + with pytest.raises(PermissionError, match="Drive root"): + fs.rm(root) with pytest.raises(PermissionError, match="Drive root"): fs.rm_file(root) assert requests == [] +@pytest.mark.parametrize( + "remove", + [ + lambda fs: fs.rm_file("SharedID"), + lambda fs: fs.rm("SharedID", recursive=True), + lambda fs: fs.rm("SharedID", recursive=True, maxdepth=1), + ], + ids=["rm_file", "recursive", "maxdepth"], +) +def test_rm_of_a_shared_drive_root_raises_after_reading_only_its_metadata( + mock_drive, remove +): + drive, requests = mock_drive( + response({"mimeType": FOLDER_MIME_TYPE, "driveId": "SharedID"}) + ) + with pytest.raises(PermissionError, match="Drive root"): + remove(filesystem(drive, "SharedID")) + assert [r[1] for r in requests] == ["GET"] + + +@pytest.mark.parametrize( + "granted", + [None, ["https://www.googleapis.com/auth/drive.file"]], + ids=["unknown", "per-file"], +) +def test_rm_recursive_without_access_to_list_everything_removes_nothing( + mock_drive, granted +): + credentials = Credentials( + "token", + scopes=["https://www.googleapis.com/auth/drive"], + granted_scopes=granted, + ) + drive, requests = mock_drive( + listing(folder("dir", "D")), credentials=credentials + ) + with pytest.raises(PermissionError) as error: + filesystem(drive).rm("root/dir", recursive=True) + assert error.value.errno == errno.EACCES + assert [r[1] for r in requests] == ["GET"] + + +@pytest.mark.parametrize( + ("replies", "remove"), + [ + ( + [listing({"id": "F", "name": "f", "mimeType": "text/plain"})], + lambda fs: fs.rm_file("root/f"), + ), + ( + [ + listing(folder("f", "D")), + response({"capabilities": {"canTrash": True}}), + listing(), + ], + lambda fs: fs.rm("root/f", recursive=True), + ), + ], + ids=["file", "folder"], +) +def test_rm_of_an_item_another_client_removed_raises_file_not_found( + mock_drive, replies, remove +): + drive, requests = mock_drive( + *replies, error_response(404, "notFound"), listing() + ) + fs = filesystem(drive) + with pytest.raises(FileNotFoundError): + remove(fs) + assert not fs.exists("root/f") + assert "name='f'" in query(requests[-1])["q"][0] + + def test_exists_rechecks_a_trashed_mount_before_using_a_cached_folder( mock_drive, ): From 0bdc7e9aaed10de5e6522b78a2713d3d4b7ce2de Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:39:49 -0800 Subject: [PATCH 6/7] Use the retry helper that main still has main renamed _gdrive_retry_read to _gdrive_retry_repeatable in #448. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 91239a05..25e5b1c3 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1507,7 +1507,7 @@ def rm(self, path, recursive=False, maxdepth=None): if not recursive or maxdepth is not None: super().rm(path, recursive=recursive, maxdepth=maxdepth) return - removed = set() + removed: set[str] = set() # A folder sorts before what is in it, which goes with the folder. for item in sorted(self.expand_path(path)): if not removed.isdisjoint(_ancestors(item)): @@ -1536,7 +1536,7 @@ def _remove_folder(self, item_id, path): self._require_scopes_that_list_everything(path) folder = self.client.CreateFile({"id": item_id}) with self._forget_if_gone(item_id, path, is_folder=True): - _gdrive_retry_read(folder.FetchMetadata)( + _gdrive_retry_repeatable(folder.FetchMetadata)( fields=f"capabilities/{capability}" ) if not folder.get("capabilities", {}).get(capability): From 6bffa94f836dada31d943bd0cff2c50a2c8c51eb Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 12:24:15 -0800 Subject: [PATCH 7/7] Check every rm target before removing any - A glob can expand to a root, so rm checks every expanded item for a Drive root before it removes anything, also with maxdepth. - Accept os.PathLike operands, as fsspec's expand_path does. - A recursive rm resolves all targets first and refuses a path that two folders share, as rmdir does. Skipping by path would otherwise skip items of the folder that stays. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 3 ++- pydrive2/fs/spec.py | 37 +++++++++++++++++++++++++------- pydrive2/test/test_fs.py | 40 +++++++++++++++++++++++++++++------ pydrive2/test/test_fs_unit.py | 11 ++++++++++ 4 files changed, 75 insertions(+), 16 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 50c10737..0ec288cf 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -66,7 +66,8 @@ raises ``PermissionError``, removing nothing, if this account cannot remove some of them, such as files that other people own. With ``trash_only=False`` the listing includes files already in the trash, which the removal deletes too. Like ``rmdir``, it needs credentials that -can list everything in the folder. Drive checks and removes in separate +can list everything in the folder, and it raises ``FileExistsError`` for a +path that two folders share. Drive checks and removes in separate requests, so coordinate concurrent writers here too. A Drive root cannot be removed. diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 25e5b1c3..1092b5f7 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -884,10 +884,14 @@ def _get_item_id(self, path, create=False): match, _ = self._lookup_path(base) return _select_item_id(path, match.ids) - def _lookup_item(self, path): + def _lookup_item(self, path, *, refuse_shared_folder_name=False): """Return the ID at a path and whether it is a folder.""" _, base = self._split_mounted_path(path) match, _ = self._lookup_path(base) + if refuse_shared_folder_name and match.folders and len(match.ids) > 1: + raise FileExistsError( + errno.EEXIST, "Ambiguous Drive path; use the folder ID", path + ) item_id = _select_item_id(path, match.ids) if base or self.root in _ROOT_ALIASES: return item_id, item_id in match.folders @@ -1502,20 +1506,37 @@ def rm(self, path, recursive=False, maxdepth=None): A folder is removed with one request, after a listing checks that this account can remove everything in it. """ - for operand in [path] if isinstance(path, str) else path: - self._refuse_drive_root(self._strip_protocol(operand)) + operands = [path] if isinstance(path, (str, os.PathLike)) else path + # A root named outright is refused before any request. + for operand in operands: + self._refuse_drive_root(self._strip_protocol(os.fspath(operand))) if not recursive or maxdepth is not None: - super().rm(path, recursive=recursive, maxdepth=maxdepth) + items = self.expand_path( + path, recursive=recursive, maxdepth=maxdepth + ) + # A glob can match a root too, so check them all before removing. + for item in items: + self._refuse_drive_root(item) + for item in reversed(items): + self.rm_file(item) return - removed: set[str] = set() + targets = [] + folders: set[str] = set() # A folder sorts before what is in it, which goes with the folder. for item in sorted(self.expand_path(path)): - if not removed.isdisjoint(_ancestors(item)): + if not folders.isdisjoint(_ancestors(item)): continue - item_id, is_folder = self._lookup_item(item) + self._refuse_drive_root(item) + # Like rmdir, refuse a path that two folders share. + item_id, is_folder = self._lookup_item( + item, refuse_shared_folder_name=True + ) + targets.append((item, item_id, is_folder)) + if is_folder: + folders.add(item.rstrip("/")) + for item, item_id, is_folder in targets: if is_folder: self._remove_folder(item_id, item) - removed.add(item.rstrip("/")) else: self._remove(item_id, item, is_folder=False) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index c2a63c86..8e9c1bd7 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -767,6 +767,18 @@ def make_tree(fs, path): fs.pipe_file(path + "/sub/c.txt", b"c") +def create_item(drive, name, parent, folder=False): + """Create a folder, or a file whose content is its name.""" + metadata = {"name": name, "parents": [parent]} + if folder: + metadata["mimeType"] = "application/vnd.google-apps.folder" + item = drive.CreateFile(metadata) + if not folder: + item.SetContentString(name) + pydrive_retry(item.Upload) + return item + + @pytest.fixture def tree(service_auth, fs_factory): """A folder with a.txt, sub/c.txt and a file in the trash. @@ -779,13 +791,7 @@ def tree(service_auth, fs_factory): ids = {} def create(name, parent, folder=False): - metadata = {"name": name, "parents": [parent]} - if folder: - metadata["mimeType"] = "application/vnd.google-apps.folder" - item = drive.CreateFile(metadata) - if not folder: - item.SetContentString(name) - pydrive_retry(item.Upload) + item = create_item(drive, name, parent, folder) ids[name] = item["id"] return item @@ -847,6 +853,26 @@ def state_on_drive(service_auth, file_id): return "is in the trash" if item["trashed"] else "is in place" +def test_rm_recursive_of_a_path_two_folders_share_raises_and_keeps_both( + service_auth, fs_factory +): + _, base_item = fs_factory() + drive = GoogleDrive(service_auth) + name = uuid.uuid4().hex + top = create_item(drive, name, base_item["id"], folder=True)["id"] + for file_name in ("a.txt", "b.txt"): + folder = create_item(drive, "dup", top, folder=True) + create_item(drive, file_name, folder["id"]) + fs = GDriveFileSystem(base_item["id"], service_auth) + path = f"{base_item['id']}/{name}" + + with pytest.raises(FileExistsError): + fs.rm([path + "/dup", path + "/dup/b.txt"], recursive=True) + + kept = GDriveFileSystem(base_item["id"], service_auth).find(path) + assert kept == [path + "/dup/a.txt", path + "/dup/b.txt"] + + def test_rm_without_recursive_of_a_folder_with_files_raises_and_keeps_them( fs, fs_factory, remote_dir ): diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 47338719..de0f9202 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -11,6 +11,7 @@ from concurrent.futures import ThreadPoolExecutor from http.client import IncompleteRead from itertools import pairwise +from pathlib import PurePosixPath from threading import Event from urllib.parse import urlsplit @@ -3447,11 +3448,21 @@ def test_rm_of_a_drive_root_raises_before_any_request(mock_drive, root): fs.rm([f"{root}/x", root], recursive=True) with pytest.raises(PermissionError, match="Drive root"): fs.rm(root) + with pytest.raises(PermissionError, match="Drive root"): + fs.rm(PurePosixPath(root), recursive=True) with pytest.raises(PermissionError, match="Drive root"): fs.rm_file(root) assert requests == [] +def test_rm_of_a_glob_that_matches_the_root_removes_nothing(mock_drive): + file = {"id": "F", "name": "f", "mimeType": "text/plain"} + drive, requests = mock_drive(*[listing(file)] * 4) + with pytest.raises(PermissionError, match="Drive root"): + filesystem(drive).rm("root/**", recursive=True, maxdepth=1) + assert {r[1] for r in requests} == {"GET"} + + @pytest.mark.parametrize( "remove", [