Skip to content
Merged
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
31 changes: 29 additions & 2 deletions pydrive2/fs/spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,20 @@ 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):
"""Return the ID at a path and whether it is a folder."""
_, base = self._split_mounted_path(path)
match, _ = self._lookup_path(base)
item_id = _select_item_id(path, match.ids)
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
)
return item_id, metadata.get("mimeType") == FOLDER_MIME_TYPE

@_gdrive_retry
def _gdrive_create_dir(self, parent_id, name):
item = self.client.CreateFile(
Expand Down Expand Up @@ -947,6 +961,9 @@ def upload_fobj(self, stream, rpath, callback=None, **kwargs):
return item

def put_file(self, lpath, rpath, callback=None, **kwargs):
if os.path.isdir(lpath):
self.makedirs(rpath, exist_ok=True)
return
if callback:
callback.set_size(os.path.getsize(lpath))
with open(lpath, "rb") as stream:
Expand All @@ -961,8 +978,12 @@ def _gdrive_upload_fobj(self, name, parent_id, stream, callback=None):

def cp_file(self, lpath, rpath, **kwargs):
"""Ask Drive to copy the file directly into the destination folder."""
self._split_mounted_path(rpath)
source_id, is_folder = self._lookup_item(lpath)
if is_folder:
self.makedirs(rpath, exist_ok=True)
return
Comment thread
shcheklein marked this conversation as resolved.
Resolved
parent, name = self._split_file_path(rpath)
source_id = self._get_item_id(lpath)
parent_id = self._get_item_id(parent, create=True)
self._gdrive_copy_file(source_id, parent_id, name)
self._dirs.file_added(parent_id, name)
Expand Down Expand Up @@ -1045,7 +1066,13 @@ def mv(self, path1, path2, maxdepth=None, **kwargs):

def get_file(self, rpath, lpath, callback=None, block_size=None, **kwargs):
with _translate_not_found(rpath):
item_id = self._get_item_id(rpath)
item_id, is_folder = self._lookup_item(rpath)
if is_folder:
os.makedirs(lpath, exist_ok=True)
return None
parent = os.path.dirname(os.fspath(lpath))
if parent:
os.makedirs(parent, exist_ok=True)
return self._gdrive_get_file(
item_id, lpath, callback=callback, block_size=block_size
)
Comment thread
shcheklein marked this conversation as resolved.
Resolved
Expand Down
89 changes: 89 additions & 0 deletions pydrive2/test/test_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,20 @@ def test_copy_file_to_new_directory(fs, remote_dir):
assert fs.cat_file(source) == b"payload"


def test_recursive_copy_copies_nested_files_and_empty_folders(fs, remote_dir):
source = remote_dir + "/source"
target = remote_dir + "/target"
fs.pipe_file(source + "/a.txt", b"a")
fs.pipe_file(source + "/nested/b.txt", b"b")
fs.makedirs(source + "/empty")

fs.copy(source, target, recursive=True)

assert fs.cat_file(target + "/a.txt") == b"a"
assert fs.cat_file(target + "/nested/b.txt") == b"b"
assert fs.isdir(target + "/empty")


def test_invalidating_parent_reloads_replaced_mount(fs, remote_dir):
mount = remote_dir + "/mount"
fs.touch(mount + "/before")
Expand Down Expand Up @@ -443,6 +457,81 @@ def test_get_file(fs, tmpdir, remote_dir):
assert dest_file.read() == "data"


def test_recursive_put_uploads_nested_files_and_empty_folders(
fs, tmp_path, remote_dir
):
source = tmp_path / "source"
target = remote_dir + "/target"
(source / "nested").mkdir(parents=True)
(source / "empty").mkdir()
(source / "a.txt").write_bytes(b"a")
(source / "nested" / "b.txt").write_bytes(b"b")

fs.put(str(source), target, recursive=True)

assert fs.cat_file(target + "/a.txt") == b"a"
assert fs.cat_file(target + "/nested/b.txt") == b"b"
assert fs.isdir(target + "/empty")


def test_recursive_get_downloads_nested_files_and_empty_folders(
fs, tmp_path, remote_dir
):
source = remote_dir + "/source"
target = tmp_path / "target"
fs.pipe_file(source + "/a.txt", b"a")
fs.pipe_file(source + "/nested/b.txt", b"b")
fs.makedirs(source + "/empty")

fs.get(source, str(target), recursive=True)

assert (target / "a.txt").read_bytes() == b"a"
assert (target / "nested" / "b.txt").read_bytes() == b"b"
assert (target / "empty").is_dir()


def test_recursive_get_with_maxdepth_creates_missing_local_folders(
fs, tmp_path, remote_dir
):
source = remote_dir + "/source"
target = tmp_path / "target"
fs.pipe_file(source + "/a.txt", b"a")
fs.pipe_file(source + "/nested/b.txt", b"b")

fs.get(source, str(target), recursive=True, maxdepth=2)

assert (target / "a.txt").read_bytes() == b"a"
assert (target / "nested" / "b.txt").read_bytes() == b"b"


def test_get_file_downloads_a_file_addressed_by_its_id(
fs, tmp_path, remote_dir
):
name = uuid.uuid4().hex
target = tmp_path / "target"
fs.pipe_file(f"{remote_dir}/{name}", b"data")
(item,) = fs.client.ListFile({"q": f"name = '{name}'"}).GetList()
by_id = GDriveFileSystem(item["id"], fs.client.auth)

by_id.get_file(item["id"], target)

assert target.read_bytes() == b"data"


def test_recursive_get_downloads_a_folder_addressed_by_its_id(
fs, tmp_path, remote_dir
):
name = uuid.uuid4().hex
target = tmp_path / "target"
fs.pipe_file(f"{remote_dir}/{name}/a.txt", b"a")
(item,) = fs.client.ListFile({"q": f"name = '{name}'"}).GetList()
by_id = GDriveFileSystem(item["id"], fs.client.auth)

by_id.get(item["id"], str(target), recursive=True)

assert (target / "a.txt").read_bytes() == b"a"


def test_get_file_callback(fs, tmpdir, remote_dir):
src_file = tmpdir / "a.txt"
dest_file = tmpdir / "b.txt"
Expand Down
29 changes: 27 additions & 2 deletions pydrive2/test/test_fs_registration.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,36 @@ def test_writes_require_filename(mock_drive, tmp_path, url):
fs.upload_fobj(io.BytesIO(), destination)
with pytest.raises(ValueError, match="folder ID and name"):
fs.put_file(local, destination)
with pytest.raises(ValueError, match="folder ID and name"):
fs.cp_file(f"{fs.root}/source", destination)
assert not requests


SOURCE_LOOKUP = response(
{"files": [{"name": "source", "id": "S", "mimeType": "text/plain"}]}
)


@pytest.mark.parametrize(
("url", "responses"),
[
("gdrive://", [SOURCE_LOOKUP]),
("gdrive://root", [SOURCE_LOOKUP]),
(
"gdrive://FoLdEr/",
[response({"mimeType": FOLDER_MIME_TYPE}), SOURCE_LOOKUP],
),
("gdrive://appDataFolder", [SOURCE_LOOKUP]),
],
)
def test_copying_a_file_onto_the_root_requires_a_filename(
mock_drive, url, responses
):
drive, requests = mock_drive(*responses)
fs, path = fsspec.core.url_to_fs(url, google_auth=drive.auth)
with pytest.raises(ValueError, match="folder ID and name"):
fs.cp_file(f"{fs.root}/source", path)
assert all(request[1] == "GET" for request in requests)


def test_copy_to_implicit_root(mock_drive):
source = {"name": "source", "id": "source-id", "mimeType": "text/plain"}
drive, requests = mock_drive(
Expand Down
123 changes: 123 additions & 0 deletions pydrive2/test/test_fs_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -2857,6 +2857,129 @@ def test_download_progress_uses_media_responses(
assert dest.read_bytes() == b"xyz"


TEXT_FILE = {"name": "a.txt", "id": "A", "mimeType": "text/plain"}
DOWNLOAD = ({"status": "200"}, b"data")


def test_recursive_get_makes_one_lookup_and_one_download_per_file(
mock_drive, tmp_path
):
drive, requests = mock_drive(
listing(folder("source", "S")),
listing(TEXT_FILE),
listing(TEXT_FILE),
DOWNLOAD,
)
filesystem(drive).get("root/source", str(tmp_path / "out"), recursive=True)
assert (tmp_path / "out" / "a.txt").read_bytes() == b"data"
assert len(requests) == 4


def test_recursive_put_uploads_files_and_creates_empty_folders(
mock_drive, tmp_path
):
(tmp_path / "source" / "empty").mkdir(parents=True)
(tmp_path / "source" / "a.txt").write_bytes(b"data")
drive, requests = mock_drive(
listing(),
listing(),
response({"id": "U"}),
({"status": "200", "location": "https://example.test/upload"}, ""),
response({"id": "A"}),
listing(),
response({"id": "E"}),
)
filesystem(drive).put(str(tmp_path / "source"), "root/up", recursive=True)
created = [json.loads(r[2]) for r in requests if r[1] == "POST"]
assert [(item["name"], item["parents"]) for item in created] == [
("up", ["root"]),
("a.txt", ["U"]),
("empty", ["U"]),
]


def test_recursive_copy_puts_the_contents_of_a_folder_into_the_root(
mock_drive,
):
drive, requests = mock_drive(
listing(folder("source", "S")),
listing(TEXT_FILE),
response({"mimeType": FOLDER_MIME_TYPE}),
listing(TEXT_FILE),
response({"id": "copy"}),
)
filesystem(drive).copy("root/source/", "root", recursive=True)
copy = requests[-1]
assert urlsplit(copy[0]).path == "/drive/v3/files/A/copy"
assert json.loads(copy[2]) == {"name": "a.txt", "parents": ["root"]}


def test_get_file_of_a_listed_folder_creates_it_locally_without_requests(
mock_drive, tmp_path
):
drive, requests = mock_drive(listing(folder("source", "S")))
fs = filesystem(drive)
fs.ls("root")
fs.get_file("root/source", tmp_path / "source")
assert (tmp_path / "source").is_dir()
assert len(requests) == 1


def test_get_file_from_a_bare_file_id_asks_for_its_type_once(
mock_drive, tmp_path
):
drive, requests = mock_drive(
response({"mimeType": "text/plain"}), DOWNLOAD, DOWNLOAD
)
fs = filesystem(drive, "FileID")
fs.get_file("FileID", tmp_path / "first")
fs.get_file("FileID", tmp_path / "second")
assert (tmp_path / "second").read_bytes() == b"data"
assert [query(r)["alt"] for r in requests] == [
["json"],
["media"],
["media"],
]


def test_get_file_from_a_bare_folder_id_creates_the_local_folder(
mock_drive, tmp_path
):
drive, _ = mock_drive(response({"mimeType": FOLDER_MIME_TYPE}))
filesystem(drive, "FolderID").get_file("FolderID", tmp_path / "folder")
assert (tmp_path / "folder").is_dir()


@pytest.mark.parametrize("mime_type", [FOLDER_MIME_TYPE, "text/plain"])
def test_get_file_from_a_trashed_bare_id_raises_not_found(
mock_drive, tmp_path, mime_type
):
drive, _ = mock_drive(response({"mimeType": mime_type, "trashed": True}))
with pytest.raises(FileNotFoundError):
filesystem(drive, "ItemID").get_file("ItemID", tmp_path / "item")
assert not (tmp_path / "item").exists()


def test_get_file_creates_missing_local_parent_folders(mock_drive, tmp_path):
drive, _ = mock_drive(listing(TEXT_FILE), DOWNLOAD)
dest = tmp_path / "new" / "nested" / "a.txt"
filesystem(drive).get_file("root/a.txt", dest)
assert dest.read_bytes() == b"data"


@pytest.mark.parametrize(
("folder_id", "file_id", "is_folder"),
[("A", "B", True), ("B", "A", False)],
)
def test_get_file_uses_the_lower_id_when_a_file_and_a_folder_share_a_name(
mock_drive, tmp_path, folder_id, file_id, is_folder
):
file = {"name": "same", "id": file_id, "mimeType": "text/plain"}
drive, _ = mock_drive(listing(folder("same", folder_id), file), DOWNLOAD)
filesystem(drive).get_file("root/same", tmp_path / "same")
assert (tmp_path / "same").is_dir() is is_folder


def test_partial_reads_and_peek_across_chunks():
stream = IterStream(iter([b"abc", b"", b"de", b"fghi"]))
assert stream.read1(0) == b""
Expand Down
Loading