Debian Codegraph @

tests/test_http.py

raw
1 #!/usr/bin/env python
2 #
3 # Copyright 2014 Google Inc. All Rights Reserved.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 """Http tests
18
19 Unit tests for the googleapiclient.http.
20 """
21 from __future__ import absolute_import
22
23 __author__ = "[email protected] (Joe Gregorio)"
24
25 import io
26 from io import FileIO
27
28 # Do not remove the httplib2 import
29 import json
30 import logging
31 import os
32 import random
33 import socket
34 import ssl
35 import time
36 import unittest
37 from unittest import mock
38 import urllib
39
40 import httplib2
41
42 from googleapiclient.discovery import build
43 from googleapiclient.errors import BatchError, HttpError, InvalidChunkSizeError
44 from googleapiclient.http import (
45 MAX_URI_LENGTH,
46 BatchHttpRequest,
47 HttpMock,
48 HttpMockSequence,
49 HttpRequest,
50 MediaFileUpload,
51 MediaInMemoryUpload,
52 MediaIoBaseDownload,
53 MediaIoBaseUpload,
54 MediaUpload,
55 _StreamSlice,
56 build_http,
57 set_user_agent,
58 )
59 from googleapiclient.model import JsonModel
60
61
62 class MockCredentials:
63 """Mock class for all Credentials objects."""
64
65 def __init__(self, bearer_token, expired=False):
66 super(MockCredentials, self).__init__()
67 self._authorized = 0
68 self._refreshed = 0
69 self._applied = 0
70 self._bearer_token = bearer_token
71 self._access_token_expired = expired
72
73 @property
74 def access_token(self):
75 return self._bearer_token
76
77 @property
78 def access_token_expired(self):
79 return self._access_token_expired
80
81 def authorize(self, http):
82 self._authorized += 1
83
84 request_orig = http.request
85
86 # The closure that will replace 'httplib2.Http.request'.
87 def new_request(
88 uri,
89 method="GET",
90 body=None,
91 headers=None,
92 redirections=httplib2.DEFAULT_MAX_REDIRECTS,
93 connection_type=None,
94 ):
95 # Modify the request headers to add the appropriate
96 # Authorization header.
97 if headers is None:
98 headers = {}
99 self.apply(headers)
100
101 resp, content = request_orig(
102 uri, method, body, headers, redirections, connection_type
103 )
104
105 return resp, content
106
107 # Replace the request method with our own closure.
108 http.request = new_request
109
110 # Set credentials as a property of the request method.
111 setattr(http.request, "credentials", self)
112
113 return http
114
115 def refresh(self, http):
116 self._refreshed += 1
117
118 def apply(self, headers):
119 self._applied += 1
120 headers["authorization"] = self._bearer_token + " " + str(self._refreshed)
121
122
123 class HttpMockWithErrors(object):
124 def __init__(self, num_errors, success_json, success_data):
125 self.num_errors = num_errors
126 self.success_json = success_json
127 self.success_data = success_data
128
129 def request(self, *args, **kwargs):
130 if not self.num_errors:
131 return httplib2.Response(self.success_json), self.success_data
132 elif self.num_errors == 5:
133 ex = ConnectionResetError # noqa: F821
134 elif self.num_errors == 4:
135 ex = httplib2.ServerNotFoundError()
136 elif self.num_errors == 3:
137 ex = OSError()
138 ex.errno = socket.errno.EPIPE
139 elif self.num_errors == 2:
140 ex = ssl.SSLError()
141 else:
142 # Initialize the timeout error code to the platform's error code.
143 try:
144 # For Windows:
145 ex = OSError()
146 ex.errno = socket.errno.WSAETIMEDOUT
147 except AttributeError:
148 # For Linux/Mac:
149 ex = socket.timeout()
150
151 self.num_errors -= 1
152 raise ex
153
154
155 class HttpMockWithNonRetriableErrors(object):
156 def __init__(self, num_errors, success_json, success_data):
157 self.num_errors = num_errors
158 self.success_json = success_json
159 self.success_data = success_data
160
161 def request(self, *args, **kwargs):
162 if not self.num_errors:
163 return httplib2.Response(self.success_json), self.success_data
164 else:
165 self.num_errors -= 1
166 ex = OSError()
167 # set errno to a non-retriable value
168 try:
169 # For Windows:
170 ex.errno = socket.errno.WSAEHOSTUNREACH
171 except AttributeError:
172 # For Linux/Mac:
173 ex.errno = socket.errno.EHOSTUNREACH
174 # Now raise the correct timeout error.
175 raise ex
176
177
178 DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
179
180
181 def datafile(filename):
182 return os.path.join(DATA_DIR, filename)
183
184
185 def _postproc_none(*kwargs):
186 pass
187
188
189 class TestUserAgent(unittest.TestCase):
190 def test_set_user_agent(self):
191 http = HttpMockSequence([({"status": "200"}, "echo_request_headers")])
192
193 http = set_user_agent(http, "my_app/5.5")
194 resp, content = http.request("http://example.com")
195 self.assertEqual("my_app/5.5", content["user-agent"])
196
197 def test_set_user_agent_nested(self):
198 http = HttpMockSequence([({"status": "200"}, "echo_request_headers")])
199
200 http = set_user_agent(http, "my_app/5.5")
201 http = set_user_agent(http, "my_library/0.1")
202 resp, content = http.request("http://example.com")
203 self.assertEqual("my_app/5.5 my_library/0.1", content["user-agent"])
204
205
206 class TestMediaUpload(unittest.TestCase):
207 def test_media_file_upload_closes_fd_in___del__(self):
208 file_desc = mock.Mock(spec=io.TextIOWrapper)
209 opener = mock.mock_open(file_desc)
210 with mock.patch("builtins.open", return_value=opener):
211 upload = MediaFileUpload(datafile("test_close"), mimetype="text/plain")
212 self.assertIs(upload.stream(), file_desc)
213 del upload
214 file_desc.close.assert_called_once_with()
215
216 def test_media_file_upload_mimetype_detection(self):
217 upload = MediaFileUpload(datafile("small.png"))
218 self.assertEqual("image/png", upload.mimetype())
219
220 upload = MediaFileUpload(datafile("empty"))
221 self.assertEqual("application/octet-stream", upload.mimetype())
222
223 def test_media_file_upload_to_from_json(self):
224 upload = MediaFileUpload(datafile("small.png"), chunksize=500, resumable=True)
225 self.assertEqual("image/png", upload.mimetype())
226 self.assertEqual(190, upload.size())
227 self.assertEqual(True, upload.resumable())
228 self.assertEqual(500, upload.chunksize())
229 self.assertEqual(b"PNG", upload.getbytes(1, 3))
230
231 json = upload.to_json()
232 new_upload = MediaUpload.new_from_json(json)
233
234 self.assertEqual("image/png", new_upload.mimetype())
235 self.assertEqual(190, new_upload.size())
236 self.assertEqual(True, new_upload.resumable())
237 self.assertEqual(500, new_upload.chunksize())
238 self.assertEqual(b"PNG", new_upload.getbytes(1, 3))
239
240 def test_media_file_upload_raises_on_file_not_found(self):
241 with self.assertRaises(FileNotFoundError):
242 MediaFileUpload(datafile("missing.png"))
243
244 def test_media_file_upload_raises_on_invalid_chunksize(self):
245 self.assertRaises(
246 InvalidChunkSizeError,
247 MediaFileUpload,
248 datafile("small.png"),
249 mimetype="image/png",
250 chunksize=-2,
251 resumable=True,
252 )
253
254 def test_media_inmemory_upload(self):
255 media = MediaInMemoryUpload(
256 b"abcdef", mimetype="text/plain", chunksize=10, resumable=True
257 )
258 self.assertEqual("text/plain", media.mimetype())
259 self.assertEqual(10, media.chunksize())
260 self.assertTrue(media.resumable())
261 self.assertEqual(b"bc", media.getbytes(1, 2))
262 self.assertEqual(6, media.size())
263
264 def test_http_request_to_from_json(self):
265 http = build_http()
266 media_upload = MediaFileUpload(
267 datafile("small.png"), chunksize=500, resumable=True
268 )
269 req = HttpRequest(
270 http,
271 _postproc_none,
272 "http://example.com",
273 method="POST",
274 body="{}",
275 headers={"content-type": 'multipart/related; boundary="---flubber"'},
276 methodId="foo",
277 resumable=media_upload,
278 )
279
280 json = req.to_json()
281 new_req = HttpRequest.from_json(json, http, _postproc_none)
282
283 self.assertEqual(
284 {"content-type": 'multipart/related; boundary="---flubber"'},
285 new_req.headers,
286 )
287 self.assertEqual("http://example.com", new_req.uri)
288 self.assertEqual("{}", new_req.body)
289 self.assertEqual(http, new_req.http)
290 self.assertEqual(media_upload.to_json(), new_req.resumable.to_json())
291
292 self.assertEqual(random.random, new_req._rand)
293 self.assertEqual(time.sleep, new_req._sleep)
294
295
296 class TestMediaIoBaseUpload(unittest.TestCase):
297 def test_media_io_base_upload_from_file_io(self):
298 fd = FileIO(datafile("small.png"), "r")
299 upload = MediaIoBaseUpload(
300 fd=fd, mimetype="image/png", chunksize=500, resumable=True
301 )
302 self.assertEqual("image/png", upload.mimetype())
303 self.assertEqual(190, upload.size())
304 self.assertEqual(True, upload.resumable())
305 self.assertEqual(500, upload.chunksize())
306 self.assertEqual(b"PNG", upload.getbytes(1, 3))
307
308 def test_media_io_base_upload_from_file_object(self):
309 f = open(datafile("small.png"), "rb")
310 upload = MediaIoBaseUpload(
311 fd=f, mimetype="image/png", chunksize=500, resumable=True
312 )
313 self.assertEqual("image/png", upload.mimetype())
314 self.assertEqual(190, upload.size())
315 self.assertEqual(True, upload.resumable())
316 self.assertEqual(500, upload.chunksize())
317 self.assertEqual(b"PNG", upload.getbytes(1, 3))
318 f.close()
319
320 def test_media_io_base_upload_serializable(self):
321 f = open(datafile("small.png"), "rb")
322 upload = MediaIoBaseUpload(fd=f, mimetype="image/png")
323
324 try:
325 json = upload.to_json()
326 self.fail("MediaIoBaseUpload should not be serializable.")
327 except NotImplementedError:
328 pass
329
330 def test_media_io_base_upload_from_bytes(self):
331 f = open(datafile("small.png"), "rb")
332 fd = io.BytesIO(f.read())
333 upload = MediaIoBaseUpload(
334 fd=fd, mimetype="image/png", chunksize=500, resumable=True
335 )
336 self.assertEqual("image/png", upload.mimetype())
337 self.assertEqual(190, upload.size())
338 self.assertEqual(True, upload.resumable())
339 self.assertEqual(500, upload.chunksize())
340 self.assertEqual(b"PNG", upload.getbytes(1, 3))
341
342 def test_media_io_base_upload_raises_on_invalid_chunksize(self):
343 f = open(datafile("small.png"), "rb")
344 fd = io.BytesIO(f.read())
345 self.assertRaises(
346 InvalidChunkSizeError,
347 MediaIoBaseUpload,
348 fd,
349 "image/png",
350 chunksize=-2,
351 resumable=True,
352 )
353
354 def test_media_io_base_upload_streamable(self):
355 fd = io.BytesIO(b"stuff")
356 upload = MediaIoBaseUpload(
357 fd=fd, mimetype="image/png", chunksize=500, resumable=True
358 )
359 self.assertEqual(True, upload.has_stream())
360 self.assertEqual(fd, upload.stream())
361
362 def test_media_io_base_next_chunk_retries(self):
363 f = open(datafile("small.png"), "rb")
364 fd = io.BytesIO(f.read())
365 upload = MediaIoBaseUpload(
366 fd=fd, mimetype="image/png", chunksize=500, resumable=True
367 )
368
369 # Simulate errors for both the request that creates the resumable upload
370 # and the upload itself.
371 http = HttpMockSequence(
372 [
373 ({"status": "500"}, ""),
374 ({"status": "500"}, ""),
375 ({"status": "503"}, ""),
376 ({"status": "200", "location": "location"}, ""),
377 ({"status": "403"}, USER_RATE_LIMIT_EXCEEDED_RESPONSE_NO_STATUS),
378 ({"status": "403"}, RATE_LIMIT_EXCEEDED_RESPONSE),
379 ({"status": "429"}, ""),
380 ({"status": "200"}, "{}"),
381 ]
382 )
383
384 model = JsonModel()
385 uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
386 method = "POST"
387 request = HttpRequest(
388 http, model.response, uri, method=method, headers={}, resumable=upload
389 )
390
391 sleeptimes = []
392 request._sleep = lambda x: sleeptimes.append(x)
393 request._rand = lambda: 10
394
395 request.execute(num_retries=3)
396 self.assertEqual([20, 40, 80, 20, 40, 80], sleeptimes)
397
398 def test_media_io_base_next_chunk_no_retry_403_not_configured(self):
399 fd = io.BytesIO(b"i am png")
400 upload = MediaIoBaseUpload(
401 fd=fd, mimetype="image/png", chunksize=500, resumable=True
402 )
403
404 http = HttpMockSequence(
405 [({"status": "403"}, NOT_CONFIGURED_RESPONSE), ({"status": "200"}, "{}")]
406 )
407
408 model = JsonModel()
409 uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
410 method = "POST"
411 request = HttpRequest(
412 http, model.response, uri, method=method, headers={}, resumable=upload
413 )
414
415 request._rand = lambda: 1.0
416 request._sleep = mock.MagicMock()
417
418 with self.assertRaises(HttpError):
419 request.execute(num_retries=3)
420 request._sleep.assert_not_called()
421
422 def test_media_io_base_empty_file(self):
423 fd = io.BytesIO()
424 upload = MediaIoBaseUpload(
425 fd=fd, mimetype="image/png", chunksize=500, resumable=True
426 )
427
428 http = HttpMockSequence(
429 [
430 (
431 {
432 "status": "200",
433 "location": "https://www.googleapis.com/someapi/v1/upload?foo=bar",
434 },
435 "{}",
436 ),
437 (
438 {
439 "status": "200",
440 "location": "https://www.googleapis.com/someapi/v1/upload?foo=bar",
441 },
442 "{}",
443 ),
444 ]
445 )
446
447 model = JsonModel()
448 uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
449 method = "POST"
450 request = HttpRequest(
451 http, model.response, uri, method=method, headers={}, resumable=upload
452 )
453
454 request.execute()
455
456 # Check that "Content-Range" header is not set in the PUT request
457 self.assertTrue("Content-Range" not in http.request_sequence[-1][-1])
458 self.assertEqual("0", http.request_sequence[-1][-1]["Content-Length"])
459
460
461 class TestMediaIoBaseDownload(unittest.TestCase):
462 def setUp(self):
463 http = HttpMock(datafile("zoo.json"), {"status": "200"})
464 zoo = build("zoo", "v1", http=http, static_discovery=False)
465 self.request = zoo.animals().get_media(name="Lion")
466 self.fd = io.BytesIO()
467
468 def test_media_io_base_download(self):
469 self.request.http = HttpMockSequence(
470 [
471 ({"status": "200", "content-range": "0-2/5"}, b"123"),
472 ({"status": "200", "content-range": "3-4/5"}, b"45"),
473 ]
474 )
475 self.assertEqual(True, self.request.http.follow_redirects)
476
477 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
478
479 self.assertEqual(self.fd, download._fd)
480 self.assertEqual(3, download._chunksize)
481 self.assertEqual(0, download._progress)
482 self.assertEqual(None, download._total_size)
483 self.assertEqual(False, download._done)
484 self.assertEqual(self.request.uri, download._uri)
485
486 status, done = download.next_chunk()
487
488 self.assertEqual(self.fd.getvalue(), b"123")
489 self.assertEqual(False, done)
490 self.assertEqual(3, download._progress)
491 self.assertEqual(5, download._total_size)
492 self.assertEqual(3, status.resumable_progress)
493
494 status, done = download.next_chunk()
495
496 self.assertEqual(self.fd.getvalue(), b"12345")
497 self.assertEqual(True, done)
498 self.assertEqual(5, download._progress)
499 self.assertEqual(5, download._total_size)
500
501 def test_media_io_base_download_range_request_header(self):
502 self.request.http = HttpMockSequence(
503 [
504 (
505 {"status": "200", "content-range": "0-2/5"},
506 "echo_request_headers_as_json",
507 ),
508 ]
509 )
510
511 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
512
513 status, done = download.next_chunk()
514 result = json.loads(self.fd.getvalue().decode("utf-8"))
515
516 self.assertEqual(result.get("range"), "bytes=0-2")
517
518 def test_media_io_base_download_custom_request_headers(self):
519 self.request.http = HttpMockSequence(
520 [
521 (
522 {"status": "200", "content-range": "0-2/5"},
523 "echo_request_headers_as_json",
524 ),
525 (
526 {"status": "200", "content-range": "3-4/5"},
527 "echo_request_headers_as_json",
528 ),
529 ]
530 )
531 self.assertEqual(True, self.request.http.follow_redirects)
532
533 self.request.headers["Cache-Control"] = "no-store"
534
535 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
536
537 self.assertEqual(download._headers.get("Cache-Control"), "no-store")
538
539 status, done = download.next_chunk()
540
541 result = json.loads(self.fd.getvalue().decode("utf-8"))
542
543 # assert that that the header we added to the original request is
544 # sent up to the server on each call to next_chunk
545
546 self.assertEqual(result.get("Cache-Control"), "no-store")
547
548 download._fd = self.fd = io.BytesIO()
549 status, done = download.next_chunk()
550
551 result = json.loads(self.fd.getvalue().decode("utf-8"))
552 self.assertEqual(result.get("Cache-Control"), "no-store")
553
554 def test_media_io_base_download_handle_redirects(self):
555 self.request.http = HttpMockSequence(
556 [
557 (
558 {
559 "status": "200",
560 "content-location": "https://secure.example.net/lion",
561 },
562 b"",
563 ),
564 ({"status": "200", "content-range": "0-2/5"}, b"abc"),
565 ]
566 )
567
568 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
569
570 status, done = download.next_chunk()
571
572 self.assertEqual("https://secure.example.net/lion", download._uri)
573
574 def test_media_io_base_download_handle_4xx(self):
575 self.request.http = HttpMockSequence([({"status": "400"}, "")])
576
577 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
578
579 try:
580 status, done = download.next_chunk()
581 self.fail("Should raise an exception")
582 except HttpError:
583 pass
584
585 # Even after raising an exception we can pick up where we left off.
586 self.request.http = HttpMockSequence(
587 [({"status": "200", "content-range": "0-2/5"}, b"123")]
588 )
589
590 status, done = download.next_chunk()
591
592 self.assertEqual(self.fd.getvalue(), b"123")
593
594 def test_media_io_base_download_retries_connection_errors(self):
595 self.request.http = HttpMockWithErrors(
596 5, {"status": "200", "content-range": "0-2/3"}, b"123"
597 )
598
599 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
600 download._sleep = lambda _x: 0 # do nothing
601 download._rand = lambda: 10
602
603 status, done = download.next_chunk(num_retries=5)
604
605 self.assertEqual(self.fd.getvalue(), b"123")
606 self.assertEqual(True, done)
607
608 def test_media_io_base_download_retries_5xx(self):
609 self.request.http = HttpMockSequence(
610 [
611 ({"status": "500"}, ""),
612 ({"status": "500"}, ""),
613 ({"status": "500"}, ""),
614 ({"status": "200", "content-range": "0-2/5"}, b"123"),
615 ({"status": "503"}, ""),
616 ({"status": "503"}, ""),
617 ({"status": "503"}, ""),
618 ({"status": "200", "content-range": "3-4/5"}, b"45"),
619 ]
620 )
621
622 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
623
624 self.assertEqual(self.fd, download._fd)
625 self.assertEqual(3, download._chunksize)
626 self.assertEqual(0, download._progress)
627 self.assertEqual(None, download._total_size)
628 self.assertEqual(False, download._done)
629 self.assertEqual(self.request.uri, download._uri)
630
631 # Set time.sleep and random.random stubs.
632 sleeptimes = []
633 download._sleep = lambda x: sleeptimes.append(x)
634 download._rand = lambda: 10
635
636 status, done = download.next_chunk(num_retries=3)
637
638 # Check for exponential backoff using the rand function above.
639 self.assertEqual([20, 40, 80], sleeptimes)
640
641 self.assertEqual(self.fd.getvalue(), b"123")
642 self.assertEqual(False, done)
643 self.assertEqual(3, download._progress)
644 self.assertEqual(5, download._total_size)
645 self.assertEqual(3, status.resumable_progress)
646
647 # Reset time.sleep stub.
648 del sleeptimes[0 : len(sleeptimes)]
649
650 status, done = download.next_chunk(num_retries=3)
651
652 # Check for exponential backoff using the rand function above.
653 self.assertEqual([20, 40, 80], sleeptimes)
654
655 self.assertEqual(self.fd.getvalue(), b"12345")
656 self.assertEqual(True, done)
657 self.assertEqual(5, download._progress)
658 self.assertEqual(5, download._total_size)
659
660 def test_media_io_base_download_empty_file(self):
661 self.request.http = HttpMockSequence(
662 [({"status": "200", "content-range": "0-0/0"}, b"")]
663 )
664
665 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
666
667 self.assertEqual(self.fd, download._fd)
668 self.assertEqual(0, download._progress)
669 self.assertEqual(None, download._total_size)
670 self.assertEqual(False, download._done)
671 self.assertEqual(self.request.uri, download._uri)
672
673 status, done = download.next_chunk()
674
675 self.assertEqual(True, done)
676 self.assertEqual(0, download._progress)
677 self.assertEqual(0, download._total_size)
678 self.assertEqual(0, status.progress())
679
680 def test_media_io_base_download_empty_file_416_response(self):
681 self.request.http = HttpMockSequence(
682 [({"status": "416", "content-range": "0-0/0"}, b"")]
683 )
684
685 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
686
687 self.assertEqual(self.fd, download._fd)
688 self.assertEqual(0, download._progress)
689 self.assertEqual(None, download._total_size)
690 self.assertEqual(False, download._done)
691 self.assertEqual(self.request.uri, download._uri)
692
693 status, done = download.next_chunk()
694
695 self.assertEqual(True, done)
696 self.assertEqual(0, download._progress)
697 self.assertEqual(0, download._total_size)
698 self.assertEqual(0, status.progress())
699
700 def test_media_io_base_download_unknown_media_size(self):
701 self.request.http = HttpMockSequence([({"status": "200"}, b"123")])
702
703 download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
704
705 self.assertEqual(self.fd, download._fd)
706 self.assertEqual(0, download._progress)
707 self.assertEqual(None, download._total_size)
708 self.assertEqual(False, download._done)
709 self.assertEqual(self.request.uri, download._uri)
710
711 status, done = download.next_chunk()
712
713 self.assertEqual(self.fd.getvalue(), b"123")
714 self.assertEqual(True, done)
715 self.assertEqual(3, download._progress)
716 self.assertEqual(None, download._total_size)
717 self.assertEqual(0, status.progress())
718
719
720 EXPECTED = """POST /someapi/v1/collection/?foo=bar HTTP/1.1
721 Content-Type: application/json
722 MIME-Version: 1.0
723 Host: www.googleapis.com
724 content-length: 2\r\n\r\n{}"""
725
726
727 NO_BODY_EXPECTED = """POST /someapi/v1/collection/?foo=bar HTTP/1.1
728 Content-Type: application/json
729 MIME-Version: 1.0
730 Host: www.googleapis.com
731 content-length: 0\r\n\r\n"""
732
733 NO_BODY_EXPECTED_GET = """GET /someapi/v1/collection/?foo=bar HTTP/1.1
734 Content-Type: application/json
735 MIME-Version: 1.0
736 Host: www.googleapis.com\r\n\r\n"""
737
738
739 RESPONSE = """HTTP/1.1 200 OK
740 Content-Type: application/json
741 Content-Length: 14
742 ETag: "etag/pony"\r\n\r\n{"answer": 42}"""
743
744
745 BATCH_RESPONSE = b"""--batch_foobarbaz
746 Content-Type: application/http
747 Content-Transfer-Encoding: binary
748 Content-ID: <randomness + 1>
749
750 HTTP/1.1 200 OK
751 Content-Type: application/json
752 Content-Length: 14
753 ETag: "etag/pony"\r\n\r\n{"foo": 42}
754
755 --batch_foobarbaz
756 Content-Type: application/http
757 Content-Transfer-Encoding: binary
758 Content-ID: <randomness + 2>
759
760 HTTP/1.1 200 OK
761 Content-Type: application/json
762 Content-Length: 14
763 ETag: "etag/sheep"\r\n\r\n{"baz": "qux"}
764 --batch_foobarbaz--"""
765
766
767 BATCH_ERROR_RESPONSE = b"""--batch_foobarbaz
768 Content-Type: application/http
769 Content-Transfer-Encoding: binary
770 Content-ID: <randomness + 1>
771
772 HTTP/1.1 200 OK
773 Content-Type: application/json
774 Content-Length: 14
775 ETag: "etag/pony"\r\n\r\n{"foo": 42}
776
777 --batch_foobarbaz
778 Content-Type: application/http
779 Content-Transfer-Encoding: binary
780 Content-ID: <randomness + 2>
781
782 HTTP/1.1 403 Access Not Configured
783 Content-Type: application/json
784 Content-Length: 245
785 ETag: "etag/sheep"\r\n\r\n{
786 "error": {
787 "errors": [
788 {
789 "domain": "usageLimits",
790 "reason": "accessNotConfigured",
791 "message": "Access Not Configured",
792 "debugInfo": "QuotaState: BLOCKED"
793 }
794 ],
795 "code": 403,
796 "message": "Access Not Configured"
797 }
798 }
799
800 --batch_foobarbaz--"""
801
802
803 BATCH_RESPONSE_WITH_401 = b"""--batch_foobarbaz
804 Content-Type: application/http
805 Content-Transfer-Encoding: binary
806 Content-ID: <randomness + 1>
807
808 HTTP/1.1 401 Authorization Required
809 Content-Type: application/json
810 Content-Length: 14
811 ETag: "etag/pony"\r\n\r\n{"error": {"message":
812 "Authorizaton failed."}}
813
814 --batch_foobarbaz
815 Content-Type: application/http
816 Content-Transfer-Encoding: binary
817 Content-ID: <randomness + 2>
818
819 HTTP/1.1 200 OK
820 Content-Type: application/json
821 Content-Length: 14
822 ETag: "etag/sheep"\r\n\r\n{"baz": "qux"}
823 --batch_foobarbaz--"""
824
825
826 BATCH_SINGLE_RESPONSE = b"""--batch_foobarbaz
827 Content-Type: application/http
828 Content-Transfer-Encoding: binary
829 Content-ID: <randomness + 1>
830
831 HTTP/1.1 200 OK
832 Content-Type: application/json
833 Content-Length: 14
834 ETag: "etag/pony"\r\n\r\n{"foo": 42}
835 --batch_foobarbaz--"""
836
837
838 USER_RATE_LIMIT_EXCEEDED_RESPONSE_NO_STATUS = """{
839 "error": {
840 "errors": [
841 {
842 "domain": "usageLimits",
843 "reason": "userRateLimitExceeded",
844 "message": "User Rate Limit Exceeded"
845 }
846 ],
847 "code": 403,
848 "message": "User Rate Limit Exceeded"
849 }
850 }"""
851
852 USER_RATE_LIMIT_EXCEEDED_RESPONSE_WITH_STATUS = """{
853 "error": {
854 "errors": [
855 {
856 "domain": "usageLimits",
857 "reason": "userRateLimitExceeded",
858 "message": "User Rate Limit Exceeded"
859 }
860 ],
861 "code": 403,
862 "message": "User Rate Limit Exceeded",
863 "status": "PERMISSION_DENIED"
864 }
865 }"""
866
867 RATE_LIMIT_EXCEEDED_RESPONSE = """{
868 "error": {
869 "errors": [
870 {
871 "domain": "usageLimits",
872 "reason": "rateLimitExceeded",
873 "message": "Rate Limit Exceeded"
874 }
875 ],
876 "code": 403,
877 "message": "Rate Limit Exceeded"
878 }
879 }"""
880
881
882 NOT_CONFIGURED_RESPONSE = """{
883 "error": {
884 "errors": [
885 {
886 "domain": "usageLimits",
887 "reason": "accessNotConfigured",
888 "message": "Access Not Configured"
889 }
890 ],
891 "code": 403,
892 "message": "Access Not Configured"
893 }
894 }"""
895
896 LIST_NOT_CONFIGURED_RESPONSE = """[
897 "error": {
898 "errors": [
899 {
900 "domain": "usageLimits",
901 "reason": "accessNotConfigured",
902 "message": "Access Not Configured"
903 }
904 ],
905 "code": 403,
906 "message": "Access Not Configured"
907 }
908 ]"""
909
910
911 class Callbacks(object):
912 def __init__(self):
913 self.responses = {}
914 self.exceptions = {}
915
916 def f(self, request_id, response, exception):
917 self.responses[request_id] = response
918 self.exceptions[request_id] = exception
919
920
921 class TestHttpRequest(unittest.TestCase):
922 def test_unicode(self):
923 http = HttpMock(datafile("zoo.json"), headers={"status": "200"})
924 model = JsonModel()
925 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
926 method = "POST"
927 request = HttpRequest(
928 http,
929 model.response,
930 uri,
931 method=method,
932 body="{}",
933 headers={"content-type": "application/json"},
934 )
935 request.execute()
936 self.assertEqual(uri, http.uri)
937 self.assertEqual(str, type(http.uri))
938 self.assertEqual(method, http.method)
939 self.assertEqual(str, type(http.method))
940
941 def test_empty_content_type(self):
942 """Test for #284"""
943 http = HttpMock(None, headers={"status": 200})
944 uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
945 method = "POST"
946 request = HttpRequest(
947 http, _postproc_none, uri, method=method, headers={"content-type": ""}
948 )
949 request.execute()
950 self.assertEqual("", http.headers.get("content-type"))
951
952 def test_no_retry_connection_errors(self):
953 model = JsonModel()
954 request = HttpRequest(
955 HttpMockWithNonRetriableErrors(1, {"status": "200"}, '{"foo": "bar"}'),
956 model.response,
957 "https://www.example.com/json_api_endpoint",
958 )
959 request._sleep = lambda _x: 0 # do nothing
960 request._rand = lambda: 10
961 with self.assertRaises(OSError):
962 response = request.execute(num_retries=3)
963
964 def test_retry_connection_errors_non_resumable(self):
965 model = JsonModel()
966 request = HttpRequest(
967 HttpMockWithErrors(5, {"status": "200"}, '{"foo": "bar"}'),
968 model.response,
969 "https://www.example.com/json_api_endpoint",
970 )
971 request._sleep = lambda _x: 0 # do nothing
972 request._rand = lambda: 10
973 response = request.execute(num_retries=5)
974 self.assertEqual({"foo": "bar"}, response)
975
976 def test_retry_connection_errors_resumable(self):
977 with open(datafile("small.png"), "rb") as small_png_file:
978 small_png_fd = io.BytesIO(small_png_file.read())
979 upload = MediaIoBaseUpload(
980 fd=small_png_fd, mimetype="image/png", chunksize=500, resumable=True
981 )
982 model = JsonModel()
983
984 request = HttpRequest(
985 HttpMockWithErrors(
986 5, {"status": "200", "location": "location"}, '{"foo": "bar"}'
987 ),
988 model.response,
989 "https://www.example.com/file_upload",
990 method="POST",
991 resumable=upload,
992 )
993 request._sleep = lambda _x: 0 # do nothing
994 request._rand = lambda: 10
995 response = request.execute(num_retries=5)
996 self.assertEqual({"foo": "bar"}, response)
997
998 def test_retry(self):
999 num_retries = 6
1000 resp_seq = [({"status": "500"}, "")] * (num_retries - 4)
1001 resp_seq.append(({"status": "403"}, RATE_LIMIT_EXCEEDED_RESPONSE))
1002 resp_seq.append(
1003 ({"status": "403"}, USER_RATE_LIMIT_EXCEEDED_RESPONSE_NO_STATUS)
1004 )
1005 resp_seq.append(
1006 ({"status": "403"}, USER_RATE_LIMIT_EXCEEDED_RESPONSE_WITH_STATUS)
1007 )
1008 resp_seq.append(({"status": "429"}, ""))
1009 resp_seq.append(({"status": "200"}, "{}"))
1010
1011 http = HttpMockSequence(resp_seq)
1012 model = JsonModel()
1013 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
1014 method = "POST"
1015 request = HttpRequest(
1016 http,
1017 model.response,
1018 uri,
1019 method=method,
1020 body="{}",
1021 headers={"content-type": "application/json"},
1022 )
1023
1024 sleeptimes = []
1025 request._sleep = lambda x: sleeptimes.append(x)
1026 request._rand = lambda: 10
1027
1028 request.execute(num_retries=num_retries)
1029
1030 self.assertEqual(num_retries, len(sleeptimes))
1031 for retry_num in range(num_retries):
1032 self.assertEqual(10 * 2 ** (retry_num + 1), sleeptimes[retry_num])
1033
1034 def test_no_retry_succeeds(self):
1035 num_retries = 5
1036 resp_seq = [({"status": "200"}, "{}")] * (num_retries)
1037
1038 http = HttpMockSequence(resp_seq)
1039 model = JsonModel()
1040 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
1041 method = "POST"
1042 request = HttpRequest(
1043 http,
1044 model.response,
1045 uri,
1046 method=method,
1047 body="{}",
1048 headers={"content-type": "application/json"},
1049 )
1050
1051 sleeptimes = []
1052 request._sleep = lambda x: sleeptimes.append(x)
1053 request._rand = lambda: 10
1054
1055 request.execute(num_retries=num_retries)
1056
1057 self.assertEqual(0, len(sleeptimes))
1058
1059 def test_no_retry_fails_fast(self):
1060 http = HttpMockSequence([({"status": "500"}, ""), ({"status": "200"}, "{}")])
1061 model = JsonModel()
1062 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
1063 method = "POST"
1064 request = HttpRequest(
1065 http,
1066 model.response,
1067 uri,
1068 method=method,
1069 body="{}",
1070 headers={"content-type": "application/json"},
1071 )
1072
1073 request._rand = lambda: 1.0
1074 request._sleep = mock.MagicMock()
1075
1076 with self.assertRaises(HttpError):
1077 request.execute()
1078 request._sleep.assert_not_called()
1079
1080 def test_no_retry_403_not_configured_fails_fast(self):
1081 http = HttpMockSequence(
1082 [({"status": "403"}, NOT_CONFIGURED_RESPONSE), ({"status": "200"}, "{}")]
1083 )
1084 model = JsonModel()
1085 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
1086 method = "POST"
1087 request = HttpRequest(
1088 http,
1089 model.response,
1090 uri,
1091 method=method,
1092 body="{}",
1093 headers={"content-type": "application/json"},
1094 )
1095
1096 request._rand = lambda: 1.0
1097 request._sleep = mock.MagicMock()
1098
1099 with self.assertRaises(HttpError):
1100 request.execute()
1101 request._sleep.assert_not_called()
1102
1103 def test_no_retry_403_fails_fast(self):
1104 http = HttpMockSequence([({"status": "403"}, ""), ({"status": "200"}, "{}")])
1105 model = JsonModel()
1106 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
1107 method = "POST"
1108 request = HttpRequest(
1109 http,
1110 model.response,
1111 uri,
1112 method=method,
1113 body="{}",
1114 headers={"content-type": "application/json"},
1115 )
1116
1117 request._rand = lambda: 1.0
1118 request._sleep = mock.MagicMock()
1119
1120 with self.assertRaises(HttpError):
1121 request.execute()
1122 request._sleep.assert_not_called()
1123
1124 def test_no_retry_401_fails_fast(self):
1125 http = HttpMockSequence([({"status": "401"}, ""), ({"status": "200"}, "{}")])
1126 model = JsonModel()
1127 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
1128 method = "POST"
1129 request = HttpRequest(
1130 http,
1131 model.response,
1132 uri,
1133 method=method,
1134 body="{}",
1135 headers={"content-type": "application/json"},
1136 )
1137
1138 request._rand = lambda: 1.0
1139 request._sleep = mock.MagicMock()
1140
1141 with self.assertRaises(HttpError):
1142 request.execute()
1143 request._sleep.assert_not_called()
1144
1145 def test_no_retry_403_list_fails(self):
1146 http = HttpMockSequence(
1147 [
1148 ({"status": "403"}, LIST_NOT_CONFIGURED_RESPONSE),
1149 ({"status": "200"}, "{}"),
1150 ]
1151 )
1152 model = JsonModel()
1153 uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
1154 method = "POST"
1155 request = HttpRequest(
1156 http,
1157 model.response,
1158 uri,
1159 method=method,
1160 body="{}",
1161 headers={"content-type": "application/json"},
1162 )
1163
1164 request._rand = lambda: 1.0
1165 request._sleep = mock.MagicMock()
1166
1167 with self.assertRaises(HttpError):
1168 request.execute()
1169 request._sleep.assert_not_called()
1170
1171 def test_null_postproc(self):
1172 resp, content = HttpRequest.null_postproc("foo", "bar")
1173 self.assertEqual(resp, "foo")
1174 self.assertEqual(content, "bar")
1175
1176
1177 class TestBatch(unittest.TestCase):
1178 def setUp(self):
1179 model = JsonModel()
1180 self.request1 = HttpRequest(
1181 None,
1182 model.response,
1183 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1184 method="POST",
1185 body="{}",
1186 headers={"content-type": "application/json"},
1187 )
1188
1189 self.request2 = HttpRequest(
1190 None,
1191 model.response,
1192 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1193 method="GET",
1194 body="",
1195 headers={"content-type": "application/json"},
1196 )
1197
1198 def test_id_to_from_content_id_header(self):
1199 batch = BatchHttpRequest()
1200 self.assertEqual("12", batch._header_to_id(batch._id_to_header("12")))
1201
1202 def test_invalid_content_id_header(self):
1203 batch = BatchHttpRequest()
1204 self.assertRaises(BatchError, batch._header_to_id, "[foo+x]")
1205 self.assertRaises(BatchError, batch._header_to_id, "foo+1")
1206 self.assertRaises(BatchError, batch._header_to_id, "<foo>")
1207
1208 def test_serialize_request(self):
1209 batch = BatchHttpRequest()
1210 request = HttpRequest(
1211 None,
1212 None,
1213 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1214 method="POST",
1215 body="{}",
1216 headers={"content-type": "application/json"},
1217 methodId=None,
1218 resumable=None,
1219 )
1220 s = batch._serialize_request(request).splitlines()
1221 self.assertEqual(EXPECTED.splitlines(), s)
1222
1223 def test_serialize_request_media_body(self):
1224 batch = BatchHttpRequest()
1225 f = open(datafile("small.png"), "rb")
1226 body = f.read()
1227 f.close()
1228
1229 request = HttpRequest(
1230 None,
1231 None,
1232 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1233 method="POST",
1234 body=body,
1235 headers={"content-type": "application/json"},
1236 methodId=None,
1237 resumable=None,
1238 )
1239 # Just testing it shouldn't raise an exception.
1240 s = batch._serialize_request(request).splitlines()
1241
1242 def test_serialize_request_no_body(self):
1243 batch = BatchHttpRequest()
1244 request = HttpRequest(
1245 None,
1246 None,
1247 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1248 method="POST",
1249 body=b"",
1250 headers={"content-type": "application/json"},
1251 methodId=None,
1252 resumable=None,
1253 )
1254 s = batch._serialize_request(request).splitlines()
1255 self.assertEqual(NO_BODY_EXPECTED.splitlines(), s)
1256
1257 def test_serialize_get_request_no_body(self):
1258 batch = BatchHttpRequest()
1259 request = HttpRequest(
1260 None,
1261 None,
1262 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1263 method="GET",
1264 body=None,
1265 headers={"content-type": "application/json"},
1266 methodId=None,
1267 resumable=None,
1268 )
1269 s = batch._serialize_request(request).splitlines()
1270 self.assertEqual(NO_BODY_EXPECTED_GET.splitlines(), s)
1271
1272 def test_deserialize_response(self):
1273 batch = BatchHttpRequest()
1274 resp, content = batch._deserialize_response(RESPONSE)
1275
1276 self.assertEqual(200, resp.status)
1277 self.assertEqual("OK", resp.reason)
1278 self.assertEqual(11, resp.version)
1279 self.assertEqual('{"answer": 42}', content)
1280
1281 def test_new_id(self):
1282 batch = BatchHttpRequest()
1283
1284 id_ = batch._new_id()
1285 self.assertEqual("1", id_)
1286
1287 id_ = batch._new_id()
1288 self.assertEqual("2", id_)
1289
1290 batch.add(self.request1, request_id="3")
1291
1292 id_ = batch._new_id()
1293 self.assertEqual("4", id_)
1294
1295 def test_add(self):
1296 batch = BatchHttpRequest()
1297 batch.add(self.request1, request_id="1")
1298 self.assertRaises(KeyError, batch.add, self.request1, request_id="1")
1299
1300 def test_add_fail_for_over_limit(self):
1301 from googleapiclient.http import MAX_BATCH_LIMIT
1302
1303 batch = BatchHttpRequest()
1304 for i in range(0, MAX_BATCH_LIMIT):
1305 batch.add(
1306 HttpRequest(
1307 None,
1308 None,
1309 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1310 method="POST",
1311 body="{}",
1312 headers={"content-type": "application/json"},
1313 )
1314 )
1315 self.assertRaises(BatchError, batch.add, self.request1)
1316
1317 def test_add_fail_for_resumable(self):
1318 batch = BatchHttpRequest()
1319
1320 upload = MediaFileUpload(datafile("small.png"), chunksize=500, resumable=True)
1321 self.request1.resumable = upload
1322 with self.assertRaises(BatchError) as batch_error:
1323 batch.add(self.request1, request_id="1")
1324 str(batch_error.exception)
1325
1326 def test_execute_empty_batch_no_http(self):
1327 batch = BatchHttpRequest()
1328 ret = batch.execute()
1329 self.assertEqual(None, ret)
1330
1331 def test_execute(self):
1332 batch = BatchHttpRequest()
1333 callbacks = Callbacks()
1334
1335 batch.add(self.request1, callback=callbacks.f)
1336 batch.add(self.request2, callback=callbacks.f)
1337 http = HttpMockSequence(
1338 [
1339 (
1340 {
1341 "status": "200",
1342 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1343 },
1344 BATCH_RESPONSE,
1345 )
1346 ]
1347 )
1348 batch.execute(http=http)
1349 self.assertEqual({"foo": 42}, callbacks.responses["1"])
1350 self.assertEqual(None, callbacks.exceptions["1"])
1351 self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
1352 self.assertEqual(None, callbacks.exceptions["2"])
1353
1354 def test_execute_request_body(self):
1355 batch = BatchHttpRequest()
1356
1357 batch.add(self.request1)
1358 batch.add(self.request2)
1359 http = HttpMockSequence(
1360 [
1361 (
1362 {
1363 "status": "200",
1364 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1365 },
1366 "echo_request_body",
1367 )
1368 ]
1369 )
1370 try:
1371 batch.execute(http=http)
1372 self.fail("Should raise exception")
1373 except BatchError as e:
1374 boundary, _ = e.content.split(None, 1)
1375 self.assertEqual("--", boundary[:2])
1376 parts = e.content.split(boundary)
1377 self.assertEqual(4, len(parts))
1378 self.assertEqual("", parts[0])
1379 self.assertEqual("--", parts[3].rstrip())
1380 header = parts[1].splitlines()[1]
1381 self.assertEqual("Content-Type: application/http", header)
1382
1383 def test_execute_request_body_with_custom_long_request_ids(self):
1384 batch = BatchHttpRequest()
1385
1386 batch.add(self.request1, request_id="abc" * 20)
1387 batch.add(self.request2, request_id="def" * 20)
1388 http = HttpMockSequence(
1389 [
1390 (
1391 {
1392 "status": "200",
1393 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1394 },
1395 "echo_request_body",
1396 )
1397 ]
1398 )
1399 try:
1400 batch.execute(http=http)
1401 self.fail("Should raise exception")
1402 except BatchError as e:
1403 boundary, _ = e.content.split(None, 1)
1404 self.assertEqual("--", boundary[:2])
1405 parts = e.content.split(boundary)
1406 self.assertEqual(4, len(parts))
1407 self.assertEqual("", parts[0])
1408 self.assertEqual("--", parts[3].rstrip())
1409 for partindex, request_id in ((1, "abc" * 20), (2, "def" * 20)):
1410 lines = parts[partindex].splitlines()
1411 for n, line in enumerate(lines):
1412 if line.startswith("Content-ID:"):
1413 # assert correct header folding
1414 self.assertTrue(line.endswith("+"), line)
1415 header_continuation = lines[n + 1]
1416 self.assertEqual(
1417 header_continuation,
1418 " %s>" % request_id,
1419 header_continuation,
1420 )
1421
1422 def test_execute_initial_refresh_oauth2(self):
1423 batch = BatchHttpRequest()
1424 callbacks = Callbacks()
1425 cred = MockCredentials("Foo", expired=True)
1426
1427 http = HttpMockSequence(
1428 [
1429 (
1430 {
1431 "status": "200",
1432 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1433 },
1434 BATCH_SINGLE_RESPONSE,
1435 )
1436 ]
1437 )
1438
1439 cred.authorize(http)
1440
1441 batch.add(self.request1, callback=callbacks.f)
1442 batch.execute(http=http)
1443
1444 self.assertEqual({"foo": 42}, callbacks.responses["1"])
1445 self.assertIsNone(callbacks.exceptions["1"])
1446
1447 self.assertEqual(1, cred._refreshed)
1448
1449 self.assertEqual(1, cred._authorized)
1450
1451 self.assertEqual(1, cred._applied)
1452
1453 def test_execute_refresh_and_retry_on_401(self):
1454 batch = BatchHttpRequest()
1455 callbacks = Callbacks()
1456 cred_1 = MockCredentials("Foo")
1457 cred_2 = MockCredentials("Bar")
1458
1459 http = HttpMockSequence(
1460 [
1461 (
1462 {
1463 "status": "200",
1464 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1465 },
1466 BATCH_RESPONSE_WITH_401,
1467 ),
1468 (
1469 {
1470 "status": "200",
1471 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1472 },
1473 BATCH_SINGLE_RESPONSE,
1474 ),
1475 ]
1476 )
1477
1478 creds_http_1 = HttpMockSequence([])
1479 cred_1.authorize(creds_http_1)
1480
1481 creds_http_2 = HttpMockSequence([])
1482 cred_2.authorize(creds_http_2)
1483
1484 self.request1.http = creds_http_1
1485 self.request2.http = creds_http_2
1486
1487 batch.add(self.request1, callback=callbacks.f)
1488 batch.add(self.request2, callback=callbacks.f)
1489 batch.execute(http=http)
1490
1491 self.assertEqual({"foo": 42}, callbacks.responses["1"])
1492 self.assertEqual(None, callbacks.exceptions["1"])
1493 self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
1494 self.assertEqual(None, callbacks.exceptions["2"])
1495
1496 self.assertEqual(1, cred_1._refreshed)
1497 self.assertEqual(0, cred_2._refreshed)
1498
1499 self.assertEqual(1, cred_1._authorized)
1500 self.assertEqual(1, cred_2._authorized)
1501
1502 self.assertEqual(1, cred_2._applied)
1503 self.assertEqual(2, cred_1._applied)
1504
1505 def test_http_errors_passed_to_callback(self):
1506 batch = BatchHttpRequest()
1507 callbacks = Callbacks()
1508 cred_1 = MockCredentials("Foo")
1509 cred_2 = MockCredentials("Bar")
1510
1511 http = HttpMockSequence(
1512 [
1513 (
1514 {
1515 "status": "200",
1516 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1517 },
1518 BATCH_RESPONSE_WITH_401,
1519 ),
1520 (
1521 {
1522 "status": "200",
1523 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1524 },
1525 BATCH_RESPONSE_WITH_401,
1526 ),
1527 ]
1528 )
1529
1530 creds_http_1 = HttpMockSequence([])
1531 cred_1.authorize(creds_http_1)
1532
1533 creds_http_2 = HttpMockSequence([])
1534 cred_2.authorize(creds_http_2)
1535
1536 self.request1.http = creds_http_1
1537 self.request2.http = creds_http_2
1538
1539 batch.add(self.request1, callback=callbacks.f)
1540 batch.add(self.request2, callback=callbacks.f)
1541 batch.execute(http=http)
1542
1543 self.assertEqual(None, callbacks.responses["1"])
1544 self.assertEqual(401, callbacks.exceptions["1"].resp.status)
1545 self.assertEqual(
1546 "Authorization Required", callbacks.exceptions["1"].resp.reason
1547 )
1548 self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
1549 self.assertEqual(None, callbacks.exceptions["2"])
1550
1551 def test_execute_global_callback(self):
1552 callbacks = Callbacks()
1553 batch = BatchHttpRequest(callback=callbacks.f)
1554
1555 batch.add(self.request1)
1556 batch.add(self.request2)
1557 http = HttpMockSequence(
1558 [
1559 (
1560 {
1561 "status": "200",
1562 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1563 },
1564 BATCH_RESPONSE,
1565 )
1566 ]
1567 )
1568 batch.execute(http=http)
1569 self.assertEqual({"foo": 42}, callbacks.responses["1"])
1570 self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
1571
1572 def test_execute_batch_http_error(self):
1573 callbacks = Callbacks()
1574 batch = BatchHttpRequest(callback=callbacks.f)
1575
1576 batch.add(self.request1)
1577 batch.add(self.request2)
1578 http = HttpMockSequence(
1579 [
1580 (
1581 {
1582 "status": "200",
1583 "content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
1584 },
1585 BATCH_ERROR_RESPONSE,
1586 )
1587 ]
1588 )
1589 batch.execute(http=http)
1590 self.assertEqual({"foo": 42}, callbacks.responses["1"])
1591 expected = (
1592 "<HttpError 403 when requesting "
1593 "https://www.googleapis.com/someapi/v1/collection/?foo=bar returned "
1594 '"Access Not Configured". '
1595 "Details: \"[{'domain': 'usageLimits', 'reason': 'accessNotConfigured', 'message': 'Access Not Configured', 'debugInfo': 'QuotaState: BLOCKED'}]\">"
1596 )
1597 self.assertEqual(expected, str(callbacks.exceptions["2"]))
1598
1599
1600 class TestRequestUriTooLong(unittest.TestCase):
1601 def test_turn_get_into_post(self):
1602 def _postproc(resp, content):
1603 return content
1604
1605 http = HttpMockSequence(
1606 [
1607 ({"status": "200"}, "echo_request_body"),
1608 ({"status": "200"}, "echo_request_headers"),
1609 ]
1610 )
1611
1612 # Send a long query parameter.
1613 query = {"q": "a" * MAX_URI_LENGTH + "?&"}
1614 req = HttpRequest(
1615 http,
1616 _postproc,
1617 "http://example.com?" + urllib.parse.urlencode(query),
1618 method="GET",
1619 body=None,
1620 headers={},
1621 methodId="foo",
1622 resumable=None,
1623 )
1624
1625 # Query parameters should be sent in the body.
1626 response = req.execute()
1627 self.assertEqual(b"q=" + b"a" * MAX_URI_LENGTH + b"%3F%26", response)
1628
1629 # Extra headers should be set.
1630 response = req.execute()
1631 self.assertEqual("GET", response["x-http-method-override"])
1632 self.assertEqual(str(MAX_URI_LENGTH + 8), response["content-length"])
1633 self.assertEqual("application/x-www-form-urlencoded", response["content-type"])
1634
1635
1636 class TestStreamSlice(unittest.TestCase):
1637 """Test _StreamSlice."""
1638
1639 def setUp(self):
1640 self.stream = io.BytesIO(b"0123456789")
1641
1642 def test_read(self):
1643 s = _StreamSlice(self.stream, 0, 4)
1644 self.assertEqual(b"", s.read(0))
1645 self.assertEqual(b"0", s.read(1))
1646 self.assertEqual(b"123", s.read())
1647
1648 def test_read_too_much(self):
1649 s = _StreamSlice(self.stream, 1, 4)
1650 self.assertEqual(b"1234", s.read(6))
1651
1652 def test_read_all(self):
1653 s = _StreamSlice(self.stream, 2, 1)
1654 self.assertEqual(b"2", s.read(-1))
1655
1656
1657 class TestResponseCallback(unittest.TestCase):
1658 """Test adding callbacks to responses."""
1659
1660 def test_ensure_response_callback(self):
1661 m = JsonModel()
1662 request = HttpRequest(
1663 None,
1664 m.response,
1665 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1666 method="POST",
1667 body="{}",
1668 headers={"content-type": "application/json"},
1669 )
1670 h = HttpMockSequence([({"status": 200}, "{}")])
1671 responses = []
1672
1673 def _on_response(resp, responses=responses):
1674 responses.append(resp)
1675
1676 request.add_response_callback(_on_response)
1677 request.execute(http=h)
1678 self.assertEqual(1, len(responses))
1679
1680
1681 class TestHttpMock(unittest.TestCase):
1682 def test_default_response_headers(self):
1683 http = HttpMock(datafile("zoo.json"))
1684 resp, content = http.request("http://example.com")
1685 self.assertEqual(resp.status, 200)
1686
1687 def test_error_response(self):
1688 http = HttpMock(datafile("bad_request.json"), {"status": "400"})
1689 model = JsonModel()
1690 request = HttpRequest(
1691 http,
1692 model.response,
1693 "https://www.googleapis.com/someapi/v1/collection/?foo=bar",
1694 method="GET",
1695 headers={},
1696 )
1697 self.assertRaises(HttpError, request.execute)
1698
1699
1700 class TestHttpBuild(unittest.TestCase):
1701 original_socket_default_timeout = None
1702
1703 @classmethod
1704 def setUpClass(cls):
1705 cls.original_socket_default_timeout = socket.getdefaulttimeout()
1706
1707 @classmethod
1708 def tearDownClass(cls):
1709 socket.setdefaulttimeout(cls.original_socket_default_timeout)
1710
1711 def test_build_http_sets_default_timeout_if_none_specified(self):
1712 socket.setdefaulttimeout(None)
1713 http = build_http()
1714 self.assertIsInstance(http.timeout, int)
1715 self.assertGreater(http.timeout, 0)
1716
1717 def test_build_http_default_timeout_can_be_overridden(self):
1718 socket.setdefaulttimeout(1.5)
1719 http = build_http()
1720 self.assertAlmostEqual(http.timeout, 1.5, delta=0.001)
1721
1722 def test_build_http_default_timeout_can_be_set_to_zero(self):
1723 socket.setdefaulttimeout(0)
1724 http = build_http()
1725 self.assertEqual(http.timeout, 0)
1726
1727 def test_build_http_default_308_is_excluded_as_redirect(self):
1728 http = build_http()
1729 self.assertTrue(308 not in http.redirect_codes)
1730
1731
1732 if __name__ == "__main__":
1733 logging.getLogger().setLevel(logging.ERROR)
1734 unittest.main()