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
|
import asyncio
import io
import json
import pathlib
import sys
import zlib
from unittest import mock
import pytest
import aiohttp
from aiohttp import payload
from aiohttp.hdrs import (
CONTENT_DISPOSITION,
CONTENT_ENCODING,
CONTENT_TRANSFER_ENCODING,
CONTENT_TYPE,
)
from aiohttp.helpers import parse_mimetype
from aiohttp.multipart import MultipartResponseWrapper
from aiohttp.streams import StreamReader
from aiohttp.test_utils import make_mocked_coro
BOUNDARY = b"--:"
newline = b"\r\n"
@pytest.fixture
def buf():
return bytearray()
@pytest.fixture
def stream(buf):
writer = mock.Mock()
async def write(chunk):
buf.extend(chunk)
writer.write.side_effect = write
return writer
@pytest.fixture
def writer():
return aiohttp.MultipartWriter(boundary=":")
class Response:
def __init__(self, headers, content):
self.headers = headers
self.content = content
class Stream:
def __init__(self, content):
self.content = io.BytesIO(content)
async def read(self, size=None):
return self.content.read(size)
def at_eof(self):
return self.content.tell() == len(self.content.getbuffer())
async def readline(self):
return self.content.readline()
def unread_data(self, data):
self.content = io.BytesIO(data + self.content.read())
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.content.close()
class StreamWithShortenRead(Stream):
def __init__(self, content):
self._first = True
super().__init__(content)
async def read(self, size=None):
if size is not None and self._first:
self._first = False
size = size // 2
return await super().read(size)
class TestMultipartResponseWrapper:
def test_at_eof(self) -> None:
wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock())
wrapper.at_eof()
assert wrapper.resp.content.at_eof.called
async def test_next(self) -> None:
wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock())
wrapper.stream.next = make_mocked_coro(b"")
wrapper.stream.at_eof.return_value = False
await wrapper.next()
assert wrapper.stream.next.called
async def test_release(self) -> None:
wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock())
wrapper.resp.release = make_mocked_coro(None)
await wrapper.release()
assert wrapper.resp.release.called
async def test_release_when_stream_at_eof(self) -> None:
wrapper = MultipartResponseWrapper(mock.Mock(), mock.Mock())
wrapper.resp.release = make_mocked_coro(None)
wrapper.stream.next = make_mocked_coro(b"")
wrapper.stream.at_eof.return_value = True
await wrapper.next()
assert wrapper.stream.next.called
assert wrapper.resp.release.called
class TestPartReader:
async def test_next(self) -> None:
data = b"Hello, world!%s--:" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.next()
assert b"Hello, world!" == result
assert obj.at_eof()
async def test_next_next(self) -> None:
data = b"Hello, world!%s--:" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.next()
assert b"Hello, world!" == result
assert obj.at_eof()
result = await obj.next()
assert result is None
async def test_read(self) -> None:
data = b"Hello, world!%s--:" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.read()
assert b"Hello, world!" == result
assert obj.at_eof()
async def test_read_chunk_at_eof(self) -> None:
with Stream(b"--:") as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
obj._at_eof = True
result = await obj.read_chunk()
assert b"" == result
async def test_read_chunk_without_content_length(self) -> None:
data = b"Hello, world!%s--:" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
c1 = await obj.read_chunk(8)
c2 = await obj.read_chunk(8)
c3 = await obj.read_chunk(8)
assert c1 + c2 == b"Hello, world!"
assert c3 == b""
async def test_read_incomplete_chunk(self) -> None:
with Stream(b"") as stream:
def prepare(data):
return data
with mock.patch.object(
stream,
"read",
side_effect=[
prepare(b"Hello, "),
prepare(b"World"),
prepare(b"!%s--:" % newline),
prepare(b""),
],
):
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
c1 = await obj.read_chunk(8)
assert c1 == b"Hello, "
c2 = await obj.read_chunk(8)
assert c2 == b"World"
c3 = await obj.read_chunk(8)
assert c3 == b"!"
async def test_read_all_at_once(self) -> None:
data = b"Hello, World!%s--:--%s" % (newline, newline)
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.read_chunk()
assert b"Hello, World!" == result
result = await obj.read_chunk()
assert b"" == result
assert obj.at_eof()
async def test_read_incomplete_body_chunked(self) -> None:
data = b"Hello, World!%s--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = b""
with pytest.raises(AssertionError):
for _ in range(4):
result += await obj.read_chunk(7)
assert data == result
async def test_read_boundary_with_incomplete_chunk(self) -> None:
with Stream(b"") as stream:
def prepare(data):
return data
with mock.patch.object(
stream,
"read",
side_effect=[
prepare(b"Hello, World"),
prepare(b"!%s" % newline),
prepare(b"--:"),
prepare(b""),
],
):
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
c1 = await obj.read_chunk(12)
assert c1 == b"Hello, World"
c2 = await obj.read_chunk(8)
assert c2 == b"!"
c3 = await obj.read_chunk(8)
assert c3 == b""
async def test_multi_read_chunk(self) -> None:
data = b"Hello,%s--:%s%sworld!%s--:--" % ((newline,) * 4)
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.read_chunk(8)
assert b"Hello," == result
result = await obj.read_chunk(8)
assert b"" == result
assert obj.at_eof()
async def test_read_chunk_properly_counts_read_bytes(self) -> None:
expected = b"." * 10
tail = b"%s--:--" % newline
size = len(expected)
with StreamWithShortenRead(expected + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{"CONTENT-LENGTH": size},
stream,
)
result = bytearray()
while True:
chunk = await obj.read_chunk()
if not chunk:
break
result.extend(chunk)
assert size == len(result)
assert b"." * size == result
assert obj.at_eof()
async def test_read_does_not_read_boundary(self) -> None:
data = b"Hello, world!%s--:" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.read()
assert b"Hello, world!" == result
assert b"--:" == (await stream.read())
async def test_multiread(self) -> None:
data = b"Hello,%s--:%s%sworld!%s--:--" % ((newline,) * 4)
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.read()
assert b"Hello," == result
result = await obj.read()
assert b"" == result
assert obj.at_eof()
async def test_read_multiline(self) -> None:
data = b"Hello\n,\r\nworld!%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
result = await obj.read()
assert b"Hello\n,\r\nworld!" == result
result = await obj.read()
assert b"" == result
assert obj.at_eof()
async def test_read_respects_content_length(self) -> None:
data = b"." * 100500
tail = b"%s--:--" % newline
with Stream(data + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{"CONTENT-LENGTH": 100500},
stream,
)
result = await obj.read()
assert data == result
assert obj.at_eof()
async def test_read_with_content_encoding_gzip(self) -> None:
with Stream(
b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x0b\xc9\xccMU"
b"(\xc9W\x08J\xcdI\xacP\x04\x00$\xfb\x9eV\x0e\x00\x00\x00"
b"%s--:--" % newline
) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_ENCODING: "gzip"},
stream,
)
result = await obj.read(decode=True)
assert b"Time to Relax!" == result
async def test_read_with_content_encoding_deflate(self) -> None:
data = b"\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00"
tail = b"%s--:--" % newline
with Stream(data + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_ENCODING: "deflate"},
stream,
)
result = await obj.read(decode=True)
assert b"Time to Relax!" == result
async def test_read_with_content_encoding_identity(self) -> None:
thing = (
b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x0b\xc9\xccMU"
b"(\xc9W\x08J\xcdI\xacP\x04\x00$\xfb\x9eV\x0e\x00\x00\x00"
)
with Stream(thing + b"%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_ENCODING: "identity"},
stream,
)
result = await obj.read(decode=True)
assert thing == result
async def test_read_with_content_encoding_unknown(self) -> None:
with Stream(b"\x0e4Time to Relax!%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_ENCODING: "snappy"},
stream,
)
with pytest.raises(RuntimeError):
await obj.read(decode=True)
async def test_read_with_content_transfer_encoding_base64(self) -> None:
with Stream(b"VGltZSB0byBSZWxheCE=%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TRANSFER_ENCODING: "base64"},
stream,
)
result = await obj.read(decode=True)
assert b"Time to Relax!" == result
async def test_read_with_content_transfer_encoding_quoted_printable(self) -> None:
with Stream(
b"=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,"
b" =D0=BC=D0=B8=D1=80!%s--:--" % newline
) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TRANSFER_ENCODING: "quoted-printable"},
stream,
)
result = await obj.read(decode=True)
expected = (
b"\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,"
b" \xd0\xbc\xd0\xb8\xd1\x80!"
)
assert result == expected
async def test_decode_with_content_transfer_encoding_base64(self) -> None:
with Stream(b"VG\r\r\nltZSB0byBSZ\r\nWxheCE=\r\n--:--") as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY, {CONTENT_TRANSFER_ENCODING: "base64"}, stream
)
result = b""
while not obj.at_eof():
chunk = await obj.read_chunk(size=6)
result += obj.decode(chunk)
assert b"Time to Relax!" == result
@pytest.mark.parametrize("encoding", ("binary", "8bit", "7bit"))
async def test_read_with_content_transfer_encoding_binary(
self, encoding: str
) -> None:
data = (
b"\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82,"
b" \xd0\xbc\xd0\xb8\xd1\x80!"
)
with Stream(data + b"%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TRANSFER_ENCODING: encoding},
stream,
)
result = await obj.read(decode=True)
assert data == result
async def test_read_with_content_transfer_encoding_unknown(self) -> None:
with Stream(b"\x0e4Time to Relax!%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TRANSFER_ENCODING: "unknown"},
stream,
)
with pytest.raises(RuntimeError):
await obj.read(decode=True)
async def test_read_text(self) -> None:
with Stream(b"Hello, world!%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{},
stream,
)
result = await obj.text()
assert "Hello, world!" == result
async def test_read_text_default_encoding(self) -> None:
data = "Привет, Мир!"
tail = b"%s--:--" % newline
with Stream(data.encode("utf-8") + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{},
stream,
)
result = await obj.text()
assert data == result
async def test_read_text_encoding(self) -> None:
data = "Привет, Мир!"
tail = b"%s--:--" % newline
with Stream(data.encode("cp1251") + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{},
stream,
)
result = await obj.text(encoding="cp1251")
assert data == result
async def test_read_text_guess_encoding(self) -> None:
data = "Привет, Мир!"
tail = b"%s--:--" % newline
with Stream(data.encode("cp1251") + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "text/plain;charset=cp1251"},
stream,
)
result = await obj.text()
assert data == result
async def test_read_text_compressed(self) -> None:
data = b"\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_ENCODING: "deflate", CONTENT_TYPE: "text/plain"},
stream,
)
result = await obj.text()
assert "Time to Relax!" == result
async def test_read_text_while_closed(self) -> None:
with Stream(b"") as stream:
obj = aiohttp.BodyPartReader(BOUNDARY, {CONTENT_TYPE: "text/plain"}, stream)
obj._at_eof = True
result = await obj.text()
assert "" == result
async def test_read_json(self) -> None:
with Stream(b'{"test": "passed"}%s--:--' % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/json"},
stream,
)
result = await obj.json()
assert {"test": "passed"} == result
async def test_read_json_encoding(self) -> None:
data = '{"тест": "пассед"}'.encode("cp1251")
tail = b"%s--:--" % newline
with Stream(data + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/json"},
stream,
)
result = await obj.json(encoding="cp1251")
assert {"тест": "пассед"} == result
async def test_read_json_guess_encoding(self) -> None:
data = '{"тест": "пассед"}'.encode("cp1251")
tail = b"%s--:--" % newline
with Stream(data + tail) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/json; charset=cp1251"},
stream,
)
result = await obj.json()
assert {"тест": "пассед"} == result
async def test_read_json_compressed(self) -> None:
with Stream(b"\xabV*I-.Q\xb2RP*H,.NMQ\xaa\x05\x00%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_ENCODING: "deflate", CONTENT_TYPE: "application/json"},
stream,
)
result = await obj.json()
assert {"test": "passed"} == result
async def test_read_json_while_closed(self) -> None:
with Stream(b"") as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY, {CONTENT_TYPE: "application/json"}, stream
)
obj._at_eof = True
result = await obj.json()
assert result is None
async def test_read_form(self) -> None:
data = b"foo=bar&foo=baz&boo=%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/x-www-form-urlencoded"},
stream,
)
result = await obj.form()
assert [("foo", "bar"), ("foo", "baz"), ("boo", "")] == result
async def test_read_form_invalid_utf8(self) -> None:
invalid_unicode_byte = b"\xff"
data = invalid_unicode_byte + b"%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/x-www-form-urlencoded"},
stream,
)
with pytest.raises(
ValueError, match="data cannot be decoded with utf-8 encoding"
):
await obj.form()
async def test_read_form_encoding(self) -> None:
data = b"foo=bar&foo=baz&boo=%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/x-www-form-urlencoded"},
stream,
)
result = await obj.form(encoding="cp1251")
assert [("foo", "bar"), ("foo", "baz"), ("boo", "")] == result
async def test_read_form_guess_encoding(self) -> None:
data = b"foo=bar&foo=baz&boo=%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/x-www-form-urlencoded; charset=utf-8"},
stream,
)
result = await obj.form()
assert [("foo", "bar"), ("foo", "baz"), ("boo", "")] == result
async def test_read_form_while_closed(self) -> None:
with Stream(b"") as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{CONTENT_TYPE: "application/x-www-form-urlencoded"},
stream,
)
obj._at_eof = True
result = await obj.form()
assert not result
async def test_readline(self) -> None:
data = b"Hello\n,\r\nworld!%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{},
stream,
)
result = await obj.readline()
assert b"Hello\n" == result
result = await obj.readline()
assert b",\r\n" == result
result = await obj.readline()
assert b"world!" == result
result = await obj.readline()
assert b"" == result
assert obj.at_eof()
async def test_release(self) -> None:
data = b"Hello,%s--:\r\n\r\nworld!%s--:--" % (newline, newline)
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{},
stream,
)
remained = b"--:\r\n\r\nworld!%s--:--" % newline
await obj.release()
assert obj.at_eof()
assert remained == stream.content.read()
async def test_release_respects_content_length(self) -> None:
with Stream(b"." * 100500 + b"%s--:--" % newline) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{"CONTENT-LENGTH": 100500},
stream,
)
result = await obj.release()
assert result is None
assert obj.at_eof()
async def test_release_release(self) -> None:
data = b"Hello,%s--:\r\n\r\nworld!%s--:--" % (newline, newline)
remained = b"--:\r\n\r\nworld!%s--:--" % newline
with Stream(data) as stream:
obj = aiohttp.BodyPartReader(
BOUNDARY,
{},
stream,
)
await obj.release()
await obj.release()
assert remained == stream.content.read()
async def test_filename(self) -> None:
part = aiohttp.BodyPartReader(
BOUNDARY, {CONTENT_DISPOSITION: "attachment; filename=foo.html"}, None
)
assert "foo.html" == part.filename
async def test_reading_long_part(self) -> None:
size = 2 * 2**16
protocol = mock.Mock(_reading_paused=False)
stream = StreamReader(protocol, 2**16, loop=asyncio.get_event_loop())
stream.feed_data(b"0" * size + b"\r\n--:--")
stream.feed_eof()
obj = aiohttp.BodyPartReader(BOUNDARY, {}, stream)
data = await obj.read()
assert len(data) == size
class TestMultipartReader:
def test_from_response(self) -> None:
with Stream(b"--:%s\r\nhello%s--:--" % (newline, newline)) as stream:
resp = Response(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
res = aiohttp.MultipartReader.from_response(resp)
assert isinstance(res, MultipartResponseWrapper)
assert isinstance(res.stream, aiohttp.MultipartReader)
def test_bad_boundary(self) -> None:
with Stream(b"") as stream:
resp = Response(
{CONTENT_TYPE: "multipart/related;boundary=" + "a" * 80}, stream
)
with pytest.raises(ValueError):
aiohttp.MultipartReader.from_response(resp)
def test_dispatch(self) -> None:
with Stream(b"--:%s\r\necho%s--:--" % (newline, newline)) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
res = reader._get_part_reader({CONTENT_TYPE: "text/plain"})
assert isinstance(res, reader.part_reader_cls)
def test_dispatch_bodypart(self) -> None:
with Stream(b"--:%s\r\necho%s--:--" % (newline, newline)) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
res = reader._get_part_reader({CONTENT_TYPE: "text/plain"})
assert isinstance(res, reader.part_reader_cls)
def test_dispatch_multipart(self) -> None:
with Stream(
newline.join(
[
b"----:--",
b"",
b"test",
b"----:--",
b"",
b"passed",
b"----:------:--",
]
)
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
res = reader._get_part_reader(
{CONTENT_TYPE: "multipart/related;boundary=--:--"}
)
assert isinstance(res, reader.__class__)
def test_dispatch_custom_multipart_reader(self) -> None:
class CustomReader(aiohttp.MultipartReader):
pass
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
Stream(
b"----:--\r\n"
b"\r\n"
b"test\r\n"
b"----:--\r\n"
b"\r\n"
b"passed\r\n"
b"----:----\r\n"
b"--:--"
),
)
reader.multipart_reader_cls = CustomReader
res = reader._get_part_reader(
{CONTENT_TYPE: "multipart/related;boundary=--:--"}
)
assert isinstance(res, CustomReader)
async def test_emit_next(self) -> None:
with Stream(b"--:%s\r\necho%s--:--" % (newline, newline)) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
res = await reader.next()
assert isinstance(res, reader.part_reader_cls)
async def test_invalid_boundary(self) -> None:
with Stream(b"---:%s\r\necho%s---:--" % (newline, newline)) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
with pytest.raises(ValueError):
await reader.next()
@pytest.mark.skipif(sys.version_info < (3, 10), reason="Needs anext()")
async def test_read_boundary_across_chunks(self) -> None:
class SplitBoundaryStream:
def __init__(self) -> None:
self.content = [
b"--foobar\r\n\r\n",
b"Hello,\r\n-",
b"-fo",
b"ob",
b"ar\r\n",
b"\r\nwor",
b"ld!",
b"\r\n--f",
b"oobar--",
]
async def read(self, size=None) -> bytes:
chunk = self.content.pop(0)
assert len(chunk) <= size
return chunk
def at_eof(self) -> bool:
return not self.content
async def readline(self) -> bytes:
line = b""
while self.content and b"\n" not in line:
line += self.content.pop(0)
line, *extra = line.split(b"\n", maxsplit=1)
if extra and extra[0]:
self.content.insert(0, extra[0])
return line + b"\n"
def unread_data(self, data: bytes) -> None:
if self.content:
self.content[0] = data + self.content[0]
else:
self.content.append(data)
stream = SplitBoundaryStream()
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary="foobar"'}, stream
)
part = await anext(reader)
result = await part.read_chunk(10)
assert result == b"Hello,"
result = await part.read_chunk(10)
assert result == b""
assert part.at_eof()
part = await anext(reader)
result = await part.read_chunk(10)
assert result == b"world!"
result = await part.read_chunk(10)
assert result == b""
assert part.at_eof()
with pytest.raises(StopAsyncIteration):
await anext(reader)
async def test_release(self) -> None:
with Stream(
newline.join(
[
b"--:",
b"Content-Type: multipart/related;boundary=--:--",
b"",
b"----:--",
b"",
b"test",
b"----:--",
b"",
b"passed",
b"----:----",
b"",
b"--:--",
]
)
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/mixed;boundary=":"'},
stream,
)
await reader.release()
assert reader.at_eof()
async def test_release_release(self) -> None:
with Stream(b"--:%s\r\necho%s--:--" % (newline, newline)) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
await reader.release()
assert reader.at_eof()
await reader.release()
assert reader.at_eof()
async def test_release_next(self) -> None:
with Stream(b"--:%s\r\necho%s--:--" % (newline, newline)) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
await reader.release()
assert reader.at_eof()
res = await reader.next()
assert res is None
async def test_second_next_releases_previous_object(self) -> None:
with Stream(
newline.join(
[
b"--:",
b"",
b"test",
b"--:",
b"",
b"passed",
b"--:--",
]
)
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
first = await reader.next()
assert isinstance(first, aiohttp.BodyPartReader)
second = await reader.next()
assert first.at_eof()
assert not second.at_eof()
async def test_release_without_read_the_last_object(self) -> None:
with Stream(
newline.join(
[
b"--:",
b"",
b"test",
b"--:",
b"",
b"passed",
b"--:--",
]
)
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
first = await reader.next()
second = await reader.next()
third = await reader.next()
assert first.at_eof()
assert second.at_eof()
assert second.at_eof()
assert third is None
async def test_read_chunk_by_length_doesnt_breaks_reader(self) -> None:
with Stream(
newline.join(
[
b"--:",
b"Content-Length: 4",
b"",
b"test",
b"--:",
b"Content-Length: 6",
b"",
b"passed",
b"--:--",
]
)
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
body_parts = []
while True:
read_part = b""
part = await reader.next()
if part is None:
break
while not part.at_eof():
read_part += await part.read_chunk(3)
body_parts.append(read_part)
assert body_parts == [b"test", b"passed"]
async def test_read_chunk_from_stream_doesnt_breaks_reader(self) -> None:
with Stream(
newline.join(
[
b"--:",
b"",
b"chunk",
b"--:",
b"",
b"two_chunks",
b"--:--",
]
)
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
body_parts = []
while True:
read_part = b""
part = await reader.next()
if part is None:
break
while not part.at_eof():
chunk = await part.read_chunk(5)
assert chunk
read_part += chunk
body_parts.append(read_part)
assert body_parts == [b"chunk", b"two_chunks"]
async def test_reading_skips_prelude(self) -> None:
with Stream(
newline.join(
[
b"Multi-part data is not supported.",
b"",
b"--:",
b"",
b"test",
b"--:",
b"",
b"passed",
b"--:--",
]
)
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/related;boundary=":"'},
stream,
)
first = await reader.next()
assert isinstance(first, aiohttp.BodyPartReader)
second = await reader.next()
assert first.at_eof()
assert not second.at_eof()
async def test_read_form_default_encoding(self) -> None:
with Stream(
b"--:\r\n"
b'Content-Disposition: form-data; name="_charset_"\r\n\r\n'
b"ascii"
b"\r\n"
b"--:\r\n"
b'Content-Disposition: form-data; name="field1"\r\n\r\n'
b"foo"
b"\r\n"
b"--:\r\n"
b"Content-Type: text/plain;charset=UTF-8\r\n"
b'Content-Disposition: form-data; name="field2"\r\n\r\n'
b"foo"
b"\r\n"
b"--:\r\n"
b'Content-Disposition: form-data; name="field3"\r\n\r\n'
b"foo"
b"\r\n"
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/form-data;boundary=":"'},
stream,
)
field1 = await reader.next()
assert field1.name == "field1"
assert field1.get_charset("default") == "ascii"
field2 = await reader.next()
assert field2.name == "field2"
assert field2.get_charset("default") == "UTF-8"
field3 = await reader.next()
assert field3.name == "field3"
assert field3.get_charset("default") == "ascii"
async def test_read_form_invalid_default_encoding(self) -> None:
with Stream(
b"--:\r\n"
b'Content-Disposition: form-data; name="_charset_"\r\n\r\n'
b"this-value-is-too-long-to-be-a-charset"
b"\r\n"
b"--:\r\n"
b'Content-Disposition: form-data; name="field1"\r\n\r\n'
b"foo"
b"\r\n"
) as stream:
reader = aiohttp.MultipartReader(
{CONTENT_TYPE: 'multipart/form-data;boundary=":"'},
stream,
)
with pytest.raises(RuntimeError, match="Invalid default charset"):
await reader.next()
async def test_writer(writer) -> None:
assert writer.size == 7
assert writer.boundary == ":"
async def test_writer_serialize_io_chunk(buf, stream, writer) -> None:
with io.BytesIO(b"foobarbaz") as file_handle:
writer.append(file_handle)
await writer.write(stream)
assert (
buf == b"--:\r\nContent-Type: application/octet-stream"
b"\r\nContent-Length: 9\r\n\r\nfoobarbaz\r\n--:--\r\n"
)
async def test_writer_serialize_json(buf, stream, writer) -> None:
writer.append_json({"привет": "мир"})
await writer.write(stream)
assert (
b'{"\\u043f\\u0440\\u0438\\u0432\\u0435\\u0442":'
b' "\\u043c\\u0438\\u0440"}' in buf
)
async def test_writer_serialize_form(buf, stream, writer) -> None:
data = [("foo", "bar"), ("foo", "baz"), ("boo", "zoo")]
writer.append_form(data)
await writer.write(stream)
assert b"foo=bar&foo=baz&boo=zoo" in buf
async def test_writer_serialize_form_dict(buf, stream, writer) -> None:
data = {"hello": "мир"}
writer.append_form(data)
await writer.write(stream)
assert b"hello=%D0%BC%D0%B8%D1%80" in buf
async def test_writer_write(buf, stream, writer) -> None:
writer.append("foo-bar-baz")
writer.append_json({"test": "passed"})
writer.append_form({"test": "passed"})
writer.append_form([("one", 1), ("two", 2)])
sub_multipart = aiohttp.MultipartWriter(boundary="::")
sub_multipart.append("nested content")
sub_multipart.headers["X-CUSTOM"] = "test"
writer.append(sub_multipart)
await writer.write(stream)
assert (
b"--:\r\n"
b"Content-Type: text/plain; charset=utf-8\r\n"
b"Content-Length: 11\r\n\r\n"
b"foo-bar-baz"
b"\r\n"
b"--:\r\n"
b"Content-Type: application/json\r\n"
b"Content-Length: 18\r\n\r\n"
b'{"test": "passed"}'
b"\r\n"
b"--:\r\n"
b"Content-Type: application/x-www-form-urlencoded\r\n"
b"Content-Length: 11\r\n\r\n"
b"test=passed"
b"\r\n"
b"--:\r\n"
b"Content-Type: application/x-www-form-urlencoded\r\n"
b"Content-Length: 11\r\n\r\n"
b"one=1&two=2"
b"\r\n"
b"--:\r\n"
b'Content-Type: multipart/mixed; boundary="::"\r\n'
b"X-CUSTOM: test\r\nContent-Length: 93\r\n\r\n"
b"--::\r\n"
b"Content-Type: text/plain; charset=utf-8\r\n"
b"Content-Length: 14\r\n\r\n"
b"nested content\r\n"
b"--::--\r\n"
b"\r\n"
b"--:--\r\n"
) == bytes(buf)
async def test_writer_write_no_close_boundary(buf, stream) -> None:
writer = aiohttp.MultipartWriter(boundary=":")
writer.append("foo-bar-baz")
writer.append_json({"test": "passed"})
writer.append_form({"test": "passed"})
writer.append_form([("one", 1), ("two", 2)])
await writer.write(stream, close_boundary=False)
assert (
b"--:\r\n"
b"Content-Type: text/plain; charset=utf-8\r\n"
b"Content-Length: 11\r\n\r\n"
b"foo-bar-baz"
b"\r\n"
b"--:\r\n"
b"Content-Type: application/json\r\n"
b"Content-Length: 18\r\n\r\n"
b'{"test": "passed"}'
b"\r\n"
b"--:\r\n"
b"Content-Type: application/x-www-form-urlencoded\r\n"
b"Content-Length: 11\r\n\r\n"
b"test=passed"
b"\r\n"
b"--:\r\n"
b"Content-Type: application/x-www-form-urlencoded\r\n"
b"Content-Length: 11\r\n\r\n"
b"one=1&two=2"
b"\r\n"
) == bytes(buf)
async def test_writer_write_no_parts(buf, stream, writer) -> None:
await writer.write(stream)
assert b"--:--\r\n" == bytes(buf)
async def test_writer_serialize_with_content_encoding_gzip(buf, stream, writer):
writer.append("Time to Relax!", {CONTENT_ENCODING: "gzip"})
await writer.write(stream)
headers, message = bytes(buf).split(b"\r\n\r\n", 1)
assert (
b"--:\r\nContent-Type: text/plain; charset=utf-8\r\n"
b"Content-Encoding: gzip" == headers
)
decompressor = zlib.decompressobj(wbits=16 + zlib.MAX_WBITS)
data = decompressor.decompress(message.split(b"\r\n")[0])
data += decompressor.flush()
assert b"Time to Relax!" == data
async def test_writer_serialize_with_content_encoding_deflate(buf, stream, writer):
writer.append("Time to Relax!", {CONTENT_ENCODING: "deflate"})
await writer.write(stream)
headers, message = bytes(buf).split(b"\r\n\r\n", 1)
assert (
b"--:\r\nContent-Type: text/plain; charset=utf-8\r\n"
b"Content-Encoding: deflate" == headers
)
thing = b"\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00\r\n--:--\r\n"
assert thing == message
async def test_writer_serialize_with_content_encoding_identity(buf, stream, writer):
thing = b"\x0b\xc9\xccMU(\xc9W\x08J\xcdI\xacP\x04\x00"
writer.append(thing, {CONTENT_ENCODING: "identity"})
await writer.write(stream)
headers, message = bytes(buf).split(b"\r\n\r\n", 1)
assert (
b"--:\r\nContent-Type: application/octet-stream\r\n"
b"Content-Encoding: identity\r\n"
b"Content-Length: 16" == headers
)
assert thing == message.split(b"\r\n")[0]
def test_writer_serialize_with_content_encoding_unknown(buf, stream, writer):
with pytest.raises(RuntimeError):
writer.append("Time to Relax!", {CONTENT_ENCODING: "snappy"})
async def test_writer_with_content_transfer_encoding_base64(buf, stream, writer):
writer.append("Time to Relax!", {CONTENT_TRANSFER_ENCODING: "base64"})
await writer.write(stream)
headers, message = bytes(buf).split(b"\r\n\r\n", 1)
assert (
b"--:\r\nContent-Type: text/plain; charset=utf-8\r\n"
b"Content-Transfer-Encoding: base64" == headers
)
assert b"VGltZSB0byBSZWxheCE=" == message.split(b"\r\n")[0]
async def test_writer_content_transfer_encoding_quote_printable(buf, stream, writer):
writer.append("Привет, мир!", {CONTENT_TRANSFER_ENCODING: "quoted-printable"})
await writer.write(stream)
headers, message = bytes(buf).split(b"\r\n\r\n", 1)
assert (
b"--:\r\nContent-Type: text/plain; charset=utf-8\r\n"
b"Content-Transfer-Encoding: quoted-printable" == headers
)
assert (
b"=D0=9F=D1=80=D0=B8=D0=B2=D0=B5=D1=82,"
b" =D0=BC=D0=B8=D1=80!" == message.split(b"\r\n")[0]
)
def test_writer_content_transfer_encoding_unknown(buf, stream, writer) -> None:
with pytest.raises(RuntimeError):
writer.append("Time to Relax!", {CONTENT_TRANSFER_ENCODING: "unknown"})
class TestMultipartWriter:
def test_default_subtype(self, writer) -> None:
mimetype = parse_mimetype(writer.headers.get(CONTENT_TYPE))
assert "multipart" == mimetype.type
assert "mixed" == mimetype.subtype
def test_unquoted_boundary(self) -> None:
writer = aiohttp.MultipartWriter(boundary="abc123")
expected = {CONTENT_TYPE: "multipart/mixed; boundary=abc123"}
assert expected == writer.headers
def test_quoted_boundary(self) -> None:
writer = aiohttp.MultipartWriter(boundary=R"\"")
expected = {CONTENT_TYPE: R'multipart/mixed; boundary="\\\""'}
assert expected == writer.headers
def test_bad_boundary(self) -> None:
with pytest.raises(ValueError):
aiohttp.MultipartWriter(boundary="тест")
with pytest.raises(ValueError):
aiohttp.MultipartWriter(boundary="test\n")
def test_default_headers(self, writer) -> None:
expected = {CONTENT_TYPE: 'multipart/mixed; boundary=":"'}
assert expected == writer.headers
def test_iter_parts(self, writer) -> None:
writer.append("foo")
writer.append("bar")
writer.append("baz")
assert 3 == len(list(writer))
def test_append(self, writer) -> None:
assert 0 == len(writer)
writer.append("hello, world!")
assert 1 == len(writer)
assert isinstance(writer._parts[0][0], payload.Payload)
def test_append_with_headers(self, writer) -> None:
writer.append("hello, world!", {"x-foo": "bar"})
assert 1 == len(writer)
assert "x-foo" in writer._parts[0][0].headers
assert writer._parts[0][0].headers["x-foo"] == "bar"
def test_append_json(self, writer) -> None:
writer.append_json({"foo": "bar"})
assert 1 == len(writer)
part = writer._parts[0][0]
assert part.headers[CONTENT_TYPE] == "application/json"
def test_append_part(self, writer) -> None:
part = payload.get_payload("test", headers={CONTENT_TYPE: "text/plain"})
writer.append(part, {CONTENT_TYPE: "test/passed"})
assert 1 == len(writer)
part = writer._parts[0][0]
assert part.headers[CONTENT_TYPE] == "test/passed"
def test_append_json_overrides_content_type(self, writer) -> None:
writer.append_json({"foo": "bar"}, {CONTENT_TYPE: "test/passed"})
assert 1 == len(writer)
part = writer._parts[0][0]
assert part.headers[CONTENT_TYPE] == "test/passed"
def test_append_form(self, writer) -> None:
writer.append_form({"foo": "bar"}, {CONTENT_TYPE: "test/passed"})
assert 1 == len(writer)
part = writer._parts[0][0]
assert part.headers[CONTENT_TYPE] == "test/passed"
def test_append_multipart(self, writer) -> None:
subwriter = aiohttp.MultipartWriter(boundary=":")
subwriter.append_json({"foo": "bar"})
writer.append(subwriter, {CONTENT_TYPE: "test/passed"})
assert 1 == len(writer)
part = writer._parts[0][0]
assert part.headers[CONTENT_TYPE] == "test/passed"
def test_set_content_disposition_after_append(self):
writer = aiohttp.MultipartWriter("form-data")
part = writer.append("some-data")
part.set_content_disposition("form-data", name="method")
assert 'name="method"' in part.headers[CONTENT_DISPOSITION]
def test_automatic_content_disposition(self):
writer = aiohttp.MultipartWriter("form-data")
writer.append_json(())
part = payload.StringPayload("foo")
part.set_content_disposition("form-data", name="second")
writer.append_payload(part)
writer.append("foo")
disps = tuple(p[0].headers[CONTENT_DISPOSITION] for p in writer._parts)
assert 'name="section-0"' in disps[0]
assert 'name="second"' in disps[1]
assert 'name="section-2"' in disps[2]
def test_with(self) -> None:
with aiohttp.MultipartWriter(boundary=":") as writer:
writer.append("foo")
writer.append(b"bar")
writer.append_json({"baz": True})
assert 3 == len(writer)
def test_append_int_not_allowed(self) -> None:
with pytest.raises(TypeError):
with aiohttp.MultipartWriter(boundary=":") as writer:
writer.append(1)
def test_append_float_not_allowed(self) -> None:
with pytest.raises(TypeError):
with aiohttp.MultipartWriter(boundary=":") as writer:
writer.append(1.1)
def test_append_none_not_allowed(self) -> None:
with pytest.raises(TypeError):
with aiohttp.MultipartWriter(boundary=":") as writer:
writer.append(None)
async def test_write_preserves_content_disposition(self, buf, stream) -> None:
with aiohttp.MultipartWriter(boundary=":") as writer:
part = writer.append(b"foo", headers={CONTENT_TYPE: "test/passed"})
part.set_content_disposition("form-data", filename="bug")
await writer.write(stream)
headers, message = bytes(buf).split(b"\r\n\r\n", 1)
assert headers == (
b"--:\r\n"
b"Content-Type: test/passed\r\n"
b"Content-Length: 3\r\n"
b"Content-Disposition:"
b' form-data; filename="bug"'
)
assert message == b"foo\r\n--:--\r\n"
async def test_preserve_content_disposition_header(self, buf, stream):
# https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
with pathlib.Path(__file__).open("rb") as fobj:
with aiohttp.MultipartWriter("form-data", boundary=":") as writer:
part = writer.append(
fobj,
headers={
CONTENT_DISPOSITION: 'attachments; filename="bug.py"',
CONTENT_TYPE: "text/python",
},
)
await writer.write(stream)
assert part.headers[CONTENT_TYPE] == "text/python"
assert part.headers[CONTENT_DISPOSITION] == ('attachments; filename="bug.py"')
headers, _ = bytes(buf).split(b"\r\n\r\n", 1)
assert headers == (
b"--:\r\n"
b"Content-Type: text/python\r\n"
b'Content-Disposition: attachments; filename="bug.py"'
)
async def test_set_content_disposition_override(self, buf, stream):
# https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
with pathlib.Path(__file__).open("rb") as fobj:
with aiohttp.MultipartWriter("form-data", boundary=":") as writer:
part = writer.append(
fobj,
headers={
CONTENT_DISPOSITION: 'attachments; filename="bug.py"',
CONTENT_TYPE: "text/python",
},
)
await writer.write(stream)
assert part.headers[CONTENT_TYPE] == "text/python"
assert part.headers[CONTENT_DISPOSITION] == ('attachments; filename="bug.py"')
headers, _ = bytes(buf).split(b"\r\n\r\n", 1)
assert headers == (
b"--:\r\n"
b"Content-Type: text/python\r\n"
b'Content-Disposition: attachments; filename="bug.py"'
)
async def test_reset_content_disposition_header(self, buf, stream):
# https://github.com/aio-libs/aiohttp/pull/3475#issuecomment-451072381
with pathlib.Path(__file__).open("rb") as fobj:
with aiohttp.MultipartWriter("form-data", boundary=":") as writer:
part = writer.append(
fobj,
headers={CONTENT_TYPE: "text/plain"},
)
assert CONTENT_DISPOSITION in part.headers
part.set_content_disposition("attachments", filename="bug.py")
await writer.write(stream)
headers, _ = bytes(buf).split(b"\r\n\r\n", 1)
assert headers == (
b"--:\r\n"
b"Content-Type: text/plain\r\n"
b"Content-Disposition:"
b' attachments; filename="bug.py"'
)
async def test_async_for_reader() -> None:
data = [{"test": "passed"}, 42, b"plain text", b"aiohttp\n", b"no epilogue"]
with Stream(
b"\r\n".join(
[
b"--:",
b"Content-Type: application/json",
b"",
json.dumps(data[0]).encode(),
b"--:",
b"Content-Type: application/json",
b"",
json.dumps(data[1]).encode(),
b"--:",
b'Content-Type: multipart/related; boundary="::"',
b"",
b"--::",
b"Content-Type: text/plain",
b"",
data[2],
b"--::",
b'Content-Disposition: attachment; filename="aiohttp"',
b"Content-Type: text/plain",
b"Content-Length: 28",
b"Content-Encoding: gzip",
b"",
b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03K\xcc\xcc\xcf())"
b"\xe0\x02\x00\xd6\x90\xe2O\x08\x00\x00\x00",
b"--::",
b'Content-Type: multipart/related; boundary=":::"',
b"",
b"--:::",
b"Content-Type: text/plain",
b"",
data[4],
b"--:::--",
b"--::--",
b"",
b"--:--",
b"",
]
)
) as stream:
reader = aiohttp.MultipartReader(
headers={CONTENT_TYPE: 'multipart/mixed; boundary=":"'},
content=stream,
)
idata = iter(data)
async def check(reader):
async for part in reader:
if isinstance(part, aiohttp.BodyPartReader):
if part.headers[CONTENT_TYPE] == "application/json":
assert next(idata) == (await part.json())
else:
assert next(idata) == await part.read(decode=True)
else:
await check(part)
await check(reader)
async def test_async_for_bodypart() -> None:
with Stream(b"foobarbaz\r\n--:--") as stream:
part = aiohttp.BodyPartReader(boundary=b"--:", headers={}, content=stream)
async for data in part:
assert data == b"foobarbaz"
|