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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion pydrive2/files.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import codecs
import copy
import io
import json
import mimetypes
Expand Down Expand Up @@ -55,6 +56,34 @@
"expirationDate": "'expirationTime'",
}

# Fields that an upload can change and that hold a list of strings or a
# dict of strings.
_EDITABLE_FLAT_FIELDS = ("appProperties", "parents", "properties")
# Fields that an upload can change and that hold dicts inside.
_EDITABLE_NESTED_FIELDS = (
Comment thread
shcheklein marked this conversation as resolved.
Resolved
Comment thread
shcheklein marked this conversation as resolved.
Resolved
"contentHints",
"contentRestrictions",
"downloadRestrictions",
)


def _saved_copy(values):
"""Copy of the values to find edits by when uploading.

Values that an upload can change get their own copy, so that an edit
made in place, such as file["appProperties"]["stage"] = "done", shows
up as a change.
"""
saved = dict(values)
for key in _EDITABLE_FLAT_FIELDS:
if key in saved:
saved[key] = copy.copy(saved[key])
for key in _EDITABLE_NESTED_FIELDS:
if key in saved:
saved[key] = copy.deepcopy(saved[key])
Comment thread
shcheklein marked this conversation as resolved.
Resolved
Comment thread
shcheklein marked this conversation as resolved.
Resolved
return saved


# One request must send its whole body within http_timeout, so keep it small.
_SINGLE_REQUEST_UPLOAD_SIZE = 1024 * 1024
# The Google client cannot put these in a one-request body as raw bytes.
Expand Down Expand Up @@ -316,6 +345,12 @@ def __init__(self, auth=None, metadata=None, uploaded=False):
self.has_bom = True
self._export_mimetype = None

def UpdateMetadata(self, metadata=None):
"""Update metadata and mark all of them to be clean."""
if metadata:
self.update(metadata)
self.metadata = _saved_copy(self)

def __getitem__(self, key):
"""Overwrites manner of accessing Files resource.

Expand Down Expand Up @@ -549,7 +584,9 @@ def FetchMetadata(self, fields=None, fetch_all=False):
pending.pop("id", None)
self.uploaded = True
# What Drive is known to hold: earlier answers, then this one.
self.metadata = {**self.metadata, "id": file_id, **metadata}
self.metadata = _saved_copy(
{**self.metadata, "id": file_id, **metadata}
)
self.update(metadata)
self.update(pending)
self["id"] = self.metadata["id"]
Expand Down
84 changes: 84 additions & 0 deletions pydrive2/test/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,90 @@ def test_move_after_a_partial_read_puts_the_file_in_the_new_folder(
}


@pytest.mark.parametrize(
("field", "created", "edited"),
[
("appProperties", {"stage": "draft"}, {"stage": "done"}),
("properties", {"owner": "ml"}, {"owner": "ops"}),
],
ids=["appProperties", "properties"],
)
def test_upload_after_an_in_place_edit_of_a_nested_field_stores_the_edit(
service_auth, request, field, created, edited
):
drive = GoogleDrive(service_auth)
file = drive.CreateFile(
{"name": test_util.CreateRandomFileName(), field: created}
)
pydrive_retry(file.Upload)
request.addfinalizer(lambda: pydrive_retry(file.Delete))

read = drive.CreateFile({"id": file["id"]})
pydrive_retry(read.FetchMetadata, fields=field)
(key,) = edited
read[field][key] = edited[key]
pydrive_retry(read.Upload)

assert stored(service_auth, file["id"], field) == {field: edited}


# new_folder comes first, so that the file in it is deleted before it.
def test_upload_after_an_in_place_edit_of_parents_moves_the_file(
Comment thread
shcheklein marked this conversation as resolved.
Resolved
service_auth, new_folder, uploaded_file
):
read = GoogleDrive(service_auth).CreateFile({"id": uploaded_file["id"]})
pydrive_retry(read.FetchMetadata, fields="parents")
read["parents"][0] = new_folder["id"]
pydrive_retry(read.Upload)

assert stored(service_auth, uploaded_file["id"], "parents") == {
"parents": [new_folder["id"]]
}


# new_folder comes first, so that the file in it is deleted before it.
def test_upload_after_an_in_place_edit_of_parents_of_a_listed_file_moves_it(
service_auth, new_folder, uploaded_file
):
query = f"name = '{uploaded_file['name']}'"
listing = GoogleDrive(service_auth).ListFile({"q": query})
(listed,) = pydrive_retry(listing.GetList)
listed["parents"][0] = new_folder["id"]
pydrive_retry(listed.Upload)

assert stored(service_auth, uploaded_file["id"], "parents") == {
"parents": [new_folder["id"]]
}


def test_upload_after_appending_a_second_parent_in_place_raises(
service_auth, uploaded_file
):
read = GoogleDrive(service_auth).CreateFile({"id": uploaded_file["id"]})
pydrive_retry(read.FetchMetadata, fields="parents")
read["parents"].append("another-folder")
with pytest.raises(ValueError, match="only one parent"):
read.Upload()


def test_upload_after_an_in_place_edit_of_content_restrictions_unlocks_it(
service_auth, uploaded_file
):
uploaded_file["contentRestrictions"] = [{"readOnly": True}]
pydrive_retry(uploaded_file.Upload)

read = GoogleDrive(service_auth).CreateFile({"id": uploaded_file["id"]})
pydrive_retry(read.FetchMetadata, fields="contentRestrictions(readOnly)")
read["contentRestrictions"][0]["readOnly"] = False
pydrive_retry(read.Upload)

restrictions = stored(service_auth, read["id"], "contentRestrictions")
assert not any(
restriction.get("readOnly")
for restriction in restrictions["contentRestrictions"] or []
)


def test_changing_the_id_of_an_uploaded_file_raises_and_changes_neither_file(
service_auth, uploaded_file, request
):
Expand Down
16 changes: 16 additions & 0 deletions pydrive2/test/test_files_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,22 @@ def test_upload_rejects_listed_file_without_id(mock_drive):
assert [request[1] for request in requests] == ["GET"]


def test_upload_after_an_in_place_edit_of_content_hints_sends_them(
mock_drive,
):
# Drive never returns contentHints, so only the request can show this.
drive, requests = mock_drive(response({"id": "A"}), response({"id": "A"}))
file = drive.CreateFile({"contentHints": {"indexableText": "draft"}})
file.Upload()
file["contentHints"]["indexableText"] = "final"
file.Upload()
update = requests[-1]
assert update[1] == "PATCH"
assert json.loads(update[2]) == {
"contentHints": {"indexableText": "final"}
}


def test_upload_updates_listed_file_with_id(mock_drive):
drive, requests = mock_drive(
response({"files": [{"id": "existing", "name": "original"}]}),
Expand Down
Loading