File size: 28,838 Bytes
065fee7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 |
# Copyright 2014 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import http.client
from http.client import SERVICE_UNAVAILABLE
from http.client import NO_CONTENT
import unittest
import mock
import requests
from google.cloud.storage._helpers import _DEFAULT_UNIVERSE_DOMAIN
def _make_credentials():
import google.auth.credentials
return mock.Mock(
spec=google.auth.credentials.Credentials,
universe_domain=_DEFAULT_UNIVERSE_DOMAIN,
)
def _make_response(status=http.client.OK, content=b"", headers={}):
response = requests.Response()
response.status_code = status
response._content = content
response.headers = headers
response.request = requests.Request()
return response
def _make_requests_session(responses):
session = mock.create_autospec(requests.Session, instance=True)
session.request.side_effect = responses
return session
class TestMIMEApplicationHTTP(unittest.TestCase):
@staticmethod
def _get_target_class():
from google.cloud.storage.batch import MIMEApplicationHTTP
return MIMEApplicationHTTP
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_ctor_body_None(self):
METHOD = "DELETE"
PATH = "/path/to/api"
LINES = ["DELETE /path/to/api HTTP/1.1", ""]
mah = self._make_one(METHOD, PATH, {}, None)
self.assertEqual(mah.get_content_type(), "application/http")
self.assertEqual(mah.get_payload().splitlines(), LINES)
def test_ctor_body_str(self):
METHOD = "GET"
PATH = "/path/to/api"
BODY = "ABC"
HEADERS = {"Content-Length": len(BODY), "Content-Type": "text/plain"}
LINES = [
"GET /path/to/api HTTP/1.1",
"Content-Length: 3",
"Content-Type: text/plain",
"",
"ABC",
]
mah = self._make_one(METHOD, PATH, HEADERS, BODY)
self.assertEqual(mah.get_payload().splitlines(), LINES)
def test_ctor_body_dict(self):
METHOD = "GET"
PATH = "/path/to/api"
BODY = {"foo": "bar"}
HEADERS = {}
LINES = [
"GET /path/to/api HTTP/1.1",
"Content-Length: 14",
"Content-Type: application/json",
"",
'{"foo": "bar"}',
]
mah = self._make_one(METHOD, PATH, HEADERS, BODY)
self.assertEqual(mah.get_payload().splitlines(), LINES)
class TestBatch(unittest.TestCase):
@staticmethod
def _get_default_timeout():
from google.cloud.storage.constants import _DEFAULT_TIMEOUT
return _DEFAULT_TIMEOUT
@staticmethod
def _get_target_class():
from google.cloud.storage.batch import Batch
return Batch
def _make_one(self, *args, **kw):
return self._get_target_class()(*args, **kw)
def test_ctor(self):
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
self.assertIs(batch._client, client)
self.assertEqual(len(batch._requests), 0)
self.assertEqual(len(batch._target_objects), 0)
def test_current(self):
from google.cloud.storage.client import Client
project = "PROJECT"
credentials = _make_credentials()
client = Client(project=project, credentials=credentials)
batch1 = self._make_one(client)
self.assertIsNone(batch1.current())
client._push_batch(batch1)
self.assertIs(batch1.current(), batch1)
batch2 = self._make_one(client)
client._push_batch(batch2)
self.assertIs(batch1.current(), batch2)
def test__make_request_GET_normal(self):
from google.cloud.storage.batch import _FutureDict
url = "http://example.com/api"
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
target = _MockObject()
response = batch._make_request("GET", url, target_object=target)
# Check the respone
self.assertEqual(response.status_code, 204)
self.assertIsInstance(response.json(), _FutureDict)
self.assertIsInstance(response.content, _FutureDict)
self.assertIs(target._properties, response.content)
# The real http request should not have been called yet.
http.request.assert_not_called()
# Check the queued request
self.assertEqual(len(batch._requests), 1)
request = batch._requests[0]
request_method, request_url, _, request_data, _ = request
self.assertEqual(request_method, "GET")
self.assertEqual(request_url, url)
self.assertIsNone(request_data)
def test__make_request_POST_normal(self):
from google.cloud.storage.batch import _FutureDict
url = "http://example.com/api"
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
data = {"foo": 1}
target = _MockObject()
response = batch._make_request(
"POST", url, data={"foo": 1}, target_object=target
)
self.assertEqual(response.status_code, 204)
self.assertIsInstance(response.content, _FutureDict)
self.assertIs(target._properties, response.content)
# The real http request should not have been called yet.
http.request.assert_not_called()
request = batch._requests[0]
request_method, request_url, _, request_data, _ = request
self.assertEqual(request_method, "POST")
self.assertEqual(request_url, url)
self.assertEqual(request_data, data)
def test__make_request_PATCH_normal(self):
from google.cloud.storage.batch import _FutureDict
url = "http://example.com/api"
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
data = {"foo": 1}
target = _MockObject()
response = batch._make_request(
"PATCH", url, data={"foo": 1}, target_object=target
)
self.assertEqual(response.status_code, 204)
self.assertIsInstance(response.content, _FutureDict)
self.assertIs(target._properties, response.content)
# The real http request should not have been called yet.
http.request.assert_not_called()
request = batch._requests[0]
request_method, request_url, _, request_data, _ = request
self.assertEqual(request_method, "PATCH")
self.assertEqual(request_url, url)
self.assertEqual(request_data, data)
def test__make_request_DELETE_normal(self):
from google.cloud.storage.batch import _FutureDict
url = "http://example.com/api"
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
target = _MockObject()
response = batch._make_request("DELETE", url, target_object=target)
# Check the respone
self.assertEqual(response.status_code, 204)
self.assertIsInstance(response.content, _FutureDict)
self.assertIs(target._properties, response.content)
# The real http request should not have been called yet.
http.request.assert_not_called()
# Check the queued request
self.assertEqual(len(batch._requests), 1)
request = batch._requests[0]
request_method, request_url, _, request_data, _ = request
self.assertEqual(request_method, "DELETE")
self.assertEqual(request_url, url)
self.assertIsNone(request_data)
def test__make_request_POST_too_many_requests(self):
url = "http://example.com/api"
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
batch._MAX_BATCH_SIZE = 1
batch._requests.append(("POST", url, {}, {"bar": 2}))
with self.assertRaises(ValueError):
batch._make_request("POST", url, data={"foo": 1})
def test_finish_empty(self):
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
with self.assertRaises(ValueError):
batch.finish()
def _get_payload_chunks(self, boundary, payload):
divider = "--" + boundary[len('boundary="') : -1]
chunks = payload.split(divider)[1:-1] # discard prolog / epilog
return chunks
def _check_subrequest_no_payload(self, chunk, method, url):
lines = chunk.splitlines()
# blank + 2 headers + blank + request + blank + blank
self.assertEqual(len(lines), 7)
self.assertEqual(lines[0], "")
self.assertEqual(lines[1], "Content-Type: application/http")
self.assertEqual(lines[2], "MIME-Version: 1.0")
self.assertEqual(lines[3], "")
self.assertEqual(lines[4], f"{method} {url} HTTP/1.1")
self.assertEqual(lines[5], "")
self.assertEqual(lines[6], "")
def _check_subrequest_payload(self, chunk, method, url, payload):
import json
lines = chunk.splitlines()
# blank + 2 headers + blank + request + 2 headers + blank + body
payload_str = json.dumps(payload)
self.assertEqual(lines[0], "")
self.assertEqual(lines[1], "Content-Type: application/http")
self.assertEqual(lines[2], "MIME-Version: 1.0")
self.assertEqual(lines[3], "")
self.assertEqual(lines[4], f"{method} {url} HTTP/1.1")
if method == "GET":
self.assertEqual(len(lines), 7)
self.assertEqual(lines[5], "")
self.assertEqual(lines[6], "")
else:
self.assertEqual(len(lines), 9)
self.assertEqual(lines[5], f"Content-Length: {len(payload_str)}")
self.assertEqual(lines[6], "Content-Type: application/json")
self.assertEqual(lines[7], "")
self.assertEqual(json.loads(lines[8]), payload)
def _get_mutlipart_request(self, http):
request_call = http.request.mock_calls[0][2]
request_headers = request_call["headers"]
request_body = request_call["data"]
content_type, boundary = [
value.strip() for value in request_headers["Content-Type"].split(";")
]
return request_headers, request_body, content_type, boundary
def test_finish_nonempty(self):
url = "http://api.example.com/other_api"
expected_response = _make_response(
content=_THREE_PART_MIME_RESPONSE,
headers={"content-type": 'multipart/mixed; boundary="DEADBEEF="'},
)
http = _make_requests_session([expected_response])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
batch.API_BASE_URL = "http://api.example.com"
batch._do_request("POST", url, {}, {"foo": 1, "bar": 2}, None)
batch._do_request("PATCH", url, {}, {"bar": 3}, None)
batch._do_request("DELETE", url, {}, None, None)
result = batch.finish()
self.assertEqual(len(result), len(batch._requests))
self.assertEqual(len(result), len(batch._responses))
response1, response2, response3 = result
self.assertEqual(
response1.headers,
{"Content-Length": "20", "Content-Type": "application/json; charset=UTF-8"},
)
self.assertEqual(response1.json(), {"foo": 1, "bar": 2})
self.assertEqual(
response2.headers,
{"Content-Length": "20", "Content-Type": "application/json; charset=UTF-8"},
)
self.assertEqual(response2.json(), {"foo": 1, "bar": 3})
self.assertEqual(response3.headers, {"Content-Length": "0"})
self.assertEqual(response3.status_code, NO_CONTENT)
expected_url = f"{batch.API_BASE_URL}/batch/storage/v1"
http.request.assert_called_once_with(
method="POST",
url=expected_url,
headers=mock.ANY,
data=mock.ANY,
timeout=self._get_default_timeout(),
)
request_info = self._get_mutlipart_request(http)
request_headers, request_body, content_type, boundary = request_info
self.assertEqual(content_type, "multipart/mixed")
self.assertTrue(boundary.startswith('boundary="=='))
self.assertTrue(boundary.endswith('=="'))
self.assertEqual(request_headers["MIME-Version"], "1.0")
chunks = self._get_payload_chunks(boundary, request_body)
self.assertEqual(len(chunks), 3)
self._check_subrequest_payload(chunks[0], "POST", url, {"foo": 1, "bar": 2})
self._check_subrequest_payload(chunks[1], "PATCH", url, {"bar": 3})
self._check_subrequest_no_payload(chunks[2], "DELETE", url)
def test_finish_responses_mismatch(self):
url = "http://api.example.com/other_api"
expected_response = _make_response(
content=_TWO_PART_MIME_RESPONSE_WITH_FAIL,
headers={"content-type": 'multipart/mixed; boundary="DEADBEEF="'},
)
http = _make_requests_session([expected_response])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
batch.API_BASE_URL = "http://api.example.com"
batch._requests.append(("GET", url, {}, None))
with self.assertRaises(ValueError):
batch.finish()
def test_finish_nonempty_with_status_failure(self):
from google.cloud.exceptions import NotFound
url = "http://api.example.com/other_api"
expected_response = _make_response(
content=_TWO_PART_MIME_RESPONSE_WITH_FAIL,
headers={"content-type": 'multipart/mixed; boundary="DEADBEEF="'},
)
http = _make_requests_session([expected_response])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
batch.API_BASE_URL = "http://api.example.com"
target1 = _MockObject()
target2 = _MockObject()
batch._do_request("GET", url, {}, None, target1, timeout=42)
batch._do_request("GET", url, {}, None, target2, timeout=420)
# Make sure futures are not populated.
self.assertEqual(
[future for future in batch._target_objects], [target1, target2]
)
target2_future_before = target2._properties
with self.assertRaises(NotFound):
batch.finish()
self.assertEqual(target1._properties, {"foo": 1, "bar": 2})
self.assertIs(target2._properties, target2_future_before)
expected_url = f"{batch.API_BASE_URL}/batch/storage/v1"
http.request.assert_called_once_with(
method="POST",
url=expected_url,
headers=mock.ANY,
data=mock.ANY,
timeout=420, # the last request timeout prevails
)
_, request_body, _, boundary = self._get_mutlipart_request(http)
chunks = self._get_payload_chunks(boundary, request_body)
self.assertEqual(len(chunks), 2)
self._check_subrequest_payload(chunks[0], "GET", url, {})
self._check_subrequest_payload(chunks[1], "GET", url, {})
def test_finish_no_raise_exception(self):
url = "http://api.example.com/other_api"
expected_response = _make_response(
content=_TWO_PART_MIME_RESPONSE_WITH_FAIL,
headers={"content-type": 'multipart/mixed; boundary="DEADBEEF="'},
)
http = _make_requests_session([expected_response])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
batch.API_BASE_URL = "http://api.example.com"
target1 = _MockObject()
target2 = _MockObject()
batch._do_request("GET", url, {}, None, target1, timeout=42)
batch._do_request("GET", url, {}, None, target2, timeout=420)
# Make sure futures are not populated.
self.assertEqual(
[future for future in batch._target_objects], [target1, target2]
)
batch.finish(raise_exception=False)
self.assertEqual(len(batch._requests), 2)
self.assertEqual(len(batch._responses), 2)
# Make sure NotFound exception is added to responses and target2
self.assertEqual(target1._properties, {"foo": 1, "bar": 2})
self.assertEqual(target2._properties, {"error": {"message": "Not Found"}})
expected_url = f"{batch.API_BASE_URL}/batch/storage/v1"
http.request.assert_called_once_with(
method="POST",
url=expected_url,
headers=mock.ANY,
data=mock.ANY,
timeout=420, # the last request timeout prevails
)
_, request_body, _, boundary = self._get_mutlipart_request(http)
chunks = self._get_payload_chunks(boundary, request_body)
self.assertEqual(len(chunks), 2)
self._check_subrequest_payload(chunks[0], "GET", url, {})
self._check_subrequest_payload(chunks[1], "GET", url, {})
self.assertEqual(batch._responses[0].status_code, 200)
self.assertEqual(batch._responses[1].status_code, 404)
def test_finish_nonempty_non_multipart_response(self):
url = "http://api.example.com/other_api"
http = _make_requests_session([_make_response()])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
batch._requests.append(("POST", url, {}, {"foo": 1, "bar": 2}))
with self.assertRaises(ValueError):
batch.finish()
def test_finish_multipart_response_with_status_failure(self):
from google.cloud.exceptions import ServiceUnavailable
url = "http://api.example.com/other_api"
expected_response = _make_response(
status=SERVICE_UNAVAILABLE,
headers={"content-type": 'multipart/mixed; boundary="DEADBEEF="'},
)
http = _make_requests_session([expected_response])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
batch.API_BASE_URL = "http://api.example.com"
batch._requests.append(("POST", url, {}, {"foo": 1, "bar": 2}, None))
with self.assertRaises(ServiceUnavailable):
batch.finish()
def test_as_context_mgr_wo_error(self):
from google.cloud.storage.client import Client
url = "http://example.com/api"
expected_response = _make_response(
content=_THREE_PART_MIME_RESPONSE,
headers={"content-type": 'multipart/mixed; boundary="DEADBEEF="'},
)
http = _make_requests_session([expected_response])
project = "PROJECT"
credentials = _make_credentials()
client = Client(project=project, credentials=credentials)
client._http_internal = http
self.assertEqual(list(client._batch_stack), [])
target1 = _MockObject()
target2 = _MockObject()
target3 = _MockObject()
with self._make_one(client) as batch:
self.assertEqual(list(client._batch_stack), [batch])
batch._make_request(
"POST", url, {"foo": 1, "bar": 2}, target_object=target1
)
batch._make_request("PATCH", url, {"bar": 3}, target_object=target2)
batch._make_request("DELETE", url, target_object=target3)
self.assertEqual(list(client._batch_stack), [])
self.assertEqual(len(batch._requests), 3)
self.assertEqual(len(batch._responses), 3)
self.assertEqual(batch._requests[0][0], "POST")
self.assertEqual(batch._requests[1][0], "PATCH")
self.assertEqual(batch._requests[2][0], "DELETE")
self.assertEqual(batch._target_objects, [target1, target2, target3])
self.assertEqual(target1._properties, {"foo": 1, "bar": 2})
self.assertEqual(target2._properties, {"foo": 1, "bar": 3})
self.assertEqual(target3._properties, b"")
def test_as_context_mgr_no_raise_exception(self):
from google.cloud.storage.client import Client
url = "http://api.example.com/other_api"
expected_response = _make_response(
content=_TWO_PART_MIME_RESPONSE_WITH_FAIL,
headers={"content-type": 'multipart/mixed; boundary="DEADBEEF="'},
)
http = _make_requests_session([expected_response])
project = "PROJECT"
credentials = _make_credentials()
client = Client(project=project, credentials=credentials)
client._http_internal = http
self.assertEqual(list(client._batch_stack), [])
target1 = _MockObject()
target2 = _MockObject()
with self._make_one(client, raise_exception=False) as batch:
self.assertEqual(list(client._batch_stack), [batch])
batch._make_request("GET", url, {}, target_object=target1)
batch._make_request("GET", url, {}, target_object=target2)
self.assertEqual(list(client._batch_stack), [])
self.assertEqual(len(batch._requests), 2)
self.assertEqual(len(batch._responses), 2)
self.assertEqual(batch._requests[0][0], "GET")
self.assertEqual(batch._requests[1][0], "GET")
self.assertEqual(batch._target_objects, [target1, target2])
# Make sure NotFound exception is added to responses and target2
self.assertEqual(batch._responses[0].status_code, 200)
self.assertEqual(batch._responses[1].status_code, 404)
self.assertEqual(target1._properties, {"foo": 1, "bar": 2})
self.assertEqual(target2._properties, {"error": {"message": "Not Found"}})
def test_as_context_mgr_w_error(self):
from google.cloud.storage.batch import _FutureDict
from google.cloud.storage.client import Client
URL = "http://example.com/api"
http = _make_requests_session([])
connection = _Connection(http=http)
project = "PROJECT"
credentials = _make_credentials()
client = Client(project=project, credentials=credentials)
client._base_connection = connection
self.assertEqual(list(client._batch_stack), [])
target1 = _MockObject()
target2 = _MockObject()
target3 = _MockObject()
try:
with self._make_one(client) as batch:
self.assertEqual(list(client._batch_stack), [batch])
batch._make_request(
"POST", URL, {"foo": 1, "bar": 2}, target_object=target1
)
batch._make_request("PATCH", URL, {"bar": 3}, target_object=target2)
batch._make_request("DELETE", URL, target_object=target3)
raise ValueError()
except ValueError:
pass
http.request.assert_not_called()
self.assertEqual(list(client._batch_stack), [])
self.assertEqual(len(batch._requests), 3)
self.assertEqual(batch._target_objects, [target1, target2, target3])
# Since the context manager fails, finish will not get called and
# the _properties will still be futures.
self.assertIsInstance(target1._properties, _FutureDict)
self.assertIsInstance(target2._properties, _FutureDict)
self.assertIsInstance(target3._properties, _FutureDict)
def test_respect_client_existing_connection(self):
client_endpoint = "http://localhost:9023"
http = _make_requests_session([])
connection = _Connection(http=http, api_endpoint=client_endpoint)
client = _Client(connection)
batch = self._make_one(client)
self.assertEqual(batch.API_BASE_URL, client_endpoint)
self.assertEqual(batch._client._connection.API_BASE_URL, client_endpoint)
def test_use_default_api_without_existing_connection(self):
default_api_endpoint = "https://storage.googleapis.com"
http = _make_requests_session([])
connection = _Connection(http=http)
client = _Client(connection)
batch = self._make_one(client)
self.assertEqual(batch.API_BASE_URL, default_api_endpoint)
self.assertIsNone(batch._client._connection.API_BASE_URL)
self.assertIsNone(batch._client._connection._client_info)
class Test__unpack_batch_response(unittest.TestCase):
def _call_fut(self, headers, content):
from google.cloud.storage.batch import _unpack_batch_response
response = _make_response(content=content, headers=headers)
return _unpack_batch_response(response)
def _unpack_helper(self, response, content):
result = list(self._call_fut(response, content))
self.assertEqual(len(result), 3)
self.assertEqual(result[0].status_code, http.client.OK)
self.assertEqual(result[0].json(), {"bar": 2, "foo": 1})
self.assertEqual(result[1].status_code, http.client.OK)
self.assertEqual(result[1].json(), {"foo": 1, "bar": 3})
self.assertEqual(result[2].status_code, http.client.NO_CONTENT)
def test_bytes_headers(self):
RESPONSE = {"content-type": b'multipart/mixed; boundary="DEADBEEF="'}
CONTENT = _THREE_PART_MIME_RESPONSE
self._unpack_helper(RESPONSE, CONTENT)
def test_unicode_headers(self):
RESPONSE = {"content-type": 'multipart/mixed; boundary="DEADBEEF="'}
CONTENT = _THREE_PART_MIME_RESPONSE
self._unpack_helper(RESPONSE, CONTENT)
_TWO_PART_MIME_RESPONSE_WITH_FAIL = b"""\
--DEADBEEF=
Content-Type: application/json
Content-ID: <response-8a09ca85-8d1d-4f45-9eb0-da8e8b07ec83+1>
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Content-Length: 20
{"foo": 1, "bar": 2}
--DEADBEEF=
Content-Type: application/json
Content-ID: <response-8a09ca85-8d1d-4f45-9eb0-da8e8b07ec83+2>
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=UTF-8
Content-Length: 35
{"error": {"message": "Not Found"}}
--DEADBEEF=--
"""
_THREE_PART_MIME_RESPONSE = b"""\
--DEADBEEF=
Content-Type: application/json
Content-ID: <response-8a09ca85-8d1d-4f45-9eb0-da8e8b07ec83+1>
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Content-Length: 20
{"foo": 1, "bar": 2}
--DEADBEEF=
Content-Type: application/json
Content-ID: <response-8a09ca85-8d1d-4f45-9eb0-da8e8b07ec83+2>
HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Content-Length: 20
{"foo": 1, "bar": 3}
--DEADBEEF=
Content-Type: text/plain
Content-ID: <response-8a09ca85-8d1d-4f45-9eb0-da8e8b07ec83+3>
HTTP/1.1 204 No Content
Content-Length: 0
--DEADBEEF=--
"""
class Test__FutureDict(unittest.TestCase):
def _make_one(self, *args, **kw):
from google.cloud.storage.batch import _FutureDict
return _FutureDict(*args, **kw)
def test_get(self):
future = self._make_one()
self.assertRaises(KeyError, future.get, None)
def test___getitem__(self):
future = self._make_one()
value = orig_value = object()
with self.assertRaises(KeyError):
value = future[None]
self.assertIs(value, orig_value)
def test___setitem__(self):
future = self._make_one()
with self.assertRaises(KeyError):
future[None] = None
class _Connection(object):
project = "TESTING"
def __init__(self, **kw):
self.__dict__.update(kw)
self._client_info = kw.get("client_info", None)
self.API_BASE_URL = kw.get("api_endpoint", None)
def _make_request(self, method, url, data=None, headers=None, timeout=None):
return self.http.request(
url=url, method=method, headers=headers, data=data, timeout=timeout
)
class _MockObject(object):
pass
class _Client(object):
def __init__(self, connection):
self._base_connection = connection
self._connection = connection
|