From 4e18085b6550675b170fb6f80304cfb0c6aad5ee Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 19:22:11 -0800 Subject: [PATCH 1/9] Close path-owned upload files and retain retry support --- pydrive2/files.py | 37 +++++++++++++++++---- pydrive2/test/test_files_unit.py | 57 ++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index acad9c9..f2ca1b2 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -226,7 +226,7 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource): Can access and modify metadata like dictionary. """ - content = ApiAttribute("content") + _content = ApiAttribute("content") uploaded = ApiAttribute("uploaded") metadata = ApiAttribute("metadata") @@ -244,6 +244,7 @@ def __init__(self, auth=None, metadata=None, uploaded=False): ApiResource.__init__(self) self.metadata = {} self.dirty = {"content": False} + self._owns_content = False self.auth = auth self.uploaded = uploaded if uploaded: @@ -275,6 +276,17 @@ def __getitem__(self, key): else: raise FileNotUploadedError() + @property + def content(self): + return self._content + + @content.setter + def content(self, stream): + if self._owns_content and self._content is not stream: + self._content.close() + self._owns_content = False + self._content = stream + def SetContentString(self, content, encoding="utf-8"): """Set content of this file to be a string. @@ -297,14 +309,17 @@ def SetContentFile(self, filename): """Set content of this file from a file. Opens the file specified by this method. - Will be read, uploaded, and closed by Upload() method. + Upload() closes the file after each attempt. If an upload fails, + retrying it reopens the same path. Assigning another content source + also closes the file opened here. Sets metadata 'name' and 'mimeType' automatically if not specified and the file is uploaded for the first time (id is not set). :param filename: name of the file to be uploaded. :type filename: str. """ - self.content = open(filename, "rb") # noqa: SIM115 - retained for upload + self.content = open(os.path.abspath(filename), "rb") # noqa: SIM115 + self._owns_content = True if self.get("id") is None: if self.get("name") is None: self["name"] = os.path.basename(filename) @@ -495,13 +510,22 @@ def FetchContent(self, mimetype=None, remove_bom=False): self.has_bom = not remove_bom self._export_mimetype = mimetype - @LoadAuth def Upload(self, param=None, *, media_mime_type=None): """Create or update a file, optionally importing uploaded media. For a Workspace import, set the destination MIME type in the file metadata and pass the source MIME type as media_mime_type. """ + if self._owns_content: + if self.content.closed: + # A previous attempt failed. Reopen the source for this retry. + self._content = open(self.content.name, "rb") # noqa: SIM115 + with self.content: + return self._Upload(param, media_mime_type) + return self._Upload(param, media_mime_type) + + @LoadAuth + def _Upload(self, param, media_mime_type): params = dict(param or {}, supportsAllDrives=True) params["fields"] = params.get("fields") or DEFAULT_FILE_FIELDS body = self.GetChanges() @@ -537,8 +561,9 @@ def Upload(self, param=None, *, media_mime_type=None): destination_type = ( metadata.get("mimeType") or self.get("mimeType") or "" ) - if self.dirty["content"] and destination_type.startswith( - "application/vnd.google-apps." + if self._owns_content or ( + self.dirty["content"] + and destination_type.startswith("application/vnd.google-apps.") ): self.content = None self.uploaded = True diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 1577bec..796d66a 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -1,4 +1,5 @@ import gc +import io import json import weakref from codecs import BOM_UTF8 @@ -447,3 +448,59 @@ def check_request(uri, method, **kwargs): dest = tmp_path / "download" drive.CreateFile({"id": "file"}).GetContentFile(dest, chunksize=2) assert dest.read_bytes() == b"abcd" + + +def test_path_upload_closes_file_and_can_retry( + mock_drive, tmp_path, monkeypatch +): + source = tmp_path / "source" + source.write_bytes(b"payload") + drive, requests = mock_drive( + error_response(503, "backendError"), + ({"status": "200", "location": "https://example.test/session"}, ""), + response({"id": "uploaded"}), + response({"id": "uploaded"}), + ) + http = drive.auth.thread_local.http + send = http.request + payloads = [] + + def record(uri, method, body=None, **kwargs): + if method == "PUT": + payloads.append(body.read()) + return send(uri, method, body=body, **kwargs) + + monkeypatch.setattr(http, "request", record) + file = drive.CreateFile() + monkeypatch.chdir(tmp_path) + file.SetContentFile("source") + opened = file.content + with pytest.raises(ApiRequestError): + file.Upload() + assert opened.closed + monkeypatch.chdir(tmp_path.parent) + file.Upload() + assert payloads == [b"payload"] + assert file.content is None + source.unlink() + file["name"] = "renamed" + file.Upload() + assert requests[-1][1] == "PATCH" + + +def test_replacing_upload_content_respects_ownership(mock_drive, tmp_path): + source = tmp_path / "source" + source.write_bytes(b"payload") + drive, _ = mock_drive( + ({"status": "200", "location": "https://example.test/session"}, ""), + response({"id": "uploaded"}), + ) + file = drive.CreateFile() + file.SetContentFile(source) + owned = file.content + external = io.BytesIO(b"external") + file.content = external + assert owned.closed + file.Upload() + file.SetContentString("replacement") + assert external.getvalue() == b"external" From 4fc1c675e5389e58e5739d449a88a4189b4c600a Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 21 Nov 2026 22:58:49 -0800 Subject: [PATCH 2/9] Exercise upload-owned handle cleanup in the conversion test --- pydrive2/test/test_file.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pydrive2/test/test_file.py b/pydrive2/test/test_file.py index 3e9fa43..1d2c086 100644 --- a/pydrive2/test/test_file.py +++ b/pydrive2/test/test_file.py @@ -851,8 +851,7 @@ def upload_test_document(self): {"mimeType": "application/vnd.google-apps.document"} ) file.SetContentFile(source) - with file.content: - pydrive_retry(file.Upload, media_mime_type="text/plain") + pydrive_retry(file.Upload, media_mime_type="text/plain") self.addCleanup(pydrive_retry, file.Delete) return file, test_util.StripNewlines(content) From 60968b989479890f11e5182b1f7bddb8f03b3e7a Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 08:49:04 -0800 Subject: [PATCH 3/9] Verify retry payload through the HTTP response echo --- pydrive2/test/test_files_unit.py | 18 ++++-------------- 1 file changed, 4 insertions(+), 14 deletions(-) diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 796d66a..fecfdea 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -454,23 +454,13 @@ def test_path_upload_closes_file_and_can_retry( mock_drive, tmp_path, monkeypatch ): source = tmp_path / "source" - source.write_bytes(b"payload") + source.write_bytes(b'{"id":"from-retried-upload"}') drive, requests = mock_drive( error_response(503, "backendError"), ({"status": "200", "location": "https://example.test/session"}, ""), - response({"id": "uploaded"}), - response({"id": "uploaded"}), + ({"status": "200"}, "echo_request_body"), + response({"id": "from-retried-upload"}), ) - http = drive.auth.thread_local.http - send = http.request - payloads = [] - - def record(uri, method, body=None, **kwargs): - if method == "PUT": - payloads.append(body.read()) - return send(uri, method, body=body, **kwargs) - - monkeypatch.setattr(http, "request", record) file = drive.CreateFile() monkeypatch.chdir(tmp_path) file.SetContentFile("source") @@ -480,7 +470,7 @@ def record(uri, method, body=None, **kwargs): assert opened.closed monkeypatch.chdir(tmp_path.parent) file.Upload() - assert payloads == [b"payload"] + assert file["id"] == "from-retried-upload" assert file.content is None source.unlink() file["name"] = "renamed" From 0fdb186ba88f84b6a79719ff061e49e418c18b5f Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 18:08:37 -0800 Subject: [PATCH 4/9] Assert per-attempt Drive requests for path uploads and retries --- pydrive2/test/test_files_unit.py | 36 ++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index fecfdea..ae4d631 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -450,6 +450,27 @@ def check_request(uri, method, **kwargs): assert dest.read_bytes() == b"abcd" +@pytest.mark.parametrize("existing", [False, True], ids=["create", "update"]) +def test_path_upload_uses_one_session(mock_drive, tmp_path, existing): + source = tmp_path / "source" + source.write_bytes(b"payload") + drive, requests = mock_drive( + ({"status": "200", "location": "https://example.test/session"}, ""), + response({"id": "file"}), + ) + file = drive.CreateFile({"id": "file"} if existing else {}) + file.SetContentFile(source) + opened = file.content + assert not requests + file.Upload() + assert opened.closed + start, body = requests + assert start[1] == ("PATCH" if existing else "POST") + path = "/upload/drive/v3/files" + ("/file" if existing else "") + assert urlsplit(start[0]).path == path + assert body[:2] == ("https://example.test/session", "PUT") + + def test_path_upload_closes_file_and_can_retry( mock_drive, tmp_path, monkeypatch ): @@ -465,23 +486,32 @@ def test_path_upload_closes_file_and_can_retry( monkeypatch.chdir(tmp_path) file.SetContentFile("source") opened = file.content + assert not requests with pytest.raises(ApiRequestError): file.Upload() assert opened.closed + (failed_create,) = requests + assert failed_create[1] == "POST" monkeypatch.chdir(tmp_path.parent) file.Upload() assert file["id"] == "from-retried-upload" assert file.content is None + retry, upload = requests[1:] + assert retry[:2] == failed_create[:2] + assert upload[:2] == ("https://example.test/session", "PUT") source.unlink() file["name"] = "renamed" file.Upload() - assert requests[-1][1] == "PATCH" + (update,) = requests[3:] + assert update[1] == "PATCH" + assert urlsplit(update[0]).path == "/drive/v3/files/from-retried-upload" + assert json.loads(update[2]) == {"name": "renamed"} def test_replacing_upload_content_respects_ownership(mock_drive, tmp_path): source = tmp_path / "source" source.write_bytes(b"payload") - drive, _ = mock_drive( + drive, requests = mock_drive( ({"status": "200", "location": "https://example.test/session"}, ""), response({"id": "uploaded"}), ) @@ -491,6 +521,8 @@ def test_replacing_upload_content_respects_ownership(mock_drive, tmp_path): external = io.BytesIO(b"external") file.content = external assert owned.closed + assert not requests file.Upload() file.SetContentString("replacement") assert external.getvalue() == b"external" + assert [r[1] for r in requests] == ["POST", "PUT"] From 99776fca793240ef501ec8e5eb4e0b0aaca43925 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sun, 22 Nov 2026 18:14:52 -0800 Subject: [PATCH 5/9] Cover upload retries after the session has been created --- pydrive2/test/test_files_unit.py | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index ae4d631..7a1dbde 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -471,14 +471,20 @@ def test_path_upload_uses_one_session(mock_drive, tmp_path, existing): assert body[:2] == ("https://example.test/session", "PUT") +@pytest.mark.parametrize("fail_on_put", [False, True], ids=["session", "body"]) def test_path_upload_closes_file_and_can_retry( - mock_drive, tmp_path, monkeypatch + mock_drive, tmp_path, monkeypatch, fail_on_put ): source = tmp_path / "source" source.write_bytes(b'{"id":"from-retried-upload"}') + session = ( + {"status": "200", "location": "https://example.test/session"}, + "", + ) drive, requests = mock_drive( + *([session] if fail_on_put else []), error_response(503, "backendError"), - ({"status": "200", "location": "https://example.test/session"}, ""), + session, ({"status": "200"}, "echo_request_body"), response({"id": "from-retried-upload"}), ) @@ -490,19 +496,22 @@ def test_path_upload_closes_file_and_can_retry( with pytest.raises(ApiRequestError): file.Upload() assert opened.closed - (failed_create,) = requests - assert failed_create[1] == "POST" + assert [r[1] for r in requests] == ( + ["POST", "PUT"] if fail_on_put else ["POST"] + ) monkeypatch.chdir(tmp_path.parent) + before = len(requests) file.Upload() assert file["id"] == "from-retried-upload" assert file.content is None - retry, upload = requests[1:] - assert retry[:2] == failed_create[:2] + retry, upload = requests[before:] + assert retry[:2] == requests[0][:2] assert upload[:2] == ("https://example.test/session", "PUT") source.unlink() file["name"] = "renamed" + before = len(requests) file.Upload() - (update,) = requests[3:] + (update,) = requests[before:] assert update[1] == "PATCH" assert urlsplit(update[0]).path == "/drive/v3/files/from-retried-upload" assert json.loads(update[2]) == {"name": "renamed"} From 7ed2026949d1d24769bc80c6551eb3644cfc6bf8 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 24 Nov 2026 18:24:26 -0800 Subject: [PATCH 6/9] Clarify the local upload test and shorten SetContentFile documentation --- pydrive2/files.py | 6 +----- pydrive2/test/test_files_unit.py | 4 +++- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index f2ca1b2..33dbbec 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -306,12 +306,8 @@ def SetContentString(self, content, encoding="utf-8"): self["mimeType"] = "text/plain" def SetContentFile(self, filename): - """Set content of this file from a file. + """Open a local file for upload. - Opens the file specified by this method. - Upload() closes the file after each attempt. If an upload fails, - retrying it reopens the same path. Assigning another content source - also closes the file opened here. Sets metadata 'name' and 'mimeType' automatically if not specified and the file is uploaded for the first time (id is not set). diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 7a1dbde..93b6a50 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -451,7 +451,9 @@ def check_request(uri, method, **kwargs): @pytest.mark.parametrize("existing", [False, True], ids=["create", "update"]) -def test_path_upload_uses_one_session(mock_drive, tmp_path, existing): +def test_uploading_a_local_file_takes_two_requests( + mock_drive, tmp_path, existing +): source = tmp_path / "source" source.write_bytes(b"payload") drive, requests = mock_drive( From f39c4fda93d3d74bc3dbd3c50a8541b3cff24962 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 24 Nov 2026 18:55:42 -0800 Subject: [PATCH 7/9] Preserve symlink traversal when reopening upload paths --- pydrive2/files.py | 8 +++++++- pydrive2/test/test_files_unit.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index 33dbbec..218c96f 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -4,6 +4,7 @@ import mimetypes import os from functools import wraps +from pathlib import Path from googleapiclient import errors from googleapiclient.http import ( @@ -314,7 +315,12 @@ def SetContentFile(self, filename): :param filename: name of the file to be uploaded. :type filename: str. """ - self.content = open(os.path.abspath(filename), "rb") # noqa: SIM115 + source = os.fsdecode(filename) + path = Path(source) + if source and not path.is_absolute(): + # Anchor retries to the original working directory, preserving "..". + source = os.path.join(os.path.abspath(path.drive), source) + self.content = open(source, "rb") # noqa: SIM115 self._owns_content = True if self.get("id") is None: if self.get("name") is None: diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 93b6a50..3339dc6 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -519,6 +519,37 @@ def test_path_upload_closes_file_and_can_retry( assert json.loads(update[2]) == {"name": "renamed"} +def test_upload_and_retry_follow_the_same_directory_symlink( + mock_drive, tmp_path, monkeypatch +): + monkeypatch.chdir(tmp_path) + child = tmp_path / "target" / "child" + child.mkdir(parents=True) + alias = tmp_path / "alias" + try: + alias.symlink_to(child, target_is_directory=True) + except OSError: + pytest.skip("Directory symlinks unavailable") + (child.parent / "source").write_bytes(b'{"id":"through-symlink"}') + (tmp_path / "source").write_bytes(b'{"id":"beside-symlink"}') + source = alias.relative_to(tmp_path) / ".." / "source" + expected = source.read_bytes() + drive, _ = mock_drive( + error_response(503, "backendError"), + ({"status": "200", "location": "https://example.test/session"}, ""), + ({"status": "200"}, "echo_request_body"), + ) + file = drive.CreateFile() + file.SetContentFile(source) + assert file.content.read() == expected + file.content.seek(0) + with pytest.raises(ApiRequestError): + file.Upload() + monkeypatch.chdir(tmp_path.parent) + file.Upload() + assert file["id"] == json.loads(expected)["id"] + + def test_replacing_upload_content_respects_ownership(mock_drive, tmp_path): source = tmp_path / "source" source.write_bytes(b"payload") From 86dcc1444c5370e35104da20b8d9265581e2ec5b Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 24 Nov 2026 19:08:32 -0800 Subject: [PATCH 8/9] Explain why upload retries keep parent path components --- pydrive2/files.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pydrive2/files.py b/pydrive2/files.py index 218c96f..986713d 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -318,7 +318,10 @@ def SetContentFile(self, filename): source = os.fsdecode(filename) path = Path(source) if source and not path.is_absolute(): - # Anchor retries to the original working directory, preserving "..". + # Include the current directory so a retry can reopen the file + # even if the caller changes directories. Keep ".." in the path + # so the OS follows symlinks first. For example, if "link" points + # to "/data/photos", "link/../image.jpg" opens "/data/image.jpg". source = os.path.join(os.path.abspath(path.drive), source) self.content = open(source, "rb") # noqa: SIM115 self._owns_content = True From 196bb58412209aacbc1b9dcc9ce62ac1ff3e1032 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Tue, 24 Nov 2026 19:18:15 -0800 Subject: [PATCH 9/9] Keep the original upload file open for retries --- docs/filemanagement.rst | 5 ++++ pydrive2/files.py | 24 +++---------------- pydrive2/test/test_files_unit.py | 40 ++++++++++++++------------------ 3 files changed, 26 insertions(+), 43 deletions(-) diff --git a/docs/filemanagement.rst b/docs/filemanagement.rst index 3186f38..3ed2a5c 100644 --- a/docs/filemanagement.rst +++ b/docs/filemanagement.rst @@ -254,6 +254,11 @@ Set the content with :meth:`~pydrive2.files.GoogleDriveFile.SetContentFile` or :meth:`~pydrive2.files.GoogleDriveFile.SetContentString`, then call :meth:`~pydrive2.files.GoogleDriveFile.Upload`. +``SetContentFile()`` opens the local file. If ``Upload()`` fails, you can call +``Upload()`` again to retry with the same open file. PyDrive2 closes the file +when the upload succeeds or when you replace its content. If you abandon the +upload after an error, call ``file.content.close()`` to release it immediately. + Sample code continues from `Download file metadata from file ID`_: .. code-block:: python diff --git a/pydrive2/files.py b/pydrive2/files.py index 986713d..a796a86 100644 --- a/pydrive2/files.py +++ b/pydrive2/files.py @@ -4,7 +4,6 @@ import mimetypes import os from functools import wraps -from pathlib import Path from googleapiclient import errors from googleapiclient.http import ( @@ -228,6 +227,7 @@ class GoogleDriveFile(ApiAttributeMixin, ApiResource): """ _content = ApiAttribute("content") + _owns_content = ApiAttribute("owns_content") uploaded = ApiAttribute("uploaded") metadata = ApiAttribute("metadata") @@ -245,7 +245,6 @@ def __init__(self, auth=None, metadata=None, uploaded=False): ApiResource.__init__(self) self.metadata = {} self.dirty = {"content": False} - self._owns_content = False self.auth = auth self.uploaded = uploaded if uploaded: @@ -315,15 +314,7 @@ def SetContentFile(self, filename): :param filename: name of the file to be uploaded. :type filename: str. """ - source = os.fsdecode(filename) - path = Path(source) - if source and not path.is_absolute(): - # Include the current directory so a retry can reopen the file - # even if the caller changes directories. Keep ".." in the path - # so the OS follows symlinks first. For example, if "link" points - # to "/data/photos", "link/../image.jpg" opens "/data/image.jpg". - source = os.path.join(os.path.abspath(path.drive), source) - self.content = open(source, "rb") # noqa: SIM115 + self.content = open(filename, "rb") # noqa: SIM115 - retained for upload self._owns_content = True if self.get("id") is None: if self.get("name") is None: @@ -515,22 +506,13 @@ def FetchContent(self, mimetype=None, remove_bom=False): self.has_bom = not remove_bom self._export_mimetype = mimetype + @LoadAuth def Upload(self, param=None, *, media_mime_type=None): """Create or update a file, optionally importing uploaded media. For a Workspace import, set the destination MIME type in the file metadata and pass the source MIME type as media_mime_type. """ - if self._owns_content: - if self.content.closed: - # A previous attempt failed. Reopen the source for this retry. - self._content = open(self.content.name, "rb") # noqa: SIM115 - with self.content: - return self._Upload(param, media_mime_type) - return self._Upload(param, media_mime_type) - - @LoadAuth - def _Upload(self, param, media_mime_type): params = dict(param or {}, supportsAllDrives=True) params["fields"] = params.get("fields") or DEFAULT_FILE_FIELDS body = self.GetChanges() diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 3339dc6..5e4b9ea 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -3,6 +3,7 @@ import json import weakref from codecs import BOM_UTF8 +from copy import copy from urllib.parse import urlsplit import pytest @@ -474,7 +475,7 @@ def test_uploading_a_local_file_takes_two_requests( @pytest.mark.parametrize("fail_on_put", [False, True], ids=["session", "body"]) -def test_path_upload_closes_file_and_can_retry( +def test_failed_upload_keeps_the_file_open_until_retry_succeeds( mock_drive, tmp_path, monkeypatch, fail_on_put ): source = tmp_path / "source" @@ -497,13 +498,14 @@ def test_path_upload_closes_file_and_can_retry( assert not requests with pytest.raises(ApiRequestError): file.Upload() - assert opened.closed + assert not opened.closed assert [r[1] for r in requests] == ( ["POST", "PUT"] if fail_on_put else ["POST"] ) monkeypatch.chdir(tmp_path.parent) before = len(requests) file.Upload() + assert opened.closed assert file["id"] == "from-retried-upload" assert file.content is None retry, upload = requests[before:] @@ -519,7 +521,7 @@ def test_path_upload_closes_file_and_can_retry( assert json.loads(update[2]) == {"name": "renamed"} -def test_upload_and_retry_follow_the_same_directory_symlink( +def test_set_content_file_follows_directory_symlinks( mock_drive, tmp_path, monkeypatch ): monkeypatch.chdir(tmp_path) @@ -530,41 +532,35 @@ def test_upload_and_retry_follow_the_same_directory_symlink( alias.symlink_to(child, target_is_directory=True) except OSError: pytest.skip("Directory symlinks unavailable") - (child.parent / "source").write_bytes(b'{"id":"through-symlink"}') - (tmp_path / "source").write_bytes(b'{"id":"beside-symlink"}') + (child.parent / "source").write_bytes(b"through symlink") + (tmp_path / "source").write_bytes(b"beside symlink") source = alias.relative_to(tmp_path) / ".." / "source" - expected = source.read_bytes() - drive, _ = mock_drive( - error_response(503, "backendError"), - ({"status": "200", "location": "https://example.test/session"}, ""), - ({"status": "200"}, "echo_request_body"), - ) + drive, _ = mock_drive() file = drive.CreateFile() file.SetContentFile(source) - assert file.content.read() == expected - file.content.seek(0) - with pytest.raises(ApiRequestError): - file.Upload() - monkeypatch.chdir(tmp_path.parent) - file.Upload() - assert file["id"] == json.loads(expected)["id"] + with file.content: + assert file.content.read() == source.read_bytes() -def test_replacing_upload_content_respects_ownership(mock_drive, tmp_path): +def test_replacing_content_on_a_copy_closes_only_the_owned_file( + mock_drive, tmp_path +): source = tmp_path / "source" source.write_bytes(b"payload") drive, requests = mock_drive( + error_response(503, "backendError"), ({"status": "200", "location": "https://example.test/session"}, ""), response({"id": "uploaded"}), ) file = drive.CreateFile() file.SetContentFile(source) owned = file.content + with pytest.raises(ApiRequestError): + file.Upload() external = io.BytesIO(b"external") - file.content = external + copy(file).content = external assert owned.closed - assert not requests file.Upload() file.SetContentString("replacement") assert external.getvalue() == b"external" - assert [r[1] for r in requests] == ["POST", "PUT"] + assert [r[1] for r in requests] == ["POST", "POST", "PUT"]