From e13365ffe344bdd262f9533fc3940fc18ab2a4aa Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:29:42 -0800 Subject: [PATCH 1/3] Replace the content of an existing file on a write A write to the path of an existing file added a second file with the same name, and reads then picked one of the two by ID. pipe_file(), put_file() and open(path, "wb") now replace the content of that file, which keeps its ID and sharing. With several files of the name, the one that reads return is replaced. A write to the path of a folder raises IsADirectoryError. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 6 ++- docs/upgrading.rst | 5 ++ pydrive2/fs/spec.py | 30 ++++++++++- pydrive2/test/test_fs.py | 93 +++++++++++++++++++++++++++++++++++ pydrive2/test/test_fs_unit.py | 28 +++++------ 5 files changed, 144 insertions(+), 18 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index f2886084..74a40e44 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -65,8 +65,10 @@ A filesystem instance is scoped to one root. Use URLs under the same folder ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse the filesystem and its directory ID cache. Reads by file ID skip name lookups. Reads are sequential. To create a file, use a folder ID or root -alias followed by a filename. As with the direct PyDrive2 filesystem, -a write creates a Drive item even when a sibling has the same name. All +alias followed by a filename. Writing to the path of an existing file +replaces its content and keeps the file, with its ID and sharing. When +several files share the name, the write replaces the one that reads +return. Writing to the path of a folder raises ``IsADirectoryError``. All reads require credentials, including files shared by link. Listings diff --git a/docs/upgrading.rst b/docs/upgrading.rst index 9f28692a..d249b587 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -65,6 +65,11 @@ Filesystem directories Both raise ``FileExistsError`` if the folder already exists. Use ``fs.makedirs(path, exist_ok=True)`` when repeating a setup step. +Writing to the path of an existing file, with ``pipe_file()``, +``put_file()`` or ``open(path, "wb")``, now replaces that file's content. +It used to add a second file with the same name. Writing to the path of a +folder raises ``IsADirectoryError``. + The :doc:`fsspec filesystem ` now caches folders returned by ``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. If another client moves or removes a folder, list its parent again or diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index ac47994b..0c570bea 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -1218,15 +1218,43 @@ def find( return contents def upload_fobj(self, stream, rpath, callback=None, **kwargs): + """Write a file. A file already at the path gets the new content.""" parent, name = self._split_file_path(rpath) parent_id = self._get_item_id(parent, create=True) + existing = self._file_to_replace(rpath, parent_id, name) if callback: stream = _ReadProgress(stream, callback.relative_update) with _unwrap_not_retried(): - item = self._gdrive_upload_fobj(name, parent_id, stream) + if existing is None: + item = self._gdrive_upload_fobj(name, parent_id, stream) + else: + item = self._gdrive_replace_content(existing, stream) self._dirs.file_added(parent_id, name) return item + def _file_to_replace(self, path, parent_id, name): + """The ID of the file a write to the path replaces, if there is one.""" + _, base = self._split_mounted_path(path) + match, _ = self._resolver().child( + [parent_id], base, name, folders_only=False + ) + if match.folders: + raise IsADirectoryError( + errno.EISDIR, os.strerror(errno.EISDIR), path + ) + # Reads of a name that several files share use the lowest ID. + return min((file.id for file in match.files), default=None) + + def _gdrive_replace_content(self, file_id, stream): + def send(): + item = self.client.CreateFile({"id": file_id}) + item.content = stream + item.Upload() + return item + + # Sending the same content to the same file again changes nothing. + return _gdrive_retry_repeatable(send)() + def put_file(self, lpath, rpath, callback=None, **kwargs): if os.path.isdir(lpath): self.makedirs(rpath, exist_ok=True) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 1e853a3a..2c209ec9 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -734,3 +734,96 @@ 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 files_in_base(service_auth, fs_factory, base_remote_dir): + """Create files under the base folder with the core API; return IDs.""" + _, base = fs_factory() + drive = GoogleDrive(service_auth) + + def create(name, content): + file = drive.CreateFile({"name": name, "parents": [base["id"]]}) + file.SetContentString(content) + pydrive_retry(file.Upload) + return file["id"] + + return create + + +def content_on_drive(service_auth, file_id): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + return b"".join(pydrive_retry(file.GetContentIOBuffer)) + + +def pipe(fs, path, data, tmp_path): + fs.pipe_file(path, data) + + +def put(fs, path, data, tmp_path): + source = tmp_path / "source" + source.write_bytes(data) + fs.put_file(str(source), path) + + +def write_through_open(fs, path, data, tmp_path): + with fs.open(path, "wb") as stream: + stream.write(data) + + +@pytest.mark.parametrize( + ("write", "data"), + [ + (pipe, b"new"), + (write_through_open, b"new"), + # Larger than one request, so the upload is resumable. + (put, os.urandom(2 * 1024 * 1024)), + ], + ids=["pipe_file", "open", "put_file-2MiB"], +) +def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file( + service_auth, + fs, + fs_factory, + base_remote_dir, + files_in_base, + tmp_path, + write, + data, +): + name = uuid.uuid4().hex + path = f"{base_remote_dir}/{name}" + file_id = files_in_base(name, "old") + + write(fs, path, data, tmp_path) + + assert content_on_drive(service_auth, file_id) == data + listed = fs_factory()[0].ls(base_remote_dir) + assert listed.count(path) == 1 + + +def test_write_to_a_path_two_files_share_replaces_the_one_reads_return( + service_auth, fs, fs_factory, base_remote_dir, files_in_base +): + name = uuid.uuid4().hex + path = f"{base_remote_dir}/{name}" + files = { + files_in_base(name, "one"): b"one", + files_in_base(name, "two"): b"two", + } + read_id, other_id = sorted(files) + + fs.pipe_file(path, b"new") + + assert fs_factory()[0].cat_file(path) == b"new" + assert content_on_drive(service_auth, read_id) == b"new" + assert content_on_drive(service_auth, other_id) == files[other_id] + + +def test_write_to_a_folder_path_raises_and_creates_no_file( + fs, fs_factory, remote_dir +): + fs.makedirs(remote_dir + "/dir") + with pytest.raises(IsADirectoryError): + fs.pipe_file(remote_dir + "/dir", b"data") + assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index d9492b21..64e93024 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -889,6 +889,7 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( listing(sub), listing(note), listing(note), + listing(), # No file of that name yet. response({"id": "uploaded"}), ) fs = filesystem(drive, mount) @@ -901,7 +902,7 @@ def test_warm_calls_below_a_folder_with_a_same_name_file_reuse_its_id( ["('S' in parents) and trashed=false and name='note'"] ] fs.touch("root/data/uploaded") - assert [req[1] for req in requests[before + 1 :]] == ["POST"] + assert [req[1] for req in requests[before + 1 :]] == ["GET", "POST"] def test_find_caches_only_the_new_path_for_a_folder_moved_between_batches( @@ -1124,11 +1125,6 @@ def list_after_lookup_starts(request): @pytest.mark.parametrize( ("write", "responses"), [ - pytest.param( - lambda fs: fs.touch("root/dest/item"), - [response(WRITTEN_FILE)], - id="touch", - ), pytest.param( lambda fs: fs.cp_file("root/source", "root/dest/item"), [ @@ -1446,6 +1442,7 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): response(b), listing(), response(c), + listing(), # No file of that name yet. response({"id": "file"}), listing(file), listing(a), @@ -1458,14 +1455,10 @@ def test_nested_file_operations_reuse_resolved_directories(mock_drive): leaf = parent + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert [r[1] for r in requests] == [ - "GET", - *(["GET", "POST"] * 4), - "POST", - ] + assert [r[1] for r in requests] == ["GET", *(["GET", "POST"] * 5)] assert [ query(r)["q"][0].split("name=")[-1] for r in requests if r[1] == "GET" - ] == ["'mount'", "'run'", "'a'", "'b'", "'c'"] + ] == ["'mount'", "'run'", "'a'", "'b'", "'c'", "'test.txt'"] for operation, target, expected in ( (fs.exists, path, True), @@ -2218,6 +2211,7 @@ def pause_create(request): listing(), response(directory), on_request=pause_create ) drive, requests = mock_drive( + listing(), # The folder has not been created yet. response(file), listing(file, directory), ({"status": "200", "content-length": "1"}, b"x"), @@ -2970,7 +2964,10 @@ def send(request): "", ) drive, _ = mock_drive( - *[session] * attempts, response({"id": "file"}), on_request=send + listing(), + *[session] * attempts, + response({"id": "file"}), + on_request=send, ) progress = ProgressSteps() filesystem(drive).put_file(str(source), "root/source", callback=progress) @@ -3001,6 +2998,7 @@ def test_recursive_put_uploads_files_and_creates_empty_folders( listing(), listing(), response({"id": "U"}), + listing(), # No a.txt in the new folder. response({"id": "A"}), listing(), response({"id": "E"}), @@ -3957,7 +3955,7 @@ def fail(size, value): reports.append(value) raise TimeoutError("The progress report timed out") - drive, requests = mock_drive() + drive, requests = mock_drive(listing()) with pytest.raises(TimeoutError, match="progress report"): filesystem(drive).upload_fobj( io.BytesIO(b"data"), @@ -3965,7 +3963,7 @@ def fail(size, value): callback=Callback(hooks={"f": fail}), ) assert reports == [4] - assert requests == [] + assert [r[1] for r in requests] == ["GET"] sleep.assert_not_called() From e085164a7cd801e483223ec6a5f1f39eb0542446 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 19:29:56 -0800 Subject: [PATCH 2/3] Count the file name lookup in the request count of a write Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_fs.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index 2c209ec9..a417cc1a 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -238,7 +238,8 @@ def record_listing(request, *args, **kwargs): leaf = remote_dir + "/a/b/c" path = leaf + "/test.txt" fs.touch(path) - assert len(queries) == 5 + # One lookup for each missing folder, and one for the file name. + assert len(queries) == 6 for operation, target, expected in ( (fs.exists, path, True), From f0a6896468b4db1d3faf2e2a01b61620357a7062 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:07:33 -0800 Subject: [PATCH 3/3] Find the file to replace under every same-name parent, one write at a time A write looks for an existing file under all folders that share the parent path, as reads do. Threads of one filesystem that write the same path take turns, so they no longer create two files. A replace keeps the file's type, and a write onto a Google Docs file or a shortcut raises PermissionError before sending anything. A file deleted between the lookup and the replace raises FileNotFoundError. The live tests work in their own folder and cover an empty write, a lost answer to a replace, and two same-name parent folders. Co-Authored-By: Claude Opus 5.5 --- docs/fsspec.rst | 12 ++- docs/upgrading.rst | 3 +- pydrive2/fs/spec.py | 71 ++++++++++++----- pydrive2/test/test_fs.py | 144 +++++++++++++++++++++++++--------- pydrive2/test/test_fs_unit.py | 98 ++++++++++++++++------- 5 files changed, 238 insertions(+), 90 deletions(-) diff --git a/docs/fsspec.rst b/docs/fsspec.rst index 74a40e44..a90e2f49 100644 --- a/docs/fsspec.rst +++ b/docs/fsspec.rst @@ -66,10 +66,14 @@ ID or root alias in a single ``fsspec.open_files`` call. Sibling URLs reuse the filesystem and its directory ID cache. Reads by file ID skip name lookups. Reads are sequential. To create a file, use a folder ID or root alias followed by a filename. Writing to the path of an existing file -replaces its content and keeps the file, with its ID and sharing. When -several files share the name, the write replaces the one that reads -return. Writing to the path of a folder raises ``IsADirectoryError``. All -reads require credentials, including files shared by link. +replaces its content and keeps the file, with its ID, type and sharing. +When several files share the path, the write replaces the one that reads +return. Writing to the path of a folder raises ``IsADirectoryError``, and +to the path of a Google Docs file or a shortcut ``PermissionError``. +Threads that write one path through the same filesystem instance take +turns. Other instances and other clients do not wait, so two of them can +still create two files with the same name. All reads require credentials, +including files shared by link. Listings -------- diff --git a/docs/upgrading.rst b/docs/upgrading.rst index d249b587..967d4fba 100644 --- a/docs/upgrading.rst +++ b/docs/upgrading.rst @@ -68,7 +68,8 @@ Both raise ``FileExistsError`` if the folder already exists. Use Writing to the path of an existing file, with ``pipe_file()``, ``put_file()`` or ``open(path, "wb")``, now replaces that file's content. It used to add a second file with the same name. Writing to the path of a -folder raises ``IsADirectoryError``. +folder raises ``IsADirectoryError``, and to the path of a Google Docs file +or a shortcut ``PermissionError``. The :doc:`fsspec filesystem ` now caches folders returned by ``ls()``. Later calls such as ``exists("root/data")`` can reuse those IDs. diff --git a/pydrive2/fs/spec.py b/pydrive2/fs/spec.py index 0c570bea..d61a5b55 100644 --- a/pydrive2/fs/spec.py +++ b/pydrive2/fs/spec.py @@ -50,6 +50,8 @@ _LIST_FIELDS = ( f"nextPageToken,incompleteSearch,files(id,name,parents,{_INFO_FIELDS})" ) +# Folders, Google Docs, Sheets and the like, and shortcuts. +_WORKSPACE_TYPE_PREFIX = "application/vnd.google-apps." _NAME_FIELDS = "nextPageToken,incompleteSearch,files(id,name,parents,mimeType)" _MAX_QUERY_TERMS = 50 _CONNECTION_RETRIES = 3 @@ -86,7 +88,7 @@ class _ListedChild: id: str parent: str | None name: str - is_folder: bool + mime_type: str ambiguous: bool size: int | None checksum: str | None @@ -98,12 +100,17 @@ def from_drive(cls, parent, item): id=item["id"], parent=parent, name=item["name"], - is_folder=item["mimeType"] == FOLDER_MIME_TYPE, + # Listed items share a few types, so they share the strings. + mime_type=sys.intern(item["mimeType"]), ambiguous=len(item.get("parents", ())) > 1, size=int(size) if size is not None else None, checksum=item.get("md5Checksum"), ) + @property + def is_folder(self): + return self.mime_type == FOLDER_MIME_TYPE + def entry(self, name, detail=True): if not detail: return name @@ -1219,35 +1226,57 @@ def find( def upload_fobj(self, stream, rpath, callback=None, **kwargs): """Write a file. A file already at the path gets the new content.""" + _, base = self._split_mounted_path(rpath) parent, name = self._split_file_path(rpath) - parent_id = self._get_item_id(parent, create=True) - existing = self._file_to_replace(rpath, parent_id, name) + _, parent_base = self._split_mounted_path(parent) + resolver = self._resolver() + parents = ( + resolver.directory(parent_base, create=True).folders + if parent_base + else [self.root] + ) + parent_id = min(parents) if callback: stream = _ReadProgress(stream, callback.relative_update) - with _unwrap_not_retried(): - if existing is None: - item = self._gdrive_upload_fobj(name, parent_id, stream) - else: - item = self._gdrive_replace_content(existing, stream) - self._dirs.file_added(parent_id, name) - return item - - def _file_to_replace(self, path, parent_id, name): - """The ID of the file a write to the path replaces, if there is one.""" - _, base = self._split_mounted_path(path) - match, _ = self._resolver().child( - [parent_id], base, name, folders_only=False - ) + # Threads of this filesystem that write the same path take turns. + with self._creation_lock(parent_id, name): + existing = self._file_to_replace( + resolver, rpath, base, parents, name + ) + with _unwrap_not_retried(): + if existing is None: + item = self._gdrive_upload_fobj(name, parent_id, stream) + self._dirs.file_added(parent_id, name) + return item + with _translate_not_found(rpath): + return self._gdrive_replace_content(existing, stream) + + def _file_to_replace(self, resolver, path, base, parents, name): + """The file a write to the path replaces, as reads find it.""" + match, _ = resolver.child(parents, base, name, folders_only=False) if match.folders: raise IsADirectoryError( errno.EISDIR, os.strerror(errno.EISDIR), path ) + if not match.files: + return None # Reads of a name that several files share use the lowest ID. - return min((file.id for file in match.files), default=None) + existing = min(match.files, key=attrgetter("id")) + if existing.mime_type.startswith(_WORKSPACE_TYPE_PREFIX): + raise PermissionError( + errno.EPERM, + "Drive cannot replace a Google Workspace file or a " + "shortcut with bytes", + path, + ) + return existing - def _gdrive_replace_content(self, file_id, stream): + def _gdrive_replace_content(self, existing, stream): def send(): - item = self.client.CreateFile({"id": file_id}) + # Without the type, Drive sets it from the uploaded content. + item = self.client.CreateFile( + {"id": existing.id, "mimeType": existing.mime_type} + ) item.content = stream item.Upload() return item diff --git a/pydrive2/test/test_fs.py b/pydrive2/test/test_fs.py index a417cc1a..194d7931 100644 --- a/pydrive2/test/test_fs.py +++ b/pydrive2/test/test_fs.py @@ -13,6 +13,7 @@ from googleapiclient.http import HttpRequest from pydrive2.drive import GoogleDrive +from pydrive2.files import FOLDER_MIME_TYPE from pydrive2.fs import GDriveFileSystem from pydrive2.test.test_util import ( GDRIVE_USER_CREDENTIALS_DATA, @@ -737,19 +738,25 @@ def test_cp_file_of_a_shortcut_after_the_answer_was_lost_leaves_one_copy( assert items_below(fs_factory()[0], remote_dir) == ["copy"] -@pytest.fixture -def files_in_base(service_auth, fs_factory, base_remote_dir): - """Create files under the base folder with the core API; return IDs.""" - _, base = fs_factory() - drive = GoogleDrive(service_auth) - - def create(name, content): - file = drive.CreateFile({"name": name, "parents": [base["id"]]}) +def create_on_drive(service_auth, parent_id, name, content=None, **extra): + """Create a file, or a folder without content, as another client would.""" + metadata = {"name": name, "parents": [parent_id], **extra} + if content is None: + metadata["mimeType"] = FOLDER_MIME_TYPE + file = GoogleDrive(service_auth).CreateFile(metadata) + if content is not None: file.SetContentString(content) - pydrive_retry(file.Upload) - return file["id"] + pydrive_retry(file.Upload) + return file["id"] - return create + +@pytest.fixture +def remote_dir_id(service_auth, fs_factory, remote_dir): + """Create remote_dir with the core API and return its ID.""" + _, base = fs_factory() + return create_on_drive( + service_auth, base["id"], posixpath.basename(remote_dir) + ) def content_on_drive(service_auth, file_id): @@ -757,6 +764,18 @@ def content_on_drive(service_auth, file_id): return b"".join(pydrive_retry(file.GetContentIOBuffer)) +def metadata_on_drive(service_auth, file_id, fields): + file = GoogleDrive(service_auth).CreateFile({"id": file_id}) + pydrive_retry(file.FetchMetadata, fields=fields) + return file + + +def ids_in(service_auth, folder_id): + query = f"'{folder_id}' in parents and trashed=false" + listing = GoogleDrive(service_auth).ListFile({"q": query}) + return [item["id"] for item in pydrive_retry(listing.GetList)] + + def pipe(fs, path, data, tmp_path): fs.pipe_file(path, data) @@ -773,54 +792,99 @@ def write_through_open(fs, path, data, tmp_path): @pytest.mark.parametrize( - ("write", "data"), + ("write", "size"), [ - (pipe, b"new"), - (write_through_open, b"new"), + (pipe, 3), + (write_through_open, 3), # Larger than one request, so the upload is resumable. - (put, os.urandom(2 * 1024 * 1024)), + (put, 2 * 1024 * 1024), ], ids=["pipe_file", "open", "put_file-2MiB"], ) def test_write_to_a_file_path_replaces_the_content_and_keeps_the_file( - service_auth, - fs, - fs_factory, - base_remote_dir, - files_in_base, - tmp_path, - write, - data, + service_auth, fs, remote_dir, remote_dir_id, tmp_path, write, size ): - name = uuid.uuid4().hex - path = f"{base_remote_dir}/{name}" - file_id = files_in_base(name, "old") + data = (b"0123456789abcdef" * (size // 16 + 1))[:size] + file_id = create_on_drive( + service_auth, + remote_dir_id, + "a.json", + "{}", + mimeType="application/json", + ) - write(fs, path, data, tmp_path) + write(fs, remote_dir + "/a.json", data, tmp_path) + assert ids_in(service_auth, remote_dir_id) == [file_id] assert content_on_drive(service_auth, file_id) == data - listed = fs_factory()[0].ls(base_remote_dir) - assert listed.count(path) == 1 + kept = metadata_on_drive(service_auth, file_id, "mimeType") + assert kept["mimeType"] == "application/json" + + +@pytest.mark.parametrize( + "write", + [ + lambda fs, path: fs.touch(path), + lambda fs, path: fs.pipe_file(path, b""), + ], + ids=["touch", "pipe_file"], +) +def test_empty_write_to_a_file_path_empties_the_file( + service_auth, fs, remote_dir, remote_dir_id, write +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + + write(fs, remote_dir + "/file") + + assert ids_in(service_auth, remote_dir_id) == [file_id] + assert content_on_drive(service_auth, file_id) == b"" def test_write_to_a_path_two_files_share_replaces_the_one_reads_return( - service_auth, fs, fs_factory, base_remote_dir, files_in_base + service_auth, fs, fs_factory, remote_dir, remote_dir_id ): - name = uuid.uuid4().hex - path = f"{base_remote_dir}/{name}" files = { - files_in_base(name, "one"): b"one", - files_in_base(name, "two"): b"two", + create_on_drive(service_auth, remote_dir_id, "file", "one"): b"one", + create_on_drive(service_auth, remote_dir_id, "file", "two"): b"two", } read_id, other_id = sorted(files) - fs.pipe_file(path, b"new") + fs.pipe_file(remote_dir + "/file", b"new") - assert fs_factory()[0].cat_file(path) == b"new" + assert fs_factory()[0].cat_file(remote_dir + "/file") == b"new" assert content_on_drive(service_auth, read_id) == b"new" assert content_on_drive(service_auth, other_id) == files[other_id] +def test_write_below_two_folders_with_one_name_replaces_the_file_in_either( + service_auth, fs, remote_dir, remote_dir_id +): + folders = sorted( + create_on_drive(service_auth, remote_dir_id, "dup") for _ in range(2) + ) + # Writes would create a new file in the folder with the lower ID. + file_id = create_on_drive(service_auth, folders[1], "file", "old") + + fs.pipe_file(remote_dir + "/dup/file", b"new") + + assert ids_in(service_auth, folders[0]) == [] + assert ids_in(service_auth, folders[1]) == [file_id] + assert content_on_drive(service_auth, file_id) == b"new" + + +def test_replace_after_drive_did_it_and_the_answer_was_lost_keeps_one_file( + service_auth, fs, remote_dir, remote_dir_id, lose_answers +): + file_id = create_on_drive(service_auth, remote_dir_id, "file", "old") + lost = lose_answers("PATCH", "") + + fs.pipe_file(remote_dir + "/file", b"new") + + assert len(lost) == 1 + assert ids_in(service_auth, remote_dir_id) == [file_id] + assert content_on_drive(service_auth, file_id) == b"new" + + def test_write_to_a_folder_path_raises_and_creates_no_file( fs, fs_factory, remote_dir ): @@ -828,3 +892,11 @@ def test_write_to_a_folder_path_raises_and_creates_no_file( with pytest.raises(IsADirectoryError): fs.pipe_file(remote_dir + "/dir", b"data") assert fs_factory()[0].ls(remote_dir) == [remote_dir + "/dir/"] + + +@pytest.mark.parametrize("suffix", ["", "-link"], ids=["doc", "shortcut"]) +def test_write_to_a_google_doc_or_shortcut_path_raises_permission_error( + fs, workspace_files, suffix +): + with pytest.raises(PermissionError): + fs.pipe_file(f"root/{workspace_files}{suffix}", b"data") diff --git a/pydrive2/test/test_fs_unit.py b/pydrive2/test/test_fs_unit.py index 64e93024..b82a687f 100644 --- a/pydrive2/test/test_fs_unit.py +++ b/pydrive2/test/test_fs_unit.py @@ -7,6 +7,7 @@ import ssl import sys import tempfile +import time import tracemalloc from concurrent.futures import ThreadPoolExecutor from http.client import IncompleteRead @@ -2195,46 +2196,87 @@ def test_rmdir_checks_emptiness_again_after_transient_failure(mock_drive): assert [r[1] for r in requests] == ["GET", "GET", "DELETE", "GET"] -def test_upload_while_mkdir_is_waiting_for_drive_keeps_both_matches( - mock_drive, -): +def reporting(http, on_request): + """A mock connection that reports each request before answering it.""" + http.on_request = on_request + return http + + +def run_while_paused(first, second, pause_method): + """Start second while first waits for Drive's answer to pause_method. + + Return the methods second sent before first was answered. + """ started, release = Event(), Event() + early = [] - def pause_create(request): - if request[1] == "POST": + def pause(request): + if request[1] == pause_method: started.set() assert release.wait(5) - directory = folder("item", "Z") - file = {"id": "A", "name": "item", "mimeType": "text/plain"} - creator, _ = mock_drive( - listing(), response(directory), on_request=pause_create - ) - drive, requests = mock_drive( - listing(), # The folder has not been created yet. - response(file), - listing(file, directory), - ({"status": "200", "content-length": "1"}, b"x"), - ) - fs = filesystem(drive) - http = creator.auth.thread_local.http + def record(request): + if not release.is_set(): + early.append(request[1]) - def create(): - drive.auth.thread_local.http = http - fs.mkdir("root/item") - - with ThreadPoolExecutor(max_workers=1) as pool: - pending = pool.submit(create) + with ThreadPoolExecutor(max_workers=2) as pool: + pending = pool.submit(first, pause) try: assert started.wait(5) - fs.touch("root/item") + later = pool.submit(second, record) + # Give the second thread time to send a request if it can. + time.sleep(0.2) finally: release.set() pending.result(timeout=5) + return early, later - with fs.open("root/item", "rb") as stream: - assert stream.read() == b"x" - assert urlsplit(requests[-1][0]).path.endswith("/files/A") + +def test_write_waits_for_mkdir_of_the_same_name_and_raises_is_a_directory_error( + mock_drive, +): + creator, _ = mock_drive(listing(), response(folder("item", "Z"))) + writer, _ = mock_drive() + fs = filesystem(creator) + threads = creator.auth.thread_local + creator_http = creator.auth.thread_local.http + writer_http = writer.auth.thread_local.http + + def make_folder(on_request): + threads.http = reporting(creator_http, on_request) + fs.mkdir("root/item") + + def write(on_request): + threads.http = reporting(writer_http, on_request) + fs.touch("root/item") + + early, later = run_while_paused(make_folder, write, "POST") + assert early == [] + with pytest.raises(IsADirectoryError): + later.result(timeout=5) + + +def test_two_threads_writing_one_new_path_create_one_file(mock_drive): + file = {"id": "A", "name": "new", "mimeType": "text/plain"} + first, _ = mock_drive(listing(), response(file)) + second, second_requests = mock_drive(listing(file), response(file)) + fs = filesystem(first) + threads = first.auth.thread_local + first_http = first.auth.thread_local.http + second_http = second.auth.thread_local.http + + def write_first(on_request): + threads.http = reporting(first_http, on_request) + fs.pipe_file("root/new", b"one") + + def write_second(on_request): + threads.http = reporting(second_http, on_request) + fs.pipe_file("root/new", b"two") + + early, later = run_while_paused(write_first, write_second, "POST") + later.result(timeout=5) + assert early == [] + assert [r[1] for r in second_requests] == ["GET", "PATCH"] def overlap_requests(