Spaces:
Paused
Paused
File size: 70,424 Bytes
a5784e9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 | """
Tests for api_utils.request_processor module.
Test Strategy:
- Unit tests: Test helper functions individually (_prepare_and_validate_request,
_analyze_model_requirements, _validate_page_status, etc.)
- Mock only external boundaries: Browser/page (Playwright), network requests
- Use REAL internal state: Don't mock helper functions, test actual logic
- Integration tests: Full _process_request_refactored flow with real locks/state
(see tests/integration/test_request_flow.py)
Coverage Target: 90%+
Mock Budget: <50 (down from 103)
"""
import asyncio
import json
from typing import cast
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException, Request
from playwright.async_api import Error as PlaywrightAsyncError
from api_utils.context_types import RequestContext
from api_utils.request_processor import (
_analyze_model_requirements,
_handle_model_switch_failure,
_prepare_and_validate_request,
_validate_page_status,
)
from api_utils.server_state import state
from models import ChatCompletionRequest, Message
# ==================== Unit Tests for Helper Functions ====================
class TestAnalyzeModelRequirements:
"""Unit tests for _analyze_model_requirements helper function."""
@pytest.mark.asyncio
async def test_analyze_same_model_no_switch_needed(
self, make_request_context, make_chat_request
):
"""Test that analyzing same model as current doesn't require switch."""
req_id = "test-req"
context = make_request_context(current_ai_studio_model_id="gemini-1.5-pro")
request = make_chat_request(model="gemini-1.5-pro")
with patch("api_utils.request_processor.MODEL_NAME", "gemini-1.5-pro"):
result = await _analyze_model_requirements(req_id, context, request)
# Should return context (possibly modified)
assert isinstance(result, dict)
assert "is_streaming" in result # Verify it's a valid RequestContext
@pytest.mark.asyncio
async def test_analyze_different_model_requires_switch(
self, make_request_context, make_chat_request
):
"""Test that different model is detected and flagged for switching."""
req_id = "test-req"
context = make_request_context(current_ai_studio_model_id="gemini-1.5-pro")
request = make_chat_request(model="gemini-1.5-flash")
with patch("api_utils.request_processor.MODEL_NAME", "gemini-1.5-pro"):
with patch(
"api_utils.request_processor.ms_analyze",
new_callable=AsyncMock,
) as mock_ms_analyze:
mock_ms_analyze.return_value = {
**context,
"need_switch": True,
"model_id_to_use": "gemini-1.5-flash",
}
result = await _analyze_model_requirements(req_id, context, request)
# Verify delegate was called with correct args
mock_ms_analyze.assert_called_once_with(
req_id, context, "gemini-1.5-flash", "gemini-1.5-pro"
)
assert result["model_id_to_use"] == "gemini-1.5-flash"
class TestValidatePageStatus:
"""Unit tests for _validate_page_status helper function."""
@pytest.mark.asyncio
async def test_validate_page_ready_success(self, mock_playwright_stack):
"""Test validation succeeds when page is ready."""
_, _, _, page = mock_playwright_stack
page.is_closed.return_value = False
context = cast(
RequestContext,
{
"page": page,
"is_page_ready": True,
},
)
check_disco = MagicMock() # Should be called
# Should not raise
await _validate_page_status("test-req", context, check_disco)
check_disco.assert_called_once_with("Initial Page Check")
@pytest.mark.asyncio
async def test_validate_page_closed_raises_503(self, mock_playwright_stack):
"""Test validation fails with 503 when page is closed."""
_, _, _, page = mock_playwright_stack
page.is_closed.return_value = True # Page closed
context = cast(
RequestContext,
{
"page": page,
"is_page_ready": True,
},
)
check_disco = MagicMock()
with pytest.raises(HTTPException) as exc:
await _validate_page_status("test-req", context, check_disco)
assert exc.value.status_code == 503
assert "AI Studio page lost" in exc.value.detail
assert exc.value.headers is not None
assert exc.value.headers.get("Retry-After") == "30"
@pytest.mark.asyncio
async def test_validate_page_not_ready_raises_503(self, mock_playwright_stack):
"""Test validation fails when page is not ready."""
_, _, _, page = mock_playwright_stack
page.is_closed.return_value = False
context = cast(
RequestContext,
{
"page": page,
"is_page_ready": False, # Not ready
},
)
check_disco = MagicMock()
with pytest.raises(HTTPException) as exc:
await _validate_page_status("test-req", context, check_disco)
assert exc.value.status_code == 503
@pytest.mark.asyncio
async def test_validate_page_none_raises_503(self):
"""Test validation fails when page is None."""
context = cast(
RequestContext,
{
"page": None, # No page
"is_page_ready": True,
},
)
check_disco = MagicMock()
with pytest.raises(HTTPException) as exc:
await _validate_page_status("test-req", context, check_disco)
assert exc.value.status_code == 503
class TestPrepareAndValidateRequest:
"""Unit tests for _prepare_and_validate_request helper function."""
@pytest.mark.asyncio
async def test_prepare_simple_text_message(self, mock_env):
"""Test preparing a simple text message without attachments or tools."""
req_id = "test-req"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Hello AI")],
model="gemini-1.5-pro",
)
check_disco = MagicMock()
with (
patch("api_utils.request_processor.validate_chat_request") as mock_validate,
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("Hello AI", []),
) as mock_prep,
patch(
"api_utils.request_processor.maybe_execute_tools",
new_callable=AsyncMock,
return_value=None,
),
):
prompt, images, tool_results = await _prepare_and_validate_request(
req_id, request, check_disco
)
# Verify validation was called
mock_validate.assert_called_once_with(request.messages, req_id)
# Verify prompt preparation was called
mock_prep.assert_called_once()
# Check results
assert prompt == "Hello AI"
assert images == []
assert tool_results is None
check_disco.assert_called_once_with("After Prompt Prep")
@pytest.mark.asyncio
async def test_prepare_with_tool_execution(self, mock_env):
"""Test preparing request with tool execution results."""
req_id = "test-req"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Calculate 2+2")],
model="gemini-1.5-pro",
tools=[{"type": "function", "function": {"name": "calculator"}}],
)
check_disco = MagicMock()
tool_results = [
{"name": "calculator", "arguments": '{"expr": "2+2"}', "result": "4"}
]
with (
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("Calculate 2+2", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools",
new_callable=AsyncMock,
return_value=tool_results,
),
):
prompt, images, _ = await _prepare_and_validate_request(
req_id, request, check_disco
)
# Tool execution results should be appended to prompt
assert "Tool Execution: calculator" in prompt
assert "Arguments:\n" in prompt
assert "Result:\n4" in prompt
@pytest.mark.asyncio
async def test_prepare_with_file_attachments(self, mock_env, tmp_path):
"""Test preparing request with file attachments."""
req_id = "test-req"
# Create a temporary file
test_file = tmp_path / "test_image.png"
test_file.write_bytes(b"fake image data")
request = ChatCompletionRequest(
messages=[
Message(
role="user",
content="Look at this image",
attachments=[str(test_file)], # Absolute path
)
],
model="gemini-1.5-pro",
)
check_disco = MagicMock()
with (
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("Look at this image", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools",
new_callable=AsyncMock,
return_value=None,
),
patch(
"config.settings.ONLY_COLLECT_CURRENT_USER_ATTACHMENTS",
True,
),
):
prompt, images, _ = await _prepare_and_validate_request(
req_id, request, check_disco
)
# Should extract attachment from latest user message
assert len(images) == 1
assert "test_image.png" in images[0]
@pytest.mark.asyncio
async def test_prepare_validation_error_raises_bad_request(self, mock_env):
"""Test that validation errors are converted to bad request exceptions."""
req_id = "test-req"
request = ChatCompletionRequest(
messages=[], # Empty messages - invalid
model="gemini-1.5-pro",
)
check_disco = MagicMock()
with patch(
"api_utils.request_processor.validate_chat_request",
side_effect=ValueError("Messages cannot be empty"),
):
with pytest.raises(HTTPException) as exc:
await _prepare_and_validate_request(req_id, request, check_disco)
assert exc.value.status_code == 400 # Bad request
assert "Invalid request" in exc.value.detail
@pytest.mark.asyncio
async def test_prepare_tool_execution_exception(self, mock_env):
"""Test that tool execution exceptions are caught and handled gracefully."""
req_id = "test-req"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Test")],
model="gemini-1.5-pro",
tools=[{"type": "function", "function": {"name": "test_tool"}}],
)
check_disco = MagicMock()
with (
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("Test prompt", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools",
new_callable=AsyncMock,
side_effect=Exception("Tool execution failed"),
),
):
# Should not raise - exception is caught and tool_exec_results becomes None
prompt, images, _ = await _prepare_and_validate_request(
req_id, request, check_disco
)
# Verify prompt is returned without tool results
assert prompt == "Test prompt"
assert images == []
# Tool execution failure should be silently handled
check_disco.assert_called_once_with("After Prompt Prep")
@pytest.mark.asyncio
async def test_prepare_tool_results_append_exception(self, mock_env):
"""Test that exceptions during tool result formatting are caught."""
req_id = "test-req"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Test")],
model="gemini-1.5-pro",
tools=[{"type": "function", "function": {"name": "test_tool"}}],
)
check_disco = MagicMock()
# Tool result with missing/invalid keys to trigger exception during formatting
tool_results = [{"name": "test_tool"}] # Missing "arguments" and "result" keys
with (
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("Test prompt", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools",
new_callable=AsyncMock,
return_value=tool_results,
),
):
# Should not raise - exception during result appending is caught
prompt, images, _ = await _prepare_and_validate_request(
req_id, request, check_disco
)
# Verify base prompt is returned (tool results not appended due to error)
assert "Test prompt" in prompt
# The append might partially succeed or fail - main point is no exception raised
@pytest.mark.asyncio
async def test_prepare_file_url_attachments(self, mock_env, tmp_path):
"""Test preparing request with file:// URL attachments."""
req_id = "test-req"
# Create a temporary file
test_file = tmp_path / "test_doc.pdf"
test_file.write_bytes(b"fake pdf data")
# Create file:// URL
file_url = f"file://{test_file.as_posix()}"
request = ChatCompletionRequest(
messages=[
Message(
role="user",
content="Check this document",
attachments=[file_url], # file:// URL
)
],
model="gemini-1.5-pro",
)
check_disco = MagicMock()
with (
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("Check this document", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools",
new_callable=AsyncMock,
return_value=None,
),
patch(
"config.settings.ONLY_COLLECT_CURRENT_USER_ATTACHMENTS",
True,
),
):
prompt, images, _ = await _prepare_and_validate_request(
req_id, request, check_disco
)
# Should parse file:// URL and extract local path
assert len(images) == 1
assert "test_doc.pdf" in images[0]
@pytest.mark.asyncio
async def test_prepare_dict_attachment_with_url_key(self, mock_env, tmp_path):
"""Test preparing request with dict attachments containing url/path keys."""
req_id = "test-req"
# Create a temporary file
test_file = tmp_path / "image.jpg"
test_file.write_bytes(b"fake image")
request = ChatCompletionRequest(
messages=[
Message(
role="user",
content="Analyze image",
# Dict-style attachment with "url" key
attachments=[{"url": str(test_file)}],
)
],
model="gemini-1.5-pro",
)
check_disco = MagicMock()
with (
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("Analyze image", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools",
new_callable=AsyncMock,
return_value=None,
),
patch(
"config.settings.ONLY_COLLECT_CURRENT_USER_ATTACHMENTS",
True,
),
):
prompt, images, _ = await _prepare_and_validate_request(
req_id, request, check_disco
)
# Should extract path from dict["url"]
assert len(images) == 1
assert "image.jpg" in images[0]
class TestHandleModelSwitchFailure:
"""Unit tests for _handle_model_switch_failure helper function."""
@pytest.mark.asyncio
async def test_handle_switch_failure_restores_state(self, mock_playwright_stack):
"""Test that model switch failure restores original model in state."""
from api_utils.server_state import state
_, _, _, page = mock_playwright_stack
logger = MagicMock()
req_id = "test-req"
# Store original
original_model = state.current_ai_studio_model_id
try:
# Simulate state was changed during failed switch attempt
state.current_ai_studio_model_id = "changed-model"
with pytest.raises(HTTPException) as exc:
await _handle_model_switch_failure(
req_id, page, "gemini-2.0", "gemini-1.5-pro", logger
)
# Verify state was restored to model_before_switch
assert state.current_ai_studio_model_id == "gemini-1.5-pro"
# Verify exception details
assert exc.value.status_code == 422
assert "Failed to switch to model 'gemini-2.0'" in exc.value.detail
# Verify warning was logged
logger.warning.assert_called_once()
finally:
# Restore original state
state.current_ai_studio_model_id = original_model
# ==================== Integration-Style Tests (with Real Helper Functions) ====================
class TestProcessRequestRefactoredFlow:
"""
Tests for _process_request_refactored using REAL helper functions.
These tests mock only external boundaries (browser, network) but use
the actual helper function logic. This catches integration issues that
over-mocked tests miss.
Note: Full integration tests with real locks are in tests/integration/test_request_flow.py
"""
@pytest.mark.asyncio
async def test_client_disconnected_before_processing(
self, mock_env, mock_playwright_stack
):
"""Test that early client disconnect is detected and handled."""
from api_utils.request_processor import _process_request_refactored
req_id = "test-req-id"
request_data = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")], model="gemini-1.5-pro"
)
http_request = MagicMock(spec=Request)
http_request.is_disconnected = AsyncMock(return_value=True) # Disconnected
result_future = asyncio.Future()
# Don't mock _check_client_connection - use real function
result = await _process_request_refactored(
req_id, request_data, http_request, result_future
)
# Should return None (early exit)
assert result is None
# Future should be set with 499 error
assert result_future.done()
with pytest.raises(HTTPException) as exc:
result_future.result()
assert exc.value.status_code == 499 # Client closed request
@pytest.mark.asyncio
async def test_context_initialization_failure_bubbles_up(
self, mock_env, mock_playwright_stack
):
"""Test that context initialization failures are not swallowed."""
from api_utils.request_processor import _process_request_refactored
req_id = "test-req-id"
request_data = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")], model="gemini-1.5-pro"
)
http_request = MagicMock(spec=Request)
http_request.is_disconnected = AsyncMock(return_value=False)
result_future = asyncio.Future()
# Mock only _initialize_request_context to fail
with patch(
"api_utils.request_processor._initialize_request_context",
new_callable=AsyncMock,
side_effect=Exception("Context init failed"),
):
with pytest.raises(Exception) as exc:
await _process_request_refactored(
req_id, request_data, http_request, result_future
)
assert "Context init failed" in str(exc.value)
# Future not set (exception bubbles to queue_worker)
assert not result_future.done()
@pytest.mark.asyncio
async def test_playwright_error_sets_502_in_future(
self, mock_env, make_request_context
):
"""Test that Playwright errors are caught and set proper HTTP status."""
from api_utils.request_processor import _process_request_refactored
req_id = "test-req-id"
request_data = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")], model="gemini-1.5-pro"
)
http_request = MagicMock(spec=Request)
http_request.is_disconnected = AsyncMock(return_value=False)
result_future = asyncio.Future()
context = make_request_context(req_id=req_id)
# Mock context init to succeed, PageController to fail with Playwright error
with (
patch(
"api_utils.request_processor._initialize_request_context",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor._analyze_model_requirements",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor.PageController",
side_effect=PlaywrightAsyncError("Browser crashed"),
),
patch("browser_utils.save_error_snapshot", new_callable=AsyncMock),
):
await _process_request_refactored(
req_id, request_data, http_request, result_future
)
# Future should have 503 error (page not ready)
assert result_future.done()
with pytest.raises(HTTPException) as exc:
result_future.result()
assert exc.value.status_code == 503 # Service unavailable (page not ready)
assert "page lost or not ready" in exc.value.detail
# ==================== Tests for Specific Response Handling ====================
class TestAuxiliaryStreamResponse:
"""Tests for auxiliary stream response handling (Stream Proxy tier)."""
@pytest.mark.asyncio
async def test_auxiliary_stream_non_streaming_success(
self, mock_env, make_request_context
):
"""Test non-streaming response from auxiliary stream (Stream Proxy)."""
from api_utils.request_processor import _handle_auxiliary_stream_response
req_id = "test-req-id"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")],
model="gemini-1.5-pro",
stream=False,
)
context = make_request_context(req_id=req_id)
result_future = asyncio.Future()
submit_locator = MagicMock()
check_disco = MagicMock()
# Mock stream response generator
mock_stream_data = [
{"body": "Hello", "done": False},
{"body": " world", "done": False},
{"body": "Hello world", "done": True, "reason": None, "function": []},
]
async def mock_stream_gen(*args, **kwargs):
for data in mock_stream_data:
yield data
with (
patch(
"api_utils.request_processor.use_stream_response",
side_effect=mock_stream_gen,
),
patch(
"api_utils.request_processor.calculate_usage_stats",
return_value={
"prompt_tokens": 10,
"completion_tokens": 5,
"total_tokens": 15,
},
),
):
result = await _handle_auxiliary_stream_response(
req_id,
request,
context,
result_future,
submit_locator,
check_disco,
timeout=30.0,
)
# Non-streaming returns None
assert isinstance(result, dict)
# Future should have JSONResponse
assert result_future.done()
response = result_future.result()
assert response.status_code == 200
# Verify response content
content = json.loads(response.body)
assert content["choices"][0]["message"]["content"] == "Hello world"
assert content["usage"]["total_tokens"] == 15
@pytest.mark.asyncio
async def test_auxiliary_stream_non_streaming_with_function_calls(
self, mock_env, make_request_context
):
"""Test non-streaming response with function calls (tool_calls) from auxiliary stream."""
from api_utils.request_processor import _handle_auxiliary_stream_response
req_id = "test-req-id"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Get weather")],
model="gemini-1.5-pro",
stream=False,
tools=[{"type": "function", "function": {"name": "get_weather"}}],
)
context = make_request_context(req_id=req_id)
result_future = asyncio.Future()
submit_locator = MagicMock()
check_disco = MagicMock()
# Mock stream response with function calls
mock_stream_data = [
{
"body": "",
"done": True,
"reason": None,
"function": [
{"name": "get_weather", "params": {"location": "San Francisco"}}
],
},
]
async def mock_stream_gen(*args, **kwargs):
for data in mock_stream_data:
yield data
with (
patch(
"api_utils.request_processor.use_stream_response",
side_effect=mock_stream_gen,
),
patch(
"api_utils.request_processor.calculate_usage_stats",
return_value={
"prompt_tokens": 20,
"completion_tokens": 10,
"total_tokens": 30,
},
),
):
result = await _handle_auxiliary_stream_response(
req_id,
request,
context,
result_future,
submit_locator,
check_disco,
timeout=30.0,
)
# Non-streaming with function calls returns None
assert isinstance(result, dict)
# Future should have JSONResponse with tool_calls
assert result_future.done()
response = result_future.result()
assert response.status_code == 200
# Verify tool_calls in response
content = json.loads(response.body)
assert content["choices"][0]["finish_reason"] == "tool_calls"
assert "tool_calls" in content["choices"][0]["message"]
tool_calls = content["choices"][0]["message"]["tool_calls"]
assert len(tool_calls) == 1
assert tool_calls[0]["type"] == "function"
assert tool_calls[0]["function"]["name"] == "get_weather"
# Arguments should be JSON string
args = json.loads(tool_calls[0]["function"]["arguments"])
assert args["location"] == "San Francisco"
# Content should be None when tool_calls present
assert content["choices"][0]["message"]["content"] is None
@pytest.mark.asyncio
async def test_auxiliary_stream_non_streaming_no_content_error(
self, mock_env, make_request_context
):
"""Test error when aux stream completes with done=True but no content."""
from api_utils.request_processor import _handle_auxiliary_stream_response
req_id = "test-req-id"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")],
model="gemini-1.5-pro",
stream=False,
)
context = make_request_context(req_id=req_id)
result_future = asyncio.Future()
submit_locator = MagicMock()
check_disco = MagicMock()
# Mock stream that completes with no content and no functions
mock_stream_data = [
{"body": None, "done": True, "reason": None, "function": []},
]
async def mock_stream_gen(*args, **kwargs):
for data in mock_stream_data:
yield data
with patch(
"api_utils.request_processor.use_stream_response",
side_effect=mock_stream_gen,
):
with pytest.raises(HTTPException) as exc:
await _handle_auxiliary_stream_response(
req_id,
request,
context,
result_future,
submit_locator,
check_disco,
timeout=30.0,
)
# Should raise 502 error for no content provided
assert exc.value.status_code == 502
assert "no content provided" in exc.value.detail.lower()
@pytest.mark.asyncio
async def test_auxiliary_stream_non_streaming_json_parse_error(
self, mock_env, make_request_context
):
"""Test handling of JSON parse errors in non-streaming aux stream."""
from api_utils.request_processor import _handle_auxiliary_stream_response
req_id = "test-req-id"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")],
model="gemini-1.5-pro",
stream=False,
)
context = make_request_context(req_id=req_id)
result_future = asyncio.Future()
submit_locator = MagicMock()
check_disco = MagicMock()
# Mock stream that yields invalid JSON string
mock_stream_data = [
"invalid json string", # This will trigger JSON parse error
{"body": "Final content", "done": True, "reason": None},
]
async def mock_stream_gen(*args, **kwargs):
for data in mock_stream_data:
yield data
with (
patch(
"api_utils.request_processor.use_stream_response",
side_effect=mock_stream_gen,
),
patch(
"api_utils.request_processor.calculate_usage_stats",
return_value={
"prompt_tokens": 5,
"completion_tokens": 3,
"total_tokens": 8,
},
),
):
result = await _handle_auxiliary_stream_response(
req_id,
request,
context,
result_future,
submit_locator,
check_disco,
timeout=30.0,
)
# Should complete successfully, skipping invalid JSON
assert isinstance(result, dict)
assert result_future.done()
response = result_future.result()
content = json.loads(response.body)
assert content["choices"][0]["message"]["content"] == "Final content"
@pytest.mark.asyncio
async def test_auxiliary_stream_non_streaming_unknown_data_type(
self, mock_env, make_request_context
):
"""Test handling of unknown data types in non-streaming aux stream."""
from api_utils.request_processor import _handle_auxiliary_stream_response
req_id = "test-req-id"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")],
model="gemini-1.5-pro",
stream=False,
)
context = make_request_context(req_id=req_id)
result_future = asyncio.Future()
submit_locator = MagicMock()
check_disco = MagicMock()
# Mock stream with unknown data type (not str or dict)
mock_stream_data = [
12345, # Integer - unknown type
{"body": "Valid content", "done": True, "reason": None},
]
async def mock_stream_gen(*args, **kwargs):
for data in mock_stream_data:
yield data
with (
patch(
"api_utils.request_processor.use_stream_response",
side_effect=mock_stream_gen,
),
patch(
"api_utils.request_processor.calculate_usage_stats",
return_value={
"prompt_tokens": 5,
"completion_tokens": 3,
"total_tokens": 8,
},
),
):
result = await _handle_auxiliary_stream_response(
req_id,
request,
context,
result_future,
submit_locator,
check_disco,
timeout=30.0,
)
# Should complete successfully, skipping unknown type
assert isinstance(result, dict)
assert result_future.done()
response = result_future.result()
content = json.loads(response.body)
assert content["choices"][0]["message"]["content"] == "Valid content"
@pytest.mark.asyncio
async def test_auxiliary_stream_streaming_cancelled_error(
self, mock_env, make_request_context
):
"""Test CancelledError handling in streaming auxiliary stream."""
from api_utils.request_processor import _handle_auxiliary_stream_response
req_id = "test-req-id"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")],
model="gemini-1.5-pro",
stream=True, # Streaming mode
)
context = make_request_context(req_id=req_id)
result_future = asyncio.Future()
submit_locator = MagicMock()
check_disco = MagicMock()
# Mock gen_sse_from_aux_stream to raise CancelledError
async def mock_cancelled_gen(*args, **kwargs):
raise asyncio.CancelledError("Request cancelled")
yield "" # make it a generator
with patch(
"api_utils.request_processor.gen_sse_from_aux_stream",
side_effect=mock_cancelled_gen,
):
await _handle_auxiliary_stream_response(
req_id,
request,
context,
result_future,
submit_locator,
check_disco,
timeout=30.0,
)
streaming_response = result_future.result()
with pytest.raises(asyncio.CancelledError):
async for _ in streaming_response.body_iterator:
pass
@pytest.mark.asyncio
async def test_auxiliary_stream_streaming_exception_sets_event(
self, mock_env, make_request_context
):
"""Test that exceptions in streaming mode set completion event before raising."""
from api_utils.request_processor import _handle_auxiliary_stream_response
req_id = "test-req-id"
request = ChatCompletionRequest(
messages=[Message(role="user", content="Hello")],
model="gemini-1.5-pro",
stream=True,
)
context = make_request_context(req_id=req_id)
result_future = asyncio.Future()
submit_locator = MagicMock()
check_disco = MagicMock()
# Mock gen_sse_from_aux_stream to raise generic exception
async def mock_error_gen(*args, **kwargs):
raise Exception("Stream error")
yield "" # make it a generator
with patch(
"api_utils.request_processor.gen_sse_from_aux_stream",
side_effect=mock_error_gen,
):
await _handle_auxiliary_stream_response(
req_id,
request,
context,
result_future,
submit_locator,
check_disco,
timeout=30.0,
)
streaming_response = result_future.result()
with pytest.raises(Exception) as exc:
async for _ in streaming_response.body_iterator:
pass
assert "Stream error" in str(exc.value)
from api_utils.request_processor import (
_cleanup_request_resources,
_handle_auxiliary_stream_response,
_handle_model_switching,
_handle_parameter_cache,
_handle_playwright_response,
_handle_response_processing,
_process_request_refactored,
)
# --- Fixtures ---
@pytest.fixture
def mock_http_request():
return MagicMock(spec=Request)
@pytest.fixture
def mock_context():
page_mock = AsyncMock()
# is_closed is synchronous in Playwright, so it shouldn't return a coroutine
page_mock.is_closed = MagicMock(return_value=False)
return {
"page": page_mock,
"is_page_ready": True,
"current_ai_studio_model_id": "gemini-2.0-flash",
"logger": MagicMock(),
"page_params_cache": {},
"params_cache_lock": AsyncMock(),
"model_id_to_use": "gemini-2.0-flash",
"parsed_model_list": [],
}
@pytest.fixture
def mock_request():
return ChatCompletionRequest(
messages=[Message(role="user", content="Hello")],
model="gemini-2.0-flash",
stream=False,
)
@pytest.fixture
def mock_check_disconnected():
return MagicMock()
# --- Tests ---
@pytest.mark.asyncio
async def test_analyze_model_requirements(mock_context, mock_request):
with patch(
"api_utils.request_processor.ms_analyze", new_callable=AsyncMock
) as mock_ms_analyze:
await _analyze_model_requirements("req1", mock_context, mock_request)
mock_ms_analyze.assert_called_once()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"page_none,is_closed,is_page_ready,should_raise,test_id",
[
(False, False, True, False, "success"),
(True, None, None, True, "page_none"),
(False, True, None, True, "page_closed"),
(False, False, False, True, "page_not_ready"),
],
)
async def test_validate_page_status(
mock_context,
mock_check_disconnected,
page_none,
is_closed,
is_page_ready,
should_raise,
test_id,
):
"""Test page status validation with various scenarios."""
if page_none:
mock_context["page"] = None
else:
if mock_context["page"] is None:
mock_context["page"] = AsyncMock()
mock_context["page"].is_closed.return_value = is_closed
if is_page_ready is not None:
mock_context["is_page_ready"] = is_page_ready
if should_raise:
with pytest.raises(HTTPException) as exc:
await _validate_page_status("req1", mock_context, mock_check_disconnected)
assert exc.value.status_code == 503
else:
await _validate_page_status("req1", mock_context, mock_check_disconnected)
mock_check_disconnected.assert_called_once()
@pytest.mark.asyncio
async def test_handle_model_switching(mock_context, mock_check_disconnected):
with patch(
"api_utils.request_processor.ms_switch", new_callable=AsyncMock
) as mock_ms_switch:
await _handle_model_switching("req1", mock_context, mock_check_disconnected)
mock_ms_switch.assert_called_once()
@pytest.mark.asyncio
async def test_handle_model_switch_failure():
mock_page = AsyncMock()
mock_logger = MagicMock()
with patch.object(state, "current_ai_studio_model_id", "old_model"):
with pytest.raises(HTTPException) as exc:
await _handle_model_switch_failure(
"req1", mock_page, "new_model", "old_model", mock_logger
)
assert exc.value.status_code == 422
# Check if logger warning was called
mock_logger.warning.assert_called()
@pytest.mark.asyncio
async def test_handle_parameter_cache(mock_context):
with patch(
"api_utils.request_processor.ms_param_cache", new_callable=AsyncMock
) as mock_ms_cache:
await _handle_parameter_cache("req1", mock_context)
mock_ms_cache.assert_called_once()
@pytest.mark.asyncio
async def test_prepare_and_validate_request_basic(
mock_request, mock_check_disconnected
):
with (
patch("api_utils.request_processor.validate_chat_request") as mock_validate,
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("prompt", []),
) as mock_prep,
patch(
"api_utils.request_processor.maybe_execute_tools", new_callable=AsyncMock
) as mock_tools,
):
mock_tools.return_value = None
prompt, images, _ = await _prepare_and_validate_request(
"req1", mock_request, mock_check_disconnected
)
assert prompt == "prompt"
assert images == []
mock_validate.assert_called_once()
mock_prep.assert_called_once()
mock_tools.assert_called_once()
mock_check_disconnected.assert_called_once()
@pytest.mark.asyncio
async def test_prepare_and_validate_request_with_tools(
mock_request, mock_check_disconnected
):
mock_request.tools = [{"type": "function", "function": {"name": "test"}}]
mock_request.mcp_endpoint = "http://mcp"
tool_results = [{"name": "test_tool", "arguments": "{}", "result": "success"}]
with (
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("prompt", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools", new_callable=AsyncMock
) as mock_tools,
patch("api_utils.tools_registry.register_runtime_tools") as mock_register,
):
mock_tools.return_value = tool_results
prompt, _, _ = await _prepare_and_validate_request(
"req1", mock_request, mock_check_disconnected
)
assert "Tool Execution: test_tool" in prompt
assert "Result:\nsuccess" in prompt
mock_register.assert_called_once()
@pytest.mark.asyncio
async def test_prepare_and_validate_request_attachments(
mock_request, mock_check_disconnected
):
# Mock ONLY_COLLECT_CURRENT_USER_ATTACHMENTS to True
with (
patch("config.settings.ONLY_COLLECT_CURRENT_USER_ATTACHMENTS", True),
patch("api_utils.request_processor.validate_chat_request"),
patch(
"api_utils.request_processor.prepare_combined_prompt",
return_value=("prompt", []),
),
patch(
"api_utils.request_processor.maybe_execute_tools", new_callable=AsyncMock
) as mock_tools,
patch(
"api_utils.request_processor.collect_and_validate_attachments",
return_value=["/tmp/file.png"],
) as mock_collect,
):
mock_tools.return_value = None
# Use a mock object that supports getattr for role and attachments
msg_mock = MagicMock()
msg_mock.role = "user"
msg_mock.content = "hi"
msg_mock.attachments = [
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
]
# Make sure model_dump works if called (though not called in this specific path, but good practice)
msg_mock.model_dump.return_value = {"role": "user", "content": "hi"}
mock_request.messages = [msg_mock]
_, images, _ = await _prepare_and_validate_request(
"req1", mock_request, mock_check_disconnected
)
assert "/tmp/file.png" in images
mock_collect.assert_called_once()
@pytest.mark.asyncio
async def test_handle_response_processing_aux_stream(
mock_request, mock_context, mock_check_disconnected
):
mock_future = asyncio.Future()
mock_locator = MagicMock()
with (
patch(
"api_utils.request_processor.get_environment_variable", return_value="8000"
),
patch(
"api_utils.request_processor._handle_auxiliary_stream_response",
new_callable=AsyncMock,
) as mock_aux,
):
await _handle_response_processing(
"req1",
mock_request,
None,
mock_context,
mock_future,
mock_locator,
mock_check_disconnected,
100,
30.0,
)
mock_aux.assert_called_once()
@pytest.mark.asyncio
async def test_handle_response_processing_playwright(
mock_request, mock_context, mock_check_disconnected
):
mock_future = asyncio.Future()
mock_locator = MagicMock()
mock_page = AsyncMock()
with (
patch("api_utils.request_processor.get_environment_variable", return_value="0"),
patch(
"api_utils.request_processor._handle_playwright_response",
new_callable=AsyncMock,
) as mock_pw,
):
await _handle_response_processing(
"req1",
mock_request,
mock_page,
mock_context,
mock_future,
mock_locator,
mock_check_disconnected,
100,
30.0,
)
mock_pw.assert_called_once()
@pytest.mark.asyncio
async def test_handle_auxiliary_stream_response_streaming(
mock_request, mock_context, mock_check_disconnected
):
mock_request.stream = True
mock_future = asyncio.Future()
mock_locator = MagicMock()
async def mock_gen_sse(*args, **kwargs):
if False:
yield ""
with patch(
"api_utils.request_processor.gen_sse_from_aux_stream", side_effect=mock_gen_sse
):
result = await _handle_auxiliary_stream_response(
"req1",
mock_request,
mock_context,
mock_future,
mock_locator,
mock_check_disconnected,
timeout=30.0,
)
assert result is not None
completion_event, _, _ = (
result if isinstance(result, tuple) else (None, None, None)
)
assert isinstance(completion_event, asyncio.Event)
# Note: stream_state is no longer returned in the tuple, it's used internally
assert mock_future.done()
# Check if result is StreamingResponse
# Note: In actual code it sets StreamingResponse, which might not be easily checkable for class type if not imported,
# but we can check attributes
assert hasattr(mock_future.result(), "body_iterator")
@pytest.mark.asyncio
async def test_handle_auxiliary_stream_response_non_streaming_success(
mock_request, mock_context, mock_check_disconnected
):
mock_request.stream = False
mock_future = asyncio.Future()
mock_locator = MagicMock()
async def mock_use_stream_response(*args, **kwargs):
yield {"done": False, "body": "part1"}
yield {"done": True, "body": "full_content", "reason": "stop"}
with (
patch(
"api_utils.request_processor.use_stream_response",
side_effect=mock_use_stream_response,
),
patch("api_utils.request_processor.calculate_usage_stats", return_value={}),
patch(
"api_utils.request_processor.build_chat_completion_response_json",
return_value={"id": "resp1"},
),
):
result = await _handle_auxiliary_stream_response(
"req1",
mock_request,
mock_context,
mock_future,
mock_locator,
mock_check_disconnected,
timeout=30.0,
)
assert isinstance(result, dict)
assert mock_future.done()
# Verify result is JSONResponse
assert hasattr(mock_future.result(), "body")
@pytest.mark.asyncio
async def test_handle_auxiliary_stream_response_non_streaming_internal_timeout(
mock_request, mock_context, mock_check_disconnected
):
mock_request.stream = False
mock_future = asyncio.Future()
mock_locator = MagicMock()
async def mock_use_stream_response(*args, **kwargs):
yield {"done": True, "reason": "internal_timeout"}
with patch(
"api_utils.request_processor.use_stream_response",
side_effect=mock_use_stream_response,
):
with pytest.raises(HTTPException) as exc:
await _handle_auxiliary_stream_response(
"req1",
mock_request,
mock_context,
mock_future,
mock_locator,
mock_check_disconnected,
timeout=30.0,
)
assert exc.value.status_code == 502
@pytest.mark.asyncio
async def test_handle_playwright_response_streaming(
mock_request, mock_context, mock_check_disconnected
):
mock_request.stream = True
mock_future = asyncio.Future()
mock_locator = MagicMock()
mock_page = AsyncMock()
async def mock_gen_sse(*args, **kwargs):
if False:
yield ""
with (
patch(
"api_utils.request_processor.locate_response_elements",
new_callable=AsyncMock,
),
patch(
"api_utils.request_processor.gen_sse_from_playwright",
side_effect=mock_gen_sse,
),
):
result = await _handle_playwright_response(
"req1",
mock_request,
mock_page,
mock_context,
mock_future,
mock_locator,
mock_check_disconnected,
prompt_length=100,
timeout=30.0,
)
assert result is not None
completion_event, _, _ = (
result if isinstance(result, tuple) else (None, None, None)
)
assert isinstance(completion_event, asyncio.Event)
assert mock_future.done()
@pytest.mark.asyncio
async def test_handle_playwright_response_non_streaming(
mock_request, mock_context, mock_check_disconnected
):
mock_request.stream = False
mock_future = asyncio.Future()
mock_locator = MagicMock()
mock_page = AsyncMock()
with (
patch(
"api_utils.request_processor.locate_response_elements",
new_callable=AsyncMock,
),
patch(
"browser_utils.page_controller.PageController.get_response",
new_callable=AsyncMock,
) as mock_get_resp,
patch("api_utils.request_processor.calculate_usage_stats", return_value={}),
patch(
"api_utils.request_processor.build_chat_completion_response_json",
return_value={"id": "resp1"},
),
):
mock_get_resp.return_value = "response content"
result = await _handle_playwright_response(
"req1",
mock_request,
mock_page,
mock_context,
mock_future,
mock_locator,
mock_check_disconnected,
prompt_length=100,
timeout=30.0,
)
assert isinstance(result, dict)
assert mock_future.done()
class TestCleanupRequestResources:
"""Tests for _cleanup_request_resources helper function."""
@pytest.mark.asyncio
async def test_cleanup_request_resources_basic(self):
"""Test basic cleanup of request resources."""
# Create a real task that we can cancel
async def dummy_task():
await asyncio.sleep(100) # Will be cancelled
mock_task = asyncio.create_task(dummy_task())
mock_event = asyncio.Event()
mock_future = asyncio.Future()
mock_future.set_exception(Exception("error"))
with (
patch("shutil.rmtree") as mock_rmtree,
patch("os.path.isdir", return_value=True),
):
await _cleanup_request_resources(
"req1", mock_task, mock_event, mock_future, True
)
assert mock_task.cancelled()
mock_rmtree.assert_called_once()
assert mock_event.is_set()
@pytest.mark.asyncio
async def test_cleanup_directory_removal_exception(self):
"""Test that directory removal exceptions are caught and logged."""
mock_task = AsyncMock()
mock_task.done.return_value = True
mock_event = asyncio.Event()
mock_future = asyncio.Future()
mock_future.set_result(MagicMock())
with (
patch("os.path.isdir", return_value=True),
patch("shutil.rmtree", side_effect=PermissionError("Access denied")),
):
# Should not raise exception - error is logged but swallowed
await _cleanup_request_resources(
"req1", mock_task, mock_event, mock_future, False
)
# Cleanup should complete despite directory removal failure
@pytest.mark.asyncio
async def test_cleanup_cancelled_error_in_directory_removal(self):
"""Test that CancelledError during cleanup is re-raised."""
mock_task = AsyncMock()
mock_task.done.return_value = True
mock_event = asyncio.Event()
mock_future = asyncio.Future()
mock_future.set_result(MagicMock())
with (
patch("os.path.isdir", return_value=True),
patch("shutil.rmtree", side_effect=asyncio.CancelledError()),
):
# CancelledError should be re-raised
with pytest.raises(asyncio.CancelledError):
await _cleanup_request_resources(
"req1", mock_task, mock_event, mock_future, False
)
@pytest.mark.asyncio
async def test_process_request_refactored_client_disconnected_early(
mock_request, mock_http_request
):
mock_future = asyncio.Future()
with patch(
"api_utils.request_processor._check_client_connection", new_callable=AsyncMock
) as mock_check:
mock_check.return_value = False
result = await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
assert result is None
exc = mock_future.exception()
assert exc is not None
assert isinstance(exc, HTTPException)
assert exc.status_code == 499
@pytest.mark.asyncio
async def test_process_request_refactored_success(
mock_request, mock_http_request, mock_context
):
"""Test successful request processing flow through all stages."""
mock_future = asyncio.Future()
mock_check_disconnected = MagicMock(return_value=False)
# Setup mocks for all refactored steps
patches = {
"_check_client_connection": AsyncMock(return_value=True),
"_initialize_request_context": AsyncMock(return_value=mock_context),
"_analyze_model_requirements": AsyncMock(return_value=mock_context),
"_setup_disconnect_monitoring": AsyncMock(
return_value=(None, AsyncMock(), mock_check_disconnected)
),
"_validate_page_status": AsyncMock(),
"PageController": MagicMock(autospec=True),
"_handle_model_switching": AsyncMock(),
"_handle_parameter_cache": AsyncMock(),
"_prepare_and_validate_request": AsyncMock(return_value=("prompt", [], None)),
"_handle_response_processing": AsyncMock(),
"_cleanup_request_resources": AsyncMock(),
"save_error_snapshot": AsyncMock(),
}
with (
patch(
"api_utils.request_processor._check_client_connection",
patches["_check_client_connection"],
),
patch(
"api_utils.request_processor._initialize_request_context",
patches["_initialize_request_context"],
),
patch(
"api_utils.request_processor._analyze_model_requirements",
patches["_analyze_model_requirements"],
),
patch(
"api_utils.request_processor._setup_disconnect_monitoring",
patches["_setup_disconnect_monitoring"],
),
patch(
"api_utils.request_processor._validate_page_status",
patches["_validate_page_status"],
),
patch("api_utils.request_processor.PageController", patches["PageController"]),
patch(
"api_utils.request_processor._handle_model_switching",
patches["_handle_model_switching"],
),
patch(
"api_utils.request_processor._handle_parameter_cache",
patches["_handle_parameter_cache"],
),
patch(
"api_utils.request_processor._prepare_and_validate_request",
patches["_prepare_and_validate_request"],
),
patch(
"api_utils.request_processor._handle_response_processing",
patches["_handle_response_processing"],
),
patch(
"api_utils.request_processor._cleanup_request_resources",
patches["_cleanup_request_resources"],
),
patch(
"api_utils.request_processor.save_error_snapshot",
patches["save_error_snapshot"],
),
patch("api_utils.utils.collect_and_validate_attachments", return_value=[]),
patch("api_utils.request_processor.get_environment_variable", return_value="0"),
):
# Setup PageController mock instance
mock_pc_instance = patches["PageController"].return_value
mock_pc_instance.page = mock_context["page"]
mock_pc_instance.adjust_parameters = AsyncMock()
mock_pc_instance.submit_prompt = AsyncMock()
# Setup response processing result
mock_event = asyncio.Event()
mock_locator = MagicMock()
patches["_handle_response_processing"].return_value = (
mock_event,
mock_locator,
mock_check_disconnected,
)
mock_context["page"].locator = MagicMock(return_value=mock_locator)
# Execute
result = await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
# Verify success
assert result is not None, (
"_process_request_refactored returned None unexpectedly"
)
# Verify the elements of the tuple individually since submit_button_locator might be recaptured
assert result[0] == mock_event
assert result[2] == mock_check_disconnected
# Verify all stages were called
patches["_validate_page_status"].assert_called_once()
patches["_handle_model_switching"].assert_called_once()
mock_pc_instance.adjust_parameters.assert_called_once()
mock_pc_instance.submit_prompt.assert_called_once()
patches["_handle_response_processing"].assert_called_once()
patches["_cleanup_request_resources"].assert_called_once()
class TestProcessRequestRefactoredExceptionHandling:
"""Tests for exception handling in _process_request_refactored."""
@pytest.mark.asyncio
async def test_process_request_stream_queue_clear_exception(
self, mock_request, mock_http_request
):
"""Test that stream queue clear exceptions are caught and logged."""
mock_future = asyncio.Future()
with (
patch(
"api_utils.request_processor._check_client_connection",
new_callable=AsyncMock,
return_value=True,
),
patch(
"api_utils.request_processor.get_environment_variable",
return_value="3120",
), # Stream enabled
patch(
"api_utils.clear_stream_queue", # Fixed: patch from api_utils module
new_callable=AsyncMock,
side_effect=Exception("Queue clear failed"),
),
patch(
"api_utils.request_processor._initialize_request_context",
new_callable=AsyncMock,
) as mock_init,
):
# Exception in clear_stream_queue should be caught and logged
# Processing should continue
mock_init.side_effect = Exception("Stop processing early")
with pytest.raises(Exception):
await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
@pytest.mark.asyncio
async def test_process_request_stream_queue_clear_cancelled_error(
self, mock_request, mock_http_request
):
"""Test that CancelledError during stream queue clear is re-raised."""
mock_future = asyncio.Future()
with (
patch(
"api_utils.request_processor._check_client_connection",
new_callable=AsyncMock,
return_value=True,
),
patch(
"api_utils.request_processor.get_environment_variable",
return_value="3120",
),
patch(
"api_utils.clear_stream_queue",
new_callable=AsyncMock,
side_effect=asyncio.CancelledError(),
),
):
# CancelledError should be re-raised
with pytest.raises(asyncio.CancelledError):
await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
@pytest.mark.asyncio
async def test_process_request_page_none_error(
self, mock_request, mock_http_request, make_request_context
):
"""Test error when page is None in _process_request_refactored."""
mock_future = asyncio.Future()
context = make_request_context(page=None, is_page_ready=False)
with (
patch(
"api_utils.request_processor._check_client_connection",
new_callable=AsyncMock,
return_value=True,
),
patch(
"api_utils.request_processor.get_environment_variable", return_value="0"
),
patch(
"api_utils.request_processor._initialize_request_context",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor._analyze_model_requirements",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor._setup_disconnect_monitoring",
new_callable=AsyncMock,
return_value=(None, AsyncMock(), MagicMock()),
),
patch(
"api_utils.request_processor._cleanup_request_resources",
new_callable=AsyncMock,
),
):
# Should raise HTTPException when page is None
await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
# Future should have 503 error set
assert mock_future.done()
exc = mock_future.exception()
assert isinstance(exc, HTTPException)
assert exc.status_code == 503
@pytest.mark.asyncio
async def test_process_request_cancelled_error_handling(
self, mock_request, mock_http_request, make_request_context
):
"""Test CancelledError handling in _process_request_refactored."""
mock_future = asyncio.Future()
context = make_request_context()
with (
patch(
"api_utils.request_processor._check_client_connection",
new_callable=AsyncMock,
return_value=True,
),
patch(
"api_utils.request_processor.get_environment_variable", return_value="0"
),
patch(
"api_utils.request_processor._initialize_request_context",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor._analyze_model_requirements",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor._setup_disconnect_monitoring",
new_callable=AsyncMock,
return_value=(None, AsyncMock(), MagicMock()),
),
patch(
"api_utils.request_processor._validate_page_status",
new_callable=AsyncMock,
),
patch("api_utils.request_processor.PageController"),
patch(
"api_utils.request_processor._handle_model_switching",
new_callable=AsyncMock,
side_effect=asyncio.CancelledError(),
),
patch(
"api_utils.request_processor._cleanup_request_resources",
new_callable=AsyncMock,
),
):
# CancelledError should be caught, and re-raised
with pytest.raises(asyncio.CancelledError):
await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
@pytest.mark.asyncio
async def test_process_request_client_disconnected_error_handling(
self, mock_request, mock_http_request, make_request_context
):
"""Test ClientDisconnectedError handling in _process_request_refactored."""
from models import ClientDisconnectedError
mock_future = asyncio.Future()
context = make_request_context()
local_check_disconnected = MagicMock(return_value=False)
with (
patch(
"api_utils.request_processor._check_client_connection",
new_callable=AsyncMock,
return_value=True,
),
patch(
"api_utils.request_processor.get_environment_variable", return_value="0"
),
patch(
"api_utils.request_processor._initialize_request_context",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor._analyze_model_requirements",
new_callable=AsyncMock,
return_value=context,
),
patch(
"api_utils.request_processor._setup_disconnect_monitoring",
new_callable=AsyncMock,
return_value=(None, AsyncMock(), local_check_disconnected),
),
patch(
"api_utils.request_processor._validate_page_status",
new_callable=AsyncMock,
),
patch("api_utils.request_processor.PageController"),
patch(
"api_utils.request_processor._handle_model_switching",
new_callable=AsyncMock,
side_effect=ClientDisconnectedError("Client disconnected"),
),
patch(
"api_utils.request_processor._cleanup_request_resources",
new_callable=AsyncMock,
),
):
# Should catch ClientDisconnectedError and set exception in future
result = await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
# Should return tuple with completion_event (even if None)
assert isinstance(result, tuple)
assert result[2] == local_check_disconnected
# Future should have HTTPException with 499 status
assert mock_future.done()
exc = mock_future.exception()
assert isinstance(exc, HTTPException)
assert exc.status_code == 499
@pytest.mark.asyncio
async def test_process_request_refactored_exception(
mock_request, mock_http_request, mock_context
):
mock_future = asyncio.Future()
with (
patch(
"api_utils.request_processor._check_client_connection",
new_callable=AsyncMock,
) as mock_check_conn,
patch(
"api_utils.request_processor._initialize_request_context",
side_effect=Exception("Unexpected Error"),
),
patch(
"api_utils.request_processor.save_error_snapshot", new_callable=AsyncMock
) as mock_snapshot,
patch(
"api_utils.request_processor._cleanup_request_resources",
new_callable=AsyncMock,
) as mock_cleanup,
):
mock_check_conn.return_value = True
with pytest.raises(Exception) as exc:
await _process_request_refactored(
"req1", mock_request, mock_http_request, mock_future
)
assert "Unexpected Error" in str(exc.value)
# Initialization happens before try/finally, so cleanup/snapshot won't be called
mock_snapshot.assert_not_called()
mock_cleanup.assert_not_called()
|