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
|
# Tests for streams.py
import abc
import asyncio
import gc
import types
from collections import defaultdict
from itertools import groupby
from unittest import mock
import pytest
from re_assert import Matches
from aiohttp import streams
from aiohttp.helpers import PY_311
DATA = b"line1\nline2\nline3\n"
def chunkify(seq, n):
for i in range(0, len(seq), n):
yield seq[i : i + n]
async def create_stream():
loop = asyncio.get_event_loop()
protocol = mock.Mock(_reading_paused=False)
stream = streams.StreamReader(protocol, 2**16, loop=loop)
stream.feed_data(DATA)
stream.feed_eof()
return stream
@pytest.fixture
def protocol():
return mock.Mock(_reading_paused=False)
MEMLEAK_SKIP_TYPES = (
*(getattr(types, name) for name in types.__all__ if name.endswith("Type")),
mock.Mock,
abc.ABCMeta,
)
def get_memory_usage(obj):
objs = [obj]
# Memory leak may be caused by leaked links to same objects.
# Without link counting, [1,2,3] is indistiguishable from [1,2,3,3,3,3,3,3]
known = defaultdict(int)
known[id(obj)] += 1
while objs:
refs = gc.get_referents(*objs)
objs = []
for obj in refs:
if isinstance(obj, MEMLEAK_SKIP_TYPES):
continue
i = id(obj)
known[i] += 1
if known[i] == 1:
objs.append(obj)
# Make list of unhashable objects uniq
objs.sort(key=id)
objs = [next(g) for (i, g) in groupby(objs, id)]
return sum(known.values())
class TestStreamReader:
DATA = b"line1\nline2\nline3\n"
def _make_one(self, *args, **kwargs):
kwargs.setdefault("limit", 2**16)
return streams.StreamReader(mock.Mock(_reading_paused=False), *args, **kwargs)
async def test_create_waiter(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one(loop=loop)
stream._waiter = loop.create_future
with pytest.raises(RuntimeError):
await stream._wait("test")
@pytest.mark.xfail(
PY_311,
reason="No idea why ClientRequest() is constructed out of loop but "
"it calls `asyncio.get_event_loop()`",
raises=DeprecationWarning,
)
def test_ctor_global_loop(self) -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
stream = streams.StreamReader(mock.Mock(_reading_paused=False), 2**16)
assert stream._loop is loop
finally: # Otherwise an unstopped/unclosed loop affects the next test
# Cleanup, leaks into `test_at_eof` otherwise:
loop.stop()
loop.run_forever()
loop.close()
gc.collect()
async def test_at_eof(self) -> None:
stream = self._make_one()
assert not stream.at_eof()
stream.feed_data(b"some data\n")
assert not stream.at_eof()
await stream.readline()
assert not stream.at_eof()
stream.feed_data(b"some data\n")
stream.feed_eof()
await stream.readline()
assert stream.at_eof()
async def test_wait_eof(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
wait_task = loop.create_task(stream.wait_eof())
async def cb():
await asyncio.sleep(0.1)
stream.feed_eof()
loop.create_task(cb())
await wait_task
assert stream.is_eof()
assert stream._eof_waiter is None
async def test_wait_eof_eof(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
stream.feed_eof()
wait_task = loop.create_task(stream.wait_eof())
await wait_task
assert stream.is_eof()
async def test_feed_empty_data(self) -> None:
stream = self._make_one()
stream.feed_data(b"")
stream.feed_eof()
data = await stream.read()
assert b"" == data
async def test_feed_nonempty_data(self) -> None:
stream = self._make_one()
stream.feed_data(self.DATA)
stream.feed_eof()
data = await stream.read()
assert self.DATA == data
async def test_read_zero(self) -> None:
# Read zero bytes.
stream = self._make_one()
stream.feed_data(self.DATA)
data = await stream.read(0)
assert b"" == data
stream.feed_eof()
data = await stream.read()
assert self.DATA == data
async def test_read(self) -> None:
loop = asyncio.get_event_loop()
# Read bytes.
stream = self._make_one()
read_task = loop.create_task(stream.read(30))
def cb():
stream.feed_data(self.DATA)
loop.call_soon(cb)
data = await read_task
assert self.DATA == data
stream.feed_eof()
data = await stream.read()
assert b"" == data
async def test_read_line_breaks(self) -> None:
# Read bytes without line breaks.
stream = self._make_one()
stream.feed_data(b"line1")
stream.feed_data(b"line2")
data = await stream.read(5)
assert b"line1" == data
data = await stream.read(5)
assert b"line2" == data
async def test_read_all(self) -> None:
# Read all available buffered bytes
stream = self._make_one()
stream.feed_data(b"line1")
stream.feed_data(b"line2")
stream.feed_eof()
data = await stream.read()
assert b"line1line2" == data
async def test_read_up_to(self) -> None:
# Read available buffered bytes up to requested amount
stream = self._make_one()
stream.feed_data(b"line1")
stream.feed_data(b"line2")
data = await stream.read(8)
assert b"line1lin" == data
data = await stream.read(8)
assert b"e2" == data
async def test_read_eof(self) -> None:
loop = asyncio.get_event_loop()
# Read bytes, stop at eof.
stream = self._make_one()
read_task = loop.create_task(stream.read(1024))
def cb():
stream.feed_eof()
loop.call_soon(cb)
data = await read_task
assert b"" == data
data = await stream.read()
assert data == b""
async def test_read_eof_infinite(self) -> None:
# Read bytes.
stream = self._make_one()
stream.feed_eof()
with mock.patch("aiohttp.streams.internal_logger") as internal_logger:
await stream.read()
await stream.read()
await stream.read()
await stream.read()
await stream.read()
await stream.read()
assert internal_logger.warning.called
async def test_read_eof_unread_data_no_warning(self) -> None:
# Read bytes.
stream = self._make_one()
stream.feed_eof()
with mock.patch("aiohttp.streams.internal_logger") as internal_logger:
await stream.read()
await stream.read()
await stream.read()
await stream.read()
await stream.read()
with pytest.warns(DeprecationWarning):
stream.unread_data(b"data")
await stream.read()
await stream.read()
assert not internal_logger.warning.called
async def test_read_until_eof(self) -> None:
loop = asyncio.get_event_loop()
# Read all bytes until eof.
stream = self._make_one()
read_task = loop.create_task(stream.read(-1))
def cb():
stream.feed_data(b"chunk1\n")
stream.feed_data(b"chunk2")
stream.feed_eof()
loop.call_soon(cb)
data = await read_task
assert b"chunk1\nchunk2" == data
data = await stream.read()
assert b"" == data
async def test_read_exception(self) -> None:
stream = self._make_one()
stream.feed_data(b"line\n")
data = await stream.read(2)
assert b"li" == data
stream.set_exception(ValueError())
with pytest.raises(ValueError):
await stream.read(2)
async def test_readline(self) -> None:
loop = asyncio.get_event_loop()
# Read one line. 'readline' will need to wait for the data
# to come from 'cb'
stream = self._make_one()
stream.feed_data(b"chunk1 ")
read_task = loop.create_task(stream.readline())
def cb():
stream.feed_data(b"chunk2 ")
stream.feed_data(b"chunk3 ")
stream.feed_data(b"\n chunk4")
loop.call_soon(cb)
line = await read_task
assert b"chunk1 chunk2 chunk3 \n" == line
stream.feed_eof()
data = await stream.read()
assert b" chunk4" == data
async def test_readline_limit_with_existing_data(self) -> None:
# Read one line. The data is in StreamReader's buffer
# before the event loop is run.
stream = self._make_one(limit=2)
stream.feed_data(b"li")
stream.feed_data(b"ne1\nline2\n")
with pytest.raises(ValueError):
await stream.readline()
# The buffer should contain the remaining data after exception
stream.feed_eof()
data = await stream.read()
assert b"line2\n" == data
async def test_readline_limit(self) -> None:
loop = asyncio.get_event_loop()
# Read one line. StreamReaders are fed with data after
# their 'readline' methods are called.
stream = self._make_one(limit=4)
def cb():
stream.feed_data(b"chunk1")
stream.feed_data(b"chunk2\n")
stream.feed_data(b"chunk3\n")
stream.feed_eof()
loop.call_soon(cb)
with pytest.raises(ValueError):
await stream.readline()
data = await stream.read()
assert b"chunk3\n" == data
async def test_readline_nolimit_nowait(self) -> None:
# All needed data for the first 'readline' call will be
# in the buffer.
stream = self._make_one()
stream.feed_data(self.DATA[:6])
stream.feed_data(self.DATA[6:])
line = await stream.readline()
assert b"line1\n" == line
stream.feed_eof()
data = await stream.read()
assert b"line2\nline3\n" == data
async def test_readline_eof(self) -> None:
stream = self._make_one()
stream.feed_data(b"some data")
stream.feed_eof()
line = await stream.readline()
assert b"some data" == line
async def test_readline_empty_eof(self) -> None:
stream = self._make_one()
stream.feed_eof()
line = await stream.readline()
assert b"" == line
async def test_readline_read_byte_count(self) -> None:
stream = self._make_one()
stream.feed_data(self.DATA)
await stream.readline()
data = await stream.read(7)
assert b"line2\nl" == data
stream.feed_eof()
data = await stream.read()
assert b"ine3\n" == data
async def test_readline_exception(self) -> None:
stream = self._make_one()
stream.feed_data(b"line\n")
data = await stream.readline()
assert b"line\n" == data
stream.set_exception(ValueError())
with pytest.raises(ValueError):
await stream.readline()
async def test_readuntil(self) -> None:
loop = asyncio.get_event_loop()
# Read one chunk. 'readuntil' will need to wait for the data
# to come from 'cb'
stream = self._make_one()
stream.feed_data(b"chunk1 ")
read_task = loop.create_task(stream.readuntil(b"*"))
def cb():
stream.feed_data(b"chunk2 ")
stream.feed_data(b"chunk3 ")
stream.feed_data(b"* chunk4")
loop.call_soon(cb)
line = await read_task
assert b"chunk1 chunk2 chunk3 *" == line
stream.feed_eof()
data = await stream.read()
assert b" chunk4" == data
async def test_readuntil_limit_with_existing_data(self) -> None:
# Read one chunk. The data is in StreamReader's buffer
# before the event loop is run.
stream = self._make_one(limit=2)
stream.feed_data(b"li")
stream.feed_data(b"ne1&line2&")
with pytest.raises(ValueError):
await stream.readuntil(b"&")
# The buffer should contain the remaining data after exception
stream.feed_eof()
data = await stream.read()
assert b"line2&" == data
async def test_readuntil_limit(self) -> None:
loop = asyncio.get_event_loop()
# Read one chunk. StreamReaders are fed with data after
# their 'readuntil' methods are called.
stream = self._make_one(limit=4)
def cb():
stream.feed_data(b"chunk1")
stream.feed_data(b"chunk2$")
stream.feed_data(b"chunk3#")
stream.feed_eof()
loop.call_soon(cb)
with pytest.raises(ValueError):
await stream.readuntil(b"$")
data = await stream.read()
assert b"chunk3#" == data
async def test_readuntil_nolimit_nowait(self) -> None:
# All needed data for the first 'readuntil' call will be
# in the buffer.
stream = self._make_one()
data = b"line1!line2!line3!"
stream.feed_data(data[:6])
stream.feed_data(data[6:])
line = await stream.readuntil(b"!")
assert b"line1!" == line
stream.feed_eof()
data = await stream.read()
assert b"line2!line3!" == data
async def test_readuntil_eof(self) -> None:
stream = self._make_one()
stream.feed_data(b"some data")
stream.feed_eof()
line = await stream.readuntil(b"@")
assert b"some data" == line
async def test_readuntil_empty_eof(self) -> None:
stream = self._make_one()
stream.feed_eof()
line = await stream.readuntil(b"@")
assert b"" == line
async def test_readuntil_read_byte_count(self) -> None:
stream = self._make_one()
data = b"line1!line2!line3!"
stream.feed_data(data)
await stream.readuntil(b"!")
data = await stream.read(7)
assert b"line2!l" == data
stream.feed_eof()
data = await stream.read()
assert b"ine3!" == data
async def test_readuntil_exception(self) -> None:
stream = self._make_one()
stream.feed_data(b"line#")
data = await stream.readuntil(b"#")
assert b"line#" == data
stream.set_exception(ValueError())
with pytest.raises(ValueError):
await stream.readuntil(b"#")
async def test_readexactly_zero_or_less(self) -> None:
# Read exact number of bytes (zero or less).
stream = self._make_one()
stream.feed_data(self.DATA)
data = await stream.readexactly(0)
assert b"" == data
stream.feed_eof()
data = await stream.read()
assert self.DATA == data
stream = self._make_one()
stream.feed_data(self.DATA)
data = await stream.readexactly(-1)
assert b"" == data
stream.feed_eof()
data = await stream.read()
assert self.DATA == data
async def test_readexactly(self) -> None:
loop = asyncio.get_event_loop()
# Read exact number of bytes.
stream = self._make_one()
n = 2 * len(self.DATA)
read_task = loop.create_task(stream.readexactly(n))
def cb():
stream.feed_data(self.DATA)
stream.feed_data(self.DATA)
stream.feed_data(self.DATA)
loop.call_soon(cb)
data = await read_task
assert self.DATA + self.DATA == data
stream.feed_eof()
data = await stream.read()
assert self.DATA == data
async def test_readexactly_eof(self) -> None:
loop = asyncio.get_event_loop()
# Read exact number of bytes (eof).
stream = self._make_one(loop=loop)
n = 2 * len(self.DATA)
read_task = loop.create_task(stream.readexactly(n))
def cb():
stream.feed_data(self.DATA)
stream.feed_eof()
loop.call_soon(cb)
with pytest.raises(asyncio.IncompleteReadError) as cm:
await read_task
assert cm.value.partial == self.DATA
assert cm.value.expected == n
assert str(cm.value) == "18 bytes read on a total of 36 expected bytes"
data = await stream.read()
assert b"" == data
async def test_readexactly_exception(self) -> None:
stream = self._make_one()
stream.feed_data(b"line\n")
data = await stream.readexactly(2)
assert b"li" == data
stream.set_exception(ValueError())
with pytest.raises(ValueError):
await stream.readexactly(2)
async def test_unread_data(self) -> None:
stream = self._make_one()
stream.feed_data(b"line1")
stream.feed_data(b"line2")
stream.feed_data(b"onemoreline")
data = await stream.read(5)
assert b"line1" == data
with pytest.warns(DeprecationWarning):
stream.unread_data(data)
data = await stream.read(5)
assert b"line1" == data
data = await stream.read(4)
assert b"line" == data
with pytest.warns(DeprecationWarning):
stream.unread_data(b"line1line")
data = b""
while len(data) < 10:
data += await stream.read(10)
assert b"line1line2" == data
data = await stream.read(7)
assert b"onemore" == data
with pytest.warns(DeprecationWarning):
stream.unread_data(data)
data = b""
while len(data) < 11:
data += await stream.read(11)
assert b"onemoreline" == data
with pytest.warns(DeprecationWarning):
stream.unread_data(b"line")
data = await stream.read(4)
assert b"line" == data
stream.feed_eof()
with pytest.warns(DeprecationWarning):
stream.unread_data(b"at_eof")
data = await stream.read(6)
assert b"at_eof" == data
async def test_exception(self) -> None:
stream = self._make_one()
assert stream.exception() is None
exc = ValueError()
stream.set_exception(exc)
assert stream.exception() is exc
async def test_exception_waiter(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
async def set_err():
stream.set_exception(ValueError())
t1 = loop.create_task(stream.readline())
t2 = loop.create_task(set_err())
await asyncio.wait([t1, t2])
with pytest.raises(ValueError):
t1.result()
async def test_exception_cancel(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
async def read_a_line():
await stream.readline()
t = loop.create_task(read_a_line())
await asyncio.sleep(0)
t.cancel()
await asyncio.sleep(0)
# The following line fails if set_exception() isn't careful.
stream.set_exception(RuntimeError("message"))
await asyncio.sleep(0)
assert stream._waiter is None
async def test_readany_eof(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
read_task = loop.create_task(stream.readany())
loop.call_soon(stream.feed_data, b"chunk1\n")
data = await read_task
assert b"chunk1\n" == data
stream.feed_eof()
data = await stream.read()
assert b"" == data
async def test_readany_empty_eof(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
stream.feed_eof()
read_task = loop.create_task(stream.readany())
data = await read_task
assert b"" == data
async def test_readany_exception(self) -> None:
stream = self._make_one()
stream.feed_data(b"line\n")
data = await stream.readany()
assert b"line\n" == data
stream.set_exception(ValueError())
with pytest.raises(ValueError):
await stream.readany()
async def test_read_nowait(self) -> None:
stream = self._make_one()
stream.feed_data(b"line1\nline2\n")
assert stream.read_nowait() == b"line1\nline2\n"
assert stream.read_nowait() == b""
stream.feed_eof()
data = await stream.read()
assert b"" == data
async def test_read_nowait_n(self) -> None:
stream = self._make_one()
stream.feed_data(b"line1\nline2\n")
assert stream.read_nowait(4) == b"line"
assert stream.read_nowait() == b"1\nline2\n"
assert stream.read_nowait() == b""
stream.feed_eof()
data = await stream.read()
assert b"" == data
async def test_read_nowait_exception(self) -> None:
stream = self._make_one()
stream.feed_data(b"line\n")
stream.set_exception(ValueError())
with pytest.raises(ValueError):
stream.read_nowait()
async def test_read_nowait_waiter(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
stream.feed_data(b"line\n")
stream._waiter = loop.create_future()
with pytest.raises(RuntimeError):
stream.read_nowait()
async def test_readchunk(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
def cb():
stream.feed_data(b"chunk1")
stream.feed_data(b"chunk2")
stream.feed_eof()
loop.call_soon(cb)
data, end_of_chunk = await stream.readchunk()
assert b"chunk1" == data
assert not end_of_chunk
data, end_of_chunk = await stream.readchunk()
assert b"chunk2" == data
assert not end_of_chunk
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert not end_of_chunk
async def test_readchunk_wait_eof(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
async def cb():
await asyncio.sleep(0.1)
stream.feed_eof()
loop.create_task(cb())
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert not end_of_chunk
assert stream.is_eof()
async def test_begin_and_end_chunk_receiving(self) -> None:
stream = self._make_one()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part1")
stream.feed_data(b"part2")
stream.end_http_chunk_receiving()
data, end_of_chunk = await stream.readchunk()
assert b"part1part2" == data
assert end_of_chunk
stream.begin_http_chunk_receiving()
stream.feed_data(b"part3")
data, end_of_chunk = await stream.readchunk()
assert b"part3" == data
assert not end_of_chunk
stream.end_http_chunk_receiving()
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert end_of_chunk
stream.feed_eof()
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert not end_of_chunk
async def test_readany_chunk_end_race(self) -> None:
stream = self._make_one()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part1")
data = await stream.readany()
assert data == b"part1"
loop = asyncio.get_event_loop()
task = loop.create_task(stream.readany())
# Give a chance for task to create waiter and start waiting for it.
await asyncio.sleep(0.1)
assert stream._waiter is not None
assert not task.done() # Just for sure.
# This will trigger waiter, but without feeding any data.
# The stream should re-create waiter again.
stream.end_http_chunk_receiving()
# Give a chance for task to resolve.
# If everything is OK, previous action SHOULD NOT resolve the task.
await asyncio.sleep(0.1)
assert not task.done() # The actual test.
stream.begin_http_chunk_receiving()
# This SHOULD unblock the task actually.
stream.feed_data(b"part2")
stream.end_http_chunk_receiving()
data = await task
assert data == b"part2"
async def test_end_chunk_receiving_without_begin(self) -> None:
stream = self._make_one()
with pytest.raises(RuntimeError):
stream.end_http_chunk_receiving()
async def test_readchunk_with_unread(self) -> None:
# Test that stream.unread does not break controlled chunk receiving.
stream = self._make_one()
# Send 2 chunks
stream.begin_http_chunk_receiving()
stream.feed_data(b"part1")
stream.end_http_chunk_receiving()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part2")
stream.end_http_chunk_receiving()
# Read only one chunk
data, end_of_chunk = await stream.readchunk()
# Try to unread a part of the first chunk
with pytest.warns(DeprecationWarning):
stream.unread_data(b"rt1")
# The end_of_chunk signal was already received for the first chunk,
# so we receive up to the second one
data, end_of_chunk = await stream.readchunk()
assert b"rt1part2" == data
assert end_of_chunk
# Unread a part of the second chunk
with pytest.warns(DeprecationWarning):
stream.unread_data(b"rt2")
data, end_of_chunk = await stream.readchunk()
assert b"rt2" == data
# end_of_chunk was already received for this chunk
assert not end_of_chunk
stream.feed_eof()
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert not end_of_chunk
async def test_readchunk_with_other_read_calls(self) -> None:
# Test that stream.readchunk works when other read calls are made on
# the stream.
stream = self._make_one()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part1")
stream.end_http_chunk_receiving()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part2")
stream.end_http_chunk_receiving()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part3")
stream.end_http_chunk_receiving()
data = await stream.read(7)
assert b"part1pa" == data
data, end_of_chunk = await stream.readchunk()
assert b"rt2" == data
assert end_of_chunk
# Corner case between read/readchunk
data = await stream.read(5)
assert b"part3" == data
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert end_of_chunk
stream.feed_eof()
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert not end_of_chunk
async def test_chunksplits_memory_leak(self) -> None:
# Test for memory leak on chunksplits
stream = self._make_one()
N = 500
# Warm-up variables
stream.begin_http_chunk_receiving()
stream.feed_data(b"Y" * N)
stream.end_http_chunk_receiving()
await stream.read(N)
N = 300
before = get_memory_usage(stream)
for _ in range(N):
stream.begin_http_chunk_receiving()
stream.feed_data(b"X")
stream.end_http_chunk_receiving()
await stream.read(N)
after = get_memory_usage(stream)
assert abs(after - before) == 0
async def test_read_empty_chunks(self) -> None:
# Test that feeding empty chunks does not break stream
stream = self._make_one()
# Simulate empty first chunk. This is significant special case
stream.begin_http_chunk_receiving()
stream.end_http_chunk_receiving()
stream.begin_http_chunk_receiving()
stream.feed_data(b"ungzipped")
stream.end_http_chunk_receiving()
# Possible when compression is enabled.
stream.begin_http_chunk_receiving()
stream.end_http_chunk_receiving()
# is also possible
stream.begin_http_chunk_receiving()
stream.end_http_chunk_receiving()
stream.begin_http_chunk_receiving()
stream.feed_data(b" data")
stream.end_http_chunk_receiving()
stream.feed_eof()
data = await stream.read()
assert data == b"ungzipped data"
async def test_readchunk_separate_http_chunk_tail(self) -> None:
# Test that stream.readchunk returns (b'', True) when end of
# http chunk received after body
loop = asyncio.get_event_loop()
stream = self._make_one()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part1")
data, end_of_chunk = await stream.readchunk()
assert b"part1" == data
assert not end_of_chunk
async def cb():
await asyncio.sleep(0.1)
stream.end_http_chunk_receiving()
loop.create_task(cb())
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert end_of_chunk
stream.begin_http_chunk_receiving()
stream.feed_data(b"part2")
data, end_of_chunk = await stream.readchunk()
assert b"part2" == data
assert not end_of_chunk
stream.end_http_chunk_receiving()
stream.begin_http_chunk_receiving()
stream.feed_data(b"part3")
stream.end_http_chunk_receiving()
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert end_of_chunk
data, end_of_chunk = await stream.readchunk()
assert b"part3" == data
assert end_of_chunk
stream.begin_http_chunk_receiving()
stream.feed_data(b"part4")
data, end_of_chunk = await stream.readchunk()
assert b"part4" == data
assert not end_of_chunk
async def cb():
await asyncio.sleep(0.1)
stream.end_http_chunk_receiving()
stream.feed_eof()
loop.create_task(cb())
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert end_of_chunk
data, end_of_chunk = await stream.readchunk()
assert b"" == data
assert not end_of_chunk
async def test___repr__(self) -> None:
stream = self._make_one()
assert "<StreamReader>" == repr(stream)
async def test___repr__nondefault_limit(self) -> None:
stream = self._make_one(limit=123)
assert "<StreamReader low=123 high=246>" == repr(stream)
async def test___repr__eof(self) -> None:
stream = self._make_one()
stream.feed_eof()
assert "<StreamReader eof>" == repr(stream)
async def test___repr__data(self) -> None:
stream = self._make_one()
stream.feed_data(b"data")
assert "<StreamReader 4 bytes>" == repr(stream)
async def test___repr__exception(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one(loop=loop)
exc = RuntimeError()
stream.set_exception(exc)
assert "<StreamReader e=RuntimeError()>" == repr(stream)
async def test___repr__waiter(self) -> None:
loop = asyncio.get_event_loop()
stream = self._make_one()
stream._waiter = loop.create_future()
assert Matches(r"<StreamReader w=<Future pending[\S ]*>>") == repr(stream)
stream._waiter.set_result(None)
await stream._waiter
stream._waiter = None
assert "<StreamReader>" == repr(stream)
async def test_unread_empty(self) -> None:
stream = self._make_one()
stream.feed_data(b"line1")
stream.feed_eof()
with pytest.warns(DeprecationWarning):
stream.unread_data(b"")
data = await stream.read(5)
assert b"line1" == data
assert stream.at_eof()
async def test_empty_stream_reader() -> None:
s = streams.EmptyStreamReader()
assert s.set_exception(ValueError()) is None
assert s.exception() is None
assert s.feed_eof() is None
assert s.feed_data(b"data") is None
assert s.at_eof()
assert (await s.wait_eof()) is None
assert await s.read() == b""
assert await s.readline() == b""
assert await s.readany() == b""
assert await s.readchunk() == (b"", True)
with pytest.raises(asyncio.IncompleteReadError):
await s.readexactly(10)
assert s.read_nowait() == b""
@pytest.fixture
async def buffer(loop):
return streams.DataQueue(loop)
class TestDataQueue:
def test_is_eof(self, buffer) -> None:
assert not buffer.is_eof()
buffer.feed_eof()
assert buffer.is_eof()
def test_at_eof(self, buffer) -> None:
assert not buffer.at_eof()
buffer.feed_eof()
assert buffer.at_eof()
buffer._buffer.append(object())
assert not buffer.at_eof()
def test_feed_data(self, buffer) -> None:
item = object()
buffer.feed_data(item, 1)
assert [(item, 1)] == list(buffer._buffer)
def test_feed_eof(self, buffer) -> None:
buffer.feed_eof()
assert buffer._eof
async def test_read(self, buffer) -> None:
loop = asyncio.get_event_loop()
item = object()
def cb():
buffer.feed_data(item, 1)
loop.call_soon(cb)
data = await buffer.read()
assert item is data
async def test_read_eof(self, buffer) -> None:
loop = asyncio.get_event_loop()
def cb():
buffer.feed_eof()
loop.call_soon(cb)
with pytest.raises(streams.EofStream):
await buffer.read()
async def test_read_cancelled(self, buffer) -> None:
loop = asyncio.get_event_loop()
read_task = loop.create_task(buffer.read())
await asyncio.sleep(0)
waiter = buffer._waiter
assert asyncio.isfuture(waiter)
read_task.cancel()
with pytest.raises(asyncio.CancelledError):
await read_task
assert waiter.cancelled()
assert buffer._waiter is None
buffer.feed_data(b"test", 4)
assert buffer._waiter is None
async def test_read_until_eof(self, buffer) -> None:
item = object()
buffer.feed_data(item, 1)
buffer.feed_eof()
data = await buffer.read()
assert data is item
with pytest.raises(streams.EofStream):
await buffer.read()
async def test_read_exc(self, buffer) -> None:
item = object()
buffer.feed_data(item)
buffer.set_exception(ValueError)
data = await buffer.read()
assert item is data
with pytest.raises(ValueError):
await buffer.read()
async def test_read_exception(self, buffer) -> None:
buffer.set_exception(ValueError())
with pytest.raises(ValueError):
await buffer.read()
async def test_read_exception_with_data(self, buffer) -> None:
val = object()
buffer.feed_data(val, 1)
buffer.set_exception(ValueError())
assert val is (await buffer.read())
with pytest.raises(ValueError):
await buffer.read()
async def test_read_exception_on_wait(self, buffer) -> None:
loop = asyncio.get_event_loop()
read_task = loop.create_task(buffer.read())
await asyncio.sleep(0)
assert asyncio.isfuture(buffer._waiter)
buffer.feed_eof()
buffer.set_exception(ValueError())
with pytest.raises(ValueError):
await read_task
def test_exception(self, buffer) -> None:
assert buffer.exception() is None
exc = ValueError()
buffer.set_exception(exc)
assert buffer.exception() is exc
async def test_exception_waiter(self, buffer) -> None:
loop = asyncio.get_event_loop()
async def set_err():
buffer.set_exception(ValueError())
t1 = loop.create_task(buffer.read())
t2 = loop.create_task(set_err())
await asyncio.wait([t1, t2])
with pytest.raises(ValueError):
t1.result()
async def test_feed_data_waiters(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
waiter = reader._waiter = loop.create_future()
eof_waiter = reader._eof_waiter = loop.create_future()
reader.feed_data(b"1")
assert list(reader._buffer) == [b"1"]
assert reader._size == 1
assert reader.total_bytes == 1
assert waiter.done()
assert not eof_waiter.done()
assert reader._waiter is None
assert reader._eof_waiter is eof_waiter
async def test_feed_data_completed_waiters(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
waiter = reader._waiter = loop.create_future()
waiter.set_result(1)
reader.feed_data(b"1")
assert reader._waiter is None
async def test_feed_eof_waiters(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
waiter = reader._waiter = loop.create_future()
eof_waiter = reader._eof_waiter = loop.create_future()
reader.feed_eof()
assert reader._eof
assert waiter.done()
assert eof_waiter.done()
assert reader._waiter is None
assert reader._eof_waiter is None
async def test_feed_eof_cancelled(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
waiter = reader._waiter = loop.create_future()
eof_waiter = reader._eof_waiter = loop.create_future()
waiter.set_result(1)
eof_waiter.set_result(1)
reader.feed_eof()
assert waiter.done()
assert eof_waiter.done()
assert reader._waiter is None
assert reader._eof_waiter is None
async def test_on_eof(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
on_eof = mock.Mock()
reader.on_eof(on_eof)
assert not on_eof.called
reader.feed_eof()
assert on_eof.called
async def test_on_eof_empty_reader() -> None:
reader = streams.EmptyStreamReader()
on_eof = mock.Mock()
reader.on_eof(on_eof)
assert on_eof.called
async def test_on_eof_exc_in_callback(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
on_eof = mock.Mock()
on_eof.side_effect = ValueError
reader.on_eof(on_eof)
assert not on_eof.called
reader.feed_eof()
assert on_eof.called
assert not reader._eof_callbacks
async def test_on_eof_exc_in_callback_empty_stream_reader() -> None:
reader = streams.EmptyStreamReader()
on_eof = mock.Mock()
on_eof.side_effect = ValueError
reader.on_eof(on_eof)
assert on_eof.called
async def test_on_eof_eof_is_set(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
reader.feed_eof()
on_eof = mock.Mock()
reader.on_eof(on_eof)
assert on_eof.called
assert not reader._eof_callbacks
async def test_on_eof_eof_is_set_exception(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
reader.feed_eof()
on_eof = mock.Mock()
on_eof.side_effect = ValueError
reader.on_eof(on_eof)
assert on_eof.called
assert not reader._eof_callbacks
async def test_set_exception(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
waiter = reader._waiter = loop.create_future()
eof_waiter = reader._eof_waiter = loop.create_future()
exc = ValueError()
reader.set_exception(exc)
assert waiter.exception() is exc
assert eof_waiter.exception() is exc
assert reader._waiter is None
assert reader._eof_waiter is None
async def test_set_exception_cancelled(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
waiter = reader._waiter = loop.create_future()
eof_waiter = reader._eof_waiter = loop.create_future()
waiter.set_result(1)
eof_waiter.set_result(1)
exc = ValueError()
reader.set_exception(exc)
assert waiter.exception() is None
assert eof_waiter.exception() is None
assert reader._waiter is None
assert reader._eof_waiter is None
async def test_set_exception_eof_callbacks(protocol) -> None:
loop = asyncio.get_event_loop()
reader = streams.StreamReader(protocol, 2**16, loop=loop)
on_eof = mock.Mock()
reader.on_eof(on_eof)
reader.set_exception(ValueError())
assert not on_eof.called
assert not reader._eof_callbacks
async def test_stream_reader_lines() -> None:
line_iter = iter(DATA.splitlines(keepends=True))
async for line in await create_stream():
assert line == next(line_iter, None)
pytest.raises(StopIteration, next, line_iter)
async def test_stream_reader_chunks_complete() -> None:
# Tests if chunked iteration works if the chunking works out
# (i.e. the data is divisible by the chunk size)
chunk_iter = chunkify(DATA, 9)
async for data in (await create_stream()).iter_chunked(9):
assert data == next(chunk_iter, None)
pytest.raises(StopIteration, next, chunk_iter)
async def test_stream_reader_chunks_incomplete() -> None:
# Tests if chunked iteration works if the last chunk is incomplete
chunk_iter = chunkify(DATA, 8)
async for data in (await create_stream()).iter_chunked(8):
assert data == next(chunk_iter, None)
pytest.raises(StopIteration, next, chunk_iter)
async def test_data_queue_empty() -> None:
# Tests that async looping yields nothing if nothing is there
loop = asyncio.get_event_loop()
buffer = streams.DataQueue(loop)
buffer.feed_eof()
async for _ in buffer:
assert False
async def test_data_queue_items() -> None:
# Tests that async looping yields objects identically
loop = asyncio.get_event_loop()
buffer = streams.DataQueue(loop)
items = [object(), object()]
buffer.feed_data(items[0], 1)
buffer.feed_data(items[1], 1)
buffer.feed_eof()
item_iter = iter(items)
async for item in buffer:
assert item is next(item_iter, None)
pytest.raises(StopIteration, next, item_iter)
async def test_stream_reader_iter_any() -> None:
it = iter([b"line1\nline2\nline3\n"])
async for raw in (await create_stream()).iter_any():
assert raw == next(it)
pytest.raises(StopIteration, next, it)
async def test_stream_reader_iter() -> None:
it = iter([b"line1\n", b"line2\n", b"line3\n"])
async for raw in await create_stream():
assert raw == next(it)
pytest.raises(StopIteration, next, it)
async def test_stream_reader_iter_chunks_no_chunked_encoding() -> None:
it = iter([b"line1\nline2\nline3\n"])
async for data, end_of_chunk in (await create_stream()).iter_chunks():
assert (data, end_of_chunk) == (next(it), False)
pytest.raises(StopIteration, next, it)
async def test_stream_reader_iter_chunks_chunked_encoding(protocol) -> None:
loop = asyncio.get_event_loop()
stream = streams.StreamReader(protocol, 2**16, loop=loop)
for line in DATA.splitlines(keepends=True):
stream.begin_http_chunk_receiving()
stream.feed_data(line)
stream.end_http_chunk_receiving()
stream.feed_eof()
it = iter([b"line1\n", b"line2\n", b"line3\n"])
async for data, end_of_chunk in stream.iter_chunks():
assert (data, end_of_chunk) == (next(it), True)
pytest.raises(StopIteration, next, it)
def test_isinstance_check() -> None:
assert isinstance(streams.EMPTY_PAYLOAD, streams.StreamReader)
|