From ae0d8572fbc4e3b35707c9ad19616388aa9b21b8 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 19:22:08 -0800 Subject: [PATCH 1/6] Create Drive directories in mkdir and makedirs --- pydrive2/fs/spec.py | 47 ++++++++++++++++++++++++++++++++++- pydrive2/test/test_fs.py | 10 +++++++- pydrive2/test/test_fs_unit.py | 46 ++++++++++++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 2 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 57eb993..76162c2 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -475,9 +475,11 @@ def _gdrive_create_dir(self, parent_id, name): return item @wrap_with(threading.RLock()) - def _create_dir(self, parent_id, name, remote_path): + def _create_dir(self, parent_id, name, remote_path, *, exist_ok=True): cached = self._ids_cache["dirs"].get(remote_path) if cached: + if not exist_ok: + raise FileExistsError(posixpath.join(self.root, remote_path)) return cached[0] item = self._gdrive_create_dir(parent_id, name) @@ -485,6 +487,49 @@ def _create_dir(self, parent_id, name, remote_path): return item["id"] + def mkdir(self, path, create_parents=True, **kwargs): + self._mkdir(path, create_parents, exist_ok=False) + + def makedirs(self, path, exist_ok=False): + self._mkdir(path, create_parents=True, exist_ok=exist_ok) + + def _mkdir(self, path, create_parents, exist_ok): + root, base = self._split_mounted_path(path) + if not base: + if ( + root not in {"root", "appDataFolder"} + and self.info(path)["type"] != "directory" + ): + raise FileExistsError(path) + if not exist_ok: + raise FileExistsError(path) + return + + parent_ids = [root] + parent = "" + for name in base.split("/"): + child = posixpath.join(parent, name) + leaf = child == base + dirs = self._get_cached_item_ids(child, use_cache=True) + if not dirs: + items = self._get_remote_item_ids(parent_ids, parent, name) + dirs = self._get_cached_item_ids(child, use_cache=True) + if items and not dirs: + if leaf: + raise FileExistsError(path) + raise NotADirectoryError(posixpath.join(root, child)) + if dirs: + if leaf and not exist_ok: + raise FileExistsError(path) + else: + if not leaf and not create_parents: + raise FileNotFoundError(posixpath.join(root, child)) + item_id = self._create_dir( + min(parent_ids), name, child, exist_ok=not leaf or exist_ok + ) + dirs = [item_id] + parent, parent_ids = child, dirs + def exists(self, path): root, base = self._split_mounted_path(path) try: diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index cc444a6..0b0b9da 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -131,6 +131,14 @@ def test_move(fs, remote_dir): assert initial_info == secondary_info +def test_create_empty_directory(fs, fs_factory, remote_dir): + path = remote_dir + "/empty/sub" + fs.makedirs(path) + other, _ = fs_factory() + assert other.info(path)["type"] == "directory" + assert other.ls(path) == [] + + def test_copy_file_to_new_directory(fs, remote_dir): source = remote_dir + "/source" target = remote_dir + "/nested/copy" @@ -285,7 +293,7 @@ def test_find(fs, fs_factory, remote_dir): dirnames = {posixpath.dirname(file) for file in files} for dirname in dirnames: - fs.mkdir(dirname) + fs.makedirs(dirname, exist_ok=True) for file in files: fs.touch(file) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 23ff39d..9efa123 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -352,3 +352,49 @@ def test_large_write_after_close_does_not_open_a_tempfile(mock_drive, mocker): with pytest.raises(ValueError, match="closed"): writer.write(b"too large") backing_file.assert_not_called() + + +def test_makedirs_creates_empty_drive_folders(mock_drive): + drive, requests = mock_drive( + response({"driveId": "shared"}), + response({"files": []}), + response({"id": "A"}), + response({"files": []}), + response({"id": "B"}), + ) + fs = filesystem(drive, "shared") + fs.makedirs("gdrive://shared/parent/leaf") + assert fs.exists("shared/parent/leaf") + fs.makedirs("shared/parent/leaf", exist_ok=True) + with pytest.raises(FileExistsError): + fs.makedirs("shared/parent/leaf") + assert [json.loads(req[2]) for req in requests if req[1] == "POST"] == [ + { + "name": "parent", + "parents": ["shared"], + "mimeType": FOLDER_MIME_TYPE, + }, + {"name": "leaf", "parents": ["A"], "mimeType": FOLDER_MIME_TYPE}, + ] + + +def test_mkdir_without_missing_parents(mock_drive): + drive, requests = mock_drive(response({"files": []})) + with pytest.raises(FileNotFoundError): + filesystem(drive).mkdir("root/missing/leaf", create_parents=False) + assert [req[1] for req in requests] == ["GET"] + + +@pytest.mark.parametrize( + "path,expected", + [("root/blob", FileExistsError), ("root/blob/sub", NotADirectoryError)], +) +def test_makedirs_rejects_file(mock_drive, path, expected): + drive, requests = mock_drive( + response( + {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} + ) + ) + with pytest.raises(expected): + filesystem(drive).makedirs(path, exist_ok=True) + assert [req[1] for req in requests] == ["GET"] From 3323a4247ea64d1e41928d59be78fc277442d7ce Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 22:58:47 -0800 Subject: [PATCH 2/6] Reuse verified directories and resolve mkdir paths from Drive results --- pydrive2/fs/spec.py | 84 ++++++++++++++++++++++++----------- pydrive2/test/test_fs_unit.py | 81 +++++++++++++++++++++++++++++++++ 2 files changed, 140 insertions(+), 25 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 76162c2..9b7a442 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -8,7 +8,7 @@ from collections import defaultdict from contextlib import contextmanager from itertools import chain -from typing import TypedDict +from typing import NotRequired, TypedDict import appdirs from fsspec.spec import AbstractFileSystem @@ -45,6 +45,7 @@ class _IdsCache(TypedDict): dirs: defaultdict[str, list[str]] ids: dict[str, str] + root_is_directory: NotRequired[bool] class GDriveAuthError(Exception): @@ -322,17 +323,36 @@ def _split_file_path(self, path): def _ids_cache(self) -> _IdsCache: cache: _IdsCache = {"dirs": defaultdict(list), "ids": {}} - base_item_ids = self._path_to_item_ids(self.base, use_cache=False) - if not base_item_ids: + self._cache_path_id( + self.base, *self._mount_directory_ids(), cache=cache + ) + return cache + + def _mount_directory_ids(self): + if not self.base: + return [self.root] + parent, name = posixpath.split(self.base) + parent_ids = self._path_to_item_ids(parent, use_cache=False) + items = self._named_items(parent_ids, name) + if not items: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), f"Confirm {self.path} exists and you can access it", ) - - self._cache_path_id(self.base, *base_item_ids, cache=cache) - - return cache + return [ + item["id"] + for item in items + if item["mimeType"] == FOLDER_MIME_TYPE + ] + + def _named_items(self, parent_ids, name): + # Drive's name query is case-insensitive. + return [ + item + for item in self._gdrive_list_ids(parent_ids, name=name) + if item["name"] == name + ] def _cache_path_id(self, path, *item_ids, cache=None): cache = cache or self._ids_cache @@ -476,14 +496,15 @@ def _gdrive_create_dir(self, parent_id, name): @wrap_with(threading.RLock()) def _create_dir(self, parent_id, name, remote_path, *, exist_ok=True): - cached = self._ids_cache["dirs"].get(remote_path) + cached = self._get_cached_item_ids(remote_path, use_cache=True) if cached: if not exist_ok: raise FileExistsError(posixpath.join(self.root, remote_path)) return cached[0] + cache = self._ids_cache item = self._gdrive_create_dir(parent_id, name) - self._cache_path_id(remote_path, item["id"]) + self._cache_path_id(remote_path, item["id"], cache=cache) return item["id"] @@ -496,31 +517,44 @@ def makedirs(self, path, exist_ok=False): def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) if not base: - if ( - root not in {"root", "appDataFolder"} - and self.info(path)["type"] != "directory" - ): - raise FileExistsError(path) + if root not in {"root", "appDataFolder"}: + cache = self._ids_cache + if not cache.get("root_is_directory"): + if self.info(path)["type"] != "directory": + raise FileExistsError(path) + cache["root_is_directory"] = True if not exist_ok: raise FileExistsError(path) return - parent_ids = [root] - parent = "" - for name in base.split("/"): + cache = self._ids_cache + parent = base + missing = [] + while not ( + parent_ids := self._get_cached_item_ids(parent, use_cache=True) + ): + parent, name = posixpath.split(parent) + missing.append(name) + if not missing and not exist_ok: + raise FileExistsError(path) + + for name in reversed(missing): child = posixpath.join(parent, name) leaf = child == base - dirs = self._get_cached_item_ids(child, use_cache=True) - if not dirs: - items = self._get_remote_item_ids(parent_ids, parent, name) - dirs = self._get_cached_item_ids(child, use_cache=True) - if items and not dirs: - if leaf: - raise FileExistsError(path) - raise NotADirectoryError(posixpath.join(root, child)) + matches = self._named_items(parent_ids, name) + dirs = [ + item["id"] + for item in matches + if item["mimeType"] == FOLDER_MIME_TYPE + ] if dirs: + self._cache_path_id(child, *dirs, cache=cache) if leaf and not exist_ok: raise FileExistsError(path) + elif matches: + if leaf: + raise FileExistsError(path) + raise NotADirectoryError(posixpath.join(root, child)) else: if not leaf and not create_parents: raise FileNotFoundError(posixpath.join(root, child)) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 9efa123..9ef9f61 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -398,3 +398,84 @@ def test_makedirs_rejects_file(mock_drive, path, expected): with pytest.raises(expected): filesystem(drive).makedirs(path, exist_ok=True) assert [req[1] for req in requests] == ["GET"] + + +def test_makedirs_validates_mount_id_once(mock_drive): + drive, requests = mock_drive(response({"mimeType": FOLDER_MIME_TYPE})) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID", exist_ok=True) + fs.makedirs("FolderID", exist_ok=True) + with pytest.raises(FileExistsError): + fs.mkdir("FolderID") + assert len(requests) == 1 + + +@pytest.mark.parametrize( + "failure, error", + [ + (response({"mimeType": "text/plain"}), FileExistsError), + (error_response(404, "notFound"), FileNotFoundError), + ], +) +def test_makedirs_rejects_invalid_mount_id(mock_drive, failure, error): + drive, _ = mock_drive(failure) + with pytest.raises(error): + filesystem(drive, "FolderID").makedirs("FolderID", exist_ok=True) + + +def test_makedirs_starts_at_cached_mount(mock_drive): + def folder(name): + return response( + { + "files": [ + {"name": name, "id": name, "mimeType": FOLDER_MIME_TYPE} + ] + } + ) + + drive, requests = mock_drive( + response({"driveId": "shared"}), + folder("a"), + folder("b"), + response({"files": []}), + response({"id": "new"}), + ) + fs = filesystem(drive, "FolderID/a/b") + fs.makedirs("FolderID/a/b/new") + fs.makedirs("FolderID/a/b/new", exist_ok=True) + assert [query(req)["q"][0] for req in requests if "q" in query(req)] == [ + "('FolderID' in parents) and trashed=false and name='a'", + "('a' in parents) and trashed=false and name='b'", + "('b' in parents) and trashed=false and name='new'", + ] + + +def test_makedirs_classifies_drive_results_without_rereading_cache( + mock_drive, mocker +): + same_name = [ + {"name": "sub", "id": "file", "mimeType": "text/plain"}, + {"name": "Sub", "id": "wrong-case", "mimeType": FOLDER_MIME_TYPE}, + {"name": "sub", "id": "folder", "mimeType": FOLDER_MIME_TYPE}, + ] + drive, requests = mock_drive( + response({"files": same_name}), + response({"files": []}), + response({"id": "leaf"}), + ) + fs = filesystem(drive) + # Simulate a folder discovered by this lookup going into an expired cache. + mocker.patch.object(fs, "_cache_path_id") + fs.makedirs("root/sub/leaf") + assert json.loads(requests[-1][2])["parents"] == ["folder"] + + +def test_makedirs_rejects_file_at_nested_mount(mock_drive): + blob = response( + {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} + ) + drive, requests = mock_drive(blob, blob) + fs = filesystem(drive, "root/blob") + with pytest.raises(NotADirectoryError): + fs.makedirs("root/blob/child") + assert all(req[1] == "GET" for req in requests) From adb4a5cac8b6fb2611e927855fbbb622b9618bc7 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 08:50:37 -0800 Subject: [PATCH 3/6] Test mkdir races at the Drive request boundary --- pydrive2/test/test_fs_unit.py | 53 +++++++++++++---------------------- 1 file changed, 19 insertions(+), 34 deletions(-) diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 6714ebc..9aef589 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -606,20 +606,11 @@ def test_makedirs_bare_root_is_independent_of_named_mount(mock_drive): def test_makedirs_starts_at_cached_mount(mock_drive): - def folder(name): - return response( - { - "files": [ - {"name": name, "id": name, "mimeType": FOLDER_MIME_TYPE} - ] - } - ) - drive, requests = mock_drive( response({"driveId": "shared"}), - folder("a"), - folder("b"), - response({"files": []}), + listing(folder("a", "a")), + listing(folder("b", "b")), + listing(), response({"id": "new"}), ) fs = filesystem(drive, "FolderID/a/b") @@ -632,33 +623,27 @@ def folder(name): ] -def test_makedirs_classifies_drive_results_without_rereading_cache( - mock_drive, mocker -): - same_name = [ - {"name": "sub", "id": "file", "mimeType": "text/plain"}, - {"name": "Sub", "id": "wrong-case", "mimeType": FOLDER_MIME_TYPE}, - {"name": "sub", "id": "folder", "mimeType": FOLDER_MIME_TYPE}, - ] +def test_makedirs_uses_the_matching_folder_during_invalidation(mock_drive): + def invalidate(request): + if "name='sub'" in query(request).get("q", [""])[0]: + fs.invalidate_cache("root/sub") + drive, requests = mock_drive( - response({"files": same_name}), - response({"files": []}), + listing( + {"name": "sub", "id": "file", "mimeType": "text/plain"}, + folder("Sub", "wrong-case"), + folder("sub", "folder"), + ), + listing(), response({"id": "leaf"}), + listing(), + on_request=invalidate, ) fs = filesystem(drive) - cache_path = fs._cache_path_id - - def cache_then_invalidate(path, *ids, **kwargs): - cache_path(path, *ids, **kwargs) - if path == "sub": - fs.invalidate_cache("root/sub") - - mocker.patch.object( - fs, "_cache_path_id", side_effect=cache_then_invalidate - ) fs.makedirs("root/sub/leaf") - assert json.loads(requests[-1][2])["parents"] == ["folder"] - assert fs._ids_cache["ids"] == {"root": ""} + (create,) = [r for r in requests if r[1] == "POST"] + assert json.loads(create[2])["parents"] == ["folder"] + assert not fs.exists("root/sub/leaf") def test_makedirs_rejects_file_at_nested_mount(mock_drive): From a79d3a8f1ebb9c671332ab119351bbe653c275ac Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 09:06:31 -0800 Subject: [PATCH 4/6] Set up the listing test through makedirs --- pydrive2/test/test_fs.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index ad1724a..3c48536 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -177,8 +177,7 @@ def test_rm(fs, remote_dir): def test_ls(fs, remote_dir): - _, base = fs.split_path(remote_dir + "/dir/") - fs._path_to_item_ids(base, create=True) + fs.makedirs(remote_dir + "/dir") assert fs.ls(remote_dir + "/dir/") == [] files = set() From a76d0e89875dcde87521908c08ec87d9ed2acb85 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 09:48:27 -0800 Subject: [PATCH 5/6] Share root metadata across directory validation and Drive listings --- pydrive2/fs/spec.py | 81 ++++++++++++++++------------------- pydrive2/test/test_fs_unit.py | 57 ++++++++++++++++++++++-- 2 files changed, 91 insertions(+), 47 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ce02863..dec9a27 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -7,12 +7,11 @@ import threading from contextlib import contextmanager from itertools import chain -from typing import NotRequired, TypedDict +from typing import TypedDict import appdirs from fsspec.spec import AbstractFileSystem from funcy import ( - cached_property, chunks, distinct, retry, @@ -43,7 +42,6 @@ class _IdsCache(TypedDict): dirs: dict[str, list[str]] ids: dict[str, str] - root_is_directory: NotRequired[bool] def _in_subtrees(path: str, roots: tuple[str, ...]) -> bool: @@ -63,7 +61,7 @@ def _without_subtrees(cache: _IdsCache, roots: tuple[str, ...]) -> _IdsCache: paths_by_id = { item_id: path for path, ids in dirs.items() for item_id in ids } - return {**cache, "dirs": dirs, "ids": paths_by_id} + return {"dirs": dirs, "ids": paths_by_id} class GDriveAuthError(Exception): @@ -275,6 +273,7 @@ def __init__( super().__init__(**kwargs) self._cache_lock = threading.RLock() self._directory_ids: _IdsCache | None = None + self._root_metadata: dict = {} self.path = path self.root, self.base = self.split_path(self.path) @@ -401,6 +400,8 @@ def _invalidate_paths(self, *paths): for path in paths: super().invalidate_cache(path) with self._cache_lock: + if "" in subtrees: + self._root_metadata = {} if _in_subtrees(self.base, subtrees): self._directory_ids = None elif self._directory_ids is not None: @@ -411,43 +412,41 @@ def _invalidate_paths(self, *paths): def _is_cached_directory(self, item_id): with self._cache_lock: cache = self._directory_ids - return cache is not None and ( - item_id == self.root or item_id in cache["ids"] - ) + return cache is not None and item_id in cache["ids"] - @cached_property + @property def _list_params(self): params = {"corpora": "user"} if self.root == "appDataFolder": params["spaces"] = "appDataFolder" elif self.root != "root": - drive_id = self._gdrive_shared_drive_id(self.root) + try: + drive_id = self._get_root_metadata().get("driveId") + except FileNotFoundError as exc: + raise PermissionError from exc if drive_id: - logger.debug( - f"GDrive remote '{self.path}' is using shared drive id '{drive_id}'." - ) - params["driveId"] = drive_id - params["corpora"] = "drive" + params.update(driveId=drive_id, corpora="drive") return params @_gdrive_retry - def _gdrive_shared_drive_id(self, item_id): - from pydrive2.files import ApiRequestError - - param = {"id": item_id} - # it does not create a file on the remote - item = self.client.CreateFile(param) - # ID of the shared drive the item resides in. - # Only populated for items in shared drives. - try: - item.FetchMetadata("driveId") - except ApiRequestError as exc: - error_code = exc.error.get("code", 0) - if error_code == 404: - raise PermissionError from exc - raise - - return item.get("driveId", None) + def _get_root_metadata(self): + with self._cache_lock: + # A root invalidation during the request replaces this dictionary. + metadata = self._root_metadata + if not metadata: + item = self.client.CreateFile({"id": self.root}) + with _translate_not_found(self.root): + item.FetchMetadata("driveId,mimeType,trashed") + if item.get("trashed"): + return item.metadata + metadata.update(item.metadata) + if drive_id := metadata.get("driveId"): + logger.debug( + "GDrive remote %r is using shared drive id %r.", + self.path, + drive_id, + ) + return metadata def _gdrive_list(self, query): param = { @@ -585,17 +584,13 @@ def _mkdir(self, path, create_parents, exist_ok): root, base = self._split_mounted_path(path) if not base: if root not in {"root", "appDataFolder"}: - # Checking the root should not resolve a nested mount. - root_cache = ( - self._directory_ids if self.base else self._ids_cache - ) - if root_cache is None or not root_cache.get( - "root_is_directory" - ): - if self.info(path)["type"] != "directory": - raise FileExistsError(path) - if root_cache is not None: - root_cache["root_is_directory"] = True + metadata = self._get_root_metadata() + if metadata.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) + if metadata.get("mimeType") != FOLDER_MIME_TYPE: + raise FileExistsError(path) if not exist_ok: raise FileExistsError(path) return @@ -870,7 +865,7 @@ def _gdrive_open_file(self, item_id, block_size=None): def rm_file(self, path): item_id = self._get_item_id(path) self._gdrive_delete_file(item_id) - if self._is_cached_directory(item_id): + if item_id == self.root or self._is_cached_directory(item_id): self.invalidate_cache(path) @_gdrive_retry diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index e7bf04a..a8f7a05 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -319,15 +319,17 @@ def test_rediscovered_directory_id_leaves_its_old_path(mock_drive): def test_empty_root_marker_refreshes_a_folder_id_mount(mock_drive): - drive, _ = mock_drive( + drive, requests = mock_drive( response({"driveId": "shared"}), listing(folder("dir", "old")), + response({"driveId": "new-drive"}), listing(), ) fs = filesystem(drive, "FolderID") assert fs.exists("FolderID/dir") fs.invalidate_cache("") assert not fs.exists("FolderID/dir") + assert query(requests[-1])["driveId"] == ["new-drive"] @pytest.mark.parametrize("operation", ["rename", "delete"]) @@ -670,14 +672,61 @@ def test_makedirs_rejects_file(mock_drive, path, expected): assert [req[1] for req in requests] == ["GET"] -def test_makedirs_validates_mount_id_once(mock_drive): - drive, requests = mock_drive(response({"mimeType": FOLDER_MIME_TYPE})) +@pytest.mark.parametrize("list_first", [False, True]) +def test_makedirs_and_ls_share_mount_metadata(mock_drive, list_first): + drive, requests = mock_drive( + response({"driveId": "shared", "mimeType": FOLDER_MIME_TYPE}), + listing(), + ) fs = filesystem(drive, "FolderID") + if list_first: + assert fs.ls("FolderID") == [] fs.makedirs("FolderID", exist_ok=True) + fs.invalidate_cache("FolderID/sub") + if not list_first: + assert fs.ls("FolderID") == [] fs.makedirs("FolderID", exist_ok=True) with pytest.raises(FileExistsError): fs.mkdir("FolderID") - assert len(requests) == 1 + stat, children = requests + assert set(query(stat)["fields"][0].split(",")) == { + "driveId", + "mimeType", + "trashed", + } + assert query(children)["driveId"] == ["shared"] + + +def test_invalidating_root_during_stat_discards_its_result(mock_drive): + def invalidate(request): + fs.invalidate_cache("FolderID") + + root = {"mimeType": FOLDER_MIME_TYPE} + drive, _ = mock_drive( + response(root), + response(dict(root, trashed=True)), + on_request=invalidate, + ) + fs = filesystem(drive, "FolderID") + fs.makedirs("FolderID", exist_ok=True) + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + + +def test_makedirs_after_trashing_and_restoring_the_mount(mock_drive): + root = {"mimeType": FOLDER_MIME_TYPE} + drive, _ = mock_drive( + response(root), + response({"trashed": True}), + response(dict(root, trashed=True)), + response(root), + ) + fs = filesystem(drive, "FolderID", trash_only=True) + fs.makedirs("FolderID", exist_ok=True) + fs.rm_file("FolderID") + with pytest.raises(FileNotFoundError): + fs.makedirs("FolderID", exist_ok=True) + fs.makedirs("FolderID", exist_ok=True) @pytest.mark.parametrize( From 1ec813e199665fdf49092dca9c48f897e1336b8d Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 18:11:55 -0800 Subject: [PATCH 6/6] Reuse the mount lookup and enforce mkdir request budgets --- pydrive2/fs/spec.py | 71 +++++++++++++++++++---------------- pydrive2/test/test_fs_unit.py | 26 ++++++++++++- 2 files changed, 63 insertions(+), 34 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index dec9a27..14afdf9 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -339,36 +339,36 @@ def _split_file_path(self, path): @property def _ids_cache(self) -> _IdsCache: - with self._cache_lock: - if self._directory_ids is None: - self._directory_ids = self._load_directory_ids() - return self._directory_ids - - def _load_directory_ids(self) -> _IdsCache: - cache: _IdsCache = {"dirs": {}, "ids": {}} - - self._cache_path_id( - self.base, *self._mount_directory_ids(), cache=cache - ) - return cache + return self._directory_cache_and_mount_items()[0] - def _mount_directory_ids(self): - if not self.base: - return [self.root] - parent, name = posixpath.split(self.base) - parent_ids = self._path_to_item_ids(parent, use_cache=False) - items = list(self._named_items(parent_ids, name)) - if not items: - raise FileNotFoundError( - errno.ENOENT, - os.strerror(errno.ENOENT), - f"Confirm {self.path} exists and you can access it", - ) - return [ - item["id"] - for item in items - if item["mimeType"] == FOLDER_MIME_TYPE - ] + def _directory_cache_and_mount_items(self): + """Return the cache and any mount listing fetched by this call.""" + with self._cache_lock: + if self._directory_ids is not None: + return self._directory_ids, None + + cache: _IdsCache = {"dirs": {}, "ids": {}} + items = None + if self.base: + parent, name = posixpath.split(self.base) + parents = self._path_to_item_ids(parent, cache=cache) + items = list(self._named_items(parents, name)) + if not items: + raise FileNotFoundError( + errno.ENOENT, + os.strerror(errno.ENOENT), + f"Confirm {self.path} exists and you can access it", + ) + directories = [ + item["id"] + for item in items + if item["mimeType"] == FOLDER_MIME_TYPE + ] + else: + directories = [self.root] + self._cache_path_id(self.base, *directories, cache=cache) + self._directory_ids = cache + return cache, items def _named_items(self, parent_ids, name): # Drive's name query is case-insensitive. @@ -514,11 +514,14 @@ def _path_to_item_ids( ): if not path: return [self.root] + mount_items = None if use_cache and cache is None: - cache = self._ids_cache + cache, mount_items = self._directory_cache_and_mount_items() item_ids = self._get_cached_item_ids(path, use_cache, cache) if item_ids: return item_ids + if path == self.base and mount_items is not None: + return [item["id"] for item in mount_items] parent_path, name = posixpath.split(path) parent_ids = self._path_to_item_ids( @@ -595,7 +598,7 @@ def _mkdir(self, path, create_parents, exist_ok): raise FileExistsError(path) return - cache = self._ids_cache + cache, mount_items = self._directory_cache_and_mount_items() parent = base missing = [] while not ( @@ -609,7 +612,11 @@ def _mkdir(self, path, create_parents, exist_ok): for name in reversed(missing): child = posixpath.join(parent, name) leaf = child == base - matches = list(self._named_items(parent_ids, name)) + matches = ( + mount_items + if child == self.base and mount_items is not None + else list(self._named_items(parent_ids, name)) + ) dirs = [ item["id"] for item in matches diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 898cff8..cbf2fb8 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -661,10 +661,15 @@ def test_makedirs_creates_empty_drive_folders(mock_drive): ) fs = filesystem(drive, "shared") fs.makedirs("gdrive://shared/parent/leaf") + assert [r[1] for r in requests] == ["GET", "GET", "POST", "GET", "POST"] + cold_requests = len(requests) assert fs.exists("shared/parent/leaf") fs.makedirs("shared/parent/leaf", exist_ok=True) with pytest.raises(FileExistsError): fs.makedirs("shared/parent/leaf") + with pytest.raises(FileExistsError): + fs.mkdir("shared/parent/leaf") + assert len(requests) == cold_requests assert [json.loads(req[2]) for req in requests if req[1] == "POST"] == [ { "name": "parent", @@ -682,6 +687,22 @@ def test_mkdir_without_missing_parents(mock_drive): assert [req[1] for req in requests] == ["GET"] +def test_mkdir_in_existing_parent(mock_drive): + drive, requests = mock_drive( + listing(folder("parent", "P")), listing(), response({"id": "leaf"}) + ) + fs = filesystem(drive) + assert fs.exists("root/parent") + before = len(requests) + fs.mkdir("root/parent/leaf", create_parents=False) + lookup, create = requests[before:] + assert "'P' in parents" in query(lookup)["q"][0] + assert create[1] == "POST" and json.loads(create[2])["parents"] == ["P"] + before = len(requests) + fs.makedirs("root/parent/leaf", exist_ok=True) + assert len(requests) == before + + @pytest.mark.parametrize( "path,expected", [("root/blob", FileExistsError), ("root/blob/sub", NotADirectoryError)], @@ -819,8 +840,9 @@ def test_makedirs_rejects_file_at_nested_mount(mock_drive): blob = response( {"files": [{"name": "blob", "id": "F", "mimeType": "text/plain"}]} ) - drive, requests = mock_drive(blob, blob) + drive, requests = mock_drive(blob) fs = filesystem(drive, "root/blob") with pytest.raises(NotADirectoryError): fs.makedirs("root/blob/child") - assert all(req[1] == "GET" for req in requests) + (lookup,) = requests + assert "name='blob'" in query(lookup)["q"][0]