From a8d4f7e16c49658da90898507107f7da1b5b16f2 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Wed, 2 Dec 2026 20:29:14 -0800 Subject: [PATCH 1/2] Test resource keys against the real link-shared file Six tests in the live module checked resource keys against a mock transport, and the two that used the real file were manual because they downloaded all 6 MB. Four live tests now read the real file's metadata and its first kilobyte, with and without its key. Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_file.py | 202 +++++++------------------------------ 1 file changed, 37 insertions(+), 165 deletions(-) diff --git a/pydrive2/test/test_file.py b/pydrive2/test/test_file.py index b1b9170f..661d8431 100644 --- a/pydrive2/test/test_file.py +++ b/pydrive2/test/test_file.py @@ -1,15 +1,11 @@ import filecmp -import json import os import sys from concurrent.futures import ThreadPoolExecutor, as_completed from itertools import count from pathlib import Path -from tempfile import TemporaryDirectory from time import time -from unittest.mock import MagicMock -import httplib2 import pytest import timeout_decorator from googleapiclient import errors @@ -23,63 +19,11 @@ delete_file, pydrive_retry, settings_file_path, - setup_credentials, ) pytestmark = pytest.mark.drive -def auth_with_resource_key_mock() -> GoogleAuth: - """ - Create GoogleAuth with mocked inner httplib2.Http simulating need - for resourceKey header. - """ - http_mock = MagicMock() - - def resource_key_request( - uri, - method="GET", - body=None, - headers=None, - redirections=1, - connection_type=None, - ): - """httplib2.Http.request mock.""" - # If "media" is not requested, it means we expect metadata - fetch_meta_data = "alt=media" not in uri - if ( - headers - and "X-Goog-Drive-Resource-Keys" in headers - and headers["X-Goog-Drive-Resource-Keys"] - == "0BxphPoRgwhnodHNjS3JESnFNS1E/0-vjzOveuin3fnf4LUlfsD3A" - ): - if fetch_meta_data: - # Fake meta data query response - content = json.dumps({"name": "N48E012.zip"}).encode() - else: - # Fake file content query response - content = b"some content" - return ( - httplib2.Response( - {"status": "200", "content-length": str(len(content))} - ), - content, - ) - # Simulate 404 response for file not found; body must be valid error JSON - return ( - httplib2.Response({"status": "404"}), - json.dumps({"error": {"code": 404}}).encode(), - ) - - http_mock.request.side_effect = resource_key_request - setup_credentials() - with TemporaryDirectory() as tmpdir: - ga = GoogleAuth(settings_file_path("default.yaml", tmpdir)) - ga.thread_local.http = http_mock - ga.ServiceAuth() - return ga - - FILE_UPLOAD_COUNT = 10 @@ -539,126 +483,54 @@ def test_Files_Get_Content_Buffer(service_auth, delete_after_test, temp_file): assert "".join(iter(buffer2)) == content -def test_Files_Get_Content_Buffer_resourceKey_missing(): - """404 expected for file secured with resourceKey when not provided.""" - - ga = auth_with_resource_key_mock() - - drive = GoogleDrive(ga) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - } - ) - with pytest.raises(ApiRequestError, match="HttpError 404 when requesting"): - pydrive_retry(file1.GetContentIOBuffer) - - -def test_Files_Get_Content_Buffer_resourceKey(): - """End to end scenario with real file.""" - ga = auth_with_resource_key_mock() - drive = GoogleDrive(ga) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - "resourceKey": "0-vjzOveuin3fnf4LUlfsD3A", - } - ) - - buffer1 = pydrive_retry(file1.GetContentIOBuffer) - - assert len(buffer1) == 12 - - -@pytest.mark.manual -def test_Files_Get_Content_Buffer_resourceKey_missing_real(service_auth): - """ - 404 expected for file secured with resourceKey when not provided. - End to end scenario with real public file. - """ - drive = GoogleDrive(service_auth) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - } - ) - with pytest.raises(ApiRequestError, match="HttpError 404 when requesting"): - pydrive_retry(file1.GetContentIOBuffer) - - -@pytest.mark.manual -def test_Files_Get_Content_Buffer_resourceKey_real(service_auth): - """End to end scenario with real public file.""" - drive = GoogleDrive(service_auth) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - "resourceKey": "0-vjzOveuin3fnf4LUlfsD3A", - } - ) - - buffer1 = pydrive_retry(file1.GetContentIOBuffer) - - assert len(buffer1) == 6128902 +# A file shared by link before 2021: Drive serves it only with its key. +LINK_SHARED_FILE = {"id": "0BxphPoRgwhnodHNjS3JESnFNS1E"} +RESOURCE_KEY = "0-vjzOveuin3fnf4LUlfsD3A" -def test_Files_Get_Content_File_resourceKey_missing(temp_file): - """404 expected for file secured with resourceKey when not provided.""" - ga = auth_with_resource_key_mock() - drive = GoogleDrive(ga) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - } - ) - fileOut = temp_file() - with pytest.raises(ApiRequestError, match="HttpError 404 when requesting"): - pydrive_retry(file1.GetContentFile, fileOut) +def test_metadata_of_a_link_shared_file_without_its_resource_key_is_404( + service_auth, +): + file = GoogleDrive(service_auth).CreateFile(LINK_SHARED_FILE) + with pytest.raises(ApiRequestError) as error: + pydrive_retry(file.FetchMetadata, fields="name") + assert error.value.error["code"] == 404 -def test_Files_Get_Content_File_resourceKey(temp_file): - ga = auth_with_resource_key_mock() - drive = GoogleDrive(ga) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - "resourceKey": "0-vjzOveuin3fnf4LUlfsD3A", - } +def test_metadata_of_a_link_shared_file_with_its_resource_key_is_served( + service_auth, +): + file = GoogleDrive(service_auth).CreateFile( + dict(LINK_SHARED_FILE, resourceKey=RESOURCE_KEY) ) + pydrive_retry(file.FetchMetadata, fields="name") + assert file["name"] == "N48E012.zip" - fileOut = temp_file() - pydrive_retry(file1.GetContentFile, fileOut) - - with open(fileOut, "rb") as f: - assert len(f.read()) == 12 - -def test_Files_Fetch_Metadata_resourceKey_missing(): - """404 expected for file secured with resourceKey when not provided.""" - ga = auth_with_resource_key_mock() - drive = GoogleDrive(ga) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - } +def test_download_of_a_link_shared_file_without_its_resource_key_is_404( + service_auth, +): + file = GoogleDrive(service_auth).CreateFile( + dict(LINK_SHARED_FILE, mimeType="application/zip") ) - with pytest.raises(ApiRequestError, match="HttpError 404 when requesting"): - pydrive_retry(file1.FetchMetadata) + with pytest.raises(ApiRequestError) as error: + pydrive_retry(file.GetContentIOBuffer, chunksize=1024) + assert error.value.error["code"] == 404 -def test_Files_Fetch_Metadata_resourceKey(): - ga = auth_with_resource_key_mock() - drive = GoogleDrive(ga) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - "resourceKey": "0-vjzOveuin3fnf4LUlfsD3A", - } +def test_download_of_a_link_shared_file_with_its_resource_key_is_served( + service_auth, +): + file = GoogleDrive(service_auth).CreateFile( + dict( + LINK_SHARED_FILE, + resourceKey=RESOURCE_KEY, + mimeType="application/zip", + ) ) - - pydrive_retry(file1.FetchMetadata) - - assert file1.metadata["name"] == "N48E012.zip" + # The first kilobyte is enough to show that Drive serves the content. + stream = pydrive_retry(file.GetContentIOBuffer, chunksize=1024) + assert len(stream.read()) == 1024 def test_Upload_Download_Empty_File( From d34a74f4ef46de0fd4b33373e282704e0a57406e Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Thu, 3 Dec 2026 11:09:49 -0800 Subject: [PATCH 2/2] Check the resource-key header offline, keep one keyed live test Drive serves a link-shared file without its key to an account that opened it recently, and the CI account opens it on every run, so the live 404 checks depended on account history. One live test now opens the real file with its key, and an offline test checks that metadata and download requests carry the header only when the file has a key. Co-Authored-By: Claude Opus 5.5 --- pydrive2/test/test_file.py | 46 +++++--------------------------- pydrive2/test/test_files_unit.py | 30 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 39 deletions(-) diff --git a/pydrive2/test/test_file.py b/pydrive2/test/test_file.py index 661d8431..77575f11 100644 --- a/pydrive2/test/test_file.py +++ b/pydrive2/test/test_file.py @@ -483,54 +483,22 @@ def test_Files_Get_Content_Buffer(service_auth, delete_after_test, temp_file): assert "".join(iter(buffer2)) == content -# A file shared by link before 2021: Drive serves it only with its key. +# A file shared by link before 2021. Drive serves it only with its key to +# an account that has not opened it recently. LINK_SHARED_FILE = {"id": "0BxphPoRgwhnodHNjS3JESnFNS1E"} RESOURCE_KEY = "0-vjzOveuin3fnf4LUlfsD3A" -def test_metadata_of_a_link_shared_file_without_its_resource_key_is_404( - service_auth, -): - file = GoogleDrive(service_auth).CreateFile(LINK_SHARED_FILE) - with pytest.raises(ApiRequestError) as error: - pydrive_retry(file.FetchMetadata, fields="name") - assert error.value.error["code"] == 404 - - -def test_metadata_of_a_link_shared_file_with_its_resource_key_is_served( - service_auth, -): +def test_link_shared_file_with_its_resource_key_is_served(service_auth): file = GoogleDrive(service_auth).CreateFile( dict(LINK_SHARED_FILE, resourceKey=RESOURCE_KEY) ) - pydrive_retry(file.FetchMetadata, fields="name") - assert file["name"] == "N48E012.zip" - - -def test_download_of_a_link_shared_file_without_its_resource_key_is_404( - service_auth, -): - file = GoogleDrive(service_auth).CreateFile( - dict(LINK_SHARED_FILE, mimeType="application/zip") - ) - with pytest.raises(ApiRequestError) as error: - pydrive_retry(file.GetContentIOBuffer, chunksize=1024) - assert error.value.error["code"] == 404 - - -def test_download_of_a_link_shared_file_with_its_resource_key_is_served( - service_auth, -): - file = GoogleDrive(service_auth).CreateFile( - dict( - LINK_SHARED_FILE, - resourceKey=RESOURCE_KEY, - mimeType="application/zip", - ) - ) + pydrive_retry(file.FetchMetadata, fields="id") # The first kilobyte is enough to show that Drive serves the content. stream = pydrive_retry(file.GetContentIOBuffer, chunksize=1024) - assert len(stream.read()) == 1024 + chunk = stream.read() + assert len(chunk) == 1024 + assert chunk.startswith(b"PK\x03\x04") def test_Upload_Download_Empty_File( diff --git a/pydrive2/test/test_files_unit.py b/pydrive2/test/test_files_unit.py index 502dfa1f..34b3b717 100644 --- a/pydrive2/test/test_files_unit.py +++ b/pydrive2/test/test_files_unit.py @@ -22,6 +22,36 @@ from pydrive2.test.http_mock import error_response, query, response +# The CI account opens the real link-shared file in test_file.py, and Drive +# then serves it without the key, so only a mock shows the header is needed. +@pytest.mark.parametrize( + "read", + [ + lambda file: file.FetchMetadata(fields="id"), + lambda file: file.GetContentIOBuffer().read(), + ], + ids=["metadata", "download"], +) +@pytest.mark.parametrize( + ("metadata", "header"), + [ + ({"id": "file", "resourceKey": "key"}, "file/key"), + ({"id": "file"}, None), + ], + ids=["with-key", "without-key"], +) +def test_request_for_a_file_carries_its_resource_key( + mock_drive, read, metadata, header +): + body = b'{"id": "file"}' + drive, requests = mock_drive( + ({"status": "200", "content-length": str(len(body))}, body) + ) + read(drive.CreateFile(metadata)) + (request,) = requests + assert request[3].get("X-Goog-Drive-Resource-Keys") == header + + @pytest.mark.parametrize("kind", ["folder", "shortcut"]) def test_get_content_of_non_downloadable_file(mock_drive, kind): drive, requests = mock_drive(