Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 20 additions & 21 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,12 @@ def _preferred_ids(children, withdirs):
return preferred


def _refuse_trashed(item, path):
# A trashed folder still lists its children for a while.
if item.get("trashed"):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), path)


def _select_item_id(path, ids):
if ids:
return min(ids)
Expand Down Expand Up @@ -718,6 +724,7 @@ def _list_params(self):
metadata = self._get_root_metadata()
except FileNotFoundError as exc:
raise PermissionError from exc
_refuse_trashed(metadata, self.root)
Comment thread
shcheklein marked this conversation as resolved.
Resolved
if "appDataFolder" in metadata.get("spaces", ()):
params["spaces"] = "appDataFolder"
elif metadata.get("driveId"):
Expand Down Expand Up @@ -875,10 +882,7 @@ def _lookup_item(self, path):
if base or self.root in _ROOT_ALIASES:
return item_id, item_id in match.folders
metadata = self._get_root_metadata()
if metadata.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
_refuse_trashed(metadata, path)
return item_id, metadata.get("mimeType") == FOLDER_MIME_TYPE

def _forget_new_ids(self):
Expand Down Expand Up @@ -970,10 +974,7 @@ def _mkdir(self, path, create_parents, exist_ok):
cached = base and self._dirs.has_directory(base, self.base)
if not cached and root not in _ROOT_ALIASES:
metadata = self._get_root_metadata(fresh=True)
if metadata.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), root
)
_refuse_trashed(metadata, root)
if metadata.get("mimeType") != FOLDER_MIME_TYPE:
if base:
raise NotADirectoryError(
Expand Down Expand Up @@ -1023,10 +1024,8 @@ def info(self, path):
_gdrive_retry_repeatable(gdrive_file.FetchMetadata)(
fields=fields
)
if not base and gdrive_file.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
if not base:
_refuse_trashed(gdrive_file, path)

return _file_entry(
posixpath.join(bucket, base).rstrip("/"), gdrive_file
Expand All @@ -1045,11 +1044,8 @@ def ls(self, path, detail=False):
)
except FileNotFoundError as exc:
raise PermissionError from exc
_refuse_trashed(root, path)
if root["mimeType"] != FOLDER_MIME_TYPE:
if root.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
return [_file_entry(bucket, root, detail)]

match, generation = self._lookup_path(base, folders_only=True)
Expand Down Expand Up @@ -1163,7 +1159,13 @@ def find(
if maxdepth is not None and maxdepth < 1:
raise ValueError("maxdepth must be at least 1")
resolver = self._resolver()
match = resolver.resolve(base, folders_only=not (withdirs and detail))
try:
match = resolver.resolve(
base, folders_only=not (withdirs and detail)
)
except FileNotFoundError:
# The root is in the trash, so nothing under it exists.
return {} if detail else []
start = posixpath.join(root, base).rstrip("/")
check_empty_root = False
if not base and root not in _ROOT_ALIASES:
Expand Down Expand Up @@ -1433,10 +1435,7 @@ def rmdir(self, path):
errno.EPERM, "Cannot remove a Drive root", path
)
item = self._get_root_metadata(fresh=True)
if item.get("trashed"):
raise FileNotFoundError(
errno.ENOENT, os.strerror(errno.ENOENT), path
)
_refuse_trashed(item, path)
if item.get("mimeType") != FOLDER_MIME_TYPE:
raise NotADirectoryError(
errno.ENOTDIR, os.strerror(errno.ENOTDIR), path
Expand Down
51 changes: 51 additions & 0 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,3 +734,54 @@ 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 folder_with_a_file(service_auth, fs_factory, request):
drive = GoogleDrive(service_auth)
base_id = fs_factory()[1]["id"]
folder = drive.CreateFile(
{
"name": uuid.uuid4().hex,
"mimeType": "application/vnd.google-apps.folder",
"parents": [base_id],
}
)
pydrive_retry(folder.Upload)
request.addfinalizer(lambda: pydrive_retry(folder.Delete))
file = drive.CreateFile({"name": "a.txt", "parents": [folder["id"]]})
file.SetContentString("a")
pydrive_retry(file.Upload)
return folder["id"]


def assert_missing(fs, root):
child = f"{root}/a.txt"
for path in (root, child):
with pytest.raises(FileNotFoundError):
fs.ls(path)
with pytest.raises(FileNotFoundError):
fs.info(path)
assert not fs.exists(path)
with pytest.raises(FileNotFoundError):
fs.cat_file(child)
# As for any missing path, find() and walk() return nothing.
assert fs.find(root) == []
assert fs.find(child) == []
assert list(fs.walk(root)) == []


def test_folder_id_root_trashed_by_another_client_is_missing_with_or_without_cache(
service_auth, folder_with_a_file
):
root = folder_with_a_file
cached = GDriveFileSystem(root, service_auth, skip_instance_cache=True)
assert cached.ls(root) == [f"{root}/a.txt"]

pydrive_retry(GoogleDrive(service_auth).CreateFile({"id": root}).Trash)

# The filesystem learns of changes by other clients when told to.
cached.invalidate_cache()
assert_missing(cached, root)
new = GDriveFileSystem(root, service_auth, skip_instance_cache=True)
assert_missing(new, root)
38 changes: 38 additions & 0 deletions pydrive2/test/test_fs_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,44 @@ def test_find_trashed_root_id_skips_listing(mock_drive):
assert "trashed" in query(stat)["fields"][0].split(",")


@pytest.mark.parametrize(
"operation",
[
lambda fs: fs.info("FolderID/a.txt"),
lambda fs: fs.ls("FolderID/a.txt"),
lambda fs: fs.cat_file("FolderID/a.txt"),
],
ids=["info", "ls", "cat_file"],
)
def test_path_under_a_trashed_folder_id_root_is_missing_while_drive_lists_it(
mock_drive, operation
):
a_file = {"name": "a.txt", "id": "A", "mimeType": "text/plain"}
drive, requests = mock_drive(
response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}),
listing(a_file),
)
with pytest.raises(FileNotFoundError):
operation(filesystem(drive, "FolderID"))
(stat,) = requests
assert "trashed" in query(stat)["fields"][0].split(",")


@pytest.mark.parametrize(("detail", "nothing"), [(False, []), (True, {})])
def test_find_under_a_trashed_folder_id_root_finds_nothing_while_drive_lists_it(
mock_drive, detail, nothing
):
a_file = {"name": "a.txt", "id": "A", "mimeType": "text/plain"}
drive, requests = mock_drive(
response({"mimeType": FOLDER_MIME_TYPE, "trashed": True}),
listing(a_file),
)
fs = filesystem(drive, "FolderID")
assert fs.find("FolderID/a.txt", detail=detail) == nothing
(stat,) = requests
assert "trashed" in query(stat)["fields"][0].split(",")


@pytest.mark.parametrize("survivors", [[], [folder("empty", "B")]])
def test_find_after_external_removal_of_a_cached_named_folder(
mock_drive, survivors
Expand Down
Loading