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