From 8d76b802d9c0419d82f579ad517cbc988b449659 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:34:53 -0800 Subject: [PATCH 1/6] Read ranges with one request and open files in smaller blocks - head(), tail() and cat_file(path, start, end) ask Drive for the bytes they return, with one ranged request. head() used to download the first 100 MiB of a file, and cat_file() with a start failed because the stream cannot seek. A Google Workspace file is exported whole and cut, since Drive exports only whole files. - open() asks Drive for fs.blocksize bytes (4 MiB by default) per read, instead of 100 MiB, unless block_size says otherwise. Co-Authored-By: Claude Opus 5.5 --- pydrive2/files.py | 26 +++++++++++++ pydrive2/fs/spec.py | 40 +++++++++++++++++++- pydrive2/test/test_fs.py | 71 +++++++++++++++++++++++++++++++++++ pydrive2/test/test_fs_unit.py | 11 ------ 4 files changed, 136 insertions(+), 12 deletions(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index a1766669..947b3713 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -519,6 +519,32 @@ def open_stream(request, content_type): request = files.export_media(fileId=file_id, mimeType=export_type) return open_stream(request, export_type) + @LoadAuth + def _GetContentRange(self, first, last=None, acknowledge_abuse=False): + """Bytes first to last of the content, both included, in one request. + + As in an HTTP range, last=None reads to the end, and a negative first + with last=None reads the last -first bytes. Google Workspace files + cannot be read this way: Drive answers 403 fileNotDownloadable. + """ + request = self.auth.service.files().get_media( + fileId=self._FileId(), + acknowledgeAbuse=acknowledge_abuse, + supportsAllDrives=True, + ) + if first < 0: + request.headers["Range"] = f"bytes={first}" + else: + end = "" if last is None else last + request.headers["Range"] = f"bytes={first}-{end}" + try: + return self._Execute(request) + except ApiRequestError as error: + # The range starts past the end, as for any range of an empty file. + if error.error.get("code") == 416: + return b"" + raise + @LoadAuth def FetchMetadata(self, fields=None, fetch_all=False): """Download file's metadata from id using Files.get(). diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac47994b..5e44d084 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1399,7 +1399,8 @@ def _gdrive_open_file(self, item_id, block_size=None): param = {"id": item_id} # it does not create a file on the remote gdrive_file = self.client.CreateFile(param) - options = {} + # Each read() asks Drive for one block, so a short read stays short. + options = {"chunksize": self.blocksize} if block_size not in (None, "default") and block_size > 0: options["chunksize"] = block_size fd = _gdrive_retry_read(gdrive_file.GetContentIOBuffer)( @@ -1407,6 +1408,43 @@ def _gdrive_open_file(self, item_id, block_size=None): ) return IterStream(iter(_gdrive_retry_read(fd.read), None)) + def cat_file(self, path, start=None, end=None, **kwargs): + """Return the file's bytes, or bytes start to end, as a slice would. + + A range is read with one request that asks Drive for those bytes. + """ + if start is None and end is None: + return super().cat_file(path, **kwargs) + start = start or 0 + if end is not None and (start < 0 or end < 0): + size = self.info(path)["size"] + if size is None: # A Google Workspace file has no size. + return super().cat_file(path)[start:end] + start, end, _ = slice(start, end).indices(size) + if end is not None and end <= start: + return b"" + with _translate_not_found(path): + item_id = self._get_item_id(path) + file = self.client.CreateFile({"id": item_id}) + read = _gdrive_retry_repeatable(file._GetContentRange) + try: + return read( + start, + None if end is None else end - 1, + acknowledge_abuse=self._acknowledge_abuse, + ) + except ApiRequestError as error: + if error.GetField("reason") != "fileNotDownloadable": + raise + # Drive exports a Google Workspace file only as a whole. + return super().cat_file(path)[start:end] + + def head(self, path, size=1024): + return self.cat_file(path, 0, size) + + def tail(self, path, size=1024): + return self.cat_file(path, -size) + def rmdir(self, path): """Remove one empty Drive folder, honoring the trash_only setting.""" root, base = self._split_mounted_path(path) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..2185d6d3 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -734,3 +734,74 @@ 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 downloads(service_auth, monkeypatch): + """The range asked for and the bytes received in each download.""" + http = service_auth.Get_Http_Object() + send = http.request + seen = [] + + def request(uri, method="GET", body=None, headers=None, **kwargs): + response, content = send( + uri, method, body=body, headers=headers, **kwargs + ) + if "alt=media" in uri: + asked = {k.lower(): v for k, v in (headers or {}).items()} + seen.append((asked.get("range"), len(content))) + return response, content + + monkeypatch.setattr(http, "request", request) + monkeypatch.setattr(service_auth.thread_local, "http", http, raising=False) + return seen + + +@pytest.fixture +def two_mib_file(fs, remote_dir): + data = os.urandom(2 * 1024 * 1024) + path = remote_dir + "/data.bin" + fs.pipe_file(path, data) + return path, data + + +def test_head_downloads_only_the_bytes_asked_for(fs, two_mib_file, downloads): + path, data = two_mib_file + assert fs.head(path, 10) == data[:10] + assert downloads == [("bytes=0-9", 10)] + + +def test_tail_downloads_only_the_bytes_asked_for(fs, two_mib_file, downloads): + path, data = two_mib_file + assert fs.tail(path, 10) == data[-10:] + assert downloads == [("bytes=-10", 10)] + + +@pytest.mark.parametrize( + ("start", "end"), + [(5, 15), (-10, -5), (2 * 1024 * 1024 - 3, None), (3 * 1024 * 1024, None)], + ids=["middle", "from-the-end", "to-the-end", "past-the-end"], +) +def test_cat_file_of_a_range_returns_those_bytes(fs, two_mib_file, start, end): + path, data = two_mib_file + assert fs.cat_file(path, start, end) == data[start:end] + + +def test_head_of_an_empty_file_is_empty(fs, remote_dir): + fs.pipe_file(remote_dir + "/empty", b"") + assert fs.head(remote_dir + "/empty") == b"" + + +def test_head_of_a_google_doc_is_the_start_of_its_export(fs, workspace_files): + path = "root/" + workspace_files + assert fs.head(path, 5) == fs.cat_file(path)[:5] + + +def test_open_reads_one_block_per_request( + fs, two_mib_file, downloads, monkeypatch +): + path, data = two_mib_file + monkeypatch.setattr(fs, "blocksize", 512 * 1024) + with fs.open(path, "rb") as stream: + assert stream.read(10) == data[:10] + assert downloads == [("bytes=0-524287", 512 * 1024)] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..75c0e043 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -19,7 +19,6 @@ from google.auth.exceptions import TransportError from google.oauth2 import service_account from google.oauth2.credentials import Credentials -from googleapiclient.http import DEFAULT_CHUNK_SIZE from httplib2 import Response, ServerNotFoundError from pydrive2.files import ApiRequestError @@ -3162,16 +3161,6 @@ def test_open_uses_requested_download_block_size(mock_drive): assert [r[3]["range"] for r in requests] == ["bytes=0-1", "bytes=2-3"] -@pytest.mark.parametrize("block_size", [None, "default"]) -def test_open_uses_default_download_block_size(mock_drive, block_size): - drive, requests = mock_drive(({"status": "200"}, b"data")) - fs = filesystem(drive, "FileID") - with fs.open("FileID", block_size=block_size) as stream: - assert stream.read() == b"data" - (request,) = requests - assert request[3]["range"] == f"bytes=0-{DEFAULT_CHUNK_SIZE - 1}" - - @pytest.mark.parametrize("mode", ["wb", "wt"]) def test_flush_then_write_uploads_once_on_close(mock_drive, monkeypatch, mode): drive, _ = mock_drive() From b6909b85d166420e9ee8893fe4a26a1dfc0cfc0f Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:38:53 -0800 Subject: [PATCH 2/6] Describe the read sizes in the fsspec guide Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..4ed07414 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -255,8 +255,12 @@ repeated lookups. After an external move or deletion, use When listing a single Drive folder, ``ls()`` returns entries in page order. A file renamed during pagination can appear under both names. -For sequential reads, pass a positive ``block_size`` to ``fs.open()`` to set -the Drive download request size in bytes. A writer buffers data locally, +A file opened for reading downloads ``fs.blocksize`` bytes (4 MiB by +default) per request. Pass a positive ``block_size`` to ``fs.open()`` to +set another request size in bytes. ``fs.head()``, ``fs.tail()`` and +``fs.cat_file(path, start, end)`` download only the bytes they return, +except from Google Workspace files, which Drive exports whole. A writer +buffers data locally, using a temporary file for larger uploads. Calling ``flush()`` flushes the local buffer. Closing the writer uploads the file to Drive and reports any upload error. From aaf75dd3d13b1199e6eb4785f253ca44baca212b Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:11:50 -0800 Subject: [PATCH 3/6] Handle empty, folder, missing and compressed ranges, and slice exports as asked tail() of no bytes returns b"" without a download. A range of a folder raises IsADirectoryError, and of a missing file ID FileNotFoundError. A read with compression goes through fsspec, as before. A Google Workspace export is sliced with the caller's bounds, since Drive's size for such a file is not the export's length. One lookup gives the file's ID and size. The live read tests share one 2 MiB file, and check the default download block size without changing it. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 11 +++--- pydrive2/fs/spec.py | 81 ++++++++++++++++++++++++++++------------ pydrive2/test/test_fs.py | 78 +++++++++++++++++++++++++++++++++----- 3 files changed, 132 insertions(+), 38 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 4ed07414..fab65277 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -257,11 +257,12 @@ A file renamed during pagination can appear under both names. A file opened for reading downloads ``fs.blocksize`` bytes (4 MiB by default) per request. Pass a positive ``block_size`` to ``fs.open()`` to -set another request size in bytes. ``fs.head()``, ``fs.tail()`` and -``fs.cat_file(path, start, end)`` download only the bytes they return, -except from Google Workspace files, which Drive exports whole. A writer -buffers data locally, -using a temporary file for larger uploads. Calling ``flush()`` flushes the +set another request size in bytes. A program that reads large files from +start to end makes fewer requests with a larger size, such as 64 MiB. +``fs.head()``, ``fs.tail()`` and ``fs.cat_file(path, start, end)`` +download only the bytes they return, except from Google Workspace files, +which Drive exports whole. A writer buffers data locally, using a +temporary file for larger uploads. Calling ``flush()`` flushes the local buffer. Closing the writer uploads the file to Drive and reports any upload error. diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 5e44d084..ba84aeae 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1413,36 +1413,71 @@ def cat_file(self, path, start=None, end=None, **kwargs): A range is read with one request that asks Drive for those bytes. """ - if start is None and end is None: - return super().cat_file(path, **kwargs) - start = start or 0 - if end is not None and (start < 0 or end < 0): - size = self.info(path)["size"] - if size is None: # A Google Workspace file has no size. - return super().cat_file(path)[start:end] - start, end, _ = slice(start, end).indices(size) - if end is not None and end <= start: - return b"" + # Options such as compression change the bytes, so fsspec reads them. + if (start is None and end is None) or kwargs.get("compression"): + return super().cat_file(path, start=start, end=end, **kwargs) + first, last = start or 0, end + need_size = (first < 0 and last is not None) or (last or 0) < 0 with _translate_not_found(path): - item_id = self._get_item_id(path) - file = self.client.CreateFile({"id": item_id}) - read = _gdrive_retry_repeatable(file._GetContentRange) - try: - return read( - start, - None if end is None else end - 1, - acknowledge_abuse=self._acknowledge_abuse, + item_id, size = self._file_for_range(path, need_size) + if need_size and size is None: + # Drive exports a Google Workspace file only as a whole. + return super().cat_file(path, **kwargs)[start:end] + if need_size: + first, last, _ = slice(first, last).indices(size) + if last is not None and last <= first: + return b"" + file = self.client.CreateFile({"id": item_id}) + try: + return _gdrive_retry_repeatable(file._GetContentRange)( + first, + None if last is None else last - 1, + acknowledge_abuse=self._acknowledge_abuse, + ) + except ApiRequestError as error: + if error.GetField("reason") != "fileNotDownloadable": + raise + if item_id == self.root: + # A folder opened by its ID cannot be downloaded either. + self._file_for_range(path, need_size=True) + return super().cat_file(path, **kwargs)[start:end] + + def _file_for_range(self, path, need_size): + """The ID of the file at the path and, when needed, its size.""" + _, base = self._split_mounted_path(path) + if base or self.root in _ROOT_ALIASES: + match, _ = self._lookup_path(base) + item_id = _select_item_id(path, match.ids) + if item_id in match.folders: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + return item_id, next( + file.size for file in match.files if file.id == item_id ) - except ApiRequestError as error: - if error.GetField("reason") != "fileNotDownloadable": - raise - # Drive exports a Google Workspace file only as a whole. - return super().cat_file(path)[start:end] + if not need_size: + return self.root, None + item = self._get_root_metadata( + fresh=True, fields=f"driveId,trashed,{_INFO_FIELDS}" + ) + if item.get("trashed"): + raise FileNotFoundError( + errno.ENOENT, os.strerror(errno.ENOENT), path + ) + if item["mimeType"] == FOLDER_MIME_TYPE: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + size = item.get("size") + return self.root, None if size is None else int(size) def head(self, path, size=1024): return self.cat_file(path, 0, size) def tail(self, path, size=1024): + # As in fsspec, no size or a negative one returns nothing. + if size <= 0: + return b"" return self.cat_file(path, -size) def rmdir(self, path): diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 2185d6d3..feec0ed9 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -1,4 +1,5 @@ import errno +import gzip import os import posixpath import secrets @@ -757,11 +758,12 @@ def request(uri, method="GET", body=None, headers=None, **kwargs): return seen -@pytest.fixture -def two_mib_file(fs, remote_dir): +@pytest.fixture(scope="module") +def two_mib_file(fs_factory, base_remote_dir): + """A file that the read tests share and do not change.""" data = os.urandom(2 * 1024 * 1024) - path = remote_dir + "/data.bin" - fs.pipe_file(path, data) + path = f"{base_remote_dir}/{uuid.uuid4().hex}.bin" + fs_factory()[0].pipe_file(path, data) return path, data @@ -777,6 +779,13 @@ def test_tail_downloads_only_the_bytes_asked_for(fs, two_mib_file, downloads): assert downloads == [("bytes=-10", 10)] +@pytest.mark.parametrize("size", [0, -5]) +def test_tail_of_no_bytes_downloads_nothing(fs, two_mib_file, downloads, size): + path, _ = two_mib_file + assert fs.tail(path, size) == b"" + assert downloads == [] + + @pytest.mark.parametrize( ("start", "end"), [(5, 15), (-10, -5), (2 * 1024 * 1024 - 3, None), (3 * 1024 * 1024, None)], @@ -792,16 +801,65 @@ def test_head_of_an_empty_file_is_empty(fs, remote_dir): assert fs.head(remote_dir + "/empty") == b"" -def test_head_of_a_google_doc_is_the_start_of_its_export(fs, workspace_files): +def test_cat_file_of_a_range_of_a_compressed_file_returns_uncompressed_bytes( + fs, remote_dir +): + path = remote_dir + "/data.gz" + fs.pipe_file(path, gzip.compress(b"abcdefghij")) + assert fs.cat_file(path, end=5, compression="gzip") == b"abcde" + + +# Drive gives a Google Doc a size that is not the length of its export. +@pytest.mark.parametrize( + ("start", "end"), + [(0, 5), (-3, -1), (-3, None)], + ids=["head", "before-the-end", "tail"], +) +def test_cat_file_of_a_range_of_a_google_doc_slices_its_export( + fs, workspace_files, start, end +): path = "root/" + workspace_files - assert fs.head(path, 5) == fs.cat_file(path)[:5] + assert fs.cat_file(path, start, end) == fs.cat_file(path)[start:end] +@pytest.mark.parametrize( + ("start", "end"), [(0, 5), (-10, -5)], ids=["from-start", "from-end"] +) +def test_cat_file_of_a_range_of_a_folder_raises_is_a_directory_error( + fs, remote_dir, start, end +): + fs.makedirs(remote_dir + "/dir") + with pytest.raises(IsADirectoryError): + fs.cat_file(remote_dir + "/dir", start, end) + + +def test_head_of_a_folder_opened_by_its_id_raises_is_a_directory_error( + service_auth, fs_factory +): + _, base = fs_factory() + with pytest.raises(IsADirectoryError): + GDriveFileSystem(base["id"], service_auth).head(base["id"]) + + +def test_head_of_a_missing_file_id_raises_file_not_found_error(service_auth): + missing = "1" + secrets.token_hex(16) + with pytest.raises(FileNotFoundError): + GDriveFileSystem(missing, service_auth).head(missing, 1) + + +@pytest.mark.parametrize( + ("block_size", "asked"), + [ + (None, 4 * 1024 * 1024), + ("default", 4 * 1024 * 1024), + (512 * 1024, 512 * 1024), + ], + ids=["none", "default", "512KiB"], +) def test_open_reads_one_block_per_request( - fs, two_mib_file, downloads, monkeypatch + fs, two_mib_file, downloads, block_size, asked ): path, data = two_mib_file - monkeypatch.setattr(fs, "blocksize", 512 * 1024) - with fs.open(path, "rb") as stream: + with fs.open(path, "rb", block_size=block_size) as stream: assert stream.read(10) == data[:10] - assert downloads == [("bytes=0-524287", 512 * 1024)] + assert downloads == [(f"bytes=0-{asked - 1}", min(asked, len(data)))] From ee946348cebeabe3c08447ac6690d44955df316b Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 12:22:04 -0800 Subject: [PATCH 4/6] Read ranges from the end without Drive's size of the file A range that ends before the end of the file is read from its start or from the end and cut locally, so only a range from the end to a position from the start needs the size. Drive's size of a Google Workspace file is not the length of its export: real Drive gave a new Doc a size that made cat_file(doc, -3, -1) return b"". A file without a checksum, which is how Drive marks Workspace files and shortcuts, has no usable size and is exported whole. Co-Authored-By: Claude Opus 5.5 --- pydrive2/fs/spec.py | 39 ++++++++++++++++++++++++++++----------- pydrive2/test/test_fs.py | 22 ++++++++++++++++++---- 2 files changed, 46 insertions(+), 15 deletions(-) diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ba84aeae..61e55071 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -266,6 +266,17 @@ def _file_entry(name, item, detail=True): return name +def _content_size(size, checksum): + """The size of a file's stored bytes, or None if Drive stores none. + + Drive gives no checksum to Google Workspace files and shortcuts, and + their size is not the length of an export. + """ + if checksum is None or size is None: + return None + return int(size) + + def _quote_query_value(value): escaped = value.replace("\\", "\\\\").replace("'", "\\'") return f"'{escaped}'" @@ -1411,32 +1422,39 @@ def _gdrive_open_file(self, item_id, block_size=None): def cat_file(self, path, start=None, end=None, **kwargs): """Return the file's bytes, or bytes start to end, as a slice would. - A range is read with one request that asks Drive for those bytes. + A range is read with one request, not by downloading the whole file. """ # Options such as compression change the bytes, so fsspec reads them. if (start is None and end is None) or kwargs.get("compression"): return super().cat_file(path, start=start, end=end, **kwargs) first, last = start or 0, end - need_size = (first < 0 and last is not None) or (last or 0) < 0 + # Only a range from the end to a position from the start needs the + # size, and a Google Workspace file has none that fits its export. + need_size = first < 0 and last is not None and last >= 0 with _translate_not_found(path): item_id, size = self._file_for_range(path, need_size) if need_size and size is None: - # Drive exports a Google Workspace file only as a whole. return super().cat_file(path, **kwargs)[start:end] if need_size: first, last, _ = slice(first, last).indices(size) - if last is not None and last <= first: + # Bounds on the same side of the file are empty if out of order. + same_side = last is not None and (first < 0) == (last < 0) + if same_side and last <= first: return b"" + # A negative end is cut from the bytes read to the end. + cut = last if last is not None and last < 0 else None file = self.client.CreateFile({"id": item_id}) try: - return _gdrive_retry_repeatable(file._GetContentRange)( + data = _gdrive_retry_repeatable(file._GetContentRange)( first, - None if last is None else last - 1, + None if last is None or cut else last - 1, acknowledge_abuse=self._acknowledge_abuse, ) except ApiRequestError as error: if error.GetField("reason") != "fileNotDownloadable": raise + else: + return data[:cut] if item_id == self.root: # A folder opened by its ID cannot be downloaded either. self._file_for_range(path, need_size=True) @@ -1452,9 +1470,8 @@ def _file_for_range(self, path, need_size): raise IsADirectoryError( errno.EISDIR, os.strerror(errno.EISDIR), path ) - return item_id, next( - file.size for file in match.files if file.id == item_id - ) + file = next(file for file in match.files if file.id == item_id) + return item_id, _content_size(file.size, file.checksum) if not need_size: return self.root, None item = self._get_root_metadata( @@ -1468,8 +1485,8 @@ def _file_for_range(self, path, need_size): raise IsADirectoryError( errno.EISDIR, os.strerror(errno.EISDIR), path ) - size = item.get("size") - return self.root, None if size is None else int(size) + size = _content_size(item.get("size"), item.get("md5Checksum")) + return self.root, size def head(self, path, size=1024): return self.cat_file(path, 0, size) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index feec0ed9..e7b006ec 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -788,8 +788,22 @@ def test_tail_of_no_bytes_downloads_nothing(fs, two_mib_file, downloads, size): @pytest.mark.parametrize( ("start", "end"), - [(5, 15), (-10, -5), (2 * 1024 * 1024 - 3, None), (3 * 1024 * 1024, None)], - ids=["middle", "from-the-end", "to-the-end", "past-the-end"], + [ + (5, 15), + (-10, -5), + (5, -5), + (-10, 2 * 1024 * 1024 - 5), + (2 * 1024 * 1024 - 3, None), + (3 * 1024 * 1024, None), + ], + ids=[ + "middle", + "from-the-end", + "start-to-before-the-end", + "end-to-a-position", + "to-the-end", + "past-the-end", + ], ) def test_cat_file_of_a_range_returns_those_bytes(fs, two_mib_file, start, end): path, data = two_mib_file @@ -812,8 +826,8 @@ def test_cat_file_of_a_range_of_a_compressed_file_returns_uncompressed_bytes( # Drive gives a Google Doc a size that is not the length of its export. @pytest.mark.parametrize( ("start", "end"), - [(0, 5), (-3, -1), (-3, None)], - ids=["head", "before-the-end", "tail"], + [(0, 5), (-3, -1), (-3, None), (-3, 10)], + ids=["head", "before-the-end", "tail", "end-to-a-position"], ) def test_cat_file_of_a_range_of_a_google_doc_slices_its_export( fs, workspace_files, start, end From b1229819751d521c42bd3c9d72e39729dd5da418 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 13:27:10 -0800 Subject: [PATCH 5/6] Test a missing file ID with a deleted file's ID Drive answers some made-up IDs with 400 Bad Request instead of 404, so the test now uses the ID of a file it deleted. Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index e7b006ec..244adc91 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -855,10 +855,18 @@ def test_head_of_a_folder_opened_by_its_id_raises_is_a_directory_error( GDriveFileSystem(base["id"], service_auth).head(base["id"]) -def test_head_of_a_missing_file_id_raises_file_not_found_error(service_auth): - missing = "1" + secrets.token_hex(16) +def test_head_of_a_deleted_file_id_raises_file_not_found_error( + service_auth, fs_factory +): + _, base = fs_factory() + file = GoogleDrive(service_auth).CreateFile( + {"name": uuid.uuid4().hex, "parents": [base["id"]]} + ) + file.SetContentString("data") + pydrive_retry(file.Upload) + pydrive_retry(file.Delete) with pytest.raises(FileNotFoundError): - GDriveFileSystem(missing, service_auth).head(missing, 1) + GDriveFileSystem(file["id"], service_auth).head(file["id"], 1) @pytest.mark.parametrize( From 8b3a3fa1f966c64472e0ea21e37261628290e196 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 13:30:16 -0800 Subject: [PATCH 6/6] Document which ranged reads download more than they return Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index fab65277..c4a70ecd 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -260,8 +260,10 @@ default) per request. Pass a positive ``block_size`` to ``fs.open()`` to set another request size in bytes. A program that reads large files from start to end makes fewer requests with a larger size, such as 64 MiB. ``fs.head()``, ``fs.tail()`` and ``fs.cat_file(path, start, end)`` -download only the bytes they return, except from Google Workspace files, -which Drive exports whole. A writer buffers data locally, using a +download only the bytes they return, with three exceptions. A negative +``end`` downloads from ``start`` to the end of the file. A read with +``compression`` downloads blocks from the beginning of the file. Drive +exports a Google Workspace file whole. A writer buffers data locally, using a temporary file for larger uploads. Calling ``flush()`` flushes the local buffer. Closing the writer uploads the file to Drive and reports any upload error.