Debian Codegraph @

tests/test_discovery.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright 2014 Google Inc. All Rights Reserved.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17
18
19 """Discovery document tests
20
21 Unit tests for objects created from discovery documents.
22 """
23 from __future__ import absolute_import
24
25 __author__ = "[email protected] (Joe Gregorio)"
26
27 from collections import defaultdict
28 import copy
29 import datetime
30 import io
31 import itertools
32 import json
33 import os
34 import pickle
35 import re
36 import sys
37 import unittest
38 from unittest import mock
39 import urllib
40
41 import google.api_core.exceptions
42 from google.auth import __version__ as auth_version
43 import google.auth.credentials
44 from google.auth.exceptions import MutualTLSChannelError
45 import google_auth_httplib2
46 import httplib2
47 from parameterized import parameterized
48 import pytest
49 import uritemplate
50
51 try:
52 from oauth2client import GOOGLE_TOKEN_URI
53 from oauth2client.client import GoogleCredentials, OAuth2Credentials
54
55 HAS_OAUTH2CLIENT = True
56 except ImportError:
57 HAS_OAUTH2CLIENT = False
58
59 try:
60 from google.api_core import universe
61
62 HAS_UNIVERSE = True
63 except ImportError:
64 HAS_UNIVERSE = False
65
66 from googleapiclient import _helpers as util
67 from googleapiclient.discovery import (
68 DISCOVERY_URI,
69 MEDIA_BODY_PARAMETER_DEFAULT_VALUE,
70 MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE,
71 STACK_QUERY_PARAMETER_DEFAULT_VALUE,
72 STACK_QUERY_PARAMETERS,
73 V1_DISCOVERY_URI,
74 V2_DISCOVERY_URI,
75 APICoreVersionError,
76 ResourceMethodParameters,
77 _fix_up_media_path_base_url,
78 _fix_up_media_upload,
79 _fix_up_method_description,
80 _fix_up_parameters,
81 _urljoin,
82 build,
83 build_from_document,
84 key2param,
85 )
86 from googleapiclient.discovery_cache import DISCOVERY_DOC_MAX_AGE
87 from googleapiclient.discovery_cache.base import Cache
88 from googleapiclient.errors import (
89 HttpError,
90 InvalidJsonError,
91 MediaUploadSizeError,
92 ResumableUploadError,
93 UnacceptableMimeTypeError,
94 UnknownApiNameOrVersion,
95 UnknownFileType,
96 )
97 from googleapiclient.http import (
98 HttpMock,
99 HttpMockSequence,
100 MediaFileUpload,
101 MediaIoBaseUpload,
102 MediaUpload,
103 MediaUploadProgress,
104 build_http,
105 tunnel_patch,
106 )
107 from googleapiclient.model import JsonModel
108 from googleapiclient.schema import Schemas
109
110 DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
111
112
113 def _reset_universe_domain(credentials, universe_domain=None):
114 if hasattr(credentials, "universe_domain"):
115 credentials.universe_domain = universe_domain
116
117
118 def assertUrisEqual(testcase, expected, actual):
119 """Test that URIs are the same, up to reordering of query parameters."""
120 expected = urllib.parse.urlparse(expected)
121 actual = urllib.parse.urlparse(actual)
122 testcase.assertEqual(expected.scheme, actual.scheme)
123 testcase.assertEqual(expected.netloc, actual.netloc)
124 testcase.assertEqual(expected.path, actual.path)
125 testcase.assertEqual(expected.params, actual.params)
126 testcase.assertEqual(expected.fragment, actual.fragment)
127 expected_query = urllib.parse.parse_qs(expected.query)
128 actual_query = urllib.parse.parse_qs(actual.query)
129 for name in list(expected_query.keys()):
130 testcase.assertEqual(expected_query[name], actual_query[name])
131 for name in list(actual_query.keys()):
132 testcase.assertEqual(expected_query[name], actual_query[name])
133
134
135 def assert_discovery_uri(testcase, actual, service_name, version, discovery):
136 """Assert that discovery URI used was the one that was expected
137 for a given service and version."""
138 params = {"api": service_name, "apiVersion": version}
139 expanded_requested_uri = uritemplate.expand(discovery, params)
140 assertUrisEqual(testcase, expanded_requested_uri, actual)
141
142
143 def validate_discovery_requests(testcase, http_mock, service_name, version, discovery):
144 """Validates that there have > 0 calls to Http Discovery
145 and that LAST discovery URI used was the one that was expected
146 for a given service and version."""
147 testcase.assertTrue(len(http_mock.request_sequence) > 0)
148 if len(http_mock.request_sequence) > 0:
149 actual_uri = http_mock.request_sequence[-1][0]
150 assert_discovery_uri(testcase, actual_uri, service_name, version, discovery)
151
152
153 def datafile(filename):
154 return os.path.join(DATA_DIR, filename)
155
156
157 def read_datafile(filename, mode="r"):
158 with open(datafile(filename), mode=mode) as f:
159 return f.read()
160
161
162 def parse_version_to_tuple(version_string):
163 """Safely converts a semantic version string to a comparable tuple of integers.
164
165 Example: "4.25.8" -> (4, 25, 8)
166 Ignores non-numeric parts and handles common version formats.
167
168 Args:
169 version_string: Version string in the format "x.y.z" or "x.y.z<suffix>"
170
171 Returns:
172 Tuple of integers for the parsed version string.
173 """
174 parts = []
175 for part in version_string.split("."):
176 try:
177 parts.append(int(part))
178 except ValueError:
179 # If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here.
180 # This is a simplification compared to 'packaging.parse_version', but sufficient
181 # for comparing strictly numeric semantic versions.
182 break
183 return tuple(parts)
184
185
186 class SetupHttplib2(unittest.TestCase):
187 def test_retries(self):
188 # Merely loading googleapiclient.discovery should set the RETRIES to 1.
189 self.assertEqual(1, httplib2.RETRIES)
190
191
192 class Utilities(unittest.TestCase):
193 def setUp(self):
194 self.zoo_root_desc = json.loads(read_datafile("zoo.json", "r"))
195 self.zoo_get_method_desc = self.zoo_root_desc["methods"]["query"]
196 self.zoo_animals_resource = self.zoo_root_desc["resources"]["animals"]
197 self.zoo_insert_method_desc = self.zoo_animals_resource["methods"]["insert"]
198 self.zoo_schema = Schemas(self.zoo_root_desc)
199
200 def test_key2param(self):
201 self.assertEqual("max_results", key2param("max-results"))
202 self.assertEqual("x007_bond", key2param("007-bond"))
203
204 def _base_fix_up_parameters_test(self, method_desc, http_method, root_desc, schema):
205 self.assertEqual(method_desc["httpMethod"], http_method)
206
207 method_desc_copy = copy.deepcopy(method_desc)
208 self.assertEqual(method_desc, method_desc_copy)
209
210 parameters = _fix_up_parameters(
211 method_desc_copy, root_desc, http_method, schema
212 )
213
214 self.assertNotEqual(method_desc, method_desc_copy)
215
216 for param_name in STACK_QUERY_PARAMETERS:
217 self.assertEqual(
218 STACK_QUERY_PARAMETER_DEFAULT_VALUE, parameters[param_name]
219 )
220
221 for param_name, value in root_desc.get("parameters", {}).items():
222 self.assertEqual(value, parameters[param_name])
223
224 return parameters
225
226 def test_fix_up_parameters_get(self):
227 parameters = self._base_fix_up_parameters_test(
228 self.zoo_get_method_desc, "GET", self.zoo_root_desc, self.zoo_schema
229 )
230 # Since http_method is 'GET'
231 self.assertFalse("body" in parameters)
232
233 def test_fix_up_parameters_insert(self):
234 parameters = self._base_fix_up_parameters_test(
235 self.zoo_insert_method_desc, "POST", self.zoo_root_desc, self.zoo_schema
236 )
237 body = {"description": "The request body.", "type": "object", "$ref": "Animal"}
238 self.assertEqual(parameters["body"], body)
239
240 def test_fix_up_parameters_check_body(self):
241 dummy_root_desc = {}
242 dummy_schema = {
243 "Request": {
244 "properties": {
245 "description": "Required. Dummy parameter.",
246 "type": "string",
247 }
248 }
249 }
250 no_payload_http_method = "DELETE"
251 with_payload_http_method = "PUT"
252
253 invalid_method_desc = {"response": "Who cares"}
254 valid_method_desc = {
255 "request": {"key1": "value1", "key2": "value2", "$ref": "Request"}
256 }
257
258 parameters = _fix_up_parameters(
259 invalid_method_desc, dummy_root_desc, no_payload_http_method, dummy_schema
260 )
261 self.assertFalse("body" in parameters)
262
263 parameters = _fix_up_parameters(
264 valid_method_desc, dummy_root_desc, no_payload_http_method, dummy_schema
265 )
266 self.assertFalse("body" in parameters)
267
268 parameters = _fix_up_parameters(
269 invalid_method_desc, dummy_root_desc, with_payload_http_method, dummy_schema
270 )
271 self.assertFalse("body" in parameters)
272
273 parameters = _fix_up_parameters(
274 valid_method_desc, dummy_root_desc, with_payload_http_method, dummy_schema
275 )
276 body = {
277 "description": "The request body.",
278 "type": "object",
279 "$ref": "Request",
280 "key1": "value1",
281 "key2": "value2",
282 }
283 self.assertEqual(parameters["body"], body)
284
285 def test_fix_up_parameters_optional_body(self):
286 # Request with no parameters
287 dummy_schema = {"Request": {"properties": {}}}
288 method_desc = {"request": {"$ref": "Request"}}
289
290 parameters = _fix_up_parameters(method_desc, {}, "POST", dummy_schema)
291
292 def _base_fix_up_method_description_test(
293 self,
294 method_desc,
295 initial_parameters,
296 final_parameters,
297 final_accept,
298 final_max_size,
299 final_media_path_url,
300 ):
301 fake_root_desc = {
302 "rootUrl": "http://root/",
303 "servicePath": "fake/",
304 "mtlsRootUrl": "http://root/",
305 }
306 fake_path_url = "fake-path/"
307
308 accept, max_size, media_path_url = _fix_up_media_upload(
309 method_desc, fake_root_desc, fake_path_url, initial_parameters
310 )
311 self.assertEqual(accept, final_accept)
312 self.assertEqual(max_size, final_max_size)
313 self.assertEqual(media_path_url, final_media_path_url)
314 self.assertEqual(initial_parameters, final_parameters)
315
316 def test_fix_up_media_upload_no_initial_invalid(self):
317 invalid_method_desc = {"response": "Who cares"}
318 self._base_fix_up_method_description_test(
319 invalid_method_desc, {}, {}, [], 0, None
320 )
321
322 def test_fix_up_media_upload_no_initial_valid_minimal(self):
323 valid_method_desc = {"mediaUpload": {"accept": []}}
324 final_parameters = {
325 "media_body": MEDIA_BODY_PARAMETER_DEFAULT_VALUE,
326 "media_mime_type": MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE,
327 }
328 self._base_fix_up_method_description_test(
329 valid_method_desc,
330 {},
331 final_parameters,
332 [],
333 0,
334 "http://root/upload/fake/fake-path/",
335 )
336
337 def test_fix_up_media_upload_no_initial_valid_full(self):
338 valid_method_desc = {"mediaUpload": {"accept": ["*/*"], "maxSize": "10GB"}}
339 final_parameters = {
340 "media_body": MEDIA_BODY_PARAMETER_DEFAULT_VALUE,
341 "media_mime_type": MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE,
342 }
343 ten_gb = 10 * 2**30
344 self._base_fix_up_method_description_test(
345 valid_method_desc,
346 {},
347 final_parameters,
348 ["*/*"],
349 ten_gb,
350 "http://root/upload/fake/fake-path/",
351 )
352
353 def test_fix_up_media_upload_with_initial_invalid(self):
354 invalid_method_desc = {"response": "Who cares"}
355 initial_parameters = {"body": {}}
356 self._base_fix_up_method_description_test(
357 invalid_method_desc, initial_parameters, initial_parameters, [], 0, None
358 )
359
360 def test_fix_up_media_upload_with_initial_valid_minimal(self):
361 valid_method_desc = {"mediaUpload": {"accept": []}}
362 initial_parameters = {"body": {}}
363 final_parameters = {
364 "body": {},
365 "media_body": MEDIA_BODY_PARAMETER_DEFAULT_VALUE,
366 "media_mime_type": MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE,
367 }
368 self._base_fix_up_method_description_test(
369 valid_method_desc,
370 initial_parameters,
371 final_parameters,
372 [],
373 0,
374 "http://root/upload/fake/fake-path/",
375 )
376
377 def test_fix_up_media_upload_with_initial_valid_full(self):
378 valid_method_desc = {"mediaUpload": {"accept": ["*/*"], "maxSize": "10GB"}}
379 initial_parameters = {"body": {}}
380 final_parameters = {
381 "body": {},
382 "media_body": MEDIA_BODY_PARAMETER_DEFAULT_VALUE,
383 "media_mime_type": MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE,
384 }
385 ten_gb = 10 * 2**30
386 self._base_fix_up_method_description_test(
387 valid_method_desc,
388 initial_parameters,
389 final_parameters,
390 ["*/*"],
391 ten_gb,
392 "http://root/upload/fake/fake-path/",
393 )
394
395 def test_fix_up_method_description_get(self):
396 result = _fix_up_method_description(
397 self.zoo_get_method_desc, self.zoo_root_desc, self.zoo_schema
398 )
399 path_url = "query"
400 http_method = "GET"
401 method_id = "bigquery.query"
402 accept = []
403 max_size = 0
404 media_path_url = None
405 self.assertEqual(
406 result, (path_url, http_method, method_id, accept, max_size, media_path_url)
407 )
408
409 def test_fix_up_method_description_insert(self):
410 result = _fix_up_method_description(
411 self.zoo_insert_method_desc, self.zoo_root_desc, self.zoo_schema
412 )
413 path_url = "animals"
414 http_method = "POST"
415 method_id = "zoo.animals.insert"
416 accept = ["image/png"]
417 max_size = 1024
418 media_path_url = "https://www.googleapis.com/upload/zoo/v1/animals"
419 self.assertEqual(
420 result, (path_url, http_method, method_id, accept, max_size, media_path_url)
421 )
422
423 def test_fix_up_media_path_base_url_same_netloc(self):
424 result = _fix_up_media_path_base_url(
425 "https://www.googleapis.com/upload/foo",
426 "https://www.googleapis.com/upload/bar",
427 )
428 self.assertEqual(result, "https://www.googleapis.com/upload/foo")
429
430 def test_fix_up_media_path_base_url_different_netloc(self):
431 result = _fix_up_media_path_base_url(
432 "https://www.googleapis.com/upload/foo",
433 "https://www.example.com/upload/bar",
434 )
435 self.assertEqual(result, "https://www.example.com/upload/foo")
436
437 def test_urljoin(self):
438 # We want to exhaustively test various URL combinations.
439 simple_bases = ["https://www.googleapis.com", "https://www.googleapis.com/"]
440 long_urls = ["foo/v1/bar:custom?alt=json", "/foo/v1/bar:custom?alt=json"]
441
442 long_bases = [
443 "https://www.googleapis.com/foo/v1",
444 "https://www.googleapis.com/foo/v1/",
445 ]
446 simple_urls = ["bar:custom?alt=json", "/bar:custom?alt=json"]
447
448 final_url = "https://www.googleapis.com/foo/v1/bar:custom?alt=json"
449 for base, url in itertools.product(simple_bases, long_urls):
450 self.assertEqual(final_url, _urljoin(base, url))
451 for base, url in itertools.product(long_bases, simple_urls):
452 self.assertEqual(final_url, _urljoin(base, url))
453
454 def test_ResourceMethodParameters_zoo_get(self):
455 parameters = ResourceMethodParameters(self.zoo_get_method_desc)
456
457 param_types = {
458 "a": "any",
459 "b": "boolean",
460 "e": "string",
461 "er": "string",
462 "i": "integer",
463 "n": "number",
464 "o": "object",
465 "q": "string",
466 "rr": "string",
467 }
468 keys = list(param_types.keys())
469 self.assertEqual(parameters.argmap, dict((key, key) for key in keys))
470 self.assertEqual(parameters.required_params, [])
471 self.assertEqual(sorted(parameters.repeated_params), ["er", "rr"])
472 self.assertEqual(parameters.pattern_params, {"rr": "[a-z]+"})
473 self.assertEqual(
474 sorted(parameters.query_params),
475 ["a", "b", "e", "er", "i", "n", "o", "q", "rr"],
476 )
477 self.assertEqual(parameters.path_params, set())
478 self.assertEqual(parameters.param_types, param_types)
479 enum_params = {"e": ["foo", "bar"], "er": ["one", "two", "three"]}
480 self.assertEqual(parameters.enum_params, enum_params)
481
482 def test_ResourceMethodParameters_zoo_animals_patch(self):
483 method_desc = self.zoo_animals_resource["methods"]["patch"]
484 parameters = ResourceMethodParameters(method_desc)
485
486 param_types = {"name": "string"}
487 keys = list(param_types.keys())
488 self.assertEqual(parameters.argmap, dict((key, key) for key in keys))
489 self.assertEqual(parameters.required_params, ["name"])
490 self.assertEqual(parameters.repeated_params, [])
491 self.assertEqual(parameters.pattern_params, {})
492 self.assertEqual(parameters.query_params, [])
493 self.assertEqual(parameters.path_params, set(["name"]))
494 self.assertEqual(parameters.param_types, param_types)
495 self.assertEqual(parameters.enum_params, {})
496
497
498 class Discovery(unittest.TestCase):
499 def test_discovery_http_is_closed(self):
500 http = HttpMock(datafile("malformed.json"), {"status": "200"})
501 service = build("plus", "v1", credentials=mock.sentinel.credentials)
502 http.close.assert_called_once()
503
504
505 class DiscoveryErrors(unittest.TestCase):
506 def test_tests_should_be_run_with_strict_positional_enforcement(self):
507 try:
508 plus = build("plus", "v1", None, static_discovery=False)
509 self.fail("should have raised a TypeError exception over missing http=.")
510 except TypeError:
511 pass
512
513 def test_failed_to_parse_discovery_json(self):
514 self.http = HttpMock(datafile("malformed.json"), {"status": "200"})
515 try:
516 plus = build(
517 "plus",
518 "v1",
519 http=self.http,
520 cache_discovery=False,
521 static_discovery=False,
522 )
523 self.fail("should have raised an exception over malformed JSON.")
524 except InvalidJsonError:
525 pass
526
527 def test_unknown_api_name_or_version(self):
528 http = HttpMockSequence(
529 [
530 ({"status": "404"}, read_datafile("zoo.json", "rb")),
531 ({"status": "404"}, read_datafile("zoo.json", "rb")),
532 ]
533 )
534 with self.assertRaises(UnknownApiNameOrVersion):
535 plus = build("plus", "v1", http=http, cache_discovery=False)
536
537 def test_credentials_and_http_mutually_exclusive(self):
538 http = HttpMock(datafile("plus.json"), {"status": "200"})
539 with self.assertRaises(ValueError):
540 build(
541 "plus",
542 "v1",
543 http=http,
544 credentials=mock.sentinel.credentials,
545 static_discovery=False,
546 )
547
548 def test_credentials_file_and_http_mutually_exclusive(self):
549 http = HttpMock(datafile("plus.json"), {"status": "200"})
550 with self.assertRaises(ValueError):
551 build(
552 "plus",
553 "v1",
554 http=http,
555 client_options=google.api_core.client_options.ClientOptions(
556 credentials_file="credentials.json"
557 ),
558 static_discovery=False,
559 )
560
561 def test_credentials_and_credentials_file_mutually_exclusive(self):
562 with self.assertRaises(google.api_core.exceptions.DuplicateCredentialArgs):
563 build(
564 "plus",
565 "v1",
566 credentials=mock.sentinel.credentials,
567 client_options=google.api_core.client_options.ClientOptions(
568 credentials_file="credentials.json"
569 ),
570 static_discovery=False,
571 )
572
573
574 class DiscoveryFromDocument(unittest.TestCase):
575 MOCK_CREDENTIALS = mock.Mock(spec=google.auth.credentials.Credentials)
576 _reset_universe_domain(MOCK_CREDENTIALS)
577
578 def test_can_build_from_local_document(self):
579 discovery = read_datafile("plus.json")
580 plus = build_from_document(
581 discovery,
582 base="https://www.googleapis.com/",
583 credentials=self.MOCK_CREDENTIALS,
584 )
585 self.assertIsNotNone(plus)
586 self.assertTrue(hasattr(plus, "activities"))
587
588 def test_can_build_from_local_deserialized_document(self):
589 discovery = read_datafile("plus.json")
590 discovery = json.loads(discovery)
591 plus = build_from_document(
592 discovery,
593 base="https://www.googleapis.com/",
594 credentials=self.MOCK_CREDENTIALS,
595 )
596 self.assertIsNotNone(plus)
597 self.assertTrue(hasattr(plus, "activities"))
598
599 def test_building_with_base_remembers_base(self):
600 discovery = read_datafile("plus.json")
601
602 base = "https://www.example.com/"
603 plus = build_from_document(
604 discovery, base=base, credentials=self.MOCK_CREDENTIALS
605 )
606 self.assertEqual("https://www.googleapis.com/plus/v1/", plus._baseUrl)
607
608 def test_building_with_optional_http_with_authorization(self):
609 discovery = read_datafile("plus.json")
610 plus = build_from_document(
611 discovery,
612 base="https://www.googleapis.com/",
613 credentials=self.MOCK_CREDENTIALS,
614 )
615
616 # plus service requires Authorization, hence we expect to see AuthorizedHttp object here
617 self.assertIsInstance(plus._http, google_auth_httplib2.AuthorizedHttp)
618 self.assertIsInstance(plus._http.http, httplib2.Http)
619 self.assertIsInstance(plus._http.http.timeout, int)
620 self.assertGreater(plus._http.http.timeout, 0)
621
622 def test_building_with_optional_http_with_no_authorization(self):
623 discovery = read_datafile("plus.json")
624 # Cleanup auth field, so we would use plain http client
625 discovery = json.loads(discovery)
626 discovery["auth"] = {}
627 discovery = json.dumps(discovery)
628
629 plus = build_from_document(
630 discovery, base="https://www.googleapis.com/", credentials=None
631 )
632 # plus service requires Authorization
633 self.assertIsInstance(plus._http, httplib2.Http)
634 self.assertIsInstance(plus._http.timeout, int)
635 self.assertGreater(plus._http.timeout, 0)
636
637 def test_building_with_explicit_http(self):
638 http = HttpMock()
639 discovery = read_datafile("plus.json")
640 plus = build_from_document(
641 discovery, base="https://www.googleapis.com/", http=http
642 )
643 self.assertEqual(plus._http, http)
644
645 def test_building_with_developer_key_skips_adc(self):
646 discovery = read_datafile("plus.json")
647 plus = build_from_document(
648 discovery, base="https://www.googleapis.com/", developerKey="123"
649 )
650 self.assertIsInstance(plus._http, httplib2.Http)
651 # It should not be an AuthorizedHttp, because that would indicate that
652 # application default credentials were used.
653 self.assertNotIsInstance(plus._http, google_auth_httplib2.AuthorizedHttp)
654
655 def test_building_with_context_manager(self):
656 discovery = read_datafile("plus.json")
657 with mock.patch("httplib2.Http") as http:
658 with build_from_document(
659 discovery,
660 base="https://www.googleapis.com/",
661 credentials=self.MOCK_CREDENTIALS,
662 ) as plus:
663 self.assertIsNotNone(plus)
664 self.assertTrue(hasattr(plus, "activities"))
665 plus._http.http.close.assert_called_once()
666
667 def test_resource_close(self):
668 discovery = read_datafile("plus.json")
669
670 with mock.patch("httplib2.Http", autospec=True) as httplib2_http:
671 http = httplib2_http()
672 plus = build_from_document(
673 discovery,
674 base="https://www.googleapis.com/",
675 http=http,
676 )
677 plus.close()
678 http.close.assert_called_once()
679
680 def test_resource_close_authorized_http(self):
681 discovery = read_datafile("plus.json")
682 with mock.patch("google_auth_httplib2.AuthorizedHttp", autospec=True):
683 plus = build_from_document(
684 discovery,
685 base="https://www.googleapis.com/",
686 credentials=self.MOCK_CREDENTIALS,
687 )
688 plus.close()
689 plus._http.close.assert_called_once()
690
691 def test_api_endpoint_override_from_client_options(self):
692 discovery = read_datafile("plus.json")
693 api_endpoint = "https://foo.googleapis.com/"
694 options = google.api_core.client_options.ClientOptions(
695 api_endpoint=api_endpoint
696 )
697 plus = build_from_document(
698 discovery, client_options=options, credentials=self.MOCK_CREDENTIALS
699 )
700
701 self.assertEqual(plus._baseUrl, api_endpoint)
702
703 def test_api_endpoint_override_from_client_options_mapping_object(self):
704 discovery = read_datafile("plus.json")
705 api_endpoint = "https://foo.googleapis.com/"
706 mapping_object = defaultdict(str)
707 mapping_object["api_endpoint"] = api_endpoint
708 plus = build_from_document(
709 discovery, client_options=mapping_object, credentials=self.MOCK_CREDENTIALS
710 )
711
712 self.assertEqual(plus._baseUrl, api_endpoint)
713
714 def test_api_endpoint_override_from_client_options_dict(self):
715 discovery = read_datafile("plus.json")
716 api_endpoint = "https://foo.googleapis.com/"
717 plus = build_from_document(
718 discovery,
719 client_options={"api_endpoint": api_endpoint},
720 credentials=self.MOCK_CREDENTIALS,
721 )
722
723 self.assertEqual(plus._baseUrl, api_endpoint)
724
725 def test_scopes_from_client_options(self):
726 discovery = read_datafile("plus.json")
727
728 with mock.patch("googleapiclient._auth.default_credentials") as default:
729 _reset_universe_domain(default.return_value)
730 plus = build_from_document(
731 discovery,
732 client_options={"scopes": ["1", "2"]},
733 )
734
735 default.assert_called_once_with(scopes=["1", "2"], quota_project_id=None)
736
737 def test_quota_project_from_client_options(self):
738 discovery = read_datafile("plus.json")
739
740 with mock.patch("googleapiclient._auth.default_credentials") as default:
741 _reset_universe_domain(default.return_value)
742 plus = build_from_document(
743 discovery,
744 client_options=google.api_core.client_options.ClientOptions(
745 quota_project_id="my-project"
746 ),
747 )
748
749 default.assert_called_once_with(scopes=None, quota_project_id="my-project")
750
751 def test_credentials_file_from_client_options(self):
752 discovery = read_datafile("plus.json")
753
754 with mock.patch("googleapiclient._auth.credentials_from_file") as default:
755 _reset_universe_domain(default.return_value)
756 plus = build_from_document(
757 discovery,
758 client_options=google.api_core.client_options.ClientOptions(
759 credentials_file="credentials.json"
760 ),
761 )
762
763 default.assert_called_once_with(
764 "credentials.json", scopes=None, quota_project_id=None
765 )
766
767 def test_self_signed_jwt_enabled(self):
768 service_account_file_path = os.path.join(DATA_DIR, "service_account.json")
769 creds = google.oauth2.service_account.Credentials.from_service_account_file(
770 service_account_file_path
771 )
772
773 discovery = read_datafile("logging.json")
774
775 with mock.patch(
776 "google.oauth2.service_account.Credentials._create_self_signed_jwt"
777 ) as _create_self_signed_jwt:
778 build_from_document(
779 discovery,
780 credentials=creds,
781 always_use_jwt_access=True,
782 )
783 _create_self_signed_jwt.assert_called_with(
784 "https://logging.googleapis.com/"
785 )
786
787 def test_self_signed_jwt_disabled(self):
788 service_account_file_path = os.path.join(DATA_DIR, "service_account.json")
789 creds = google.oauth2.service_account.Credentials.from_service_account_file(
790 service_account_file_path
791 )
792
793 discovery = read_datafile("logging.json")
794
795 with mock.patch(
796 "google.oauth2.service_account.Credentials._create_self_signed_jwt"
797 ) as _create_self_signed_jwt:
798 build_from_document(
799 discovery,
800 credentials=creds,
801 )
802 _create_self_signed_jwt.assert_not_called()
803
804
805 REGULAR_ENDPOINT = "https://www.googleapis.com/plus/v1/"
806 MTLS_ENDPOINT = "https://www.mtls.googleapis.com/plus/v1/"
807 CONFIG_DATA_WITH_WORKLOAD = {
808 "version": 1,
809 "cert_configs": {
810 "workload": {
811 "cert_path": "path/to/cert/file",
812 "key_path": "path/to/key/file",
813 }
814 },
815 }
816 CONFIG_DATA_WITHOUT_WORKLOAD = {
817 "version": 1,
818 "cert_configs": {},
819 }
820
821
822 class DiscoveryFromDocumentMutualTLS(unittest.TestCase):
823 MOCK_CREDENTIALS = mock.Mock(spec=google.auth.credentials.Credentials)
824 _reset_universe_domain(MOCK_CREDENTIALS)
825 ADC_CERT_PATH = "adc_cert_path"
826 ADC_KEY_PATH = "adc_key_path"
827 ADC_PASSPHRASE = "adc_passphrase"
828
829 def check_http_client_cert(self, resource, has_client_cert="false"):
830 if isinstance(resource._http, google_auth_httplib2.AuthorizedHttp):
831 certs = list(resource._http.http.certificates.iter(""))
832 else:
833 certs = list(resource._http.certificates.iter(""))
834 if has_client_cert == "true":
835 self.assertEqual(len(certs), 1)
836 self.assertEqual(
837 certs[0], (self.ADC_KEY_PATH, self.ADC_CERT_PATH, self.ADC_PASSPHRASE)
838 )
839 else:
840 self.assertEqual(len(certs), 0)
841
842 def client_encrypted_cert_source(self):
843 return self.ADC_CERT_PATH, self.ADC_KEY_PATH, self.ADC_PASSPHRASE
844
845 @parameterized.expand(
846 [
847 ("never", "true"),
848 ("auto", "true"),
849 ("always", "true"),
850 ("never", "false"),
851 ("auto", "false"),
852 ("always", "false"),
853 ]
854 )
855 def test_mtls_not_trigger_if_http_provided(self, use_mtls_env, use_client_cert):
856 discovery = read_datafile("plus.json")
857
858 with mock.patch.dict(
859 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
860 ):
861 with mock.patch.dict(
862 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
863 ):
864 plus = build_from_document(discovery, http=httplib2.Http())
865 self.assertIsNotNone(plus)
866 self.assertEqual(plus._baseUrl, REGULAR_ENDPOINT)
867 self.check_http_client_cert(plus, has_client_cert="false")
868
869 @parameterized.expand(
870 [
871 ("never", "true"),
872 ("auto", "true"),
873 ("always", "true"),
874 ("never", "false"),
875 ("auto", "false"),
876 ("always", "false"),
877 ]
878 )
879 def test_exception_with_client_cert_source(self, use_mtls_env, use_client_cert):
880 discovery = read_datafile("plus.json")
881 with mock.patch.dict(
882 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
883 ):
884 with mock.patch.dict(
885 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
886 ):
887 with self.assertRaises(MutualTLSChannelError):
888 build_from_document(
889 discovery,
890 credentials=self.MOCK_CREDENTIALS,
891 client_options={"client_cert_source": mock.Mock()},
892 )
893
894 @parameterized.expand(
895 [
896 ("never", "true", REGULAR_ENDPOINT),
897 ("auto", "true", MTLS_ENDPOINT),
898 ("always", "true", MTLS_ENDPOINT),
899 ("never", "false", REGULAR_ENDPOINT),
900 ("auto", "false", REGULAR_ENDPOINT),
901 ("always", "false", MTLS_ENDPOINT),
902 ]
903 )
904 def test_mtls_with_provided_client_cert(
905 self, use_mtls_env, use_client_cert, base_url
906 ):
907 discovery = read_datafile("plus.json")
908
909 with mock.patch.dict(
910 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
911 ):
912 with mock.patch.dict(
913 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
914 ):
915 plus = build_from_document(
916 discovery,
917 credentials=self.MOCK_CREDENTIALS,
918 client_options={
919 "client_encrypted_cert_source": self.client_encrypted_cert_source
920 },
921 )
922 self.assertIsNotNone(plus)
923 self.check_http_client_cert(plus, has_client_cert=use_client_cert)
924 self.assertEqual(plus._baseUrl, base_url)
925
926 @parameterized.expand(
927 [
928 ("never", "", CONFIG_DATA_WITH_WORKLOAD, REGULAR_ENDPOINT),
929 ("auto", "", CONFIG_DATA_WITH_WORKLOAD, MTLS_ENDPOINT),
930 ("always", "", CONFIG_DATA_WITH_WORKLOAD, MTLS_ENDPOINT),
931 ("never", "", CONFIG_DATA_WITHOUT_WORKLOAD, REGULAR_ENDPOINT),
932 ("auto", "", CONFIG_DATA_WITHOUT_WORKLOAD, REGULAR_ENDPOINT),
933 ("always", "", CONFIG_DATA_WITHOUT_WORKLOAD, MTLS_ENDPOINT),
934 ]
935 )
936 @pytest.mark.skipif(
937 parse_version_to_tuple(auth_version) < (2, 43, 0),
938 reason="automatic mtls enablement when supported certs present only"
939 "enabled in google-auth<=2.43.0",
940 )
941 def test_mtls_with_provided_client_cert_unset_environment_variable(
942 self, use_mtls_env, use_client_cert, config_data, base_url
943 ):
944 """Tests that mTLS is correctly handled when a client certificate is provided.
945
946 This test case verifies that when a client certificate is explicitly provided
947 via `client_options` and GOOGLE_API_USE_CLIENT_CERTIFICATE is unset, the
948 discovery document build process correctly configures the base URL for mTLS
949 or regular endpoints based on the `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable.
950 """
951 if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
952 discovery = read_datafile("plus.json")
953 config_filename = "mock_certificate_config.json"
954 config_file_content = json.dumps(config_data)
955 m = mock.mock_open(read_data=config_file_content)
956
957 with mock.patch.dict(
958 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
959 ):
960 with mock.patch.dict(
961 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
962 ):
963 with mock.patch("builtins.open", m):
964 with mock.patch.dict(
965 "os.environ",
966 {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename},
967 ):
968 plus = build_from_document(
969 discovery,
970 credentials=self.MOCK_CREDENTIALS,
971 client_options={
972 "client_encrypted_cert_source": self.client_encrypted_cert_source
973 },
974 )
975 self.assertIsNotNone(plus)
976 self.assertEqual(plus._baseUrl, base_url)
977
978 @parameterized.expand(
979 [
980 ("never", "true"),
981 ("auto", "true"),
982 ("always", "true"),
983 ("never", "false"),
984 ("auto", "false"),
985 ("always", "false"),
986 ]
987 )
988 def test_endpoint_not_switch(self, use_mtls_env, use_client_cert):
989 # Test endpoint is not switched if user provided api endpoint
990 discovery = read_datafile("plus.json")
991
992 with mock.patch.dict(
993 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
994 ):
995 with mock.patch.dict(
996 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
997 ):
998 plus = build_from_document(
999 discovery,
1000 credentials=self.MOCK_CREDENTIALS,
1001 client_options={
1002 "api_endpoint": "https://foo.googleapis.com",
1003 "client_encrypted_cert_source": self.client_encrypted_cert_source,
1004 },
1005 )
1006 self.assertIsNotNone(plus)
1007 self.check_http_client_cert(plus, has_client_cert=use_client_cert)
1008 self.assertEqual(plus._baseUrl, "https://foo.googleapis.com")
1009
1010 @parameterized.expand(
1011 [
1012 ("never", "true", REGULAR_ENDPOINT),
1013 ("auto", "true", MTLS_ENDPOINT),
1014 ("always", "true", MTLS_ENDPOINT),
1015 ("never", "false", REGULAR_ENDPOINT),
1016 ("auto", "false", REGULAR_ENDPOINT),
1017 ("always", "false", MTLS_ENDPOINT),
1018 ]
1019 )
1020 @mock.patch(
1021 "google.auth.transport.mtls.has_default_client_cert_source", autospec=True
1022 )
1023 @mock.patch(
1024 "google.auth.transport.mtls.default_client_encrypted_cert_source", autospec=True
1025 )
1026 def test_mtls_with_default_client_cert(
1027 self,
1028 use_mtls_env,
1029 use_client_cert,
1030 base_url,
1031 default_client_encrypted_cert_source,
1032 has_default_client_cert_source,
1033 ):
1034 has_default_client_cert_source.return_value = True
1035 default_client_encrypted_cert_source.return_value = (
1036 self.client_encrypted_cert_source
1037 )
1038 discovery = read_datafile("plus.json")
1039
1040 with mock.patch.dict(
1041 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
1042 ):
1043 with mock.patch.dict(
1044 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
1045 ):
1046 plus = build_from_document(
1047 discovery,
1048 credentials=self.MOCK_CREDENTIALS,
1049 adc_cert_path=self.ADC_CERT_PATH,
1050 adc_key_path=self.ADC_KEY_PATH,
1051 )
1052 self.assertIsNotNone(plus)
1053 self.check_http_client_cert(plus, has_client_cert=use_client_cert)
1054 self.assertEqual(plus._baseUrl, base_url)
1055
1056 @parameterized.expand(
1057 [
1058 ("never", "", CONFIG_DATA_WITH_WORKLOAD, REGULAR_ENDPOINT),
1059 ("auto", "", CONFIG_DATA_WITH_WORKLOAD, MTLS_ENDPOINT),
1060 ("always", "", CONFIG_DATA_WITH_WORKLOAD, MTLS_ENDPOINT),
1061 ("never", "", CONFIG_DATA_WITHOUT_WORKLOAD, REGULAR_ENDPOINT),
1062 ("auto", "", CONFIG_DATA_WITHOUT_WORKLOAD, REGULAR_ENDPOINT),
1063 ("always", "", CONFIG_DATA_WITHOUT_WORKLOAD, MTLS_ENDPOINT),
1064 ]
1065 )
1066 @mock.patch(
1067 "google.auth.transport.mtls.has_default_client_cert_source", autospec=True
1068 )
1069 @mock.patch(
1070 "google.auth.transport.mtls.default_client_encrypted_cert_source", autospec=True
1071 )
1072 @pytest.mark.skipif(
1073 parse_version_to_tuple(auth_version) < (2, 43, 0),
1074 reason="automatic mtls enablement when supported certs present only"
1075 "enabled in google-auth<=2.43.0",
1076 )
1077 def test_mtls_with_default_client_cert_with_unset_environment_variable(
1078 self,
1079 use_mtls_env,
1080 use_client_cert,
1081 config_data,
1082 base_url,
1083 default_client_encrypted_cert_source,
1084 has_default_client_cert_source,
1085 ):
1086 """Tests mTLS handling when falling back to a default client certificate.
1087
1088 This test simulates the scenario where no client certificate is explicitly
1089 provided, and the library successfully finds and uses a default client
1090 certificate when GOOGLE_API_USE_CLIENT_CERTIFICATE is unset. It mocks the
1091 default certificate discovery process and checks that the base URL is
1092 correctly set for mTLS or regular endpoints depending on the
1093 `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable.
1094 """
1095 if hasattr(google.auth.transport.mtls, "should_use_client_cert"):
1096 has_default_client_cert_source.return_value = True
1097 default_client_encrypted_cert_source.return_value = (
1098 self.client_encrypted_cert_source
1099 )
1100 discovery = read_datafile("plus.json")
1101 config_filename = "mock_certificate_config.json"
1102 config_file_content = json.dumps(config_data)
1103 m = mock.mock_open(read_data=config_file_content)
1104
1105 with mock.patch.dict(
1106 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
1107 ):
1108 with mock.patch.dict(
1109 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
1110 ):
1111 with mock.patch("builtins.open", m):
1112 with mock.patch.dict(
1113 "os.environ",
1114 {"GOOGLE_API_CERTIFICATE_CONFIG": config_filename},
1115 ):
1116 plus = build_from_document(
1117 discovery,
1118 credentials=self.MOCK_CREDENTIALS,
1119 adc_cert_path=self.ADC_CERT_PATH,
1120 adc_key_path=self.ADC_KEY_PATH,
1121 )
1122 self.assertIsNotNone(plus)
1123 self.assertEqual(plus._baseUrl, base_url)
1124
1125 @parameterized.expand(
1126 [
1127 ("never", "true", REGULAR_ENDPOINT),
1128 ("auto", "true", REGULAR_ENDPOINT),
1129 ("always", "true", MTLS_ENDPOINT),
1130 ("never", "false", REGULAR_ENDPOINT),
1131 ("auto", "false", REGULAR_ENDPOINT),
1132 ("always", "false", MTLS_ENDPOINT),
1133 ]
1134 )
1135 @mock.patch(
1136 "google.auth.transport.mtls.has_default_client_cert_source", autospec=True
1137 )
1138 def test_mtls_with_no_client_cert(
1139 self, use_mtls_env, use_client_cert, base_url, has_default_client_cert_source
1140 ):
1141 has_default_client_cert_source.return_value = False
1142 discovery = read_datafile("plus.json")
1143
1144 with mock.patch.dict(
1145 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": use_mtls_env}
1146 ):
1147 with mock.patch.dict(
1148 "os.environ", {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert}
1149 ):
1150 plus = build_from_document(
1151 discovery,
1152 credentials=self.MOCK_CREDENTIALS,
1153 adc_cert_path=self.ADC_CERT_PATH,
1154 adc_key_path=self.ADC_KEY_PATH,
1155 )
1156 self.assertIsNotNone(plus)
1157 self.check_http_client_cert(plus, has_client_cert="false")
1158 self.assertEqual(plus._baseUrl, base_url)
1159
1160
1161 class DiscoveryFromHttp(unittest.TestCase):
1162 def setUp(self):
1163 self.old_environ = os.environ.copy()
1164
1165 def tearDown(self):
1166 os.environ = self.old_environ
1167
1168 def test_userip_is_added_to_discovery_uri(self):
1169 # build() will raise an HttpError on a 400, use this to pick the request uri
1170 # out of the raised exception.
1171 os.environ["REMOTE_ADDR"] = "10.0.0.1"
1172 try:
1173 http = HttpMockSequence(
1174 [({"status": "400"}, read_datafile("zoo.json", "rb"))]
1175 )
1176 zoo = build(
1177 "zoo",
1178 "v1",
1179 http=http,
1180 developerKey=None,
1181 discoveryServiceUrl="http://example.com",
1182 )
1183 self.fail("Should have raised an exception.")
1184 except HttpError as e:
1185 self.assertEqual(e.uri, "http://example.com?userIp=10.0.0.1")
1186
1187 def test_userip_missing_is_not_added_to_discovery_uri(self):
1188 # build() will raise an HttpError on a 400, use this to pick the request uri
1189 # out of the raised exception.
1190 try:
1191 http = HttpMockSequence(
1192 [({"status": "400"}, read_datafile("zoo.json", "rb"))]
1193 )
1194 zoo = build(
1195 "zoo",
1196 "v1",
1197 http=http,
1198 developerKey=None,
1199 discoveryServiceUrl="http://example.com",
1200 )
1201 self.fail("Should have raised an exception.")
1202 except HttpError as e:
1203 self.assertEqual(e.uri, "http://example.com")
1204
1205 def test_key_is_added_to_discovery_uri(self):
1206 # build() will raise an HttpError on a 400, use this to pick the request uri
1207 # out of the raised exception.
1208 try:
1209 http = HttpMockSequence(
1210 [({"status": "400"}, read_datafile("zoo.json", "rb"))]
1211 )
1212 zoo = build(
1213 "zoo",
1214 "v1",
1215 http=http,
1216 developerKey="foo",
1217 discoveryServiceUrl="http://example.com",
1218 static_discovery=False,
1219 )
1220 self.fail("Should have raised an exception.")
1221 except HttpError as e:
1222 self.assertEqual(e.uri, "http://example.com?key=foo")
1223
1224 def test_discovery_loading_from_v2_discovery_uri(self):
1225 http = HttpMockSequence(
1226 [
1227 ({"status": "404"}, "Not found"),
1228 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1229 ]
1230 )
1231 zoo = build(
1232 "zoo", "v1", http=http, cache_discovery=False, static_discovery=False
1233 )
1234 self.assertTrue(hasattr(zoo, "animals"))
1235
1236 def test_api_endpoint_override_from_client_options(self):
1237 http = HttpMockSequence(
1238 [
1239 ({"status": "404"}, "Not found"),
1240 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1241 ]
1242 )
1243 api_endpoint = "https://foo.googleapis.com/"
1244 options = google.api_core.client_options.ClientOptions(
1245 api_endpoint=api_endpoint
1246 )
1247 zoo = build(
1248 "zoo",
1249 "v1",
1250 http=http,
1251 cache_discovery=False,
1252 client_options=options,
1253 static_discovery=False,
1254 )
1255 self.assertEqual(zoo._baseUrl, api_endpoint)
1256
1257 def test_api_endpoint_override_from_client_options_dict(self):
1258 http = HttpMockSequence(
1259 [
1260 ({"status": "404"}, "Not found"),
1261 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1262 ]
1263 )
1264 api_endpoint = "https://foo.googleapis.com/"
1265 zoo = build(
1266 "zoo",
1267 "v1",
1268 http=http,
1269 cache_discovery=False,
1270 client_options={"api_endpoint": api_endpoint},
1271 static_discovery=False,
1272 )
1273 self.assertEqual(zoo._baseUrl, api_endpoint)
1274
1275 def test_discovery_with_empty_version_uses_v2(self):
1276 http = HttpMockSequence(
1277 [
1278 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1279 ]
1280 )
1281 build(
1282 "zoo",
1283 version=None,
1284 http=http,
1285 cache_discovery=False,
1286 static_discovery=False,
1287 )
1288 validate_discovery_requests(self, http, "zoo", None, V2_DISCOVERY_URI)
1289
1290 def test_discovery_with_empty_version_preserves_custom_uri(self):
1291 http = HttpMockSequence(
1292 [
1293 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1294 ]
1295 )
1296 custom_discovery_uri = "https://foo.bar/$discovery"
1297 build(
1298 "zoo",
1299 version=None,
1300 http=http,
1301 cache_discovery=False,
1302 discoveryServiceUrl=custom_discovery_uri,
1303 static_discovery=False,
1304 )
1305 validate_discovery_requests(self, http, "zoo", None, custom_discovery_uri)
1306
1307 def test_discovery_with_valid_version_uses_v1(self):
1308 http = HttpMockSequence(
1309 [
1310 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1311 ]
1312 )
1313 build(
1314 "zoo",
1315 version="v123",
1316 http=http,
1317 cache_discovery=False,
1318 static_discovery=False,
1319 )
1320 validate_discovery_requests(self, http, "zoo", "v123", V1_DISCOVERY_URI)
1321
1322
1323 class DiscoveryRetryFromHttp(unittest.TestCase):
1324 def test_repeated_500_retries_and_fails(self):
1325 http = HttpMockSequence(
1326 [
1327 ({"status": "500"}, read_datafile("500.json", "rb")),
1328 ({"status": "503"}, read_datafile("503.json", "rb")),
1329 ]
1330 )
1331 with self.assertRaises(HttpError):
1332 with mock.patch("time.sleep") as mocked_sleep:
1333 build(
1334 "zoo",
1335 "v1",
1336 http=http,
1337 cache_discovery=False,
1338 static_discovery=False,
1339 )
1340
1341 mocked_sleep.assert_called_once()
1342 # We also want to verify that we stayed with v1 discovery
1343 validate_discovery_requests(self, http, "zoo", "v1", V1_DISCOVERY_URI)
1344
1345 def test_v2_repeated_500_retries_and_fails(self):
1346 http = HttpMockSequence(
1347 [
1348 ({"status": "404"}, "Not found"), # last v1 discovery call
1349 ({"status": "500"}, read_datafile("500.json", "rb")),
1350 ({"status": "503"}, read_datafile("503.json", "rb")),
1351 ]
1352 )
1353 with self.assertRaises(HttpError):
1354 with mock.patch("time.sleep") as mocked_sleep:
1355 build(
1356 "zoo",
1357 "v1",
1358 http=http,
1359 cache_discovery=False,
1360 static_discovery=False,
1361 )
1362
1363 mocked_sleep.assert_called_once()
1364 # We also want to verify that we switched to v2 discovery
1365 validate_discovery_requests(self, http, "zoo", "v1", V2_DISCOVERY_URI)
1366
1367 def test_single_500_retries_and_succeeds(self):
1368 http = HttpMockSequence(
1369 [
1370 ({"status": "500"}, read_datafile("500.json", "rb")),
1371 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1372 ]
1373 )
1374 with mock.patch("time.sleep") as mocked_sleep:
1375 zoo = build(
1376 "zoo", "v1", http=http, cache_discovery=False, static_discovery=False
1377 )
1378
1379 self.assertTrue(hasattr(zoo, "animals"))
1380 mocked_sleep.assert_called_once()
1381 # We also want to verify that we stayed with v1 discovery
1382 validate_discovery_requests(self, http, "zoo", "v1", V1_DISCOVERY_URI)
1383
1384 def test_single_500_then_404_retries_and_succeeds(self):
1385 http = HttpMockSequence(
1386 [
1387 ({"status": "500"}, read_datafile("500.json", "rb")),
1388 ({"status": "404"}, "Not found"), # last v1 discovery call
1389 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1390 ]
1391 )
1392 with mock.patch("time.sleep") as mocked_sleep:
1393 zoo = build(
1394 "zoo", "v1", http=http, cache_discovery=False, static_discovery=False
1395 )
1396
1397 self.assertTrue(hasattr(zoo, "animals"))
1398 mocked_sleep.assert_called_once()
1399 # We also want to verify that we switched to v2 discovery
1400 validate_discovery_requests(self, http, "zoo", "v1", V2_DISCOVERY_URI)
1401
1402
1403 class DiscoveryFromAppEngineCache(unittest.TestCase):
1404 def setUp(self):
1405 self.old_environ = os.environ.copy()
1406 os.environ["GAE_ENV"] = "standard"
1407
1408 def tearDown(self):
1409 os.environ = self.old_environ
1410
1411 def test_appengine_memcache(self):
1412 # Hack module import
1413 self.orig_import = __import__
1414 self.mocked_api = mock.MagicMock()
1415
1416 def import_mock(name, *args, **kwargs):
1417 if name == "google.appengine.api":
1418 return self.mocked_api
1419 return self.orig_import(name, *args, **kwargs)
1420
1421 import_fullname = "__builtin__.__import__"
1422 if sys.version_info[0] >= 3:
1423 import_fullname = "builtins.__import__"
1424
1425 with mock.patch(import_fullname, side_effect=import_mock):
1426 namespace = "google-api-client"
1427 self.http = HttpMock(datafile("plus.json"), {"status": "200"})
1428
1429 self.mocked_api.memcache.get.return_value = None
1430
1431 plus = build("plus", "v1", http=self.http, static_discovery=False)
1432
1433 # memcache.get is called once
1434 url = "https://www.googleapis.com/discovery/v1/apis/plus/v1/rest"
1435 self.mocked_api.memcache.get.assert_called_once_with(
1436 url, namespace=namespace
1437 )
1438
1439 # memcache.set is called once
1440 content = read_datafile("plus.json")
1441 self.mocked_api.memcache.set.assert_called_once_with(
1442 url, content, time=DISCOVERY_DOC_MAX_AGE, namespace=namespace
1443 )
1444
1445 # Returns the cached content this time.
1446 self.mocked_api.memcache.get.return_value = content
1447
1448 # Make sure the contents are returned from the cache.
1449 # (Otherwise it should through an error)
1450 self.http = HttpMock(None, {"status": "200"})
1451
1452 plus = build("plus", "v1", http=self.http, static_discovery=False)
1453
1454 # memcache.get is called twice
1455 self.mocked_api.memcache.get.assert_has_calls(
1456 [
1457 mock.call(url, namespace=namespace),
1458 mock.call(url, namespace=namespace),
1459 ]
1460 )
1461
1462 # memcahce.set is called just once
1463 self.mocked_api.memcache.set.assert_called_once_with(
1464 url, content, time=DISCOVERY_DOC_MAX_AGE, namespace=namespace
1465 )
1466
1467
1468 class DiscoveryFromStaticDocument(unittest.TestCase):
1469 def test_retrieve_from_local_when_static_discovery_true(self):
1470 http = HttpMockSequence([({"status": "400"}, "")])
1471 drive = build(
1472 "drive", "v3", http=http, cache_discovery=False, static_discovery=True
1473 )
1474 self.assertIsNotNone(drive)
1475 self.assertTrue(hasattr(drive, "files"))
1476
1477 def test_retrieve_from_internet_when_static_discovery_false(self):
1478 http = HttpMockSequence([({"status": "400"}, "")])
1479 with self.assertRaises(HttpError):
1480 build(
1481 "drive", "v3", http=http, cache_discovery=False, static_discovery=False
1482 )
1483
1484 def test_unknown_api_when_static_discovery_true(self):
1485 with self.assertRaises(UnknownApiNameOrVersion):
1486 build("doesnotexist", "v3", cache_discovery=False, static_discovery=True)
1487
1488
1489 class DictCache(Cache):
1490 def __init__(self):
1491 self.d = {}
1492
1493 def get(self, url):
1494 return self.d.get(url, None)
1495
1496 def set(self, url, content):
1497 self.d[url] = content
1498
1499 def contains(self, url):
1500 return url in self.d
1501
1502
1503 class DiscoveryFromFileCache(unittest.TestCase):
1504 def test_file_based_cache(self):
1505 cache = mock.Mock(wraps=DictCache())
1506 with mock.patch(
1507 "googleapiclient.discovery_cache.autodetect", return_value=cache
1508 ):
1509 self.http = HttpMock(datafile("plus.json"), {"status": "200"})
1510
1511 plus = build("plus", "v1", http=self.http, static_discovery=False)
1512
1513 # cache.get is called once
1514 url = "https://www.googleapis.com/discovery/v1/apis/plus/v1/rest"
1515 cache.get.assert_called_once_with(url)
1516
1517 # cache.set is called once
1518 content = read_datafile("plus.json")
1519 cache.set.assert_called_once_with(url, content)
1520
1521 # Make sure there is a cache entry for the plus v1 discovery doc.
1522 self.assertTrue(cache.contains(url))
1523
1524 # Make sure the contents are returned from the cache.
1525 # (Otherwise it should through an error)
1526 self.http = HttpMock(None, {"status": "200"})
1527
1528 plus = build("plus", "v1", http=self.http, static_discovery=False)
1529
1530 # cache.get is called twice
1531 cache.get.assert_has_calls([mock.call(url), mock.call(url)])
1532
1533 # cahce.set is called just once
1534 cache.set.assert_called_once_with(url, content)
1535
1536
1537 class Discovery(unittest.TestCase):
1538 def test_method_error_checking(self):
1539 self.http = HttpMock(datafile("plus.json"), {"status": "200"})
1540 plus = build("plus", "v1", http=self.http, static_discovery=False)
1541
1542 # Missing required parameters
1543 try:
1544 plus.activities().list()
1545 self.fail()
1546 except TypeError as e:
1547 self.assertTrue("Missing" in str(e))
1548
1549 # Missing required parameters even if supplied as None.
1550 try:
1551 plus.activities().list(collection=None, userId=None)
1552 self.fail()
1553 except TypeError as e:
1554 self.assertTrue("Missing" in str(e))
1555
1556 # Parameter doesn't match regex
1557 try:
1558 plus.activities().list(collection="not_a_collection_name", userId="me")
1559 self.fail()
1560 except TypeError as e:
1561 self.assertTrue("not an allowed value" in str(e))
1562
1563 # Unexpected parameter
1564 try:
1565 plus.activities().list(flubber=12)
1566 self.fail()
1567 except TypeError as e:
1568 self.assertTrue("unexpected" in str(e))
1569
1570 def _check_query_types(self, request):
1571 parsed = urllib.parse.urlparse(request.uri)
1572 q = urllib.parse.parse_qs(parsed.query)
1573 self.assertEqual(q["q"], ["foo"])
1574 self.assertEqual(q["i"], ["1"])
1575 self.assertEqual(q["n"], ["1.0"])
1576 self.assertEqual(q["b"], ["false"])
1577 self.assertEqual(q["a"], ["[1, 2, 3]"])
1578 self.assertEqual(q["o"], ["{'a': 1}"])
1579 self.assertEqual(q["e"], ["bar"])
1580
1581 def test_type_coercion(self):
1582 http = HttpMock(datafile("zoo.json"), {"status": "200"})
1583 zoo = build("zoo", "v1", http=http, static_discovery=False)
1584
1585 request = zoo.query(
1586 q="foo", i=1.0, n=1.0, b=0, a=[1, 2, 3], o={"a": 1}, e="bar"
1587 )
1588 self._check_query_types(request)
1589 request = zoo.query(
1590 q="foo", i=1, n=1, b=False, a=[1, 2, 3], o={"a": 1}, e="bar"
1591 )
1592 self._check_query_types(request)
1593
1594 request = zoo.query(
1595 q="foo", i="1", n="1", b="", a=[1, 2, 3], o={"a": 1}, e="bar", er="two"
1596 )
1597
1598 request = zoo.query(
1599 q="foo",
1600 i="1",
1601 n="1",
1602 b="",
1603 a=[1, 2, 3],
1604 o={"a": 1},
1605 e="bar",
1606 er=["one", "three"],
1607 rr=["foo", "bar"],
1608 )
1609 self._check_query_types(request)
1610
1611 # Five is right out.
1612 self.assertRaises(TypeError, zoo.query, er=["one", "five"])
1613
1614 def test_optional_stack_query_parameters(self):
1615 http = HttpMock(datafile("zoo.json"), {"status": "200"})
1616 zoo = build("zoo", "v1", http=http, static_discovery=False)
1617 request = zoo.query(trace="html", fields="description")
1618
1619 parsed = urllib.parse.urlparse(request.uri)
1620 q = urllib.parse.parse_qs(parsed.query)
1621 self.assertEqual(q["trace"], ["html"])
1622 self.assertEqual(q["fields"], ["description"])
1623
1624 def test_string_params_value_of_none_get_dropped(self):
1625 http = HttpMock(datafile("zoo.json"), {"status": "200"})
1626 zoo = build("zoo", "v1", http=http, static_discovery=False)
1627 request = zoo.query(trace=None, fields="description")
1628
1629 parsed = urllib.parse.urlparse(request.uri)
1630 q = urllib.parse.parse_qs(parsed.query)
1631 self.assertFalse("trace" in q)
1632
1633 def test_model_added_query_parameters(self):
1634 http = HttpMock(datafile("zoo.json"), {"status": "200"})
1635 zoo = build("zoo", "v1", http=http, static_discovery=False)
1636 request = zoo.animals().get(name="Lion")
1637
1638 parsed = urllib.parse.urlparse(request.uri)
1639 q = urllib.parse.parse_qs(parsed.query)
1640 self.assertEqual(q["alt"], ["json"])
1641 self.assertEqual(request.headers["accept"], "application/json")
1642
1643 def test_fallback_to_raw_model(self):
1644 http = HttpMock(datafile("zoo.json"), {"status": "200"})
1645 zoo = build("zoo", "v1", http=http, static_discovery=False)
1646 request = zoo.animals().getmedia(name="Lion")
1647
1648 parsed = urllib.parse.urlparse(request.uri)
1649 q = urllib.parse.parse_qs(parsed.query)
1650 self.assertTrue("alt" not in q)
1651 self.assertEqual(request.headers["accept"], "*/*")
1652
1653 def test_patch(self):
1654 http = HttpMock(datafile("zoo.json"), {"status": "200"})
1655 zoo = build("zoo", "v1", http=http, static_discovery=False)
1656 request = zoo.animals().patch(name="lion", body='{"description": "foo"}')
1657
1658 self.assertEqual(request.method, "PATCH")
1659
1660 def test_batch_request_from_discovery(self):
1661 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1662 # zoo defines a batchPath
1663 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1664 batch_request = zoo.new_batch_http_request()
1665 self.assertEqual(
1666 batch_request._batch_uri, "https://www.googleapis.com/batchZoo"
1667 )
1668
1669 def test_batch_request_from_default(self):
1670 self.http = HttpMock(datafile("plus.json"), {"status": "200"})
1671 # plus does not define a batchPath
1672 plus = build(
1673 "plus", "v1", http=self.http, cache_discovery=False, static_discovery=False
1674 )
1675 batch_request = plus.new_batch_http_request()
1676 self.assertEqual(batch_request._batch_uri, "https://www.googleapis.com/batch")
1677
1678 def test_tunnel_patch(self):
1679 http = HttpMockSequence(
1680 [
1681 ({"status": "200"}, read_datafile("zoo.json", "rb")),
1682 ({"status": "200"}, "echo_request_headers_as_json"),
1683 ]
1684 )
1685 http = tunnel_patch(http)
1686 zoo = build(
1687 "zoo", "v1", http=http, cache_discovery=False, static_discovery=False
1688 )
1689 resp = zoo.animals().patch(name="lion", body='{"description": "foo"}').execute()
1690
1691 self.assertTrue("x-http-method-override" in resp)
1692
1693 def test_plus_resources(self):
1694 self.http = HttpMock(datafile("plus.json"), {"status": "200"})
1695 plus = build("plus", "v1", http=self.http, static_discovery=False)
1696 self.assertTrue(getattr(plus, "activities"))
1697 self.assertTrue(getattr(plus, "people"))
1698
1699 @unittest.skipIf(not HAS_OAUTH2CLIENT, "oauth2client unavailable.")
1700 def test_oauth2client_credentials(self):
1701 credentials = mock.Mock(spec=GoogleCredentials)
1702 _reset_universe_domain(credentials)
1703 credentials.create_scoped_required.return_value = False
1704
1705 discovery = read_datafile("plus.json")
1706 service = build_from_document(discovery, credentials=credentials)
1707 self.assertEqual(service._http, credentials.authorize.return_value)
1708
1709 def test_google_auth_credentials(self):
1710 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
1711 _reset_universe_domain(credentials)
1712 discovery = read_datafile("plus.json")
1713 service = build_from_document(discovery, credentials=credentials)
1714
1715 self.assertIsInstance(service._http, google_auth_httplib2.AuthorizedHttp)
1716 self.assertEqual(service._http.credentials, credentials)
1717
1718 def test_no_scopes_no_credentials(self):
1719 # Zoo doesn't have scopes
1720 discovery = read_datafile("zoo.json")
1721 service = build_from_document(discovery)
1722 # Should be an ordinary httplib2.Http instance and not AuthorizedHttp.
1723 self.assertIsInstance(service._http, httplib2.Http)
1724
1725 def test_full_featured(self):
1726 # Zoo should exercise all discovery facets
1727 # and should also have no future.json file.
1728 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1729 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1730 self.assertTrue(getattr(zoo, "animals"))
1731
1732 request = zoo.animals().list(name="bat", projection="full")
1733 parsed = urllib.parse.urlparse(request.uri)
1734 q = urllib.parse.parse_qs(parsed.query)
1735 self.assertEqual(q["name"], ["bat"])
1736 self.assertEqual(q["projection"], ["full"])
1737
1738 def test_nested_resources(self):
1739 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1740 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1741 self.assertTrue(getattr(zoo, "animals"))
1742 request = zoo.my().favorites().list(max_results="5")
1743 parsed = urllib.parse.urlparse(request.uri)
1744 q = urllib.parse.parse_qs(parsed.query)
1745 self.assertEqual(q["max-results"], ["5"])
1746
1747 def test_top_level_functions(self):
1748 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1749 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1750 self.assertTrue(getattr(zoo, "query"))
1751 request = zoo.query(q="foo")
1752 parsed = urllib.parse.urlparse(request.uri)
1753 q = urllib.parse.parse_qs(parsed.query)
1754 self.assertEqual(q["q"], ["foo"])
1755
1756 def test_simple_media_uploads(self):
1757 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1758 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1759 doc = getattr(zoo.animals().insert, "__doc__")
1760 self.assertTrue("media_body" in doc)
1761
1762 def test_simple_media_upload_no_max_size_provided(self):
1763 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1764 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1765 request = zoo.animals().crossbreed(media_body=datafile("small.png"))
1766 self.assertEqual("image/png", request.headers["content-type"])
1767 self.assertEqual(b"PNG", request.body[1:4])
1768
1769 def test_simple_media_raise_correct_exceptions(self):
1770 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1771 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1772
1773 try:
1774 zoo.animals().insert(media_body=datafile("smiley.png"))
1775 self.fail("should throw exception if media is too large.")
1776 except MediaUploadSizeError:
1777 pass
1778
1779 try:
1780 zoo.animals().insert(media_body=datafile("small.jpg"))
1781 self.fail("should throw exception if mimetype is unacceptable.")
1782 except UnacceptableMimeTypeError:
1783 pass
1784
1785 def test_simple_media_good_upload(self):
1786 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1787 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1788
1789 request = zoo.animals().insert(media_body=datafile("small.png"))
1790 self.assertEqual("image/png", request.headers["content-type"])
1791 self.assertEqual(b"PNG", request.body[1:4])
1792 assertUrisEqual(
1793 self,
1794 "https://www.googleapis.com/upload/zoo/v1/animals?uploadType=media&alt=json",
1795 request.uri,
1796 )
1797
1798 def test_simple_media_unknown_mimetype(self):
1799 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1800 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1801
1802 try:
1803 zoo.animals().insert(media_body=datafile("small-png"))
1804 self.fail("should throw exception if mimetype is unknown.")
1805 except UnknownFileType:
1806 pass
1807
1808 request = zoo.animals().insert(
1809 media_body=datafile("small-png"), media_mime_type="image/png"
1810 )
1811 self.assertEqual("image/png", request.headers["content-type"])
1812 self.assertEqual(b"PNG", request.body[1:4])
1813 assertUrisEqual(
1814 self,
1815 "https://www.googleapis.com/upload/zoo/v1/animals?uploadType=media&alt=json",
1816 request.uri,
1817 )
1818
1819 def test_multipart_media_raise_correct_exceptions(self):
1820 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1821 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1822
1823 try:
1824 zoo.animals().insert(media_body=datafile("smiley.png"), body={})
1825 self.fail("should throw exception if media is too large.")
1826 except MediaUploadSizeError:
1827 pass
1828
1829 try:
1830 zoo.animals().insert(media_body=datafile("small.jpg"), body={})
1831 self.fail("should throw exception if mimetype is unacceptable.")
1832 except UnacceptableMimeTypeError:
1833 pass
1834
1835 def test_multipart_media_good_upload(self, static_discovery=False):
1836 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1837 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1838
1839 request = zoo.animals().insert(media_body=datafile("small.png"), body={})
1840 self.assertTrue(request.headers["content-type"].startswith("multipart/related"))
1841 contents = read_datafile("small.png", "rb")
1842 boundary = re.match(b"--=+([^=]+)", request.body).group(1)
1843 self.assertEqual(
1844 request.body.rstrip(b"\n"), # Python 2.6 does not add a trailing \n
1845 b"--==============="
1846 + boundary
1847 + b"==\n"
1848 + b"Content-Type: application/json\n"
1849 + b"MIME-Version: 1.0\n\n"
1850 + b'{"data": {}}\n'
1851 + b"--==============="
1852 + boundary
1853 + b"==\n"
1854 + b"Content-Type: image/png\n"
1855 + b"MIME-Version: 1.0\n"
1856 + b"Content-Transfer-Encoding: binary\n\n"
1857 + contents
1858 + b"\n--==============="
1859 + boundary
1860 + b"==--",
1861 )
1862 assertUrisEqual(
1863 self,
1864 "https://www.googleapis.com/upload/zoo/v1/animals?uploadType=multipart&alt=json",
1865 request.uri,
1866 )
1867
1868 def test_media_capable_method_without_media(self):
1869 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1870 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1871
1872 request = zoo.animals().insert(body={})
1873 self.assertTrue(request.headers["content-type"], "application/json")
1874
1875 def test_resumable_multipart_media_good_upload(self):
1876 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1877 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1878
1879 media_upload = MediaFileUpload(datafile("small.png"), resumable=True)
1880 request = zoo.animals().insert(media_body=media_upload, body={})
1881 self.assertTrue(request.headers["content-type"].startswith("application/json"))
1882 self.assertEqual('{"data": {}}', request.body)
1883 self.assertEqual(media_upload, request.resumable)
1884
1885 self.assertEqual("image/png", request.resumable.mimetype())
1886
1887 self.assertNotEqual(request.body, None)
1888 self.assertEqual(request.resumable_uri, None)
1889
1890 http = HttpMockSequence(
1891 [
1892 ({"status": "200", "location": "http://upload.example.com"}, ""),
1893 ({"status": "308", "location": "http://upload.example.com/2"}, ""),
1894 (
1895 {
1896 "status": "308",
1897 "location": "http://upload.example.com/3",
1898 "range": "0-12",
1899 },
1900 "",
1901 ),
1902 (
1903 {
1904 "status": "308",
1905 "location": "http://upload.example.com/4",
1906 "range": "0-%d" % (media_upload.size() - 2),
1907 },
1908 "",
1909 ),
1910 ({"status": "200"}, '{"foo": "bar"}'),
1911 ]
1912 )
1913
1914 status, body = request.next_chunk(http=http)
1915 self.assertEqual(None, body)
1916 self.assertTrue(isinstance(status, MediaUploadProgress))
1917 self.assertEqual(0, status.resumable_progress)
1918
1919 # Two requests should have been made and the resumable_uri should have been
1920 # updated for each one.
1921 self.assertEqual(request.resumable_uri, "http://upload.example.com/2")
1922 self.assertEqual(media_upload, request.resumable)
1923 self.assertEqual(0, request.resumable_progress)
1924
1925 # This next chuck call should upload the first chunk
1926 status, body = request.next_chunk(http=http)
1927 self.assertEqual(request.resumable_uri, "http://upload.example.com/3")
1928 self.assertEqual(media_upload, request.resumable)
1929 self.assertEqual(13, request.resumable_progress)
1930
1931 # This call will upload the next chunk
1932 status, body = request.next_chunk(http=http)
1933 self.assertEqual(request.resumable_uri, "http://upload.example.com/4")
1934 self.assertEqual(media_upload.size() - 1, request.resumable_progress)
1935 self.assertEqual('{"data": {}}', request.body)
1936
1937 # Final call to next_chunk should complete the upload.
1938 status, body = request.next_chunk(http=http)
1939 self.assertEqual(body, {"foo": "bar"})
1940 self.assertEqual(status, None)
1941
1942 def test_resumable_media_good_upload(self):
1943 """Not a multipart upload."""
1944 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
1945 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
1946
1947 media_upload = MediaFileUpload(datafile("small.png"), resumable=True)
1948 request = zoo.animals().insert(media_body=media_upload, body=None)
1949 self.assertEqual(media_upload, request.resumable)
1950
1951 self.assertEqual("image/png", request.resumable.mimetype())
1952
1953 self.assertEqual(request.body, None)
1954 self.assertEqual(request.resumable_uri, None)
1955
1956 http = HttpMockSequence(
1957 [
1958 ({"status": "200", "location": "http://upload.example.com"}, ""),
1959 (
1960 {
1961 "status": "308",
1962 "location": "http://upload.example.com/2",
1963 "range": "0-12",
1964 },
1965 "",
1966 ),
1967 (
1968 {
1969 "status": "308",
1970 "location": "http://upload.example.com/3",
1971 "range": "0-%d" % (media_upload.size() - 2),
1972 },
1973 "",
1974 ),
1975 ({"status": "200"}, '{"foo": "bar"}'),
1976 ]
1977 )
1978
1979 status, body = request.next_chunk(http=http)
1980 self.assertEqual(None, body)
1981 self.assertTrue(isinstance(status, MediaUploadProgress))
1982 self.assertEqual(13, status.resumable_progress)
1983
1984 # Two requests should have been made and the resumable_uri should have been
1985 # updated for each one.
1986 self.assertEqual(request.resumable_uri, "http://upload.example.com/2")
1987
1988 self.assertEqual(media_upload, request.resumable)
1989 self.assertEqual(13, request.resumable_progress)
1990
1991 status, body = request.next_chunk(http=http)
1992 self.assertEqual(request.resumable_uri, "http://upload.example.com/3")
1993 self.assertEqual(media_upload.size() - 1, request.resumable_progress)
1994 self.assertEqual(request.body, None)
1995
1996 # Final call to next_chunk should complete the upload.
1997 status, body = request.next_chunk(http=http)
1998 self.assertEqual(body, {"foo": "bar"})
1999 self.assertEqual(status, None)
2000
2001 def test_resumable_media_good_upload_from_execute(self):
2002 """Not a multipart upload."""
2003 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2004 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2005
2006 media_upload = MediaFileUpload(datafile("small.png"), resumable=True)
2007 request = zoo.animals().insert(media_body=media_upload, body=None)
2008 assertUrisEqual(
2009 self,
2010 "https://www.googleapis.com/upload/zoo/v1/animals?uploadType=resumable&alt=json",
2011 request.uri,
2012 )
2013
2014 http = HttpMockSequence(
2015 [
2016 ({"status": "200", "location": "http://upload.example.com"}, ""),
2017 (
2018 {
2019 "status": "308",
2020 "location": "http://upload.example.com/2",
2021 "range": "0-12",
2022 },
2023 "",
2024 ),
2025 (
2026 {
2027 "status": "308",
2028 "location": "http://upload.example.com/3",
2029 "range": "0-%d" % media_upload.size(),
2030 },
2031 "",
2032 ),
2033 ({"status": "200"}, '{"foo": "bar"}'),
2034 ]
2035 )
2036
2037 body = request.execute(http=http)
2038 self.assertEqual(body, {"foo": "bar"})
2039
2040 def test_resumable_media_fail_unknown_response_code_first_request(self):
2041 """Not a multipart upload."""
2042 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2043 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2044
2045 media_upload = MediaFileUpload(datafile("small.png"), resumable=True)
2046 request = zoo.animals().insert(media_body=media_upload, body=None)
2047
2048 http = HttpMockSequence(
2049 [({"status": "400", "location": "http://upload.example.com"}, "")]
2050 )
2051
2052 try:
2053 request.execute(http=http)
2054 self.fail("Should have raised ResumableUploadError.")
2055 except ResumableUploadError as e:
2056 self.assertEqual(400, e.resp.status)
2057
2058 def test_resumable_media_fail_unknown_response_code_subsequent_request(self):
2059 """Not a multipart upload."""
2060 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2061 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2062
2063 media_upload = MediaFileUpload(datafile("small.png"), resumable=True)
2064 request = zoo.animals().insert(media_body=media_upload, body=None)
2065
2066 http = HttpMockSequence(
2067 [
2068 ({"status": "200", "location": "http://upload.example.com"}, ""),
2069 ({"status": "400"}, ""),
2070 ]
2071 )
2072
2073 self.assertRaises(HttpError, request.execute, http=http)
2074 self.assertTrue(request._in_error_state)
2075
2076 http = HttpMockSequence(
2077 [
2078 ({"status": "308", "range": "0-5"}, ""),
2079 ({"status": "308", "range": "0-6"}, ""),
2080 ]
2081 )
2082
2083 status, body = request.next_chunk(http=http)
2084 self.assertEqual(
2085 status.resumable_progress,
2086 7,
2087 "Should have first checked length and then tried to PUT more.",
2088 )
2089 self.assertFalse(request._in_error_state)
2090
2091 # Put it back in an error state.
2092 http = HttpMockSequence([({"status": "400"}, "")])
2093 self.assertRaises(HttpError, request.execute, http=http)
2094 self.assertTrue(request._in_error_state)
2095
2096 # Pretend the last request that 400'd actually succeeded.
2097 http = HttpMockSequence([({"status": "200"}, '{"foo": "bar"}')])
2098 status, body = request.next_chunk(http=http)
2099 self.assertEqual(body, {"foo": "bar"})
2100
2101 def test_media_io_base_stream_unlimited_chunksize_resume(self):
2102 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2103 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2104
2105 # Set up a seekable stream and try to upload in single chunk.
2106 fd = io.BytesIO(b'01234"56789"')
2107 media_upload = MediaIoBaseUpload(
2108 fd=fd, mimetype="text/plain", chunksize=-1, resumable=True
2109 )
2110
2111 request = zoo.animals().insert(media_body=media_upload, body=None)
2112
2113 # The single chunk fails, restart at the right point.
2114 http = HttpMockSequence(
2115 [
2116 ({"status": "200", "location": "http://upload.example.com"}, ""),
2117 (
2118 {
2119 "status": "308",
2120 "location": "http://upload.example.com/2",
2121 "range": "0-4",
2122 },
2123 "",
2124 ),
2125 ({"status": "200"}, "echo_request_body"),
2126 ]
2127 )
2128
2129 body = request.execute(http=http)
2130 self.assertEqual("56789", body)
2131
2132 def test_media_io_base_stream_chunksize_resume(self):
2133 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2134 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2135
2136 # Set up a seekable stream and try to upload in chunks.
2137 fd = io.BytesIO(b"0123456789")
2138 media_upload = MediaIoBaseUpload(
2139 fd=fd, mimetype="text/plain", chunksize=5, resumable=True
2140 )
2141
2142 request = zoo.animals().insert(media_body=media_upload, body=None)
2143
2144 # The single chunk fails, pull the content sent out of the exception.
2145 http = HttpMockSequence(
2146 [
2147 ({"status": "200", "location": "http://upload.example.com"}, ""),
2148 ({"status": "400"}, "echo_request_body"),
2149 ]
2150 )
2151
2152 try:
2153 body = request.execute(http=http)
2154 except HttpError as e:
2155 self.assertEqual(b"01234", e.content)
2156
2157 def test_resumable_media_handle_uploads_of_unknown_size(self):
2158 http = HttpMockSequence(
2159 [
2160 ({"status": "200", "location": "http://upload.example.com"}, ""),
2161 ({"status": "200"}, "echo_request_headers_as_json"),
2162 ]
2163 )
2164
2165 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2166 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2167
2168 # Create an upload that doesn't know the full size of the media.
2169 class IoBaseUnknownLength(MediaUpload):
2170 def chunksize(self):
2171 return 10
2172
2173 def mimetype(self):
2174 return "image/png"
2175
2176 def size(self):
2177 return None
2178
2179 def resumable(self):
2180 return True
2181
2182 def getbytes(self, begin, length):
2183 return "0123456789"
2184
2185 upload = IoBaseUnknownLength()
2186
2187 request = zoo.animals().insert(media_body=upload, body=None)
2188 status, body = request.next_chunk(http=http)
2189 self.assertEqual(body, {"Content-Range": "bytes 0-9/*", "Content-Length": "10"})
2190
2191 def test_resumable_media_no_streaming_on_unsupported_platforms(self):
2192 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2193 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2194
2195 class IoBaseHasStream(MediaUpload):
2196 def chunksize(self):
2197 return 10
2198
2199 def mimetype(self):
2200 return "image/png"
2201
2202 def size(self):
2203 return None
2204
2205 def resumable(self):
2206 return True
2207
2208 def getbytes(self, begin, length):
2209 return "0123456789"
2210
2211 def has_stream(self):
2212 return True
2213
2214 def stream(self):
2215 raise NotImplementedError()
2216
2217 upload = IoBaseHasStream()
2218
2219 orig_version = sys.version_info
2220
2221 sys.version_info = (2, 6, 5, "final", 0)
2222
2223 request = zoo.animals().insert(media_body=upload, body=None)
2224
2225 # This should raise an exception because stream() will be called.
2226 http = HttpMockSequence(
2227 [
2228 ({"status": "200", "location": "http://upload.example.com"}, ""),
2229 ({"status": "200"}, "echo_request_headers_as_json"),
2230 ]
2231 )
2232
2233 self.assertRaises(NotImplementedError, request.next_chunk, http=http)
2234
2235 sys.version_info = orig_version
2236
2237 def test_resumable_media_handle_uploads_of_unknown_size_eof(self):
2238 http = HttpMockSequence(
2239 [
2240 ({"status": "200", "location": "http://upload.example.com"}, ""),
2241 ({"status": "200"}, "echo_request_headers_as_json"),
2242 ]
2243 )
2244
2245 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2246 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2247
2248 fd = io.BytesIO(b"data goes here")
2249
2250 # Create an upload that doesn't know the full size of the media.
2251 upload = MediaIoBaseUpload(
2252 fd=fd, mimetype="image/png", chunksize=15, resumable=True
2253 )
2254
2255 request = zoo.animals().insert(media_body=upload, body=None)
2256 status, body = request.next_chunk(http=http)
2257 self.assertEqual(
2258 body, {"Content-Range": "bytes 0-13/14", "Content-Length": "14"}
2259 )
2260
2261 def test_resumable_media_handle_resume_of_upload_of_unknown_size(self):
2262 http = HttpMockSequence(
2263 [
2264 ({"status": "200", "location": "http://upload.example.com"}, ""),
2265 ({"status": "400"}, ""),
2266 ]
2267 )
2268
2269 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2270 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2271
2272 # Create an upload that doesn't know the full size of the media.
2273 fd = io.BytesIO(b"data goes here")
2274
2275 upload = MediaIoBaseUpload(
2276 fd=fd, mimetype="image/png", chunksize=500, resumable=True
2277 )
2278
2279 request = zoo.animals().insert(media_body=upload, body=None)
2280
2281 # Put it in an error state.
2282 self.assertRaises(HttpError, request.next_chunk, http=http)
2283
2284 http = HttpMockSequence(
2285 [({"status": "400", "range": "0-5"}, "echo_request_headers_as_json")]
2286 )
2287 try:
2288 # Should resume the upload by first querying the status of the upload.
2289 request.next_chunk(http=http)
2290 except HttpError as e:
2291 expected = {"Content-Range": "bytes */14", "content-length": "0"}
2292 self.assertEqual(
2293 expected,
2294 json.loads(e.content.decode("utf-8")),
2295 "Should send an empty body when requesting the current upload status.",
2296 )
2297
2298 def test_pickle(self):
2299 sorted_resource_keys = [
2300 "_baseUrl",
2301 "_credentials_validated",
2302 "_developerKey",
2303 "_dynamic_attrs",
2304 "_http",
2305 "_model",
2306 "_requestBuilder",
2307 "_resourceDesc",
2308 "_rootDesc",
2309 "_schema",
2310 "_universe_domain",
2311 "animals",
2312 "global_",
2313 "load",
2314 "loadNoTemplate",
2315 "my",
2316 "new_batch_http_request",
2317 "query",
2318 "scopedAnimals",
2319 ]
2320
2321 http = HttpMock(datafile("zoo.json"), {"status": "200"})
2322 zoo = build("zoo", "v1", http=http, static_discovery=False)
2323 self.assertEqual(sorted(zoo.__dict__.keys()), sorted_resource_keys)
2324
2325 pickled_zoo = pickle.dumps(zoo)
2326 new_zoo = pickle.loads(pickled_zoo)
2327 self.assertEqual(sorted(new_zoo.__dict__.keys()), sorted_resource_keys)
2328 self.assertTrue(hasattr(new_zoo, "animals"))
2329 self.assertTrue(callable(new_zoo.animals))
2330 self.assertTrue(hasattr(new_zoo, "global_"))
2331 self.assertTrue(callable(new_zoo.global_))
2332 self.assertTrue(hasattr(new_zoo, "load"))
2333 self.assertTrue(callable(new_zoo.load))
2334 self.assertTrue(hasattr(new_zoo, "loadNoTemplate"))
2335 self.assertTrue(callable(new_zoo.loadNoTemplate))
2336 self.assertTrue(hasattr(new_zoo, "my"))
2337 self.assertTrue(callable(new_zoo.my))
2338 self.assertTrue(hasattr(new_zoo, "query"))
2339 self.assertTrue(callable(new_zoo.query))
2340 self.assertTrue(hasattr(new_zoo, "scopedAnimals"))
2341 self.assertTrue(callable(new_zoo.scopedAnimals))
2342
2343 self.assertEqual(sorted(zoo._dynamic_attrs), sorted(new_zoo._dynamic_attrs))
2344 self.assertEqual(zoo._baseUrl, new_zoo._baseUrl)
2345 self.assertEqual(zoo._developerKey, new_zoo._developerKey)
2346 self.assertEqual(zoo._requestBuilder, new_zoo._requestBuilder)
2347 self.assertEqual(zoo._resourceDesc, new_zoo._resourceDesc)
2348 self.assertEqual(zoo._rootDesc, new_zoo._rootDesc)
2349 # _http, _model and _schema won't be equal since we will get new
2350 # instances upon un-pickling
2351
2352 def _dummy_zoo_request(self):
2353 zoo_contents = read_datafile("zoo.json")
2354
2355 zoo_uri = uritemplate.expand(DISCOVERY_URI, {"api": "zoo", "apiVersion": "v1"})
2356 if "REMOTE_ADDR" in os.environ:
2357 zoo_uri = util._add_query_parameter(
2358 zoo_uri, "userIp", os.environ["REMOTE_ADDR"]
2359 )
2360
2361 http = build_http()
2362 original_request = http.request
2363
2364 def wrapped_request(uri, method="GET", *args, **kwargs):
2365 if uri == zoo_uri:
2366 return httplib2.Response({"status": "200"}), zoo_contents
2367 return original_request(uri, method=method, *args, **kwargs)
2368
2369 http.request = wrapped_request
2370 return http
2371
2372 def _dummy_token(self):
2373 access_token = "foo"
2374 client_id = "some_client_id"
2375 client_secret = "cOuDdkfjxxnv+"
2376 refresh_token = "1/0/a.df219fjls0"
2377 token_expiry = datetime.datetime.now(datetime.timezone.utc)
2378 user_agent = "refresh_checker/1.0"
2379 return OAuth2Credentials(
2380 access_token,
2381 client_id,
2382 client_secret,
2383 refresh_token,
2384 token_expiry,
2385 GOOGLE_TOKEN_URI,
2386 user_agent,
2387 )
2388
2389 @unittest.skipIf(not HAS_OAUTH2CLIENT, "oauth2client unavailable.")
2390 def test_pickle_with_credentials(self):
2391 credentials = self._dummy_token()
2392 http = self._dummy_zoo_request()
2393 http = credentials.authorize(http)
2394 self.assertTrue(hasattr(http.request, "credentials"))
2395
2396 zoo = build("zoo", "v1", http=http, static_discovery=False)
2397 pickled_zoo = pickle.dumps(zoo)
2398 new_zoo = pickle.loads(pickled_zoo)
2399 self.assertEqual(sorted(zoo.__dict__.keys()), sorted(new_zoo.__dict__.keys()))
2400 new_http = new_zoo._http
2401 self.assertFalse(hasattr(new_http.request, "credentials"))
2402
2403 def test_resumable_media_upload_no_content(self):
2404 self.http = HttpMock(datafile("zoo.json"), {"status": "200"})
2405 zoo = build("zoo", "v1", http=self.http, static_discovery=False)
2406
2407 media_upload = MediaFileUpload(datafile("empty"), resumable=True)
2408 request = zoo.animals().insert(media_body=media_upload, body=None)
2409
2410 self.assertEqual(media_upload, request.resumable)
2411 self.assertEqual(request.body, None)
2412 self.assertEqual(request.resumable_uri, None)
2413
2414 http = HttpMockSequence(
2415 [
2416 ({"status": "200", "location": "http://upload.example.com"}, ""),
2417 (
2418 {
2419 "status": "308",
2420 "location": "http://upload.example.com/2",
2421 "range": "0-0",
2422 },
2423 "",
2424 ),
2425 ]
2426 )
2427
2428 status, body = request.next_chunk(http=http)
2429 self.assertEqual(None, body)
2430 self.assertTrue(isinstance(status, MediaUploadProgress))
2431 self.assertEqual(0, status.progress())
2432
2433
2434 class Next(unittest.TestCase):
2435 def test_next_successful_none_on_no_next_page_token(self):
2436 self.http = HttpMock(datafile("tasks.json"), {"status": "200"})
2437 tasks = build("tasks", "v1", http=self.http)
2438 request = tasks.tasklists().list()
2439 self.assertEqual(None, tasks.tasklists().list_next(request, {}))
2440
2441 def test_next_successful_none_on_empty_page_token(self):
2442 self.http = HttpMock(datafile("tasks.json"), {"status": "200"})
2443 tasks = build("tasks", "v1", http=self.http)
2444 request = tasks.tasklists().list()
2445 next_request = tasks.tasklists().list_next(request, {"nextPageToken": ""})
2446 self.assertEqual(None, next_request)
2447
2448 def test_next_successful_with_next_page_token(self):
2449 self.http = HttpMock(datafile("tasks.json"), {"status": "200"})
2450 tasks = build("tasks", "v1", http=self.http)
2451 request = tasks.tasklists().list()
2452 next_request = tasks.tasklists().list_next(request, {"nextPageToken": "123abc"})
2453 parsed = urllib.parse.urlparse(next_request.uri)
2454 q = urllib.parse.parse_qs(parsed.query)
2455 self.assertEqual(q["pageToken"][0], "123abc")
2456
2457 def test_next_successful_with_next_page_token_alternate_name(self):
2458 self.http = HttpMock(datafile("bigquery.json"), {"status": "200"})
2459 bigquery = build("bigquery", "v2", http=self.http)
2460 request = bigquery.tabledata().list(
2461 datasetId="test_dataset", projectId="test_project", tableId="test_table"
2462 )
2463 next_request = bigquery.tabledata().list_next(request, {"pageToken": "123abc"})
2464 parsed = urllib.parse.urlparse(next_request.uri)
2465 q = urllib.parse.parse_qs(parsed.query)
2466 self.assertEqual(q["pageToken"][0], "123abc")
2467
2468 def test_next_successful_with_next_page_token_in_body(self):
2469 self.http = HttpMock(datafile("logging.json"), {"status": "200"})
2470 logging = build("logging", "v2", http=self.http)
2471 request = logging.entries().list(body={})
2472 next_request = logging.entries().list_next(request, {"nextPageToken": "123abc"})
2473 body = JsonModel().deserialize(next_request.body)
2474 self.assertEqual(body["pageToken"], "123abc")
2475 # The body is changed, make sure that body_length is changed too (see
2476 # github #1403)
2477 self.assertEqual(next_request.body_size, len(next_request.body))
2478
2479 def test_next_with_method_with_no_properties(self):
2480 self.http = HttpMock(datafile("latitude.json"), {"status": "200"})
2481 service = build("latitude", "v1", http=self.http, static_discovery=False)
2482 service.currentLocation().get()
2483
2484 def test_next_nonexistent_with_no_next_page_token(self):
2485 self.http = HttpMock(datafile("drive.json"), {"status": "200"})
2486 drive = build("drive", "v3", http=self.http)
2487 drive.changes().watch(body={})
2488 self.assertFalse(callable(getattr(drive.changes(), "watch_next", None)))
2489
2490 def test_next_successful_with_next_page_token_required(self):
2491 self.http = HttpMock(datafile("drive.json"), {"status": "200"})
2492 drive = build("drive", "v3", http=self.http)
2493 request = drive.changes().list(pageToken="startPageToken")
2494 next_request = drive.changes().list_next(request, {"nextPageToken": "123abc"})
2495 parsed = urllib.parse.urlparse(next_request.uri)
2496 q = urllib.parse.parse_qs(parsed.query)
2497 self.assertEqual(q["pageToken"][0], "123abc")
2498
2499
2500 class MediaGet(unittest.TestCase):
2501 def test_get_media(self):
2502 http = HttpMock(datafile("zoo.json"), {"status": "200"})
2503 zoo = build("zoo", "v1", http=http, static_discovery=False)
2504 request = zoo.animals().get_media(name="Lion")
2505
2506 parsed = urllib.parse.urlparse(request.uri)
2507 q = urllib.parse.parse_qs(parsed.query)
2508 self.assertEqual(q["alt"], ["media"])
2509 self.assertEqual(request.headers["accept"], "*/*")
2510
2511 http = HttpMockSequence([({"status": "200"}, "standing in for media")])
2512 response = request.execute(http=http)
2513 self.assertEqual(b"standing in for media", response)
2514
2515
2516 class Universe(unittest.TestCase):
2517 if HAS_UNIVERSE:
2518
2519 def test_validate_credentials_with_no_client_options(self):
2520 http = build_http()
2521 discovery = read_datafile("zoo.json")
2522 service = build_from_document(
2523 discovery,
2524 http=http,
2525 )
2526 assert service._validate_credentials()
2527
2528 def test_validate_credentials_with_client_options_without_universe(self):
2529 http = build_http()
2530 discovery = read_datafile("zoo.json")
2531 service = build_from_document(
2532 discovery,
2533 http=http,
2534 client_options=google.api_core.client_options.ClientOptions(),
2535 )
2536 assert service._validate_credentials()
2537
2538 def test_validate_credentials_with_no_universe(self):
2539 fake_universe = "foo.com"
2540
2541 http = google_auth_httplib2.AuthorizedHttp(
2542 credentials=None, http=build_http()
2543 )
2544 discovery = read_datafile("zoo.json")
2545 service = build_from_document(
2546 discovery,
2547 http=http,
2548 client_options=google.api_core.client_options.ClientOptions(
2549 universe_domain=universe.DEFAULT_UNIVERSE
2550 ),
2551 )
2552
2553 assert service._validate_credentials()
2554
2555 http = google_auth_httplib2.AuthorizedHttp(
2556 credentials=None, http=build_http()
2557 )
2558 discovery = read_datafile("zoo.json")
2559 service = build_from_document(
2560 discovery,
2561 http=http,
2562 client_options=google.api_core.client_options.ClientOptions(
2563 universe_domain=fake_universe
2564 ),
2565 )
2566
2567 with self.assertRaises(universe.UniverseMismatchError):
2568 service._validate_credentials()
2569
2570 def test_validate_credentials_with_default_universe(self):
2571 fake_universe = "foo.com"
2572
2573 http = google_auth_httplib2.AuthorizedHttp(
2574 credentials=mock.Mock(universe_domain=universe.DEFAULT_UNIVERSE),
2575 http=build_http(),
2576 )
2577 discovery = read_datafile("zoo.json")
2578 service = build_from_document(
2579 discovery,
2580 http=http,
2581 client_options=google.api_core.client_options.ClientOptions(
2582 universe_domain=universe.DEFAULT_UNIVERSE
2583 ),
2584 )
2585
2586 assert service._validate_credentials()
2587
2588 http = google_auth_httplib2.AuthorizedHttp(
2589 credentials=mock.Mock(universe_domain=universe.DEFAULT_UNIVERSE),
2590 http=build_http(),
2591 )
2592 discovery = read_datafile("zoo.json")
2593 service = build_from_document(
2594 discovery,
2595 http=http,
2596 client_options=google.api_core.client_options.ClientOptions(
2597 universe_domain=fake_universe
2598 ),
2599 )
2600
2601 with self.assertRaises(universe.UniverseMismatchError):
2602 service._validate_credentials()
2603
2604 def test_validate_credentials_with_a_different_universe(self):
2605 fake_universe = "foo.com"
2606
2607 http = google_auth_httplib2.AuthorizedHttp(
2608 credentials=mock.Mock(universe_domain=fake_universe),
2609 http=build_http(),
2610 )
2611 discovery = read_datafile("zoo.json")
2612 service = build_from_document(
2613 discovery,
2614 http=http,
2615 client_options=google.api_core.client_options.ClientOptions(
2616 universe_domain=fake_universe
2617 ),
2618 )
2619
2620 assert service._validate_credentials()
2621
2622 http = google_auth_httplib2.AuthorizedHttp(
2623 credentials=mock.Mock(universe_domain=fake_universe), http=build_http()
2624 )
2625 discovery = read_datafile("zoo.json")
2626 service = build_from_document(
2627 discovery,
2628 http=http,
2629 client_options=google.api_core.client_options.ClientOptions(
2630 universe_domain=universe.DEFAULT_UNIVERSE
2631 ),
2632 )
2633
2634 with self.assertRaises(universe.UniverseMismatchError):
2635 service._validate_credentials()
2636
2637 def test_validate_credentials_with_already_validated_credentials(self):
2638 fake_universe = "foo.com"
2639
2640 http = google_auth_httplib2.AuthorizedHttp(
2641 credentials=mock.Mock(universe_domain=universe.DEFAULT_UNIVERSE),
2642 http=build_http(),
2643 )
2644 discovery = read_datafile("zoo.json")
2645 service = build_from_document(
2646 discovery,
2647 http=http,
2648 client_options=google.api_core.client_options.ClientOptions(
2649 universe_domain=universe.DEFAULT_UNIVERSE
2650 ),
2651 )
2652
2653 assert service._validate_credentials()
2654 assert service._credentials_validated
2655
2656 # Calling service._validate_credentials() again returns service.credentials_validated.
2657 assert service._validate_credentials()
2658
2659 http = google_auth_httplib2.AuthorizedHttp(
2660 credentials=mock.Mock(universe_domain=fake_universe), http=build_http()
2661 )
2662 discovery = read_datafile("zoo.json")
2663 service = build_from_document(
2664 discovery,
2665 http=http,
2666 client_options=google.api_core.client_options.ClientOptions(
2667 universe_domain=fake_universe
2668 ),
2669 )
2670
2671 assert service._validate_credentials()
2672 assert service._credentials_validated
2673
2674 # Calling service._validate_credentials() again returns service.credentials_validated.
2675 assert service._validate_credentials()
2676
2677 def test_validate_credentials_before_api_request_success(self):
2678 fake_universe = "foo.com"
2679 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2680 credentials.universe_domain = fake_universe
2681 discovery = read_datafile("tasks.json")
2682 tasks = build_from_document(
2683 discovery,
2684 credentials=credentials,
2685 client_options=google.api_core.client_options.ClientOptions(
2686 universe_domain=fake_universe
2687 ),
2688 )
2689
2690 tasklists = tasks.tasklists()
2691 request = tasklists.list()
2692
2693 # Check that credentials are indeed verified before request.
2694 assert tasklists._validate_credentials()
2695
2696 def test_validate_credentials_before_api_request_failure(self):
2697 fake_universe = "foo.com"
2698 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2699 credentials.universe_domain = fake_universe
2700 discovery = read_datafile("tasks.json")
2701 tasks = build_from_document(
2702 discovery,
2703 credentials=credentials,
2704 client_options=google.api_core.client_options.ClientOptions(
2705 universe_domain=universe.DEFAULT_UNIVERSE
2706 ),
2707 )
2708
2709 # Check that credentials are verified before request.
2710 with self.assertRaises(universe.UniverseMismatchError):
2711 request = tasks.tasklists().list()
2712
2713 def test_validate_credentials_before_another_universe_api_request_failure(self):
2714 fake_universe = "foo.com"
2715 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2716 credentials.universe_domain = fake_universe
2717 another_fake_universe = "bar.com"
2718 discovery = read_datafile("tasks.json")
2719 tasks = build_from_document(
2720 discovery,
2721 credentials=credentials,
2722 client_options=google.api_core.client_options.ClientOptions(
2723 universe_domain=another_fake_universe
2724 ),
2725 )
2726
2727 # Check that credentials are verified before request.
2728 with self.assertRaises(universe.UniverseMismatchError):
2729 request = tasks.tasklists().list()
2730
2731 def test_client_options_with_empty_universe(self):
2732 fake_universe = "foo.com"
2733 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2734 discovery = read_datafile("tasks.json")
2735
2736 with self.assertRaises(universe.EmptyUniverseError):
2737 tasks = build_from_document(
2738 discovery,
2739 credentials=credentials,
2740 client_options=google.api_core.client_options.ClientOptions(
2741 universe_domain=""
2742 ),
2743 )
2744
2745 def test_client_options_universe_configured_with_mtls(self):
2746 fake_universe = "foo.com"
2747 discovery = read_datafile("tasks.json")
2748
2749 with self.assertRaises(MutualTLSChannelError):
2750 with mock.patch.dict(
2751 "os.environ", {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}
2752 ):
2753 tasks = build_from_document(
2754 discovery,
2755 client_options=google.api_core.client_options.ClientOptions(
2756 universe_domain=fake_universe
2757 ),
2758 )
2759
2760 def test_client_options_universe_configured_with_api_override(self):
2761 fake_universe = "foo.com"
2762 fake_api_endpoint = "https://www.bar.com/"
2763 credentials = mock.Mock(universe_domain=fake_universe)
2764 discovery = read_datafile("tasks.json")
2765
2766 tasks = build_from_document(
2767 discovery,
2768 credentials=credentials,
2769 client_options=google.api_core.client_options.ClientOptions(
2770 api_endpoint=fake_api_endpoint, universe_domain=fake_universe
2771 ),
2772 )
2773
2774 assert tasks._baseUrl == fake_api_endpoint
2775
2776 def test_universe_env_var_configured_empty(self):
2777 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2778 discovery = read_datafile("tasks.json")
2779
2780 with self.assertRaises(universe.EmptyUniverseError):
2781 with mock.patch.dict(
2782 "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""}
2783 ):
2784 tasks = build_from_document(
2785 discovery,
2786 credentials=credentials,
2787 )
2788
2789 def test_universe_env_var_configured_with_mtls(self):
2790 fake_universe = "foo.com"
2791 discovery = read_datafile("tasks.json")
2792
2793 with self.assertRaises(MutualTLSChannelError):
2794 with mock.patch.dict(
2795 "os.environ",
2796 {
2797 "GOOGLE_API_USE_MTLS_ENDPOINT": "always",
2798 "GOOGLE_CLOUD_UNIVERSE_DOMAIN": fake_universe,
2799 },
2800 ):
2801 tasks = build_from_document(discovery)
2802
2803 def test_universe_env_var_configured_with_api_override(self):
2804 fake_universe = "foo.com"
2805 fake_api_endpoint = "https://www.bar.com/"
2806 credentials = mock.Mock(universe_domain=fake_universe)
2807 discovery = read_datafile("tasks.json")
2808
2809 with mock.patch.dict(
2810 "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": fake_universe}
2811 ):
2812 tasks = build_from_document(
2813 discovery,
2814 credentials=credentials,
2815 client_options=google.api_core.client_options.ClientOptions(
2816 api_endpoint=fake_api_endpoint
2817 ),
2818 )
2819
2820 assert tasks._baseUrl == fake_api_endpoint
2821
2822 def test_universe_env_var_configured_with_client_options_universe(self):
2823 fake_universe = "foo.com"
2824 another_fake_universe = "bar.com"
2825 credentials = mock.Mock(universe_domain=fake_universe)
2826 discovery = read_datafile("tasks.json")
2827
2828 with mock.patch.dict(
2829 "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": another_fake_universe}
2830 ):
2831 tasks = build_from_document(
2832 discovery,
2833 credentials=credentials,
2834 client_options=google.api_core.client_options.ClientOptions(
2835 universe_domain=fake_universe
2836 ),
2837 )
2838
2839 assert tasks._universe_domain == fake_universe
2840
2841 else:
2842 if hasattr(google.api_core.client_options.ClientOptions, "universe_domain"):
2843
2844 def test_client_options_universe_with_older_version_of_api_core(self):
2845 fake_universe = "foo.com"
2846 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2847 credentials.universe_domain = fake_universe
2848 discovery = read_datafile("tasks.json")
2849 with self.assertRaises(APICoreVersionError):
2850 tasks = build_from_document(
2851 discovery,
2852 credentials=credentials,
2853 client_options=google.api_core.client_options.ClientOptions(
2854 universe_domain=fake_universe
2855 ),
2856 )
2857
2858 def test_credentials_universe_with_older_version_of_api_core(self):
2859 fake_universe = "foo.com"
2860 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2861 credentials.universe_domain = fake_universe
2862 discovery = read_datafile("tasks.json")
2863 with self.assertRaises(APICoreVersionError):
2864 tasks = build_from_document(
2865 discovery,
2866 credentials=credentials,
2867 )
2868
2869 def test_credentials_default_universe_with_older_version_of_api_core(self):
2870 credentials = mock.Mock(spec=google.auth.credentials.Credentials)
2871 credentials.universe_domain = "googleapis.com"
2872 discovery = read_datafile("tasks.json")
2873 tasks = build_from_document(
2874 discovery,
2875 credentials=credentials,
2876 )
2877
2878 def test_http_credentials_universe_with_older_version_of_api_core(self):
2879 fake_universe = "foo.com"
2880 http = google_auth_httplib2.AuthorizedHttp(
2881 credentials=mock.Mock(universe_domain=fake_universe), http=build_http()
2882 )
2883 discovery = read_datafile("tasks.json")
2884 with self.assertRaises(APICoreVersionError):
2885 tasks = build_from_document(
2886 discovery,
2887 http=http,
2888 )
2889
2890 def test_http_credentials_default_universe_with_older_version_of_api_core(self):
2891 http = google_auth_httplib2.AuthorizedHttp(
2892 credentials=mock.Mock(universe_domain="googleapis.com"),
2893 http=build_http(),
2894 )
2895 discovery = read_datafile("tasks.json")
2896 tasks = build_from_document(
2897 discovery,
2898 http=http,
2899 )
2900
2901
2902 if __name__ == "__main__":
2903 unittest.main()