diff --git a/pydrive2/test/test_file.py b/pydrive2/test/test_file.py index b1b9170f..77575f11 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,22 @@ 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 - - -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) - +# 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_Files_Get_Content_File_resourceKey(temp_file): - ga = auth_with_resource_key_mock() - drive = GoogleDrive(ga) - file1 = drive.CreateFile( - { - "id": "0BxphPoRgwhnodHNjS3JESnFNS1E", - "resourceKey": "0-vjzOveuin3fnf4LUlfsD3A", - } - ) - 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", - } - ) - with pytest.raises(ApiRequestError, match="HttpError 404 when requesting"): - pydrive_retry(file1.FetchMetadata) - - -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_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(file1.FetchMetadata) - - assert file1.metadata["name"] == "N48E012.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) + 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(