File size: 57,008 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 |
# Copyright 2017 Google Inc.
#
# 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
import io
import sys
import tempfile
from unittest import mock
import pytest # type: ignore
from google.resumable_media import _helpers
from google.resumable_media import _upload
from google.resumable_media import common
URL_PREFIX = "https://www.googleapis.com/upload/storage/v1/b/{BUCKET}/o"
SIMPLE_URL = URL_PREFIX + "?uploadType=media&name={OBJECT}"
MULTIPART_URL = URL_PREFIX + "?uploadType=multipart"
RESUMABLE_URL = URL_PREFIX + "?uploadType=resumable"
ONE_MB = 1024 * 1024
BASIC_CONTENT = "text/plain"
JSON_TYPE = "application/json; charset=UTF-8"
JSON_TYPE_LINE = b"content-type: application/json; charset=UTF-8\r\n"
EXAMPLE_XML_UPLOAD_URL = "https://test-project.storage.googleapis.com/test-bucket"
EXAMPLE_HEADERS = {"example-key": "example-content"}
EXAMPLE_XML_MPU_INITIATE_TEXT_TEMPLATE = """<?xml version="1.0" encoding="UTF-8"?>
<InitiateMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Bucket>travel-maps</Bucket>
<Key>paris.jpg</Key>
<UploadId>{upload_id}</UploadId>
</InitiateMultipartUploadResult>
"""
UPLOAD_ID = "VXBsb2FkIElEIGZvciBlbHZpbmcncyBteS1tb3ZpZS5tMnRzIHVwbG9hZA"
PARTS = {1: "39a59594290b0f9a30662a56d695b71d", 2: "00000000290b0f9a30662a56d695b71d"}
FILE_DATA = b"testdata" * 128
@pytest.fixture(scope="session")
def filename():
with tempfile.NamedTemporaryFile() as f:
f.write(FILE_DATA)
f.flush()
yield f.name
class TestUploadBase(object):
def test_constructor_defaults(self):
upload = _upload.UploadBase(SIMPLE_URL)
assert upload.upload_url == SIMPLE_URL
assert upload._headers == {}
assert not upload._finished
_check_retry_strategy(upload)
def test_constructor_explicit(self):
headers = {"spin": "doctors"}
upload = _upload.UploadBase(SIMPLE_URL, headers=headers)
assert upload.upload_url == SIMPLE_URL
assert upload._headers is headers
assert not upload._finished
_check_retry_strategy(upload)
def test_finished_property(self):
upload = _upload.UploadBase(SIMPLE_URL)
# Default value of @property.
assert not upload.finished
# Make sure we cannot set it on public @property.
with pytest.raises(AttributeError):
upload.finished = False
# Set it privately and then check the @property.
upload._finished = True
assert upload.finished
def test__process_response_bad_status(self):
upload = _upload.UploadBase(SIMPLE_URL)
_fix_up_virtual(upload)
# Make sure **not finished** before.
assert not upload.finished
status_code = http.client.SERVICE_UNAVAILABLE
response = _make_response(status_code=status_code)
with pytest.raises(common.InvalidResponse) as exc_info:
upload._process_response(response)
error = exc_info.value
assert error.response is response
assert len(error.args) == 4
assert error.args[1] == status_code
assert error.args[3] == http.client.OK
# Make sure **finished** after (even in failure).
assert upload.finished
def test__process_response(self):
upload = _upload.UploadBase(SIMPLE_URL)
_fix_up_virtual(upload)
# Make sure **not finished** before.
assert not upload.finished
response = _make_response()
ret_val = upload._process_response(response)
assert ret_val is None
# Make sure **finished** after.
assert upload.finished
def test__get_status_code(self):
with pytest.raises(NotImplementedError) as exc_info:
_upload.UploadBase._get_status_code(None)
exc_info.match("virtual")
def test__get_headers(self):
with pytest.raises(NotImplementedError) as exc_info:
_upload.UploadBase._get_headers(None)
exc_info.match("virtual")
def test__get_body(self):
with pytest.raises(NotImplementedError) as exc_info:
_upload.UploadBase._get_body(None)
exc_info.match("virtual")
class TestSimpleUpload(object):
def test__prepare_request_already_finished(self):
upload = _upload.SimpleUpload(SIMPLE_URL)
upload._finished = True
with pytest.raises(ValueError) as exc_info:
upload._prepare_request(b"", None)
exc_info.match("An upload can only be used once.")
def test__prepare_request_non_bytes_data(self):
upload = _upload.SimpleUpload(SIMPLE_URL)
assert not upload.finished
with pytest.raises(TypeError) as exc_info:
upload._prepare_request("", None)
exc_info.match("must be bytes")
def test__prepare_request(self):
upload = _upload.SimpleUpload(SIMPLE_URL)
content_type = "image/jpeg"
data = b"cheetos and eetos"
method, url, payload, headers = upload._prepare_request(data, content_type)
assert method == "POST"
assert url == SIMPLE_URL
assert payload == data
assert headers == {"content-type": content_type}
def test__prepare_request_with_headers(self):
headers = {"x-goog-cheetos": "spicy"}
upload = _upload.SimpleUpload(SIMPLE_URL, headers=headers)
content_type = "image/jpeg"
data = b"some stuff"
method, url, payload, new_headers = upload._prepare_request(data, content_type)
assert method == "POST"
assert url == SIMPLE_URL
assert payload == data
assert new_headers is headers
expected = {"content-type": content_type, "x-goog-cheetos": "spicy"}
assert headers == expected
def test_transmit(self):
upload = _upload.SimpleUpload(SIMPLE_URL)
with pytest.raises(NotImplementedError) as exc_info:
upload.transmit(None, None, None)
exc_info.match("virtual")
class TestMultipartUpload(object):
def test_constructor_defaults(self):
upload = _upload.MultipartUpload(MULTIPART_URL)
assert upload.upload_url == MULTIPART_URL
assert upload._headers == {}
assert upload._checksum_type is None
assert not upload._finished
_check_retry_strategy(upload)
def test_constructor_explicit(self):
headers = {"spin": "doctors"}
upload = _upload.MultipartUpload(MULTIPART_URL, headers=headers, checksum="md5")
assert upload.upload_url == MULTIPART_URL
assert upload._headers is headers
assert upload._checksum_type == "md5"
assert not upload._finished
_check_retry_strategy(upload)
def test__prepare_request_already_finished(self):
upload = _upload.MultipartUpload(MULTIPART_URL)
upload._finished = True
with pytest.raises(ValueError):
upload._prepare_request(b"Hi", {}, BASIC_CONTENT)
def test__prepare_request_non_bytes_data(self):
data = "Nope not bytes."
upload = _upload.MultipartUpload(MULTIPART_URL)
with pytest.raises(TypeError):
upload._prepare_request(data, {}, BASIC_CONTENT)
@mock.patch("google.resumable_media._upload.get_boundary", return_value=b"==3==")
def _prepare_request_helper(
self,
mock_get_boundary,
headers=None,
checksum=None,
expected_checksum=None,
test_overwrite=False,
):
upload = _upload.MultipartUpload(
MULTIPART_URL, headers=headers, checksum=checksum
)
data = b"Hi"
if test_overwrite and checksum:
# Deliberately set metadata that conflicts with the chosen checksum.
# This should be fully overwritten by the calculated checksum, so
# the output should not change even if this is set.
if checksum == "md5":
metadata = {"md5Hash": "ZZZZZZZZZZZZZZZZZZZZZZ=="}
else:
metadata = {"crc32c": "ZZZZZZ=="}
else:
# To simplify parsing the response, omit other test metadata if a
# checksum is specified.
metadata = {"Some": "Stuff"} if not checksum else {}
content_type = BASIC_CONTENT
method, url, payload, new_headers = upload._prepare_request(
data, metadata, content_type
)
assert method == "POST"
assert url == MULTIPART_URL
preamble = b"--==3==\r\n" + JSON_TYPE_LINE + b"\r\n"
if checksum == "md5" and expected_checksum:
metadata_payload = '{{"md5Hash": "{}"}}\r\n'.format(
expected_checksum
).encode("utf8")
elif checksum == "crc32c" and expected_checksum:
metadata_payload = '{{"crc32c": "{}"}}\r\n'.format(
expected_checksum
).encode("utf8")
else:
metadata_payload = b'{"Some": "Stuff"}\r\n'
remainder = (
b"--==3==\r\n"
b"content-type: text/plain\r\n"
b"\r\n"
b"Hi\r\n"
b"--==3==--"
)
expected_payload = preamble + metadata_payload + remainder
assert payload == expected_payload
multipart_type = b'multipart/related; boundary="==3=="'
mock_get_boundary.assert_called_once_with()
return new_headers, multipart_type
def test__prepare_request(self):
headers, multipart_type = self._prepare_request_helper()
assert headers == {"content-type": multipart_type}
def test__prepare_request_with_headers(self):
headers = {"best": "shirt", "worst": "hat"}
new_headers, multipart_type = self._prepare_request_helper(headers=headers)
assert new_headers is headers
expected_headers = {
"best": "shirt",
"content-type": multipart_type,
"worst": "hat",
}
assert expected_headers == headers
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__prepare_request_with_checksum(self, checksum):
checksums = {
"md5": "waUpj5Oeh+j5YqXt/CBpGA==",
"crc32c": "ihY6wA==",
}
headers, multipart_type = self._prepare_request_helper(
checksum=checksum, expected_checksum=checksums[checksum]
)
assert headers == {
"content-type": multipart_type,
}
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__prepare_request_with_checksum_overwrite(self, checksum):
checksums = {
"md5": "waUpj5Oeh+j5YqXt/CBpGA==",
"crc32c": "ihY6wA==",
}
headers, multipart_type = self._prepare_request_helper(
checksum=checksum,
expected_checksum=checksums[checksum],
test_overwrite=True,
)
assert headers == {
"content-type": multipart_type,
}
def test_transmit(self):
upload = _upload.MultipartUpload(MULTIPART_URL)
with pytest.raises(NotImplementedError) as exc_info:
upload.transmit(None, None, None, None)
exc_info.match("virtual")
class TestResumableUpload(object):
def test_constructor(self):
chunk_size = ONE_MB
upload = _upload.ResumableUpload(RESUMABLE_URL, chunk_size)
assert upload.upload_url == RESUMABLE_URL
assert upload._headers == {}
assert not upload._finished
_check_retry_strategy(upload)
assert upload._chunk_size == chunk_size
assert upload._stream is None
assert upload._content_type is None
assert upload._bytes_uploaded == 0
assert upload._bytes_checksummed == 0
assert upload._checksum_object is None
assert upload._total_bytes is None
assert upload._resumable_url is None
assert upload._checksum_type is None
def test_constructor_bad_chunk_size(self):
with pytest.raises(ValueError):
_upload.ResumableUpload(RESUMABLE_URL, 1)
def test_invalid_property(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
# Default value of @property.
assert not upload.invalid
# Make sure we cannot set it on public @property.
with pytest.raises(AttributeError):
upload.invalid = False
# Set it privately and then check the @property.
upload._invalid = True
assert upload.invalid
def test_chunk_size_property(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
# Default value of @property.
assert upload.chunk_size == ONE_MB
# Make sure we cannot set it on public @property.
with pytest.raises(AttributeError):
upload.chunk_size = 17
# Set it privately and then check the @property.
new_size = 102
upload._chunk_size = new_size
assert upload.chunk_size == new_size
def test_resumable_url_property(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
# Default value of @property.
assert upload.resumable_url is None
# Make sure we cannot set it on public @property.
new_url = "http://test.invalid?upload_id=not-none"
with pytest.raises(AttributeError):
upload.resumable_url = new_url
# Set it privately and then check the @property.
upload._resumable_url = new_url
assert upload.resumable_url == new_url
def test_bytes_uploaded_property(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
# Default value of @property.
assert upload.bytes_uploaded == 0
# Make sure we cannot set it on public @property.
with pytest.raises(AttributeError):
upload.bytes_uploaded = 1024
# Set it privately and then check the @property.
upload._bytes_uploaded = 128
assert upload.bytes_uploaded == 128
def test_total_bytes_property(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
# Default value of @property.
assert upload.total_bytes is None
# Make sure we cannot set it on public @property.
with pytest.raises(AttributeError):
upload.total_bytes = 65536
# Set it privately and then check the @property.
upload._total_bytes = 8192
assert upload.total_bytes == 8192
def _prepare_initiate_request_helper(
self, upload_url=RESUMABLE_URL, upload_headers=None, **method_kwargs
):
data = b"some really big big data."
stream = io.BytesIO(data)
metadata = {"name": "big-data-file.txt"}
upload = _upload.ResumableUpload(upload_url, ONE_MB, headers=upload_headers)
orig_headers = upload._headers.copy()
# Check ``upload``-s state before.
assert upload._stream is None
assert upload._content_type is None
assert upload._total_bytes is None
# Call the method and check the output.
method, url, payload, headers = upload._prepare_initiate_request(
stream, metadata, BASIC_CONTENT, **method_kwargs
)
assert payload == b'{"name": "big-data-file.txt"}'
# Make sure the ``upload``-s state was updated.
assert upload._stream == stream
assert upload._content_type == BASIC_CONTENT
if method_kwargs == {"stream_final": False}:
assert upload._total_bytes is None
else:
assert upload._total_bytes == len(data)
# Make sure headers are untouched.
assert headers is not upload._headers
assert upload._headers == orig_headers
assert method == "POST"
assert url == upload.upload_url
# Make sure the stream is still at the beginning.
assert stream.tell() == 0
return data, headers
def test__prepare_initiate_request(self):
data, headers = self._prepare_initiate_request_helper()
expected_headers = {
"content-type": JSON_TYPE,
"x-upload-content-length": "{:d}".format(len(data)),
"x-upload-content-type": BASIC_CONTENT,
}
assert headers == expected_headers
def test_prepare_initiate_request_with_signed_url(self):
signed_urls = [
"https://storage.googleapis.com/b/o?x-goog-signature=123abc",
"https://storage.googleapis.com/b/o?X-Goog-Signature=123abc",
]
for signed_url in signed_urls:
data, headers = self._prepare_initiate_request_helper(
upload_url=signed_url,
)
expected_headers = {
"content-type": BASIC_CONTENT,
"x-upload-content-length": "{:d}".format(len(data)),
}
assert headers == expected_headers
def test__prepare_initiate_request_with_headers(self):
# content-type header should be overwritten, the rest should stay
headers = {
"caviar": "beluga",
"top": "quark",
"content-type": "application/xhtml",
}
data, new_headers = self._prepare_initiate_request_helper(
upload_headers=headers
)
expected_headers = {
"caviar": "beluga",
"content-type": JSON_TYPE,
"top": "quark",
"x-upload-content-length": "{:d}".format(len(data)),
"x-upload-content-type": BASIC_CONTENT,
}
assert new_headers == expected_headers
def test__prepare_initiate_request_known_size(self):
total_bytes = 25
data, headers = self._prepare_initiate_request_helper(total_bytes=total_bytes)
assert len(data) == total_bytes
expected_headers = {
"content-type": "application/json; charset=UTF-8",
"x-upload-content-length": "{:d}".format(total_bytes),
"x-upload-content-type": BASIC_CONTENT,
}
assert headers == expected_headers
def test__prepare_initiate_request_unknown_size(self):
_, headers = self._prepare_initiate_request_helper(stream_final=False)
expected_headers = {
"content-type": "application/json; charset=UTF-8",
"x-upload-content-type": BASIC_CONTENT,
}
assert headers == expected_headers
def test__prepare_initiate_request_already_initiated(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
# Fake that the upload has been started.
upload._resumable_url = "http://test.invalid?upload_id=definitely-started"
with pytest.raises(ValueError):
upload._prepare_initiate_request(io.BytesIO(), {}, BASIC_CONTENT)
def test__prepare_initiate_request_bad_stream_position(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
stream = io.BytesIO(b"data")
stream.seek(1)
with pytest.raises(ValueError):
upload._prepare_initiate_request(stream, {}, BASIC_CONTENT)
# Also test a bad object (i.e. non-stream)
with pytest.raises(AttributeError):
upload._prepare_initiate_request(None, {}, BASIC_CONTENT)
def test__process_initiate_response_non_200(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
response = _make_response(403)
with pytest.raises(common.InvalidResponse) as exc_info:
upload._process_initiate_response(response)
error = exc_info.value
assert error.response is response
assert len(error.args) == 5
assert error.args[1] == 403
assert error.args[3] == 200
assert error.args[4] == 201
def test__process_initiate_response(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
headers = {"location": "http://test.invalid?upload_id=kmfeij3234"}
response = _make_response(headers=headers)
# Check resumable_url before.
assert upload._resumable_url is None
# Process the actual headers.
ret_val = upload._process_initiate_response(response)
assert ret_val is None
# Check resumable_url after.
assert upload._resumable_url == headers["location"]
def test_initiate(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
with pytest.raises(NotImplementedError) as exc_info:
upload.initiate(None, None, {}, BASIC_CONTENT)
exc_info.match("virtual")
def test__prepare_request_already_finished(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
assert not upload.invalid
upload._finished = True
with pytest.raises(ValueError) as exc_info:
upload._prepare_request()
assert exc_info.value.args == ("Upload has finished.",)
def test__prepare_request_invalid(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
assert not upload.finished
upload._invalid = True
with pytest.raises(ValueError) as exc_info:
upload._prepare_request()
assert exc_info.match("invalid state")
assert exc_info.match("recover()")
def test__prepare_request_not_initiated(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
assert not upload.finished
assert not upload.invalid
assert upload._resumable_url is None
with pytest.raises(ValueError) as exc_info:
upload._prepare_request()
assert exc_info.match("upload has not been initiated")
assert exc_info.match("initiate()")
def test__prepare_request_invalid_stream_state(self):
stream = io.BytesIO(b"some data here")
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
upload._stream = stream
upload._resumable_url = "http://test.invalid?upload_id=not-none"
# Make stream.tell() disagree with bytes_uploaded.
upload._bytes_uploaded = 5
assert upload.bytes_uploaded != stream.tell()
with pytest.raises(ValueError) as exc_info:
upload._prepare_request()
assert exc_info.match("Bytes stream is in unexpected state.")
@staticmethod
def _upload_in_flight(data, headers=None, checksum=None):
upload = _upload.ResumableUpload(
RESUMABLE_URL, ONE_MB, headers=headers, checksum=checksum
)
upload._stream = io.BytesIO(data)
upload._content_type = BASIC_CONTENT
upload._total_bytes = len(data)
upload._resumable_url = "http://test.invalid?upload_id=not-none"
return upload
def _prepare_request_helper(self, headers=None, checksum=None):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, headers=headers, checksum=checksum)
method, url, payload, new_headers = upload._prepare_request()
# Check the response values.
assert method == "PUT"
assert url == upload.resumable_url
assert payload == data
# Make sure headers are **NOT** updated
assert upload._headers != new_headers
return new_headers
def test__prepare_request_success(self):
headers = self._prepare_request_helper()
expected_headers = {
"content-range": "bytes 0-32/33",
"content-type": BASIC_CONTENT,
}
assert headers == expected_headers
def test__prepare_request_success_with_headers(self):
headers = {"keep": "this"}
new_headers = self._prepare_request_helper(headers)
assert new_headers is not headers
expected_headers = {
"keep": "this",
"content-range": "bytes 0-32/33",
"content-type": BASIC_CONTENT,
}
assert new_headers == expected_headers
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__prepare_request_with_checksum(self, checksum):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum=checksum)
upload._prepare_request()
assert upload._checksum_object is not None
checksums = {"md5": "GRvfKbqr5klAOwLkxgIf8w==", "crc32c": "Qg8thA=="}
checksum_digest = _helpers.prepare_checksum_digest(
upload._checksum_object.digest()
)
assert checksum_digest == checksums[checksum]
assert upload._bytes_checksummed == len(data)
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__update_checksum(self, checksum):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum=checksum)
start_byte, payload, _ = _upload.get_next_chunk(upload._stream, 8, len(data))
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == 8
start_byte, payload, _ = _upload.get_next_chunk(upload._stream, 8, len(data))
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == 16
# Continue to the end.
start_byte, payload, _ = _upload.get_next_chunk(
upload._stream, len(data), len(data)
)
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == len(data)
checksums = {"md5": "GRvfKbqr5klAOwLkxgIf8w==", "crc32c": "Qg8thA=="}
checksum_digest = _helpers.prepare_checksum_digest(
upload._checksum_object.digest()
)
assert checksum_digest == checksums[checksum]
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__update_checksum_rewind(self, checksum):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum=checksum)
start_byte, payload, _ = _upload.get_next_chunk(upload._stream, 8, len(data))
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == 8
checksum_checkpoint = upload._checksum_object.digest()
# Rewind to the beginning.
upload._stream.seek(0)
start_byte, payload, _ = _upload.get_next_chunk(upload._stream, 8, len(data))
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == 8
assert upload._checksum_object.digest() == checksum_checkpoint
# Rewind but not to the beginning.
upload._stream.seek(4)
start_byte, payload, _ = _upload.get_next_chunk(upload._stream, 8, len(data))
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == 12
# Continue to the end.
start_byte, payload, _ = _upload.get_next_chunk(
upload._stream, len(data), len(data)
)
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == len(data)
checksums = {"md5": "GRvfKbqr5klAOwLkxgIf8w==", "crc32c": "Qg8thA=="}
checksum_digest = _helpers.prepare_checksum_digest(
upload._checksum_object.digest()
)
assert checksum_digest == checksums[checksum]
def test__update_checksum_none(self):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum=None)
start_byte, payload, _ = _upload.get_next_chunk(upload._stream, 8, len(data))
upload._update_checksum(start_byte, payload)
assert upload._checksum_object is None
def test__update_checksum_invalid(self):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum="invalid")
start_byte, payload, _ = _upload.get_next_chunk(upload._stream, 8, len(data))
with pytest.raises(ValueError):
upload._update_checksum(start_byte, payload)
def test__make_invalid(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
assert not upload.invalid
upload._make_invalid()
assert upload.invalid
def test__process_resumable_response_bad_status(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
# Make sure the upload is valid before the failure.
assert not upload.invalid
response = _make_response(status_code=http.client.NOT_FOUND)
with pytest.raises(common.InvalidResponse) as exc_info:
upload._process_resumable_response(response, None)
error = exc_info.value
assert error.response is response
assert len(error.args) == 5
assert error.args[1] == response.status_code
assert error.args[3] == http.client.OK
assert error.args[4] == http.client.PERMANENT_REDIRECT
# Make sure the upload is invalid after the failure.
assert upload.invalid
def test__process_resumable_response_success(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
# Check / set status before.
assert upload._bytes_uploaded == 0
upload._bytes_uploaded = 20
assert not upload._finished
# Set the response body.
bytes_sent = 158
total_bytes = upload._bytes_uploaded + bytes_sent
response_body = '{{"size": "{:d}"}}'.format(total_bytes)
response_body = response_body.encode("utf-8")
response = mock.Mock(
content=response_body,
status_code=http.client.OK,
spec=["content", "status_code"],
)
ret_val = upload._process_resumable_response(response, bytes_sent)
assert ret_val is None
# Check status after.
assert upload._bytes_uploaded == total_bytes
assert upload._finished
def test__process_resumable_response_partial_no_range(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
response = _make_response(status_code=http.client.PERMANENT_REDIRECT)
# Make sure the upload is valid before the failure.
assert not upload.invalid
with pytest.raises(common.InvalidResponse) as exc_info:
upload._process_resumable_response(response, None)
# Make sure the upload is invalid after the failure.
assert upload.invalid
# Check the error response.
error = exc_info.value
assert error.response is response
assert len(error.args) == 2
assert error.args[1] == "range"
def test__process_resumable_response_partial_bad_range(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
# Make sure the upload is valid before the failure.
assert not upload.invalid
headers = {"range": "nights 1-81"}
response = _make_response(
status_code=http.client.PERMANENT_REDIRECT, headers=headers
)
with pytest.raises(common.InvalidResponse) as exc_info:
upload._process_resumable_response(response, 81)
# Check the error response.
error = exc_info.value
assert error.response is response
assert len(error.args) == 3
assert error.args[1] == headers["range"]
# Make sure the upload is invalid after the failure.
assert upload.invalid
def test__process_resumable_response_partial(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
# Check status before.
assert upload._bytes_uploaded == 0
headers = {"range": "bytes=0-171"}
response = _make_response(
status_code=http.client.PERMANENT_REDIRECT, headers=headers
)
ret_val = upload._process_resumable_response(response, 172)
assert ret_val is None
# Check status after.
assert upload._bytes_uploaded == 172
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__validate_checksum_success(self, checksum):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum=checksum)
_fix_up_virtual(upload)
# Go ahead and process the entire data in one go for this test.
start_byte, payload, _ = _upload.get_next_chunk(
upload._stream, len(data), len(data)
)
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == len(data)
# This is only used by _validate_checksum for fetching metadata and
# logging.
metadata = {"md5Hash": "GRvfKbqr5klAOwLkxgIf8w==", "crc32c": "Qg8thA=="}
response = _make_response(metadata=metadata)
upload._finished = True
assert upload._checksum_object is not None
# Test passes if it does not raise an error (no assert needed)
upload._validate_checksum(response)
def test__validate_checksum_none(self):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(b"test", checksum=None)
_fix_up_virtual(upload)
# Go ahead and process the entire data in one go for this test.
start_byte, payload, _ = _upload.get_next_chunk(
upload._stream, len(data), len(data)
)
upload._update_checksum(start_byte, payload)
# This is only used by _validate_checksum for fetching metadata and
# logging.
metadata = {"md5Hash": "GRvfKbqr5klAOwLkxgIf8w==", "crc32c": "Qg8thA=="}
response = _make_response(metadata=metadata)
upload._finished = True
assert upload._checksum_object is None
assert upload._bytes_checksummed == 0
# Test passes if it does not raise an error (no assert needed)
upload._validate_checksum(response)
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__validate_checksum_header_no_match(self, checksum):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum=checksum)
_fix_up_virtual(upload)
# Go ahead and process the entire data in one go for this test.
start_byte, payload, _ = _upload.get_next_chunk(
upload._stream, len(data), len(data)
)
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == len(data)
# For this test, each checksum option will be provided with a valid but
# mismatching remote checksum type.
if checksum == "crc32c":
metadata = {"md5Hash": "GRvfKbqr5klAOwLkxgIf8w=="}
else:
metadata = {"crc32c": "Qg8thA=="}
# This is only used by _validate_checksum for fetching headers and
# logging, so it doesn't need to be fleshed out with a response body.
response = _make_response(metadata=metadata)
upload._finished = True
assert upload._checksum_object is not None
with pytest.raises(common.InvalidResponse) as exc_info:
upload._validate_checksum(response)
error = exc_info.value
assert error.response is response
message = error.args[0]
metadata_key = _helpers._get_metadata_key(checksum)
assert (
message
== _upload._UPLOAD_METADATA_NO_APPROPRIATE_CHECKSUM_MESSAGE.format(
metadata_key
)
)
@pytest.mark.parametrize("checksum", ["md5", "crc32c"])
def test__validate_checksum_mismatch(self, checksum):
data = b"All of the data goes in a stream."
upload = self._upload_in_flight(data, checksum=checksum)
_fix_up_virtual(upload)
# Go ahead and process the entire data in one go for this test.
start_byte, payload, _ = _upload.get_next_chunk(
upload._stream, len(data), len(data)
)
upload._update_checksum(start_byte, payload)
assert upload._bytes_checksummed == len(data)
metadata = {
"md5Hash": "ZZZZZZZZZZZZZZZZZZZZZZ==",
"crc32c": "ZZZZZZ==",
}
# This is only used by _validate_checksum for fetching headers and
# logging, so it doesn't need to be fleshed out with a response body.
response = _make_response(metadata=metadata)
upload._finished = True
assert upload._checksum_object is not None
# Test passes if it does not raise an error (no assert needed)
with pytest.raises(common.DataCorruption) as exc_info:
upload._validate_checksum(response)
error = exc_info.value
assert error.response is response
message = error.args[0]
correct_checksums = {"crc32c": "Qg8thA==", "md5": "GRvfKbqr5klAOwLkxgIf8w=="}
metadata_key = _helpers._get_metadata_key(checksum)
assert message == _upload._UPLOAD_CHECKSUM_MISMATCH_MESSAGE.format(
checksum.upper(), correct_checksums[checksum], metadata[metadata_key]
)
def test_transmit_next_chunk(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
with pytest.raises(NotImplementedError) as exc_info:
upload.transmit_next_chunk(None)
exc_info.match("virtual")
def test__prepare_recover_request_not_invalid(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
assert not upload.invalid
method, url, payload, headers = upload._prepare_recover_request()
assert method == "PUT"
assert url == upload.resumable_url
assert payload is None
assert headers == {"content-range": "bytes */*"}
# Make sure headers are untouched.
assert upload._headers == {}
def test__prepare_recover_request(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
upload._invalid = True
method, url, payload, headers = upload._prepare_recover_request()
assert method == "PUT"
assert url == upload.resumable_url
assert payload is None
assert headers == {"content-range": "bytes */*"}
# Make sure headers are untouched.
assert upload._headers == {}
def test__prepare_recover_request_with_headers(self):
headers = {"lake": "ocean"}
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB, headers=headers)
upload._invalid = True
method, url, payload, new_headers = upload._prepare_recover_request()
assert method == "PUT"
assert url == upload.resumable_url
assert payload is None
assert new_headers == {"content-range": "bytes */*"}
# Make sure the ``_headers`` are not incorporated.
assert "lake" not in new_headers
# Make sure headers are untouched.
assert upload._headers == {"lake": "ocean"}
def test__process_recover_response_bad_status(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
upload._invalid = True
response = _make_response(status_code=http.client.BAD_REQUEST)
with pytest.raises(common.InvalidResponse) as exc_info:
upload._process_recover_response(response)
error = exc_info.value
assert error.response is response
assert len(error.args) == 4
assert error.args[1] == response.status_code
assert error.args[3] == http.client.PERMANENT_REDIRECT
# Make sure still invalid.
assert upload.invalid
def test__process_recover_response_no_range(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
upload._invalid = True
upload._stream = mock.Mock(spec=["seek"])
upload._bytes_uploaded = mock.sentinel.not_zero
assert upload.bytes_uploaded != 0
response = _make_response(status_code=http.client.PERMANENT_REDIRECT)
ret_val = upload._process_recover_response(response)
assert ret_val is None
# Check the state of ``upload`` after.
assert upload.bytes_uploaded == 0
assert not upload.invalid
upload._stream.seek.assert_called_once_with(0)
def test__process_recover_response_bad_range(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
upload._invalid = True
upload._stream = mock.Mock(spec=["seek"])
upload._bytes_uploaded = mock.sentinel.not_zero
headers = {"range": "bites=9-11"}
response = _make_response(
status_code=http.client.PERMANENT_REDIRECT, headers=headers
)
with pytest.raises(common.InvalidResponse) as exc_info:
upload._process_recover_response(response)
error = exc_info.value
assert error.response is response
assert len(error.args) == 3
assert error.args[1] == headers["range"]
# Check the state of ``upload`` after (untouched).
assert upload.bytes_uploaded is mock.sentinel.not_zero
assert upload.invalid
upload._stream.seek.assert_not_called()
def test__process_recover_response_with_range(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
_fix_up_virtual(upload)
upload._invalid = True
upload._stream = mock.Mock(spec=["seek"])
upload._bytes_uploaded = mock.sentinel.not_zero
assert upload.bytes_uploaded != 0
end = 11
headers = {"range": "bytes=0-{:d}".format(end)}
response = _make_response(
status_code=http.client.PERMANENT_REDIRECT, headers=headers
)
ret_val = upload._process_recover_response(response)
assert ret_val is None
# Check the state of ``upload`` after.
assert upload.bytes_uploaded == end + 1
assert not upload.invalid
upload._stream.seek.assert_called_once_with(end + 1)
def test_recover(self):
upload = _upload.ResumableUpload(RESUMABLE_URL, ONE_MB)
with pytest.raises(NotImplementedError) as exc_info:
upload.recover(None)
exc_info.match("virtual")
@mock.patch("random.randrange", return_value=1234567890123456789)
def test_get_boundary(mock_rand):
result = _upload.get_boundary()
assert result == b"===============1234567890123456789=="
mock_rand.assert_called_once_with(sys.maxsize)
class Test_construct_multipart_request(object):
@mock.patch("google.resumable_media._upload.get_boundary", return_value=b"==1==")
def test_binary(self, mock_get_boundary):
data = b"By nary day tuh"
metadata = {"name": "hi-file.bin"}
content_type = "application/octet-stream"
payload, multipart_boundary = _upload.construct_multipart_request(
data, metadata, content_type
)
assert multipart_boundary == mock_get_boundary.return_value
expected_payload = (
b"--==1==\r\n" + JSON_TYPE_LINE + b"\r\n"
b'{"name": "hi-file.bin"}\r\n'
b"--==1==\r\n"
b"content-type: application/octet-stream\r\n"
b"\r\n"
b"By nary day tuh\r\n"
b"--==1==--"
)
assert payload == expected_payload
mock_get_boundary.assert_called_once_with()
@mock.patch("google.resumable_media._upload.get_boundary", return_value=b"==2==")
def test_unicode(self, mock_get_boundary):
data_unicode = "\N{snowman}"
# construct_multipart_request( ASSUMES callers pass bytes.
data = data_unicode.encode("utf-8")
metadata = {"name": "snowman.txt"}
content_type = BASIC_CONTENT
payload, multipart_boundary = _upload.construct_multipart_request(
data, metadata, content_type
)
assert multipart_boundary == mock_get_boundary.return_value
expected_payload = (
b"--==2==\r\n" + JSON_TYPE_LINE + b"\r\n"
b'{"name": "snowman.txt"}\r\n'
b"--==2==\r\n"
b"content-type: text/plain\r\n"
b"\r\n"
b"\xe2\x98\x83\r\n"
b"--==2==--"
)
assert payload == expected_payload
mock_get_boundary.assert_called_once_with()
def test_get_total_bytes():
data = b"some data"
stream = io.BytesIO(data)
# Check position before function call.
assert stream.tell() == 0
assert _upload.get_total_bytes(stream) == len(data)
# Check position after function call.
assert stream.tell() == 0
# Make sure this works just as well when not at beginning.
curr_pos = 3
stream.seek(curr_pos)
assert _upload.get_total_bytes(stream) == len(data)
# Check position after function call.
assert stream.tell() == curr_pos
class Test_get_next_chunk(object):
def test_exhausted_known_size(self):
data = b"the end"
stream = io.BytesIO(data)
stream.seek(len(data))
with pytest.raises(ValueError) as exc_info:
_upload.get_next_chunk(stream, 1, len(data))
exc_info.match("Stream is already exhausted. There is no content remaining.")
def test_exhausted_known_size_zero(self):
stream = io.BytesIO(b"")
answer = _upload.get_next_chunk(stream, 1, 0)
assert answer == (0, b"", "bytes */0")
def test_exhausted_known_size_zero_nonempty(self):
stream = io.BytesIO(b"not empty WAT!")
with pytest.raises(ValueError) as exc_info:
_upload.get_next_chunk(stream, 1, 0)
exc_info.match("Stream specified as empty, but produced non-empty content.")
def test_success_known_size_lt_stream_size(self):
data = b"0123456789"
stream = io.BytesIO(data)
chunk_size = 3
total_bytes = len(data) - 2
# Splits into 3 chunks: 012, 345, 67
result0 = _upload.get_next_chunk(stream, chunk_size, total_bytes)
result1 = _upload.get_next_chunk(stream, chunk_size, total_bytes)
result2 = _upload.get_next_chunk(stream, chunk_size, total_bytes)
assert result0 == (0, b"012", "bytes 0-2/8")
assert result1 == (3, b"345", "bytes 3-5/8")
assert result2 == (6, b"67", "bytes 6-7/8")
def test_success_known_size(self):
data = b"0123456789"
stream = io.BytesIO(data)
total_bytes = len(data)
chunk_size = 3
# Splits into 4 chunks: 012, 345, 678, 9
result0 = _upload.get_next_chunk(stream, chunk_size, total_bytes)
result1 = _upload.get_next_chunk(stream, chunk_size, total_bytes)
result2 = _upload.get_next_chunk(stream, chunk_size, total_bytes)
result3 = _upload.get_next_chunk(stream, chunk_size, total_bytes)
assert result0 == (0, b"012", "bytes 0-2/10")
assert result1 == (3, b"345", "bytes 3-5/10")
assert result2 == (6, b"678", "bytes 6-8/10")
assert result3 == (9, b"9", "bytes 9-9/10")
assert stream.tell() == total_bytes
def test_success_unknown_size(self):
data = b"abcdefghij"
stream = io.BytesIO(data)
chunk_size = 6
# Splits into 4 chunks: abcdef, ghij
result0 = _upload.get_next_chunk(stream, chunk_size, None)
result1 = _upload.get_next_chunk(stream, chunk_size, None)
assert result0 == (0, b"abcdef", "bytes 0-5/*")
assert result1 == (chunk_size, b"ghij", "bytes 6-9/10")
assert stream.tell() == len(data)
# Do the same when the chunk size evenly divides len(data)
stream.seek(0)
chunk_size = len(data)
# Splits into 2 chunks: `data` and empty string
result0 = _upload.get_next_chunk(stream, chunk_size, None)
result1 = _upload.get_next_chunk(stream, chunk_size, None)
assert result0 == (0, data, "bytes 0-9/*")
assert result1 == (len(data), b"", "bytes */10")
assert stream.tell() == len(data)
class Test_get_content_range(object):
def test_known_size(self):
result = _upload.get_content_range(5, 10, 40)
assert result == "bytes 5-10/40"
def test_unknown_size(self):
result = _upload.get_content_range(1000, 10000, None)
assert result == "bytes 1000-10000/*"
def test_xml_mpu_container_constructor_and_properties(filename):
container = _upload.XMLMPUContainer(EXAMPLE_XML_UPLOAD_URL, filename)
assert container.upload_url == EXAMPLE_XML_UPLOAD_URL
assert container.upload_id is None
assert container._headers == {}
assert container._parts == {}
assert container._filename == filename
container = _upload.XMLMPUContainer(
EXAMPLE_XML_UPLOAD_URL,
filename,
headers=EXAMPLE_HEADERS,
upload_id=UPLOAD_ID,
)
container._parts = PARTS
assert container.upload_url == EXAMPLE_XML_UPLOAD_URL
assert container.upload_id == UPLOAD_ID
assert container._headers == EXAMPLE_HEADERS
assert container._parts == PARTS
assert container._filename == filename
def test_xml_mpu_container_initiate(filename):
container = _upload.XMLMPUContainer(
EXAMPLE_XML_UPLOAD_URL, filename, upload_id=UPLOAD_ID
)
with pytest.raises(ValueError):
container._prepare_initiate_request(BASIC_CONTENT)
container = _upload.XMLMPUContainer(
EXAMPLE_XML_UPLOAD_URL, filename, headers=EXAMPLE_HEADERS
)
verb, url, body, headers = container._prepare_initiate_request(BASIC_CONTENT)
assert verb == _upload._POST
assert url == EXAMPLE_XML_UPLOAD_URL + _upload._MPU_INITIATE_QUERY
assert not body
assert headers == {**EXAMPLE_HEADERS, "content-type": BASIC_CONTENT}
_fix_up_virtual(container)
response = _make_xml_response(
text=EXAMPLE_XML_MPU_INITIATE_TEXT_TEMPLATE.format(upload_id=UPLOAD_ID)
)
container._process_initiate_response(response)
assert container.upload_id == UPLOAD_ID
with pytest.raises(NotImplementedError):
container.initiate(None, None)
def test_xml_mpu_container_finalize(filename):
container = _upload.XMLMPUContainer(EXAMPLE_XML_UPLOAD_URL, filename)
with pytest.raises(ValueError):
container._prepare_finalize_request()
container = _upload.XMLMPUContainer(
EXAMPLE_XML_UPLOAD_URL,
filename,
headers=EXAMPLE_HEADERS,
upload_id=UPLOAD_ID,
)
container._parts = PARTS
verb, url, body, headers = container._prepare_finalize_request()
assert verb == _upload._POST
final_query = _upload._MPU_FINAL_QUERY_TEMPLATE.format(upload_id=UPLOAD_ID)
assert url == EXAMPLE_XML_UPLOAD_URL + final_query
assert headers == EXAMPLE_HEADERS
assert b"CompleteMultipartUpload" in body
for key, value in PARTS.items():
assert str(key).encode("utf-8") in body
assert value.encode("utf-8") in body
_fix_up_virtual(container)
response = _make_xml_response()
container._process_finalize_response(response)
assert container.finished
with pytest.raises(NotImplementedError):
container.finalize(None)
def test_xml_mpu_container_cancel(filename):
container = _upload.XMLMPUContainer(EXAMPLE_XML_UPLOAD_URL, filename)
with pytest.raises(ValueError):
container._prepare_cancel_request()
container = _upload.XMLMPUContainer(
EXAMPLE_XML_UPLOAD_URL,
filename,
headers=EXAMPLE_HEADERS,
upload_id=UPLOAD_ID,
)
container._parts = PARTS
verb, url, body, headers = container._prepare_cancel_request()
assert verb == _upload._DELETE
final_query = _upload._MPU_FINAL_QUERY_TEMPLATE.format(upload_id=UPLOAD_ID)
assert url == EXAMPLE_XML_UPLOAD_URL + final_query
assert headers == EXAMPLE_HEADERS
assert not body
_fix_up_virtual(container)
response = _make_xml_response(status_code=204)
container._process_cancel_response(response)
with pytest.raises(NotImplementedError):
container.cancel(None)
def test_xml_mpu_part(filename):
PART_NUMBER = 1
START = 0
END = 256
ETAG = PARTS[1]
part = _upload.XMLMPUPart(
EXAMPLE_XML_UPLOAD_URL,
UPLOAD_ID,
filename,
START,
END,
PART_NUMBER,
headers=EXAMPLE_HEADERS,
checksum="md5",
)
assert part.upload_url == EXAMPLE_XML_UPLOAD_URL
assert part.upload_id == UPLOAD_ID
assert part.filename == filename
assert part.etag is None
assert part.start == START
assert part.end == END
assert part.part_number == PART_NUMBER
assert part._headers == EXAMPLE_HEADERS
assert part._checksum_type == "md5"
assert part._checksum_object is None
part = _upload.XMLMPUPart(
EXAMPLE_XML_UPLOAD_URL,
UPLOAD_ID,
filename,
START,
END,
PART_NUMBER,
headers=EXAMPLE_HEADERS,
)
verb, url, payload, headers = part._prepare_upload_request()
assert verb == _upload._PUT
assert url == EXAMPLE_XML_UPLOAD_URL + _upload._MPU_PART_QUERY_TEMPLATE.format(
part=PART_NUMBER, upload_id=UPLOAD_ID
)
assert headers == EXAMPLE_HEADERS
assert payload == FILE_DATA[START:END]
_fix_up_virtual(part)
response = _make_xml_response(headers={"etag": ETAG})
part._process_upload_response(response)
assert part.etag == ETAG
def test_xml_mpu_part_invalid_response(filename):
PART_NUMBER = 1
START = 0
END = 256
ETAG = PARTS[1]
part = _upload.XMLMPUPart(
EXAMPLE_XML_UPLOAD_URL,
UPLOAD_ID,
filename,
START,
END,
PART_NUMBER,
headers=EXAMPLE_HEADERS,
checksum="md5",
)
_fix_up_virtual(part)
response = _make_xml_response(headers={"etag": ETAG})
with pytest.raises(common.InvalidResponse):
part._process_upload_response(response)
def test_xml_mpu_part_checksum_failure(filename):
PART_NUMBER = 1
START = 0
END = 256
ETAG = PARTS[1]
part = _upload.XMLMPUPart(
EXAMPLE_XML_UPLOAD_URL,
UPLOAD_ID,
filename,
START,
END,
PART_NUMBER,
headers=EXAMPLE_HEADERS,
checksum="md5",
)
_fix_up_virtual(part)
part._prepare_upload_request()
response = _make_xml_response(
headers={"etag": ETAG, "x-goog-hash": "md5=Ojk9c3dhfxgoKVVHYwFbHQ=="}
) # Example md5 checksum but not the correct one
with pytest.raises(common.DataCorruption):
part._process_upload_response(response)
def test_xml_mpu_part_checksum_success(filename):
PART_NUMBER = 1
START = 0
END = 256
ETAG = PARTS[1]
part = _upload.XMLMPUPart(
EXAMPLE_XML_UPLOAD_URL,
UPLOAD_ID,
filename,
START,
END,
PART_NUMBER,
headers=EXAMPLE_HEADERS,
checksum="md5",
)
_fix_up_virtual(part)
part._prepare_upload_request()
response = _make_xml_response(
headers={"etag": ETAG, "x-goog-hash": "md5=pOUFGnohRRFFd24NztFuFw=="}
)
part._process_upload_response(response)
assert part.etag == ETAG
assert part.finished
# Test error handling
part = _upload.XMLMPUPart(
EXAMPLE_XML_UPLOAD_URL,
UPLOAD_ID,
filename,
START,
END,
PART_NUMBER,
headers=EXAMPLE_HEADERS,
checksum="md5",
)
with pytest.raises(NotImplementedError):
part.upload(None)
part._finished = True
with pytest.raises(ValueError):
part._prepare_upload_request()
def _make_response(status_code=http.client.OK, headers=None, metadata=None):
headers = headers or {}
return mock.Mock(
headers=headers,
status_code=status_code,
json=mock.Mock(return_value=metadata),
spec=["headers", "status_code"],
)
def _make_xml_response(status_code=http.client.OK, headers=None, text=None):
headers = headers or {}
return mock.Mock(
headers=headers,
status_code=status_code,
text=text,
spec=["headers", "status_code"],
)
def _get_status_code(response):
return response.status_code
def _get_headers(response):
return response.headers
def _fix_up_virtual(upload):
upload._get_status_code = _get_status_code
upload._get_headers = _get_headers
def _check_retry_strategy(upload):
retry_strategy = upload._retry_strategy
assert isinstance(retry_strategy, common.RetryStrategy)
assert retry_strategy.max_sleep == common.MAX_SLEEP
assert retry_strategy.max_cumulative_retry == common.MAX_CUMULATIVE_RETRY
assert retry_strategy.max_retries is None
|