File size: 67,335 Bytes
bf9e111 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 |
# -*- coding: utf-8 -*-
"""
Unit tests for streaming_core module.
Tests for:
- KiroEvent dataclass
- StreamResult dataclass
- FirstTokenTimeoutError exception
- parse_kiro_stream() function
- collect_stream_to_result() function
- calculate_tokens_from_context_usage() function
"""
import pytest
import asyncio
from unittest.mock import AsyncMock, MagicMock, patch
from dataclasses import asdict
from kiro.streaming_core import (
KiroEvent,
StreamResult,
FirstTokenTimeoutError,
parse_kiro_stream,
collect_stream_to_result,
calculate_tokens_from_context_usage,
stream_with_first_token_retry,
_process_chunk,
)
# ==================================================================================================
# Fixtures
# ==================================================================================================
@pytest.fixture
def mock_model_cache():
"""Mock for ModelInfoCache."""
cache = MagicMock()
cache.get_max_input_tokens.return_value = 200000
return cache
@pytest.fixture
def mock_response():
"""Mock for httpx.Response."""
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
return response
@pytest.fixture
def mock_parser():
"""Mock for AwsEventStreamParser."""
parser = MagicMock()
parser.feed.return_value = []
parser.get_tool_calls.return_value = []
return parser
# ==================================================================================================
# Tests for KiroEvent dataclass
# ==================================================================================================
class TestKiroEvent:
"""Tests for KiroEvent dataclass."""
def test_creates_content_event(self):
"""
What it does: Creates a content event with text.
Goal: Verify KiroEvent can represent content events.
"""
print("Action: Creating content event...")
event = KiroEvent(type="content", content="Hello, world!")
print(f"Comparing type: Expected 'content', Got '{event.type}'")
assert event.type == "content"
print(f"Comparing content: Expected 'Hello, world!', Got '{event.content}'")
assert event.content == "Hello, world!"
assert event.thinking_content is None
assert event.tool_use is None
print("β Content event created correctly")
def test_creates_thinking_event(self):
"""
What it does: Creates a thinking event with reasoning content.
Goal: Verify KiroEvent can represent thinking events.
"""
print("Action: Creating thinking event...")
event = KiroEvent(
type="thinking",
thinking_content="Let me think...",
is_first_thinking_chunk=True,
is_last_thinking_chunk=False
)
print(f"Comparing type: Expected 'thinking', Got '{event.type}'")
assert event.type == "thinking"
print(f"Comparing thinking_content: Expected 'Let me think...', Got '{event.thinking_content}'")
assert event.thinking_content == "Let me think..."
assert event.is_first_thinking_chunk is True
assert event.is_last_thinking_chunk is False
print("β Thinking event created correctly")
def test_creates_tool_use_event(self):
"""
What it does: Creates a tool_use event with tool data.
Goal: Verify KiroEvent can represent tool use events.
"""
print("Action: Creating tool_use event...")
tool_data = {
"id": "call_123",
"type": "function",
"function": {"name": "get_weather", "arguments": '{"city": "Moscow"}'}
}
event = KiroEvent(type="tool_use", tool_use=tool_data)
print(f"Comparing type: Expected 'tool_use', Got '{event.type}'")
assert event.type == "tool_use"
print(f"Comparing tool_use: Expected {tool_data}, Got {event.tool_use}")
assert event.tool_use == tool_data
print("β Tool use event created correctly")
def test_creates_usage_event(self):
"""
What it does: Creates a usage event with metering data.
Goal: Verify KiroEvent can represent usage events.
"""
print("Action: Creating usage event...")
usage_data = {"credits": 0.001}
event = KiroEvent(type="usage", usage=usage_data)
print(f"Comparing type: Expected 'usage', Got '{event.type}'")
assert event.type == "usage"
print(f"Comparing usage: Expected {usage_data}, Got {event.usage}")
assert event.usage == usage_data
print("β Usage event created correctly")
def test_creates_context_usage_event(self):
"""
What it does: Creates a context_usage event with percentage.
Goal: Verify KiroEvent can represent context usage events.
"""
print("Action: Creating context_usage event...")
event = KiroEvent(type="context_usage", context_usage_percentage=5.5)
print(f"Comparing type: Expected 'context_usage', Got '{event.type}'")
assert event.type == "context_usage"
print(f"Comparing context_usage_percentage: Expected 5.5, Got {event.context_usage_percentage}")
assert event.context_usage_percentage == 5.5
print("β Context usage event created correctly")
def test_default_values(self):
"""
What it does: Verifies default values for optional fields.
Goal: Ensure all optional fields default to None/False.
"""
print("Action: Creating minimal event...")
event = KiroEvent(type="content")
print("Checking default values...")
assert event.content is None
assert event.thinking_content is None
assert event.tool_use is None
assert event.usage is None
assert event.context_usage_percentage is None
assert event.is_first_thinking_chunk is False
assert event.is_last_thinking_chunk is False
print("β All default values are correct")
# ==================================================================================================
# Tests for StreamResult dataclass
# ==================================================================================================
class TestStreamResult:
"""Tests for StreamResult dataclass."""
def test_creates_empty_result(self):
"""
What it does: Creates an empty StreamResult.
Goal: Verify default values are correct.
"""
print("Action: Creating empty StreamResult...")
result = StreamResult()
print("Checking default values...")
assert result.content == ""
assert result.thinking_content == ""
assert result.tool_calls == []
assert result.usage is None
assert result.context_usage_percentage is None
print("β Empty StreamResult created correctly")
def test_creates_result_with_content(self):
"""
What it does: Creates StreamResult with content.
Goal: Verify content is stored correctly.
"""
print("Action: Creating StreamResult with content...")
result = StreamResult(content="Hello, world!")
print(f"Comparing content: Expected 'Hello, world!', Got '{result.content}'")
assert result.content == "Hello, world!"
print("β StreamResult with content created correctly")
def test_creates_result_with_tool_calls(self):
"""
What it does: Creates StreamResult with tool calls.
Goal: Verify tool calls are stored correctly.
"""
print("Action: Creating StreamResult with tool calls...")
tool_calls = [
{"id": "call_1", "function": {"name": "func1"}},
{"id": "call_2", "function": {"name": "func2"}}
]
result = StreamResult(tool_calls=tool_calls)
print(f"Comparing tool_calls count: Expected 2, Got {len(result.tool_calls)}")
assert len(result.tool_calls) == 2
assert result.tool_calls[0]["id"] == "call_1"
print("β StreamResult with tool calls created correctly")
def test_creates_result_with_usage(self):
"""
What it does: Creates StreamResult with usage data.
Goal: Verify usage is stored correctly.
"""
print("Action: Creating StreamResult with usage...")
usage = {"credits": 0.002}
result = StreamResult(usage=usage)
print(f"Comparing usage: Expected {usage}, Got {result.usage}")
assert result.usage == usage
print("β StreamResult with usage created correctly")
def test_creates_full_result(self):
"""
What it does: Creates StreamResult with all fields.
Goal: Verify all fields work together.
"""
print("Action: Creating full StreamResult...")
result = StreamResult(
content="Response text",
thinking_content="Thinking...",
tool_calls=[{"id": "call_1"}],
usage={"credits": 0.001},
context_usage_percentage=3.5
)
print("Checking all fields...")
assert result.content == "Response text"
assert result.thinking_content == "Thinking..."
assert len(result.tool_calls) == 1
assert result.usage == {"credits": 0.001}
assert result.context_usage_percentage == 3.5
print("β Full StreamResult created correctly")
# ==================================================================================================
# Tests for FirstTokenTimeoutError
# ==================================================================================================
class TestFirstTokenTimeoutError:
"""Tests for FirstTokenTimeoutError exception."""
def test_creates_exception_with_message(self):
"""
What it does: Creates exception with custom message.
Goal: Verify exception message is stored correctly.
"""
print("Action: Creating FirstTokenTimeoutError...")
error = FirstTokenTimeoutError("No response within 30 seconds")
print(f"Comparing message: Expected 'No response within 30 seconds', Got '{str(error)}'")
assert str(error) == "No response within 30 seconds"
print("β Exception created correctly")
def test_exception_is_catchable(self):
"""
What it does: Verifies exception can be caught.
Goal: Ensure exception inherits from Exception.
"""
print("Action: Raising and catching FirstTokenTimeoutError...")
with pytest.raises(FirstTokenTimeoutError) as exc_info:
raise FirstTokenTimeoutError("Timeout!")
print(f"Caught exception: {exc_info.value}")
assert "Timeout!" in str(exc_info.value)
print("β Exception is catchable")
def test_exception_inherits_from_exception(self):
"""
What it does: Verifies inheritance chain.
Goal: Ensure proper exception hierarchy.
"""
print("Action: Checking inheritance...")
error = FirstTokenTimeoutError("Test")
assert isinstance(error, Exception)
print("β FirstTokenTimeoutError inherits from Exception")
# ==================================================================================================
# Tests for parse_kiro_stream()
# ==================================================================================================
class TestParseKiroStream:
"""Tests for parse_kiro_stream() function."""
@pytest.mark.asyncio
async def test_parses_content_events(self, mock_response, mock_parser):
"""
What it does: Parses content events from Kiro stream.
Goal: Verify content events are yielded correctly.
"""
print("Setup: Mock parser to return content events...")
mock_parser.feed.return_value = [
{"type": "content", "data": "Hello"},
{"type": "content", "data": " World"}
]
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Parsing stream...")
events = []
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
print(f"Received {len(events)} events")
content_events = [e for e in events if e.type == "content"]
print(f"Content events: {len(content_events)}")
assert len(content_events) == 2
assert content_events[0].content == "Hello"
assert content_events[1].content == " World"
print("β Content events parsed correctly")
@pytest.mark.asyncio
async def test_parses_usage_events(self, mock_response, mock_parser):
"""
What it does: Parses usage events from Kiro stream.
Goal: Verify usage events are yielded correctly.
"""
print("Setup: Mock parser to return usage event...")
mock_parser.feed.return_value = [
{"type": "usage", "data": {"credits": 0.001}}
]
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Parsing stream...")
events = []
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
print(f"Received {len(events)} events")
usage_events = [e for e in events if e.type == "usage"]
assert len(usage_events) == 1
assert usage_events[0].usage == {"credits": 0.001}
print("β Usage events parsed correctly")
@pytest.mark.asyncio
async def test_parses_context_usage_events(self, mock_response, mock_parser):
"""
What it does: Parses context_usage events from Kiro stream.
Goal: Verify context usage percentage is yielded correctly.
"""
print("Setup: Mock parser to return context_usage event...")
mock_parser.feed.return_value = [
{"type": "context_usage", "data": 5.5}
]
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Parsing stream...")
events = []
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
print(f"Received {len(events)} events")
context_events = [e for e in events if e.type == "context_usage"]
assert len(context_events) == 1
assert context_events[0].context_usage_percentage == 5.5
print("β Context usage events parsed correctly")
@pytest.mark.asyncio
async def test_yields_tool_calls_at_end(self, mock_response, mock_parser):
"""
What it does: Yields tool calls collected during parsing.
Goal: Verify tool calls are yielded as events.
"""
print("Setup: Mock parser with tool calls...")
mock_parser.feed.return_value = [{"type": "content", "data": "text"}]
mock_parser.get_tool_calls.return_value = [
{"id": "call_1", "function": {"name": "func1", "arguments": "{}"}}
]
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Parsing stream...")
events = []
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
print(f"Received {len(events)} events")
tool_events = [e for e in events if e.type == "tool_use"]
assert len(tool_events) == 1
assert tool_events[0].tool_use["id"] == "call_1"
print("β Tool calls yielded correctly")
@pytest.mark.asyncio
async def test_raises_timeout_on_first_token(self, mock_response):
"""
What it does: Raises FirstTokenTimeoutError on timeout.
Goal: Verify timeout handling for first token.
"""
print("Setup: Mock response that times out...")
async def mock_aiter_bytes():
yield b'chunk'
mock_response.aiter_bytes = mock_aiter_bytes
async def mock_wait_for_timeout(*args, **kwargs):
raise asyncio.TimeoutError()
print("Action: Parsing stream with timeout...")
with patch('kiro.streaming_core.asyncio.wait_for', side_effect=mock_wait_for_timeout):
with pytest.raises(FirstTokenTimeoutError) as exc_info:
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
pass
print(f"Caught exception: {exc_info.value}")
assert "30" in str(exc_info.value)
print("β FirstTokenTimeoutError raised on timeout")
@pytest.mark.asyncio
async def test_handles_empty_response(self, mock_response):
"""
What it does: Handles empty response gracefully.
Goal: Verify no events yielded for empty response.
"""
print("Setup: Mock empty response...")
async def mock_aiter_bytes():
return
yield # Make it a generator
mock_response.aiter_bytes = mock_aiter_bytes
# Mock wait_for to raise StopAsyncIteration (empty response)
async def mock_wait_for_empty(*args, **kwargs):
raise StopAsyncIteration()
print("Action: Parsing empty stream...")
events = []
with patch('kiro.streaming_core.asyncio.wait_for', side_effect=mock_wait_for_empty):
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
print(f"Received {len(events)} events")
assert len(events) == 0
print("β Empty response handled correctly")
@pytest.mark.asyncio
async def test_handles_generator_exit(self, mock_response, mock_parser):
"""
What it does: Handles GeneratorExit gracefully.
Goal: Verify client disconnect is handled.
"""
print("Setup: Mock response that raises GeneratorExit...")
async def mock_aiter_bytes():
yield b'chunk1'
raise GeneratorExit()
mock_response.aiter_bytes = mock_aiter_bytes
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
print("Action: Parsing stream with GeneratorExit...")
events = []
generator_exit_raised = False
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
try:
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
except GeneratorExit:
generator_exit_raised = True
print(f"GeneratorExit raised: {generator_exit_raised}")
assert generator_exit_raised
print("β GeneratorExit handled correctly")
# ==================================================================================================
# Tests for _process_chunk()
# ==================================================================================================
class TestProcessChunk:
"""Tests for _process_chunk() helper function."""
@pytest.mark.asyncio
async def test_processes_content_event(self, mock_parser):
"""
What it does: Processes content event from chunk.
Goal: Verify content is converted to KiroEvent.
"""
print("Setup: Mock parser with content event...")
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
print("Action: Processing chunk...")
events = []
async for event in _process_chunk(mock_parser, b'chunk', None):
events.append(event)
print(f"Received {len(events)} events")
assert len(events) == 1
assert events[0].type == "content"
assert events[0].content == "Hello"
print("β Content event processed correctly")
@pytest.mark.asyncio
async def test_processes_usage_event(self, mock_parser):
"""
What it does: Processes usage event from chunk.
Goal: Verify usage is converted to KiroEvent.
"""
print("Setup: Mock parser with usage event...")
mock_parser.feed.return_value = [{"type": "usage", "data": {"credits": 0.001}}]
print("Action: Processing chunk...")
events = []
async for event in _process_chunk(mock_parser, b'chunk', None):
events.append(event)
print(f"Received {len(events)} events")
assert len(events) == 1
assert events[0].type == "usage"
assert events[0].usage == {"credits": 0.001}
print("β Usage event processed correctly")
@pytest.mark.asyncio
async def test_processes_context_usage_event(self, mock_parser):
"""
What it does: Processes context_usage event from chunk.
Goal: Verify context usage is converted to KiroEvent.
"""
print("Setup: Mock parser with context_usage event...")
mock_parser.feed.return_value = [{"type": "context_usage", "data": 7.5}]
print("Action: Processing chunk...")
events = []
async for event in _process_chunk(mock_parser, b'chunk', None):
events.append(event)
print(f"Received {len(events)} events")
assert len(events) == 1
assert events[0].type == "context_usage"
assert events[0].context_usage_percentage == 7.5
print("β Context usage event processed correctly")
@pytest.mark.asyncio
async def test_processes_multiple_events(self, mock_parser):
"""
What it does: Processes multiple events from single chunk.
Goal: Verify all events are yielded.
"""
print("Setup: Mock parser with multiple events...")
mock_parser.feed.return_value = [
{"type": "content", "data": "Hello"},
{"type": "content", "data": " World"},
{"type": "usage", "data": {"credits": 0.001}}
]
print("Action: Processing chunk...")
events = []
async for event in _process_chunk(mock_parser, b'chunk', None):
events.append(event)
print(f"Received {len(events)} events")
assert len(events) == 3
assert events[0].type == "content"
assert events[1].type == "content"
assert events[2].type == "usage"
print("β Multiple events processed correctly")
@pytest.mark.asyncio
async def test_processes_with_thinking_parser(self, mock_parser):
"""
What it does: Processes content through thinking parser.
Goal: Verify thinking parser integration.
"""
print("Setup: Mock parser and thinking parser...")
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
mock_thinking_parser = MagicMock()
mock_thinking_parser.feed.return_value = MagicMock(
thinking_content=None,
regular_content="Hello",
is_first_thinking_chunk=False,
is_last_thinking_chunk=False
)
print("Action: Processing chunk with thinking parser...")
events = []
async for event in _process_chunk(mock_parser, b'chunk', mock_thinking_parser):
events.append(event)
print(f"Received {len(events)} events")
assert len(events) == 1
assert events[0].type == "content"
assert events[0].content == "Hello"
print("β Thinking parser integration works correctly")
@pytest.mark.asyncio
async def test_yields_thinking_content(self, mock_parser):
"""
What it does: Yields thinking content from thinking parser.
Goal: Verify thinking events are created.
"""
print("Setup: Mock parser and thinking parser with thinking content...")
mock_parser.feed.return_value = [{"type": "content", "data": "<thinking>Let me think</thinking>"}]
mock_thinking_parser = MagicMock()
mock_thinking_parser.feed.return_value = MagicMock(
thinking_content="Let me think",
regular_content=None,
is_first_thinking_chunk=True,
is_last_thinking_chunk=True
)
mock_thinking_parser.process_for_output.return_value = "Let me think"
print("Action: Processing chunk with thinking content...")
events = []
async for event in _process_chunk(mock_parser, b'chunk', mock_thinking_parser):
events.append(event)
print(f"Received {len(events)} events")
thinking_events = [e for e in events if e.type == "thinking"]
assert len(thinking_events) == 1
assert thinking_events[0].thinking_content == "Let me think"
print("β Thinking content yielded correctly")
# ==================================================================================================
# Tests for collect_stream_to_result()
# ==================================================================================================
class TestCollectStreamToResult:
"""Tests for collect_stream_to_result() function."""
@pytest.mark.asyncio
async def test_collects_content(self, mock_response, mock_parser):
"""
What it does: Collects content from stream.
Goal: Verify content is accumulated correctly.
"""
print("Setup: Mock parser with content events...")
mock_parser.feed.return_value = [
{"type": "content", "data": "Hello"},
{"type": "content", "data": " World"}
]
mock_parser.get_tool_calls.return_value = []
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Collecting stream...")
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with patch('kiro.streaming_core.parse_bracket_tool_calls', return_value=[]):
result = await collect_stream_to_result(mock_response, first_token_timeout=30)
print(f"Collected content: '{result.content}'")
assert result.content == "Hello World"
print("β Content collected correctly")
@pytest.mark.asyncio
async def test_collects_tool_calls(self, mock_response, mock_parser):
"""
What it does: Collects tool calls from stream.
Goal: Verify tool calls are accumulated correctly.
"""
print("Setup: Mock parser with tool calls...")
mock_parser.feed.return_value = [{"type": "content", "data": "text"}]
mock_parser.get_tool_calls.return_value = [
{"id": "call_1", "function": {"name": "func1", "arguments": "{}"}}
]
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Collecting stream...")
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with patch('kiro.streaming_core.parse_bracket_tool_calls', return_value=[]):
result = await collect_stream_to_result(mock_response, first_token_timeout=30)
print(f"Collected tool calls: {len(result.tool_calls)}")
assert len(result.tool_calls) == 1
assert result.tool_calls[0]["id"] == "call_1"
print("β Tool calls collected correctly")
@pytest.mark.asyncio
async def test_collects_usage(self, mock_response, mock_parser):
"""
What it does: Collects usage from stream.
Goal: Verify usage is stored correctly.
"""
print("Setup: Mock parser with usage event...")
mock_parser.feed.return_value = [
{"type": "content", "data": "text"},
{"type": "usage", "data": {"credits": 0.002}}
]
mock_parser.get_tool_calls.return_value = []
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Collecting stream...")
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with patch('kiro.streaming_core.parse_bracket_tool_calls', return_value=[]):
result = await collect_stream_to_result(mock_response, first_token_timeout=30)
print(f"Collected usage: {result.usage}")
assert result.usage == {"credits": 0.002}
print("β Usage collected correctly")
@pytest.mark.asyncio
async def test_collects_context_usage_percentage(self, mock_response, mock_parser):
"""
What it does: Collects context usage percentage from stream.
Goal: Verify context usage is stored correctly.
"""
print("Setup: Mock parser with context_usage event...")
mock_parser.feed.return_value = [
{"type": "content", "data": "text"},
{"type": "context_usage", "data": 8.5}
]
mock_parser.get_tool_calls.return_value = []
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Collecting stream...")
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with patch('kiro.streaming_core.parse_bracket_tool_calls', return_value=[]):
result = await collect_stream_to_result(mock_response, first_token_timeout=30)
print(f"Collected context_usage_percentage: {result.context_usage_percentage}")
assert result.context_usage_percentage == 8.5
print("β Context usage percentage collected correctly")
@pytest.mark.asyncio
async def test_collects_thinking_content(self, mock_response, mock_parser):
"""
What it does: Collects thinking content from stream.
Goal: Verify thinking content is accumulated correctly.
"""
print("Setup: Mock parser with thinking content...")
# We need to mock the thinking parser behavior
mock_parser.feed.return_value = [{"type": "content", "data": "thinking text"}]
mock_parser.get_tool_calls.return_value = []
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
# Create mock events that include thinking
mock_events = [
KiroEvent(type="thinking", thinking_content="Let me think..."),
KiroEvent(type="content", content="Here is my answer")
]
async def mock_parse_kiro_stream(*args, **kwargs):
for event in mock_events:
yield event
print("Action: Collecting stream with thinking...")
with patch('kiro.streaming_core.parse_kiro_stream', mock_parse_kiro_stream):
with patch('kiro.streaming_core.parse_bracket_tool_calls', return_value=[]):
result = await collect_stream_to_result(mock_response, first_token_timeout=30)
print(f"Collected thinking_content: '{result.thinking_content}'")
print(f"Collected content: '{result.content}'")
assert result.thinking_content == "Let me think..."
assert result.content == "Here is my answer"
print("β Thinking content collected correctly")
@pytest.mark.asyncio
async def test_deduplicates_bracket_tool_calls(self, mock_response, mock_parser):
"""
What it does: Deduplicates bracket-style tool calls.
Goal: Verify duplicate tool calls are removed.
"""
print("Setup: Mock parser with tool calls and bracket tool calls...")
mock_parser.feed.return_value = [{"type": "content", "data": "text"}]
mock_parser.get_tool_calls.return_value = [
{"id": "call_1", "function": {"name": "func1", "arguments": "{}"}}
]
bracket_tool_calls = [
{"id": "call_1", "function": {"name": "func1", "arguments": "{}"}}, # Duplicate
{"id": "call_2", "function": {"name": "func2", "arguments": "{}"}} # New
]
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Collecting stream with duplicates...")
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with patch('kiro.streaming_core.parse_bracket_tool_calls', return_value=bracket_tool_calls):
with patch('kiro.streaming_core.deduplicate_tool_calls') as mock_dedup:
mock_dedup.return_value = [
{"id": "call_1", "function": {"name": "func1", "arguments": "{}"}},
{"id": "call_2", "function": {"name": "func2", "arguments": "{}"}}
]
result = await collect_stream_to_result(mock_response, first_token_timeout=30)
print(f"Collected tool calls: {len(result.tool_calls)}")
assert len(result.tool_calls) == 2
print("β Tool calls deduplicated correctly")
# ==================================================================================================
# Tests for calculate_tokens_from_context_usage()
# ==================================================================================================
class TestCalculateTokensFromContextUsage:
"""Tests for calculate_tokens_from_context_usage() function."""
def test_calculates_tokens_from_percentage(self, mock_model_cache):
"""
What it does: Calculates tokens from context usage percentage.
Goal: Verify token calculation is correct.
"""
print("Setup: Context usage 10% with 200000 max tokens...")
context_usage_percentage = 10.0
completion_tokens = 100
print("Action: Calculating tokens...")
prompt_tokens, total_tokens, prompt_source, total_source = calculate_tokens_from_context_usage(
context_usage_percentage, completion_tokens, mock_model_cache, "claude-sonnet-4"
)
# 10% of 200000 = 20000 total tokens
# prompt_tokens = 20000 - 100 = 19900
print(f"Comparing total_tokens: Expected 20000, Got {total_tokens}")
assert total_tokens == 20000
print(f"Comparing prompt_tokens: Expected 19900, Got {prompt_tokens}")
assert prompt_tokens == 19900
assert prompt_source == "subtraction"
assert total_source == "API Kiro"
print("β Tokens calculated correctly")
def test_handles_zero_percentage(self, mock_model_cache):
"""
What it does: Handles zero context usage percentage.
Goal: Verify fallback behavior for zero percentage.
"""
print("Setup: Context usage 0%...")
context_usage_percentage = 0.0
completion_tokens = 100
print("Action: Calculating tokens...")
prompt_tokens, total_tokens, prompt_source, total_source = calculate_tokens_from_context_usage(
context_usage_percentage, completion_tokens, mock_model_cache, "claude-sonnet-4"
)
print(f"Comparing prompt_tokens: Expected 0, Got {prompt_tokens}")
assert prompt_tokens == 0
print(f"Comparing total_tokens: Expected 100, Got {total_tokens}")
assert total_tokens == 100
assert prompt_source == "unknown"
assert total_source == "tiktoken"
print("β Zero percentage handled correctly")
def test_handles_none_percentage(self, mock_model_cache):
"""
What it does: Handles None context usage percentage.
Goal: Verify fallback behavior for None percentage.
"""
print("Setup: Context usage None...")
context_usage_percentage = None
completion_tokens = 100
print("Action: Calculating tokens...")
prompt_tokens, total_tokens, prompt_source, total_source = calculate_tokens_from_context_usage(
context_usage_percentage, completion_tokens, mock_model_cache, "claude-sonnet-4"
)
print(f"Comparing prompt_tokens: Expected 0, Got {prompt_tokens}")
assert prompt_tokens == 0
print(f"Comparing total_tokens: Expected 100, Got {total_tokens}")
assert total_tokens == 100
assert prompt_source == "unknown"
assert total_source == "tiktoken"
print("β None percentage handled correctly")
def test_prevents_negative_prompt_tokens(self, mock_model_cache):
"""
What it does: Prevents negative prompt tokens.
Goal: Verify prompt_tokens is never negative.
"""
print("Setup: Very small context usage with large completion...")
context_usage_percentage = 0.01 # 0.01% of 200000 = 20 total tokens
completion_tokens = 100 # More than total!
print("Action: Calculating tokens...")
prompt_tokens, total_tokens, prompt_source, total_source = calculate_tokens_from_context_usage(
context_usage_percentage, completion_tokens, mock_model_cache, "claude-sonnet-4"
)
print(f"Comparing prompt_tokens: Expected >= 0, Got {prompt_tokens}")
assert prompt_tokens >= 0
print("β Negative prompt tokens prevented")
def test_uses_model_specific_max_tokens(self, mock_model_cache):
"""
What it does: Uses model-specific max input tokens.
Goal: Verify model cache is queried correctly.
"""
print("Setup: Different max tokens for model...")
mock_model_cache.get_max_input_tokens.return_value = 100000 # Different from default
context_usage_percentage = 10.0
completion_tokens = 100
print("Action: Calculating tokens...")
prompt_tokens, total_tokens, prompt_source, total_source = calculate_tokens_from_context_usage(
context_usage_percentage, completion_tokens, mock_model_cache, "claude-haiku-3"
)
# 10% of 100000 = 10000 total tokens
print(f"Comparing total_tokens: Expected 10000, Got {total_tokens}")
assert total_tokens == 10000
# Verify model cache was called with correct model
mock_model_cache.get_max_input_tokens.assert_called_with("claude-haiku-3")
print("β Model-specific max tokens used correctly")
def test_small_percentage_calculation(self, mock_model_cache):
"""
What it does: Calculates tokens for small percentage.
Goal: Verify precision for small percentages.
"""
print("Setup: Context usage 0.5%...")
context_usage_percentage = 0.5
completion_tokens = 50
print("Action: Calculating tokens...")
prompt_tokens, total_tokens, prompt_source, total_source = calculate_tokens_from_context_usage(
context_usage_percentage, completion_tokens, mock_model_cache, "claude-sonnet-4"
)
# 0.5% of 200000 = 1000 total tokens
# prompt_tokens = 1000 - 50 = 950
print(f"Comparing total_tokens: Expected 1000, Got {total_tokens}")
assert total_tokens == 1000
print(f"Comparing prompt_tokens: Expected 950, Got {prompt_tokens}")
assert prompt_tokens == 950
print("β Small percentage calculated correctly")
def test_large_percentage_calculation(self, mock_model_cache):
"""
What it does: Calculates tokens for large percentage.
Goal: Verify calculation for high context usage.
"""
print("Setup: Context usage 95%...")
context_usage_percentage = 95.0
completion_tokens = 1000
print("Action: Calculating tokens...")
prompt_tokens, total_tokens, prompt_source, total_source = calculate_tokens_from_context_usage(
context_usage_percentage, completion_tokens, mock_model_cache, "claude-sonnet-4"
)
# 95% of 200000 = 190000 total tokens
# prompt_tokens = 190000 - 1000 = 189000
print(f"Comparing total_tokens: Expected 190000, Got {total_tokens}")
assert total_tokens == 190000
print(f"Comparing prompt_tokens: Expected 189000, Got {prompt_tokens}")
assert prompt_tokens == 189000
print("β Large percentage calculated correctly")
# ==================================================================================================
# Tests for thinking parser integration
# ==================================================================================================
class TestThinkingParserIntegration:
"""Tests for thinking parser integration in streaming."""
@pytest.mark.asyncio
async def test_thinking_parser_enabled_when_fake_reasoning_on(self, mock_response, mock_parser):
"""
What it does: Enables thinking parser when FAKE_REASONING_ENABLED is True.
Goal: Verify thinking parser is created.
"""
print("Setup: Enable fake reasoning...")
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
mock_parser.get_tool_calls.return_value = []
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Parsing stream with fake reasoning enabled...")
events = []
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', True):
with patch('kiro.streaming_core.ThinkingParser') as mock_thinking_parser_class:
mock_thinking_parser = MagicMock()
mock_thinking_parser.feed.return_value = MagicMock(
thinking_content=None,
regular_content="Hello",
is_first_thinking_chunk=False,
is_last_thinking_chunk=False
)
mock_thinking_parser.finalize.return_value = MagicMock(
thinking_content=None,
regular_content=None,
is_first_thinking_chunk=False,
is_last_thinking_chunk=False
)
mock_thinking_parser.found_thinking_block = False
mock_thinking_parser_class.return_value = mock_thinking_parser
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
# Verify ThinkingParser was instantiated
mock_thinking_parser_class.assert_called_once()
print("β Thinking parser enabled when fake reasoning is on")
@pytest.mark.asyncio
async def test_thinking_parser_disabled_when_fake_reasoning_off(self, mock_response, mock_parser):
"""
What it does: Disables thinking parser when FAKE_REASONING_ENABLED is False.
Goal: Verify thinking parser is not created.
"""
print("Setup: Disable fake reasoning...")
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
mock_parser.get_tool_calls.return_value = []
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Parsing stream with fake reasoning disabled...")
events = []
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with patch('kiro.streaming_core.ThinkingParser') as mock_thinking_parser_class:
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
events.append(event)
# Verify ThinkingParser was NOT instantiated
mock_thinking_parser_class.assert_not_called()
print("β Thinking parser disabled when fake reasoning is off")
@pytest.mark.asyncio
async def test_thinking_parser_can_be_disabled_via_parameter(self, mock_response, mock_parser):
"""
What it does: Disables thinking parser via enable_thinking_parser parameter.
Goal: Verify parameter overrides config.
"""
print("Setup: Enable fake reasoning but disable via parameter...")
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
mock_parser.get_tool_calls.return_value = []
async def mock_aiter_bytes():
yield b'chunk1'
mock_response.aiter_bytes = mock_aiter_bytes
print("Action: Parsing stream with thinking parser disabled via parameter...")
events = []
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', True):
with patch('kiro.streaming_core.ThinkingParser') as mock_thinking_parser_class:
async for event in parse_kiro_stream(
mock_response,
first_token_timeout=30,
enable_thinking_parser=False
):
events.append(event)
# Verify ThinkingParser was NOT instantiated
mock_thinking_parser_class.assert_not_called()
print("β Thinking parser disabled via parameter")
# ==================================================================================================
# Tests for error handling
# ==================================================================================================
class TestStreamingCoreErrorHandling:
"""Tests for error handling in streaming_core."""
@pytest.mark.asyncio
async def test_propagates_first_token_timeout_error(self, mock_response):
"""
What it does: Propagates FirstTokenTimeoutError.
Goal: Verify timeout error is not caught internally.
"""
print("Setup: Mock response that times out...")
async def mock_aiter_bytes():
yield b'chunk'
mock_response.aiter_bytes = mock_aiter_bytes
async def mock_wait_for_timeout(*args, **kwargs):
raise asyncio.TimeoutError()
print("Action: Parsing stream with timeout...")
with patch('kiro.streaming_core.asyncio.wait_for', side_effect=mock_wait_for_timeout):
with pytest.raises(FirstTokenTimeoutError):
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
pass
print("β FirstTokenTimeoutError propagated correctly")
@pytest.mark.asyncio
async def test_propagates_generator_exit(self, mock_response, mock_parser):
"""
What it does: Propagates GeneratorExit.
Goal: Verify client disconnect is handled.
"""
print("Setup: Mock response that raises GeneratorExit...")
async def mock_aiter_bytes():
yield b'chunk1'
raise GeneratorExit()
mock_response.aiter_bytes = mock_aiter_bytes
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
print("Action: Parsing stream with GeneratorExit...")
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with pytest.raises(GeneratorExit):
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
pass
print("β GeneratorExit propagated correctly")
@pytest.mark.asyncio
async def test_propagates_other_exceptions(self, mock_response, mock_parser):
"""
What it does: Propagates other exceptions.
Goal: Verify errors are not swallowed.
"""
print("Setup: Mock response that raises RuntimeError...")
async def mock_aiter_bytes():
yield b'chunk1'
raise RuntimeError("Test error")
mock_response.aiter_bytes = mock_aiter_bytes
mock_parser.feed.return_value = [{"type": "content", "data": "Hello"}]
print("Action: Parsing stream with RuntimeError...")
with patch('kiro.streaming_core.AwsEventStreamParser', return_value=mock_parser):
with patch('kiro.streaming_core.FAKE_REASONING_ENABLED', False):
with pytest.raises(RuntimeError) as exc_info:
async for event in parse_kiro_stream(mock_response, first_token_timeout=30):
pass
print(f"Caught exception: {exc_info.value}")
assert "Test error" in str(exc_info.value)
print("β RuntimeError propagated correctly")
# ==================================================================================================
# Tests for stream_with_first_token_retry()
# ==================================================================================================
class TestStreamWithFirstTokenRetryCore:
"""
Tests for stream_with_first_token_retry() generic function.
This function provides automatic retry logic on first token timeout.
It is used by both OpenAI and Anthropic streaming implementations.
"""
@pytest.mark.asyncio
async def test_yields_chunks_on_success(self):
"""
What it does: Yields chunks on successful streaming.
Goal: Verify normal operation without retries.
"""
print("Setup: Mock successful request...")
mock_response = AsyncMock()
mock_response.status_code = 200
mock_response.aclose = AsyncMock()
async def mock_make_request():
return mock_response
async def mock_stream_processor(response):
yield "chunk1"
yield "chunk2"
yield "chunk3"
print("Action: Streaming with retry wrapper...")
chunks = []
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=3,
first_token_timeout=30
):
chunks.append(chunk)
print(f"Received {len(chunks)} chunks")
assert len(chunks) == 3
assert chunks == ["chunk1", "chunk2", "chunk3"]
print("β Chunks yielded on success")
@pytest.mark.asyncio
async def test_retries_on_first_token_timeout(self):
"""
What it does: Retries on first token timeout.
Goal: Verify retry logic is triggered.
"""
print("Setup: Mock request that times out then succeeds...")
call_count = 0
async def mock_make_request():
nonlocal call_count
call_count += 1
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
nonlocal call_count
if call_count == 1:
raise FirstTokenTimeoutError("Timeout on first attempt")
yield "success_chunk"
print("Action: Streaming with retry on timeout...")
chunks = []
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=3,
first_token_timeout=30
):
chunks.append(chunk)
print(f"Call count: {call_count}")
print(f"Received {len(chunks)} chunks")
assert call_count == 2 # First timeout, second success
assert len(chunks) == 1
assert chunks[0] == "success_chunk"
print("β Retry on timeout works correctly")
@pytest.mark.asyncio
async def test_raises_exception_after_all_retries(self):
"""
What it does: Raises exception after all retries exhausted.
Goal: Verify error handling when all retries fail.
"""
print("Setup: Mock request that always times out...")
call_count = 0
async def mock_make_request():
nonlocal call_count
call_count += 1
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
raise FirstTokenTimeoutError("Timeout!")
yield # Make it a generator
print("Action: Streaming with all retries failing...")
with pytest.raises(Exception) as exc_info:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=3,
first_token_timeout=30
):
pass
print(f"Call count: {call_count}")
print(f"Exception: {exc_info.value}")
assert call_count == 3 # Should try exactly 3 times
assert "30" in str(exc_info.value) # Timeout value in message
assert "3" in str(exc_info.value) # Retry count in message
print("β Exception raised after all retries")
@pytest.mark.asyncio
async def test_uses_custom_error_callbacks(self):
"""
What it does: Uses custom error callbacks.
Goal: Verify on_http_error and on_all_retries_failed callbacks.
"""
print("Setup: Mock request that always times out with custom callbacks...")
async def mock_make_request():
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
raise FirstTokenTimeoutError("Timeout!")
yield # Make it a generator
def custom_all_retries_failed(max_retries, timeout):
return ValueError(f"Custom error: {max_retries} retries, {timeout}s timeout")
print("Action: Streaming with custom callback...")
with pytest.raises(ValueError) as exc_info:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=2,
first_token_timeout=15,
on_all_retries_failed=custom_all_retries_failed
):
pass
print(f"Exception: {exc_info.value}")
assert "Custom error" in str(exc_info.value)
assert "2 retries" in str(exc_info.value)
assert "15" in str(exc_info.value)
print("β Custom callback used correctly")
@pytest.mark.asyncio
async def test_handles_http_error(self):
"""
What it does: Handles HTTP error from API.
Goal: Verify HTTP errors are handled correctly.
"""
print("Setup: Mock request that returns HTTP error...")
async def mock_make_request():
response = AsyncMock()
response.status_code = 500
response.aread = AsyncMock(return_value=b"Internal Server Error")
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
yield "should not reach"
print("Action: Streaming with HTTP error...")
with pytest.raises(Exception) as exc_info:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=3,
first_token_timeout=30
):
pass
print(f"Exception: {exc_info.value}")
assert "500" in str(exc_info.value)
assert "Internal Server Error" in str(exc_info.value)
print("β HTTP error handled correctly")
@pytest.mark.asyncio
async def test_uses_custom_http_error_callback(self):
"""
What it does: Uses custom HTTP error callback.
Goal: Verify on_http_error callback is used.
"""
print("Setup: Mock request with custom HTTP error callback...")
async def mock_make_request():
response = AsyncMock()
response.status_code = 429
response.aread = AsyncMock(return_value=b"Rate limited")
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
yield "should not reach"
def custom_http_error(status_code, error_text):
return RuntimeError(f"Custom HTTP error: {status_code} - {error_text}")
print("Action: Streaming with custom HTTP error callback...")
with pytest.raises(RuntimeError) as exc_info:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=3,
first_token_timeout=30,
on_http_error=custom_http_error
):
pass
print(f"Exception: {exc_info.value}")
assert "Custom HTTP error" in str(exc_info.value)
assert "429" in str(exc_info.value)
assert "Rate limited" in str(exc_info.value)
print("β Custom HTTP error callback used correctly")
@pytest.mark.asyncio
async def test_closes_response_on_timeout(self):
"""
What it does: Closes response on timeout.
Goal: Verify response is properly closed after timeout.
"""
print("Setup: Mock request that times out...")
responses = []
async def mock_make_request():
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
responses.append(response)
return response
async def mock_stream_processor(response):
raise FirstTokenTimeoutError("Timeout!")
yield # Make it a generator
print("Action: Streaming with timeout...")
try:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=2,
first_token_timeout=30
):
pass
except Exception:
pass
print(f"Created {len(responses)} responses")
# All responses should have been closed
for i, response in enumerate(responses):
print(f"Response {i} aclose called: {response.aclose.called}")
response.aclose.assert_called()
print("β Responses closed on timeout")
@pytest.mark.asyncio
async def test_propagates_non_timeout_exceptions(self):
"""
What it does: Propagates non-timeout exceptions without retry.
Goal: Verify other exceptions are not retried.
"""
print("Setup: Mock request that raises RuntimeError...")
call_count = 0
async def mock_make_request():
nonlocal call_count
call_count += 1
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
raise RuntimeError("Not a timeout error")
yield # Make it a generator
print("Action: Streaming with non-timeout error...")
with pytest.raises(RuntimeError) as exc_info:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=3,
first_token_timeout=30
):
pass
print(f"Call count: {call_count}")
print(f"Exception: {exc_info.value}")
assert call_count == 1 # Should NOT retry
assert "Not a timeout error" in str(exc_info.value)
print("β Non-timeout exceptions propagated without retry")
@pytest.mark.asyncio
async def test_uses_configured_max_retries(self):
"""
What it does: Uses configured max_retries value.
Goal: Verify max_retries parameter is respected.
"""
print("Setup: Mock request that always times out...")
call_count = 0
async def mock_make_request():
nonlocal call_count
call_count += 1
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
raise FirstTokenTimeoutError("Timeout!")
yield # Make it a generator
print("Action: Streaming with max_retries=5...")
try:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=5,
first_token_timeout=30
):
pass
except Exception:
pass
print(f"Call count: {call_count}")
assert call_count == 5 # Should try exactly 5 times
print("β max_retries parameter respected")
@pytest.mark.asyncio
async def test_multiple_retries_then_success(self):
"""
What it does: Succeeds after multiple retries.
Goal: Verify recovery after multiple failures.
"""
print("Setup: Mock request that fails twice then succeeds...")
call_count = 0
async def mock_make_request():
nonlocal call_count
call_count += 1
response = AsyncMock()
response.status_code = 200
response.aclose = AsyncMock()
return response
async def mock_stream_processor(response):
nonlocal call_count
if call_count < 3:
raise FirstTokenTimeoutError(f"Timeout on attempt {call_count}")
yield "finally_success"
print("Action: Streaming with multiple retries...")
chunks = []
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=5,
first_token_timeout=30
):
chunks.append(chunk)
print(f"Call count: {call_count}")
print(f"Received {len(chunks)} chunks")
assert call_count == 3 # Failed twice, succeeded on third
assert len(chunks) == 1
assert chunks[0] == "finally_success"
print("β Multiple retries then success works correctly")
@pytest.mark.asyncio
async def test_closes_response_on_http_error(self):
"""
What it does: Closes response on HTTP error.
Goal: Verify response is properly closed after HTTP error.
"""
print("Setup: Mock request that returns HTTP error...")
response = AsyncMock()
response.status_code = 503
response.aread = AsyncMock(return_value=b"Service Unavailable")
response.aclose = AsyncMock()
async def mock_make_request():
return response
async def mock_stream_processor(resp):
yield "should not reach"
print("Action: Streaming with HTTP error...")
try:
async for chunk in stream_with_first_token_retry(
make_request=mock_make_request,
stream_processor=mock_stream_processor,
max_retries=3,
first_token_timeout=30
):
pass
except Exception:
pass
print(f"Response aclose called: {response.aclose.called}")
response.aclose.assert_called()
print("β Response closed on HTTP error") |