File size: 56,142 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 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 |
#!/usr/bin/env python
#
# Copyright 2014 Google Inc. All Rights Reserved.
#
# 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.
"""Http tests
Unit tests for the googleapiclient.http.
"""
from __future__ import absolute_import
__author__ = "jcgregorio@google.com (Joe Gregorio)"
import io
from io import FileIO
# Do not remove the httplib2 import
import json
import logging
import os
import random
import socket
import ssl
import time
import unittest
from unittest import mock
import urllib
import httplib2
from googleapiclient.discovery import build
from googleapiclient.errors import BatchError, HttpError, InvalidChunkSizeError
from googleapiclient.http import (
MAX_URI_LENGTH,
BatchHttpRequest,
HttpMock,
HttpMockSequence,
HttpRequest,
MediaFileUpload,
MediaInMemoryUpload,
MediaIoBaseDownload,
MediaIoBaseUpload,
MediaUpload,
_StreamSlice,
build_http,
set_user_agent,
)
from googleapiclient.model import JsonModel
class MockCredentials:
"""Mock class for all Credentials objects."""
def __init__(self, bearer_token, expired=False):
super(MockCredentials, self).__init__()
self._authorized = 0
self._refreshed = 0
self._applied = 0
self._bearer_token = bearer_token
self._access_token_expired = expired
@property
def access_token(self):
return self._bearer_token
@property
def access_token_expired(self):
return self._access_token_expired
def authorize(self, http):
self._authorized += 1
request_orig = http.request
# The closure that will replace 'httplib2.Http.request'.
def new_request(
uri,
method="GET",
body=None,
headers=None,
redirections=httplib2.DEFAULT_MAX_REDIRECTS,
connection_type=None,
):
# Modify the request headers to add the appropriate
# Authorization header.
if headers is None:
headers = {}
self.apply(headers)
resp, content = request_orig(
uri, method, body, headers, redirections, connection_type
)
return resp, content
# Replace the request method with our own closure.
http.request = new_request
# Set credentials as a property of the request method.
setattr(http.request, "credentials", self)
return http
def refresh(self, http):
self._refreshed += 1
def apply(self, headers):
self._applied += 1
headers["authorization"] = self._bearer_token + " " + str(self._refreshed)
class HttpMockWithErrors(object):
def __init__(self, num_errors, success_json, success_data):
self.num_errors = num_errors
self.success_json = success_json
self.success_data = success_data
def request(self, *args, **kwargs):
if not self.num_errors:
return httplib2.Response(self.success_json), self.success_data
elif self.num_errors == 5:
ex = ConnectionResetError # noqa: F821
elif self.num_errors == 4:
ex = httplib2.ServerNotFoundError()
elif self.num_errors == 3:
ex = OSError()
ex.errno = socket.errno.EPIPE
elif self.num_errors == 2:
ex = ssl.SSLError()
else:
# Initialize the timeout error code to the platform's error code.
try:
# For Windows:
ex = OSError()
ex.errno = socket.errno.WSAETIMEDOUT
except AttributeError:
# For Linux/Mac:
ex = socket.timeout()
self.num_errors -= 1
raise ex
class HttpMockWithNonRetriableErrors(object):
def __init__(self, num_errors, success_json, success_data):
self.num_errors = num_errors
self.success_json = success_json
self.success_data = success_data
def request(self, *args, **kwargs):
if not self.num_errors:
return httplib2.Response(self.success_json), self.success_data
else:
self.num_errors -= 1
ex = OSError()
# set errno to a non-retriable value
try:
# For Windows:
ex.errno = socket.errno.WSAEHOSTUNREACH
except AttributeError:
# For Linux/Mac:
ex.errno = socket.errno.EHOSTUNREACH
# Now raise the correct timeout error.
raise ex
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
def datafile(filename):
return os.path.join(DATA_DIR, filename)
def _postproc_none(*kwargs):
pass
class TestUserAgent(unittest.TestCase):
def test_set_user_agent(self):
http = HttpMockSequence([({"status": "200"}, "echo_request_headers")])
http = set_user_agent(http, "my_app/5.5")
resp, content = http.request("http://example.com")
self.assertEqual("my_app/5.5", content["user-agent"])
def test_set_user_agent_nested(self):
http = HttpMockSequence([({"status": "200"}, "echo_request_headers")])
http = set_user_agent(http, "my_app/5.5")
http = set_user_agent(http, "my_library/0.1")
resp, content = http.request("http://example.com")
self.assertEqual("my_app/5.5 my_library/0.1", content["user-agent"])
class TestMediaUpload(unittest.TestCase):
def test_media_file_upload_closes_fd_in___del__(self):
file_desc = mock.Mock(spec=io.TextIOWrapper)
opener = mock.mock_open(file_desc)
with mock.patch("builtins.open", return_value=opener):
upload = MediaFileUpload(datafile("test_close"), mimetype="text/plain")
self.assertIs(upload.stream(), file_desc)
del upload
file_desc.close.assert_called_once_with()
def test_media_file_upload_mimetype_detection(self):
upload = MediaFileUpload(datafile("small.png"))
self.assertEqual("image/png", upload.mimetype())
upload = MediaFileUpload(datafile("empty"))
self.assertEqual("application/octet-stream", upload.mimetype())
def test_media_file_upload_to_from_json(self):
upload = MediaFileUpload(datafile("small.png"), chunksize=500, resumable=True)
self.assertEqual("image/png", upload.mimetype())
self.assertEqual(190, upload.size())
self.assertEqual(True, upload.resumable())
self.assertEqual(500, upload.chunksize())
self.assertEqual(b"PNG", upload.getbytes(1, 3))
json = upload.to_json()
new_upload = MediaUpload.new_from_json(json)
self.assertEqual("image/png", new_upload.mimetype())
self.assertEqual(190, new_upload.size())
self.assertEqual(True, new_upload.resumable())
self.assertEqual(500, new_upload.chunksize())
self.assertEqual(b"PNG", new_upload.getbytes(1, 3))
def test_media_file_upload_raises_on_file_not_found(self):
with self.assertRaises(FileNotFoundError):
MediaFileUpload(datafile("missing.png"))
def test_media_file_upload_raises_on_invalid_chunksize(self):
self.assertRaises(
InvalidChunkSizeError,
MediaFileUpload,
datafile("small.png"),
mimetype="image/png",
chunksize=-2,
resumable=True,
)
def test_media_inmemory_upload(self):
media = MediaInMemoryUpload(
b"abcdef", mimetype="text/plain", chunksize=10, resumable=True
)
self.assertEqual("text/plain", media.mimetype())
self.assertEqual(10, media.chunksize())
self.assertTrue(media.resumable())
self.assertEqual(b"bc", media.getbytes(1, 2))
self.assertEqual(6, media.size())
def test_http_request_to_from_json(self):
http = build_http()
media_upload = MediaFileUpload(
datafile("small.png"), chunksize=500, resumable=True
)
req = HttpRequest(
http,
_postproc_none,
"http://example.com",
method="POST",
body="{}",
headers={"content-type": 'multipart/related; boundary="---flubber"'},
methodId="foo",
resumable=media_upload,
)
json = req.to_json()
new_req = HttpRequest.from_json(json, http, _postproc_none)
self.assertEqual(
{"content-type": 'multipart/related; boundary="---flubber"'},
new_req.headers,
)
self.assertEqual("http://example.com", new_req.uri)
self.assertEqual("{}", new_req.body)
self.assertEqual(http, new_req.http)
self.assertEqual(media_upload.to_json(), new_req.resumable.to_json())
self.assertEqual(random.random, new_req._rand)
self.assertEqual(time.sleep, new_req._sleep)
class TestMediaIoBaseUpload(unittest.TestCase):
def test_media_io_base_upload_from_file_io(self):
fd = FileIO(datafile("small.png"), "r")
upload = MediaIoBaseUpload(
fd=fd, mimetype="image/png", chunksize=500, resumable=True
)
self.assertEqual("image/png", upload.mimetype())
self.assertEqual(190, upload.size())
self.assertEqual(True, upload.resumable())
self.assertEqual(500, upload.chunksize())
self.assertEqual(b"PNG", upload.getbytes(1, 3))
def test_media_io_base_upload_from_file_object(self):
f = open(datafile("small.png"), "rb")
upload = MediaIoBaseUpload(
fd=f, mimetype="image/png", chunksize=500, resumable=True
)
self.assertEqual("image/png", upload.mimetype())
self.assertEqual(190, upload.size())
self.assertEqual(True, upload.resumable())
self.assertEqual(500, upload.chunksize())
self.assertEqual(b"PNG", upload.getbytes(1, 3))
f.close()
def test_media_io_base_upload_serializable(self):
f = open(datafile("small.png"), "rb")
upload = MediaIoBaseUpload(fd=f, mimetype="image/png")
try:
json = upload.to_json()
self.fail("MediaIoBaseUpload should not be serializable.")
except NotImplementedError:
pass
def test_media_io_base_upload_from_bytes(self):
f = open(datafile("small.png"), "rb")
fd = io.BytesIO(f.read())
upload = MediaIoBaseUpload(
fd=fd, mimetype="image/png", chunksize=500, resumable=True
)
self.assertEqual("image/png", upload.mimetype())
self.assertEqual(190, upload.size())
self.assertEqual(True, upload.resumable())
self.assertEqual(500, upload.chunksize())
self.assertEqual(b"PNG", upload.getbytes(1, 3))
def test_media_io_base_upload_raises_on_invalid_chunksize(self):
f = open(datafile("small.png"), "rb")
fd = io.BytesIO(f.read())
self.assertRaises(
InvalidChunkSizeError,
MediaIoBaseUpload,
fd,
"image/png",
chunksize=-2,
resumable=True,
)
def test_media_io_base_upload_streamable(self):
fd = io.BytesIO(b"stuff")
upload = MediaIoBaseUpload(
fd=fd, mimetype="image/png", chunksize=500, resumable=True
)
self.assertEqual(True, upload.has_stream())
self.assertEqual(fd, upload.stream())
def test_media_io_base_next_chunk_retries(self):
f = open(datafile("small.png"), "rb")
fd = io.BytesIO(f.read())
upload = MediaIoBaseUpload(
fd=fd, mimetype="image/png", chunksize=500, resumable=True
)
# Simulate errors for both the request that creates the resumable upload
# and the upload itself.
http = HttpMockSequence(
[
({"status": "500"}, ""),
({"status": "500"}, ""),
({"status": "503"}, ""),
({"status": "200", "location": "location"}, ""),
({"status": "403"}, USER_RATE_LIMIT_EXCEEDED_RESPONSE_NO_STATUS),
({"status": "403"}, RATE_LIMIT_EXCEEDED_RESPONSE),
({"status": "429"}, ""),
({"status": "200"}, "{}"),
]
)
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
method = "POST"
request = HttpRequest(
http, model.response, uri, method=method, headers={}, resumable=upload
)
sleeptimes = []
request._sleep = lambda x: sleeptimes.append(x)
request._rand = lambda: 10
request.execute(num_retries=3)
self.assertEqual([20, 40, 80, 20, 40, 80], sleeptimes)
def test_media_io_base_next_chunk_no_retry_403_not_configured(self):
fd = io.BytesIO(b"i am png")
upload = MediaIoBaseUpload(
fd=fd, mimetype="image/png", chunksize=500, resumable=True
)
http = HttpMockSequence(
[({"status": "403"}, NOT_CONFIGURED_RESPONSE), ({"status": "200"}, "{}")]
)
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
method = "POST"
request = HttpRequest(
http, model.response, uri, method=method, headers={}, resumable=upload
)
request._rand = lambda: 1.0
request._sleep = mock.MagicMock()
with self.assertRaises(HttpError):
request.execute(num_retries=3)
request._sleep.assert_not_called()
def test_media_io_base_empty_file(self):
fd = io.BytesIO()
upload = MediaIoBaseUpload(
fd=fd, mimetype="image/png", chunksize=500, resumable=True
)
http = HttpMockSequence(
[
(
{
"status": "200",
"location": "https://www.googleapis.com/someapi/v1/upload?foo=bar",
},
"{}",
),
(
{
"status": "200",
"location": "https://www.googleapis.com/someapi/v1/upload?foo=bar",
},
"{}",
),
]
)
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
method = "POST"
request = HttpRequest(
http, model.response, uri, method=method, headers={}, resumable=upload
)
request.execute()
# Check that "Content-Range" header is not set in the PUT request
self.assertTrue("Content-Range" not in http.request_sequence[-1][-1])
self.assertEqual("0", http.request_sequence[-1][-1]["Content-Length"])
class TestMediaIoBaseDownload(unittest.TestCase):
def setUp(self):
http = HttpMock(datafile("zoo.json"), {"status": "200"})
zoo = build("zoo", "v1", http=http, static_discovery=False)
self.request = zoo.animals().get_media(name="Lion")
self.fd = io.BytesIO()
def test_media_io_base_download(self):
self.request.http = HttpMockSequence(
[
({"status": "200", "content-range": "0-2/5"}, b"123"),
({"status": "200", "content-range": "3-4/5"}, b"45"),
]
)
self.assertEqual(True, self.request.http.follow_redirects)
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
self.assertEqual(self.fd, download._fd)
self.assertEqual(3, download._chunksize)
self.assertEqual(0, download._progress)
self.assertEqual(None, download._total_size)
self.assertEqual(False, download._done)
self.assertEqual(self.request.uri, download._uri)
status, done = download.next_chunk()
self.assertEqual(self.fd.getvalue(), b"123")
self.assertEqual(False, done)
self.assertEqual(3, download._progress)
self.assertEqual(5, download._total_size)
self.assertEqual(3, status.resumable_progress)
status, done = download.next_chunk()
self.assertEqual(self.fd.getvalue(), b"12345")
self.assertEqual(True, done)
self.assertEqual(5, download._progress)
self.assertEqual(5, download._total_size)
def test_media_io_base_download_range_request_header(self):
self.request.http = HttpMockSequence(
[
(
{"status": "200", "content-range": "0-2/5"},
"echo_request_headers_as_json",
),
]
)
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
status, done = download.next_chunk()
result = json.loads(self.fd.getvalue().decode("utf-8"))
self.assertEqual(result.get("range"), "bytes=0-2")
def test_media_io_base_download_custom_request_headers(self):
self.request.http = HttpMockSequence(
[
(
{"status": "200", "content-range": "0-2/5"},
"echo_request_headers_as_json",
),
(
{"status": "200", "content-range": "3-4/5"},
"echo_request_headers_as_json",
),
]
)
self.assertEqual(True, self.request.http.follow_redirects)
self.request.headers["Cache-Control"] = "no-store"
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
self.assertEqual(download._headers.get("Cache-Control"), "no-store")
status, done = download.next_chunk()
result = json.loads(self.fd.getvalue().decode("utf-8"))
# assert that that the header we added to the original request is
# sent up to the server on each call to next_chunk
self.assertEqual(result.get("Cache-Control"), "no-store")
download._fd = self.fd = io.BytesIO()
status, done = download.next_chunk()
result = json.loads(self.fd.getvalue().decode("utf-8"))
self.assertEqual(result.get("Cache-Control"), "no-store")
def test_media_io_base_download_handle_redirects(self):
self.request.http = HttpMockSequence(
[
(
{
"status": "200",
"content-location": "https://secure.example.net/lion",
},
b"",
),
({"status": "200", "content-range": "0-2/5"}, b"abc"),
]
)
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
status, done = download.next_chunk()
self.assertEqual("https://secure.example.net/lion", download._uri)
def test_media_io_base_download_handle_4xx(self):
self.request.http = HttpMockSequence([({"status": "400"}, "")])
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
try:
status, done = download.next_chunk()
self.fail("Should raise an exception")
except HttpError:
pass
# Even after raising an exception we can pick up where we left off.
self.request.http = HttpMockSequence(
[({"status": "200", "content-range": "0-2/5"}, b"123")]
)
status, done = download.next_chunk()
self.assertEqual(self.fd.getvalue(), b"123")
def test_media_io_base_download_retries_connection_errors(self):
self.request.http = HttpMockWithErrors(
5, {"status": "200", "content-range": "0-2/3"}, b"123"
)
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
download._sleep = lambda _x: 0 # do nothing
download._rand = lambda: 10
status, done = download.next_chunk(num_retries=5)
self.assertEqual(self.fd.getvalue(), b"123")
self.assertEqual(True, done)
def test_media_io_base_download_retries_5xx(self):
self.request.http = HttpMockSequence(
[
({"status": "500"}, ""),
({"status": "500"}, ""),
({"status": "500"}, ""),
({"status": "200", "content-range": "0-2/5"}, b"123"),
({"status": "503"}, ""),
({"status": "503"}, ""),
({"status": "503"}, ""),
({"status": "200", "content-range": "3-4/5"}, b"45"),
]
)
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
self.assertEqual(self.fd, download._fd)
self.assertEqual(3, download._chunksize)
self.assertEqual(0, download._progress)
self.assertEqual(None, download._total_size)
self.assertEqual(False, download._done)
self.assertEqual(self.request.uri, download._uri)
# Set time.sleep and random.random stubs.
sleeptimes = []
download._sleep = lambda x: sleeptimes.append(x)
download._rand = lambda: 10
status, done = download.next_chunk(num_retries=3)
# Check for exponential backoff using the rand function above.
self.assertEqual([20, 40, 80], sleeptimes)
self.assertEqual(self.fd.getvalue(), b"123")
self.assertEqual(False, done)
self.assertEqual(3, download._progress)
self.assertEqual(5, download._total_size)
self.assertEqual(3, status.resumable_progress)
# Reset time.sleep stub.
del sleeptimes[0 : len(sleeptimes)]
status, done = download.next_chunk(num_retries=3)
# Check for exponential backoff using the rand function above.
self.assertEqual([20, 40, 80], sleeptimes)
self.assertEqual(self.fd.getvalue(), b"12345")
self.assertEqual(True, done)
self.assertEqual(5, download._progress)
self.assertEqual(5, download._total_size)
def test_media_io_base_download_empty_file(self):
self.request.http = HttpMockSequence(
[({"status": "200", "content-range": "0-0/0"}, b"")]
)
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
self.assertEqual(self.fd, download._fd)
self.assertEqual(0, download._progress)
self.assertEqual(None, download._total_size)
self.assertEqual(False, download._done)
self.assertEqual(self.request.uri, download._uri)
status, done = download.next_chunk()
self.assertEqual(True, done)
self.assertEqual(0, download._progress)
self.assertEqual(0, download._total_size)
self.assertEqual(0, status.progress())
def test_media_io_base_download_empty_file_416_response(self):
self.request.http = HttpMockSequence(
[({"status": "416", "content-range": "0-0/0"}, b"")]
)
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
self.assertEqual(self.fd, download._fd)
self.assertEqual(0, download._progress)
self.assertEqual(None, download._total_size)
self.assertEqual(False, download._done)
self.assertEqual(self.request.uri, download._uri)
status, done = download.next_chunk()
self.assertEqual(True, done)
self.assertEqual(0, download._progress)
self.assertEqual(0, download._total_size)
self.assertEqual(0, status.progress())
def test_media_io_base_download_unknown_media_size(self):
self.request.http = HttpMockSequence([({"status": "200"}, b"123")])
download = MediaIoBaseDownload(fd=self.fd, request=self.request, chunksize=3)
self.assertEqual(self.fd, download._fd)
self.assertEqual(0, download._progress)
self.assertEqual(None, download._total_size)
self.assertEqual(False, download._done)
self.assertEqual(self.request.uri, download._uri)
status, done = download.next_chunk()
self.assertEqual(self.fd.getvalue(), b"123")
self.assertEqual(True, done)
self.assertEqual(3, download._progress)
self.assertEqual(None, download._total_size)
self.assertEqual(0, status.progress())
EXPECTED = """POST /someapi/v1/collection/?foo=bar HTTP/1.1
Content-Type: application/json
MIME-Version: 1.0
Host: www.googleapis.com
content-length: 2\r\n\r\n{}"""
NO_BODY_EXPECTED = """POST /someapi/v1/collection/?foo=bar HTTP/1.1
Content-Type: application/json
MIME-Version: 1.0
Host: www.googleapis.com
content-length: 0\r\n\r\n"""
NO_BODY_EXPECTED_GET = """GET /someapi/v1/collection/?foo=bar HTTP/1.1
Content-Type: application/json
MIME-Version: 1.0
Host: www.googleapis.com\r\n\r\n"""
RESPONSE = """HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 14
ETag: "etag/pony"\r\n\r\n{"answer": 42}"""
BATCH_RESPONSE = b"""--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: <randomness + 1>
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 14
ETag: "etag/pony"\r\n\r\n{"foo": 42}
--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: <randomness + 2>
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 14
ETag: "etag/sheep"\r\n\r\n{"baz": "qux"}
--batch_foobarbaz--"""
BATCH_ERROR_RESPONSE = b"""--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: <randomness + 1>
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 14
ETag: "etag/pony"\r\n\r\n{"foo": 42}
--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: <randomness + 2>
HTTP/1.1 403 Access Not Configured
Content-Type: application/json
Content-Length: 245
ETag: "etag/sheep"\r\n\r\n{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured",
"debugInfo": "QuotaState: BLOCKED"
}
],
"code": 403,
"message": "Access Not Configured"
}
}
--batch_foobarbaz--"""
BATCH_RESPONSE_WITH_401 = b"""--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: <randomness + 1>
HTTP/1.1 401 Authorization Required
Content-Type: application/json
Content-Length: 14
ETag: "etag/pony"\r\n\r\n{"error": {"message":
"Authorizaton failed."}}
--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: <randomness + 2>
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 14
ETag: "etag/sheep"\r\n\r\n{"baz": "qux"}
--batch_foobarbaz--"""
BATCH_SINGLE_RESPONSE = b"""--batch_foobarbaz
Content-Type: application/http
Content-Transfer-Encoding: binary
Content-ID: <randomness + 1>
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 14
ETag: "etag/pony"\r\n\r\n{"foo": 42}
--batch_foobarbaz--"""
USER_RATE_LIMIT_EXCEEDED_RESPONSE_NO_STATUS = """{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "userRateLimitExceeded",
"message": "User Rate Limit Exceeded"
}
],
"code": 403,
"message": "User Rate Limit Exceeded"
}
}"""
USER_RATE_LIMIT_EXCEEDED_RESPONSE_WITH_STATUS = """{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "userRateLimitExceeded",
"message": "User Rate Limit Exceeded"
}
],
"code": 403,
"message": "User Rate Limit Exceeded",
"status": "PERMISSION_DENIED"
}
}"""
RATE_LIMIT_EXCEEDED_RESPONSE = """{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "rateLimitExceeded",
"message": "Rate Limit Exceeded"
}
],
"code": 403,
"message": "Rate Limit Exceeded"
}
}"""
NOT_CONFIGURED_RESPONSE = """{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured"
}
],
"code": 403,
"message": "Access Not Configured"
}
}"""
LIST_NOT_CONFIGURED_RESPONSE = """[
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured"
}
],
"code": 403,
"message": "Access Not Configured"
}
]"""
class Callbacks(object):
def __init__(self):
self.responses = {}
self.exceptions = {}
def f(self, request_id, response, exception):
self.responses[request_id] = response
self.exceptions[request_id] = exception
class TestHttpRequest(unittest.TestCase):
def test_unicode(self):
http = HttpMock(datafile("zoo.json"), headers={"status": "200"})
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
request.execute()
self.assertEqual(uri, http.uri)
self.assertEqual(str, type(http.uri))
self.assertEqual(method, http.method)
self.assertEqual(str, type(http.method))
def test_empty_content_type(self):
"""Test for #284"""
http = HttpMock(None, headers={"status": 200})
uri = "https://www.googleapis.com/someapi/v1/upload/?foo=bar"
method = "POST"
request = HttpRequest(
http, _postproc_none, uri, method=method, headers={"content-type": ""}
)
request.execute()
self.assertEqual("", http.headers.get("content-type"))
def test_no_retry_connection_errors(self):
model = JsonModel()
request = HttpRequest(
HttpMockWithNonRetriableErrors(1, {"status": "200"}, '{"foo": "bar"}'),
model.response,
"https://www.example.com/json_api_endpoint",
)
request._sleep = lambda _x: 0 # do nothing
request._rand = lambda: 10
with self.assertRaises(OSError):
response = request.execute(num_retries=3)
def test_retry_connection_errors_non_resumable(self):
model = JsonModel()
request = HttpRequest(
HttpMockWithErrors(5, {"status": "200"}, '{"foo": "bar"}'),
model.response,
"https://www.example.com/json_api_endpoint",
)
request._sleep = lambda _x: 0 # do nothing
request._rand = lambda: 10
response = request.execute(num_retries=5)
self.assertEqual({"foo": "bar"}, response)
def test_retry_connection_errors_resumable(self):
with open(datafile("small.png"), "rb") as small_png_file:
small_png_fd = io.BytesIO(small_png_file.read())
upload = MediaIoBaseUpload(
fd=small_png_fd, mimetype="image/png", chunksize=500, resumable=True
)
model = JsonModel()
request = HttpRequest(
HttpMockWithErrors(
5, {"status": "200", "location": "location"}, '{"foo": "bar"}'
),
model.response,
"https://www.example.com/file_upload",
method="POST",
resumable=upload,
)
request._sleep = lambda _x: 0 # do nothing
request._rand = lambda: 10
response = request.execute(num_retries=5)
self.assertEqual({"foo": "bar"}, response)
def test_retry(self):
num_retries = 6
resp_seq = [({"status": "500"}, "")] * (num_retries - 4)
resp_seq.append(({"status": "403"}, RATE_LIMIT_EXCEEDED_RESPONSE))
resp_seq.append(
({"status": "403"}, USER_RATE_LIMIT_EXCEEDED_RESPONSE_NO_STATUS)
)
resp_seq.append(
({"status": "403"}, USER_RATE_LIMIT_EXCEEDED_RESPONSE_WITH_STATUS)
)
resp_seq.append(({"status": "429"}, ""))
resp_seq.append(({"status": "200"}, "{}"))
http = HttpMockSequence(resp_seq)
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
sleeptimes = []
request._sleep = lambda x: sleeptimes.append(x)
request._rand = lambda: 10
request.execute(num_retries=num_retries)
self.assertEqual(num_retries, len(sleeptimes))
for retry_num in range(num_retries):
self.assertEqual(10 * 2 ** (retry_num + 1), sleeptimes[retry_num])
def test_no_retry_succeeds(self):
num_retries = 5
resp_seq = [({"status": "200"}, "{}")] * (num_retries)
http = HttpMockSequence(resp_seq)
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
sleeptimes = []
request._sleep = lambda x: sleeptimes.append(x)
request._rand = lambda: 10
request.execute(num_retries=num_retries)
self.assertEqual(0, len(sleeptimes))
def test_no_retry_fails_fast(self):
http = HttpMockSequence([({"status": "500"}, ""), ({"status": "200"}, "{}")])
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
request._rand = lambda: 1.0
request._sleep = mock.MagicMock()
with self.assertRaises(HttpError):
request.execute()
request._sleep.assert_not_called()
def test_no_retry_403_not_configured_fails_fast(self):
http = HttpMockSequence(
[({"status": "403"}, NOT_CONFIGURED_RESPONSE), ({"status": "200"}, "{}")]
)
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
request._rand = lambda: 1.0
request._sleep = mock.MagicMock()
with self.assertRaises(HttpError):
request.execute()
request._sleep.assert_not_called()
def test_no_retry_403_fails_fast(self):
http = HttpMockSequence([({"status": "403"}, ""), ({"status": "200"}, "{}")])
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
request._rand = lambda: 1.0
request._sleep = mock.MagicMock()
with self.assertRaises(HttpError):
request.execute()
request._sleep.assert_not_called()
def test_no_retry_401_fails_fast(self):
http = HttpMockSequence([({"status": "401"}, ""), ({"status": "200"}, "{}")])
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
request._rand = lambda: 1.0
request._sleep = mock.MagicMock()
with self.assertRaises(HttpError):
request.execute()
request._sleep.assert_not_called()
def test_no_retry_403_list_fails(self):
http = HttpMockSequence(
[
({"status": "403"}, LIST_NOT_CONFIGURED_RESPONSE),
({"status": "200"}, "{}"),
]
)
model = JsonModel()
uri = "https://www.googleapis.com/someapi/v1/collection/?foo=bar"
method = "POST"
request = HttpRequest(
http,
model.response,
uri,
method=method,
body="{}",
headers={"content-type": "application/json"},
)
request._rand = lambda: 1.0
request._sleep = mock.MagicMock()
with self.assertRaises(HttpError):
request.execute()
request._sleep.assert_not_called()
def test_null_postproc(self):
resp, content = HttpRequest.null_postproc("foo", "bar")
self.assertEqual(resp, "foo")
self.assertEqual(content, "bar")
class TestBatch(unittest.TestCase):
def setUp(self):
model = JsonModel()
self.request1 = HttpRequest(
None,
model.response,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="POST",
body="{}",
headers={"content-type": "application/json"},
)
self.request2 = HttpRequest(
None,
model.response,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="GET",
body="",
headers={"content-type": "application/json"},
)
def test_id_to_from_content_id_header(self):
batch = BatchHttpRequest()
self.assertEqual("12", batch._header_to_id(batch._id_to_header("12")))
def test_invalid_content_id_header(self):
batch = BatchHttpRequest()
self.assertRaises(BatchError, batch._header_to_id, "[foo+x]")
self.assertRaises(BatchError, batch._header_to_id, "foo+1")
self.assertRaises(BatchError, batch._header_to_id, "<foo>")
def test_serialize_request(self):
batch = BatchHttpRequest()
request = HttpRequest(
None,
None,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="POST",
body="{}",
headers={"content-type": "application/json"},
methodId=None,
resumable=None,
)
s = batch._serialize_request(request).splitlines()
self.assertEqual(EXPECTED.splitlines(), s)
def test_serialize_request_media_body(self):
batch = BatchHttpRequest()
f = open(datafile("small.png"), "rb")
body = f.read()
f.close()
request = HttpRequest(
None,
None,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="POST",
body=body,
headers={"content-type": "application/json"},
methodId=None,
resumable=None,
)
# Just testing it shouldn't raise an exception.
s = batch._serialize_request(request).splitlines()
def test_serialize_request_no_body(self):
batch = BatchHttpRequest()
request = HttpRequest(
None,
None,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="POST",
body=b"",
headers={"content-type": "application/json"},
methodId=None,
resumable=None,
)
s = batch._serialize_request(request).splitlines()
self.assertEqual(NO_BODY_EXPECTED.splitlines(), s)
def test_serialize_get_request_no_body(self):
batch = BatchHttpRequest()
request = HttpRequest(
None,
None,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="GET",
body=None,
headers={"content-type": "application/json"},
methodId=None,
resumable=None,
)
s = batch._serialize_request(request).splitlines()
self.assertEqual(NO_BODY_EXPECTED_GET.splitlines(), s)
def test_deserialize_response(self):
batch = BatchHttpRequest()
resp, content = batch._deserialize_response(RESPONSE)
self.assertEqual(200, resp.status)
self.assertEqual("OK", resp.reason)
self.assertEqual(11, resp.version)
self.assertEqual('{"answer": 42}', content)
def test_new_id(self):
batch = BatchHttpRequest()
id_ = batch._new_id()
self.assertEqual("1", id_)
id_ = batch._new_id()
self.assertEqual("2", id_)
batch.add(self.request1, request_id="3")
id_ = batch._new_id()
self.assertEqual("4", id_)
def test_add(self):
batch = BatchHttpRequest()
batch.add(self.request1, request_id="1")
self.assertRaises(KeyError, batch.add, self.request1, request_id="1")
def test_add_fail_for_over_limit(self):
from googleapiclient.http import MAX_BATCH_LIMIT
batch = BatchHttpRequest()
for i in range(0, MAX_BATCH_LIMIT):
batch.add(
HttpRequest(
None,
None,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="POST",
body="{}",
headers={"content-type": "application/json"},
)
)
self.assertRaises(BatchError, batch.add, self.request1)
def test_add_fail_for_resumable(self):
batch = BatchHttpRequest()
upload = MediaFileUpload(datafile("small.png"), chunksize=500, resumable=True)
self.request1.resumable = upload
with self.assertRaises(BatchError) as batch_error:
batch.add(self.request1, request_id="1")
str(batch_error.exception)
def test_execute_empty_batch_no_http(self):
batch = BatchHttpRequest()
ret = batch.execute()
self.assertEqual(None, ret)
def test_execute(self):
batch = BatchHttpRequest()
callbacks = Callbacks()
batch.add(self.request1, callback=callbacks.f)
batch.add(self.request2, callback=callbacks.f)
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_RESPONSE,
)
]
)
batch.execute(http=http)
self.assertEqual({"foo": 42}, callbacks.responses["1"])
self.assertEqual(None, callbacks.exceptions["1"])
self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
self.assertEqual(None, callbacks.exceptions["2"])
def test_execute_request_body(self):
batch = BatchHttpRequest()
batch.add(self.request1)
batch.add(self.request2)
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
"echo_request_body",
)
]
)
try:
batch.execute(http=http)
self.fail("Should raise exception")
except BatchError as e:
boundary, _ = e.content.split(None, 1)
self.assertEqual("--", boundary[:2])
parts = e.content.split(boundary)
self.assertEqual(4, len(parts))
self.assertEqual("", parts[0])
self.assertEqual("--", parts[3].rstrip())
header = parts[1].splitlines()[1]
self.assertEqual("Content-Type: application/http", header)
def test_execute_request_body_with_custom_long_request_ids(self):
batch = BatchHttpRequest()
batch.add(self.request1, request_id="abc" * 20)
batch.add(self.request2, request_id="def" * 20)
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
"echo_request_body",
)
]
)
try:
batch.execute(http=http)
self.fail("Should raise exception")
except BatchError as e:
boundary, _ = e.content.split(None, 1)
self.assertEqual("--", boundary[:2])
parts = e.content.split(boundary)
self.assertEqual(4, len(parts))
self.assertEqual("", parts[0])
self.assertEqual("--", parts[3].rstrip())
for partindex, request_id in ((1, "abc" * 20), (2, "def" * 20)):
lines = parts[partindex].splitlines()
for n, line in enumerate(lines):
if line.startswith("Content-ID:"):
# assert correct header folding
self.assertTrue(line.endswith("+"), line)
header_continuation = lines[n + 1]
self.assertEqual(
header_continuation,
" %s>" % request_id,
header_continuation,
)
def test_execute_initial_refresh_oauth2(self):
batch = BatchHttpRequest()
callbacks = Callbacks()
cred = MockCredentials("Foo", expired=True)
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_SINGLE_RESPONSE,
)
]
)
cred.authorize(http)
batch.add(self.request1, callback=callbacks.f)
batch.execute(http=http)
self.assertEqual({"foo": 42}, callbacks.responses["1"])
self.assertIsNone(callbacks.exceptions["1"])
self.assertEqual(1, cred._refreshed)
self.assertEqual(1, cred._authorized)
self.assertEqual(1, cred._applied)
def test_execute_refresh_and_retry_on_401(self):
batch = BatchHttpRequest()
callbacks = Callbacks()
cred_1 = MockCredentials("Foo")
cred_2 = MockCredentials("Bar")
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_RESPONSE_WITH_401,
),
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_SINGLE_RESPONSE,
),
]
)
creds_http_1 = HttpMockSequence([])
cred_1.authorize(creds_http_1)
creds_http_2 = HttpMockSequence([])
cred_2.authorize(creds_http_2)
self.request1.http = creds_http_1
self.request2.http = creds_http_2
batch.add(self.request1, callback=callbacks.f)
batch.add(self.request2, callback=callbacks.f)
batch.execute(http=http)
self.assertEqual({"foo": 42}, callbacks.responses["1"])
self.assertEqual(None, callbacks.exceptions["1"])
self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
self.assertEqual(None, callbacks.exceptions["2"])
self.assertEqual(1, cred_1._refreshed)
self.assertEqual(0, cred_2._refreshed)
self.assertEqual(1, cred_1._authorized)
self.assertEqual(1, cred_2._authorized)
self.assertEqual(1, cred_2._applied)
self.assertEqual(2, cred_1._applied)
def test_http_errors_passed_to_callback(self):
batch = BatchHttpRequest()
callbacks = Callbacks()
cred_1 = MockCredentials("Foo")
cred_2 = MockCredentials("Bar")
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_RESPONSE_WITH_401,
),
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_RESPONSE_WITH_401,
),
]
)
creds_http_1 = HttpMockSequence([])
cred_1.authorize(creds_http_1)
creds_http_2 = HttpMockSequence([])
cred_2.authorize(creds_http_2)
self.request1.http = creds_http_1
self.request2.http = creds_http_2
batch.add(self.request1, callback=callbacks.f)
batch.add(self.request2, callback=callbacks.f)
batch.execute(http=http)
self.assertEqual(None, callbacks.responses["1"])
self.assertEqual(401, callbacks.exceptions["1"].resp.status)
self.assertEqual(
"Authorization Required", callbacks.exceptions["1"].resp.reason
)
self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
self.assertEqual(None, callbacks.exceptions["2"])
def test_execute_global_callback(self):
callbacks = Callbacks()
batch = BatchHttpRequest(callback=callbacks.f)
batch.add(self.request1)
batch.add(self.request2)
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_RESPONSE,
)
]
)
batch.execute(http=http)
self.assertEqual({"foo": 42}, callbacks.responses["1"])
self.assertEqual({"baz": "qux"}, callbacks.responses["2"])
def test_execute_batch_http_error(self):
callbacks = Callbacks()
batch = BatchHttpRequest(callback=callbacks.f)
batch.add(self.request1)
batch.add(self.request2)
http = HttpMockSequence(
[
(
{
"status": "200",
"content-type": 'multipart/mixed; boundary="batch_foobarbaz"',
},
BATCH_ERROR_RESPONSE,
)
]
)
batch.execute(http=http)
self.assertEqual({"foo": 42}, callbacks.responses["1"])
expected = (
"<HttpError 403 when requesting "
"https://www.googleapis.com/someapi/v1/collection/?foo=bar returned "
'"Access Not Configured". '
"Details: \"[{'domain': 'usageLimits', 'reason': 'accessNotConfigured', 'message': 'Access Not Configured', 'debugInfo': 'QuotaState: BLOCKED'}]\">"
)
self.assertEqual(expected, str(callbacks.exceptions["2"]))
class TestRequestUriTooLong(unittest.TestCase):
def test_turn_get_into_post(self):
def _postproc(resp, content):
return content
http = HttpMockSequence(
[
({"status": "200"}, "echo_request_body"),
({"status": "200"}, "echo_request_headers"),
]
)
# Send a long query parameter.
query = {"q": "a" * MAX_URI_LENGTH + "?&"}
req = HttpRequest(
http,
_postproc,
"http://example.com?" + urllib.parse.urlencode(query),
method="GET",
body=None,
headers={},
methodId="foo",
resumable=None,
)
# Query parameters should be sent in the body.
response = req.execute()
self.assertEqual(b"q=" + b"a" * MAX_URI_LENGTH + b"%3F%26", response)
# Extra headers should be set.
response = req.execute()
self.assertEqual("GET", response["x-http-method-override"])
self.assertEqual(str(MAX_URI_LENGTH + 8), response["content-length"])
self.assertEqual("application/x-www-form-urlencoded", response["content-type"])
class TestStreamSlice(unittest.TestCase):
"""Test _StreamSlice."""
def setUp(self):
self.stream = io.BytesIO(b"0123456789")
def test_read(self):
s = _StreamSlice(self.stream, 0, 4)
self.assertEqual(b"", s.read(0))
self.assertEqual(b"0", s.read(1))
self.assertEqual(b"123", s.read())
def test_read_too_much(self):
s = _StreamSlice(self.stream, 1, 4)
self.assertEqual(b"1234", s.read(6))
def test_read_all(self):
s = _StreamSlice(self.stream, 2, 1)
self.assertEqual(b"2", s.read(-1))
class TestResponseCallback(unittest.TestCase):
"""Test adding callbacks to responses."""
def test_ensure_response_callback(self):
m = JsonModel()
request = HttpRequest(
None,
m.response,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="POST",
body="{}",
headers={"content-type": "application/json"},
)
h = HttpMockSequence([({"status": 200}, "{}")])
responses = []
def _on_response(resp, responses=responses):
responses.append(resp)
request.add_response_callback(_on_response)
request.execute(http=h)
self.assertEqual(1, len(responses))
class TestHttpMock(unittest.TestCase):
def test_default_response_headers(self):
http = HttpMock(datafile("zoo.json"))
resp, content = http.request("http://example.com")
self.assertEqual(resp.status, 200)
def test_error_response(self):
http = HttpMock(datafile("bad_request.json"), {"status": "400"})
model = JsonModel()
request = HttpRequest(
http,
model.response,
"https://www.googleapis.com/someapi/v1/collection/?foo=bar",
method="GET",
headers={},
)
self.assertRaises(HttpError, request.execute)
class TestHttpBuild(unittest.TestCase):
original_socket_default_timeout = None
@classmethod
def setUpClass(cls):
cls.original_socket_default_timeout = socket.getdefaulttimeout()
@classmethod
def tearDownClass(cls):
socket.setdefaulttimeout(cls.original_socket_default_timeout)
def test_build_http_sets_default_timeout_if_none_specified(self):
socket.setdefaulttimeout(None)
http = build_http()
self.assertIsInstance(http.timeout, int)
self.assertGreater(http.timeout, 0)
def test_build_http_default_timeout_can_be_overridden(self):
socket.setdefaulttimeout(1.5)
http = build_http()
self.assertAlmostEqual(http.timeout, 1.5, delta=0.001)
def test_build_http_default_timeout_can_be_set_to_zero(self):
socket.setdefaulttimeout(0)
http = build_http()
self.assertEqual(http.timeout, 0)
def test_build_http_default_308_is_excluded_as_redirect(self):
http = build_http()
self.assertTrue(308 not in http.redirect_codes)
if __name__ == "__main__":
logging.getLogger().setLevel(logging.ERROR)
unittest.main()
|