diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..0ec288cf 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -58,6 +58,19 @@ 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. 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, 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. + One root per filesystem ----------------------- diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac47994b..1092b5f7 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})" @@ -871,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 @@ -1428,11 +1445,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 +1454,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 +1479,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 +1490,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 ()): @@ -1495,13 +1500,133 @@ def _check_empty_folder(self, item_id, path): path, ) + 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. + """ + 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: + 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 + 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 folders.isdisjoint(_ancestors(item)): + continue + 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) + else: + self._remove(item_id, item, is_folder=False) + + 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 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 self._forget_if_gone(item_id, path, is_folder=True): + _gdrive_retry_repeatable(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._item_that_would_stay(item_id, path, capability) + if stays is not None: + raise PermissionError( + errno.EACCES, + f"Nothing was removed: this account cannot have {stays} " + f"{action}", + path, + ) + self._remove(item_id, path, is_folder=True) + + 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})" + ) + 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] + # 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): + 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 None + 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 - self._gdrive_delete_file(item_id) - self._invalidate_folder(item_id, path, known_folder=known_folder) + 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._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() diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..8e9c1bd7 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 @@ -13,6 +14,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 +55,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. + base_folder = GoogleDrive(service_auth).CreateFile({"id": base_item["id"]}) + pydrive_retry(base_folder.Delete) @pytest.fixture @@ -734,3 +737,160 @@ 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 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): + 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) + 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") + + +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. + + 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 = {} + + def create(name, parent, folder=False): + item = create_item(drive, name, parent, folder) + ids[name] = item["id"] + return item + + name = uuid.uuid4().hex + top = create(name, base_item["id"], folder=True)["id"] + create("a.txt", top) + 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( + ("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, sent_requests, trash_only, removed_file +): + root, path, ids = tree + fs = GDriveFileSystem(root, service_auth, trash_only=trash_only) + + fs.rm(path, recursive=True) + + 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. + states = states_after_waiting(service_auth, ids.values(), removed_file) + assert states == dict.fromkeys(ids.values(), removed_file) + + +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: + 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): + 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_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 +): + 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..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 @@ -470,6 +471,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 +590,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 +1522,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 +1553,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 +1598,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 +1608,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 +1745,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 +1759,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 +1776,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 +2559,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 +2725,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 +3396,161 @@ 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), + 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): + 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() + 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(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", + [ + 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, ): 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 +3559,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),