Spaces:
Running
Running
File size: 83,871 Bytes
b5cb5bb 6fcd373 b5cb5bb 6fcd373 b5cb5bb 6fcd373 b5cb5bb 6fcd373 b5cb5bb 6fcd373 b5cb5bb | 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 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 | """
backend/tests/test_api.py
Comprehensive tests for all FastAPI endpoints.
Tests cover:
- Successful requests with valid data
- AI inference API failures (502 fallback)
- Timeout handling
- Malformed response data
- Error status-code mapping
Run with: pytest backend/tests/test_api.py -v
"""
import asyncio
import json
import os
import sys
import time
from typing import Any, Dict, List
from unittest.mock import AsyncMock, MagicMock, patch
import pytest # type: ignore[import-not-found]
from fastapi.testclient import TestClient
# Add backend directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
from services.inference_client import InferenceClient, InferenceRequest
# automation_engine has Firebase dependencies - mock its heavy parts
# but keep the Pydantic model classes
mock_ae = MagicMock()
# Define minimal Pydantic-like classes for payloads automation_engine exports
from pydantic import BaseModel as _BM
from services.email_service import EmailSendResult
class _DiagnosticCompletionPayload(_BM):
studentId: str
results: list
gradeLevel: str | None = None
questionBreakdown: dict | None = None
class _QuizSubmissionPayload(_BM):
studentId: str
quizId: str
subject: str
score: float
totalQuestions: int
correctAnswers: int
timeSpentSeconds: int
class _StudentEnrollmentPayload(_BM):
studentId: str
name: str
email: str
gradeLevel: str | None = None
teacherId: str | None = None
class _DataImportPayload(_BM):
teacherId: str
students: list
columnMapping: dict
class _ContentUpdatePayload(_BM):
adminId: str
action: str
contentType: str
contentId: str
subjectId: str | None = None
details: str | None = None
class _AutomationResult(_BM):
success: bool = True
message: str = ""
actions: list = []
mock_ae.automation_engine = MagicMock()
mock_ae.DiagnosticCompletionPayload = _DiagnosticCompletionPayload
mock_ae.QuizSubmissionPayload = _QuizSubmissionPayload
mock_ae.StudentEnrollmentPayload = _StudentEnrollmentPayload
mock_ae.DataImportPayload = _DataImportPayload
mock_ae.ContentUpdatePayload = _ContentUpdatePayload
mock_ae.AutomationResult = _AutomationResult
sys.modules["automation_engine"] = mock_ae
# Override tokens so client init doesn't fail
os.environ["HF_TOKEN"] = "test-token-for-testing"
os.environ["DEEPSEEK_API_KEY"] = "test-ds-key-for-testing"
# analytics.py is importable directly (its heavy deps are guarded)
import main as main_module # noqa: E402
app = main_module.app
# Mock auth verification so protected endpoints can run in tests without Firebase credentials.
main_module._firebase_ready = True
main_module._init_firebase_admin = lambda: None
main_module.firebase_firestore = None
main_module.firebase_auth = MagicMock()
main_module.firebase_auth.verify_id_token = MagicMock(
return_value={
"uid": "test-teacher-uid",
"email": "teacher@example.com",
"role": "teacher",
}
)
client = TestClient(app, headers={"Authorization": "Bearer test-auth-token"})
# โโโ Fixtures โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def make_deepseek_risk_mock(
risk_label: str = "low risk academically stable",
confidence: float = 0.85,
):
"""Create a mock DeepSeek client for risk prediction tests."""
mock_ds = MagicMock()
mock_choice = MagicMock()
mock_choice.message.content = json.dumps({
"risk_label": risk_label,
"confidence": confidence,
"reasoning": "Mock risk assessment."
})
mock_ds.chat.completions.create.return_value = MagicMock(
choices=[mock_choice]
)
return mock_ds
# โโโ Health & Root โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestHealthEndpoints:
def test_health_returns_200(self):
response = client.get("/health")
assert response.status_code == 200
data = response.json()
assert data["status"] == "healthy"
assert "models" in data
def test_root_returns_api_info(self):
response = client.get("/")
assert response.status_code == 200
data = response.json()
assert data["name"] == "MathPulse AI API"
assert "version" in data
def test_health_includes_request_id_header(self):
response = client.get("/health")
assert "x-request-id" in response.headers
class TestAuthMiddleware:
def test_accepts_user_id_claim_when_uid_missing(self):
now = int(time.time())
firestore = _FakeFirestoreModule(
{
"courseMaterials": [
{
"materialId": "mat-auth-1",
"teacherId": "test-teacher-uid",
"fileName": "auth-check.pdf",
"fileType": "pdf",
"classSectionId": "grade11_a",
"topics": [{"title": "Linear Equations"}],
"extractedTextLength": 300,
"retentionDays": 180,
"expiresAtEpoch": now + 3600,
}
]
}
)
with patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"user_id": "test-teacher-uid",
"email": "teacher@example.com",
"role": "teacher",
}), patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True):
response = client.get("/api/upload/course-materials/recent?classSectionId=grade11_a&limit=10")
assert response.status_code == 200
data = response.json()
assert data["success"] is True
assert len(data["materials"]) == 1
assert data["materials"][0]["materialId"] == "mat-auth-1"
# โโโ Chat Endpoint โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestChatEndpoint:
@patch("main.call_hf_chat")
def test_chat_success(self, mock_chat):
mock_chat.return_value = "Hello! 2+2=4."
response = client.post("/api/chat", json={
"message": "What is 2+2?",
"history": [],
})
assert response.status_code == 200
assert "4" in response.json()["response"]
@patch("main.call_hf_chat")
def test_chat_non_math_returns_refusal_and_skips_inference(self, mock_chat):
response = client.post("/api/chat", json={
"message": "Who is Elon Musk?",
"history": [],
})
assert response.status_code == 200
assert response.json()["response"] in main_module._NON_MATH_REDIRECT_RESPONSES
mock_chat.assert_not_called()
@patch("main.call_hf_chat")
def test_chat_greeting_returns_friendly_response_and_skips_inference(self, mock_chat):
response = client.post("/api/chat", json={
"message": "hello",
"history": [],
})
assert response.status_code == 200
assert response.json()["response"] in main_module._GREETING_RESPONSES
mock_chat.assert_not_called()
@patch("main.call_hf_chat")
def test_chat_thanks_returns_friendly_response_and_skips_inference(self, mock_chat):
response = client.post("/api/chat", json={
"message": "thanks",
"history": [],
})
assert response.status_code == 200
assert response.json()["response"] in main_module._THANKS_RESPONSES
mock_chat.assert_not_called()
@patch("main.call_hf_chat_async", new_callable=AsyncMock)
def test_chat_allows_contextual_followup_token_and_calls_inference(self, mock_chat_async):
mock_chat_async.return_value = "Sure. Next step: isolate x on one side."
response = client.post("/api/chat", json={
"message": "go",
"history": [
{"role": "assistant", "content": "Nice work. Shall we continue?"},
],
})
assert response.status_code == 200
assert response.json()["response"] == "Sure. Next step: isolate x on one side."
mock_chat_async.assert_called_once()
@patch("main.call_hf_chat_async", new_callable=AsyncMock)
def test_chat_followup_token_reconstructs_latest_math_intent_and_calls_inference(self, mock_chat_async):
mock_chat_async.return_value = "Continuing: subtract 3 from both sides first."
response = client.post("/api/chat", json={
"message": "more",
"history": [
{"role": "user", "content": "Solve for x in 2x + 3 = 7"},
{"role": "assistant", "content": "Start by isolating x."},
],
})
assert response.status_code == 200
assert response.json()["response"] == "Continuing: subtract 3 from both sides first."
mock_chat_async.assert_called_once()
@patch("main.call_hf_chat_async", new_callable=AsyncMock)
def test_chat_followup_token_without_context_requests_clarification(self, mock_chat_async):
response = client.post("/api/chat", json={
"message": "go",
"history": [],
})
assert response.status_code == 200
assert response.json()["response"] == main_module._CONTINUATION_CONTEXT_CLARIFY_RESPONSE
mock_chat_async.assert_not_called()
@patch("main.call_hf_chat_async", new_callable=AsyncMock)
def test_chat_punctuated_followup_token_without_context_requests_clarification(self, mock_chat_async):
response = client.post("/api/chat", json={
"message": "go!",
"history": [],
})
assert response.status_code == 200
assert response.json()["response"] == main_module._CONTINUATION_CONTEXT_CLARIFY_RESPONSE
mock_chat_async.assert_not_called()
@patch("main.call_hf_chat_async", new_callable=AsyncMock)
def test_chat_followup_token_after_refused_request_remains_blocked(self, mock_chat_async):
response = client.post("/api/chat", json={
"message": "continue",
"history": [
{"role": "user", "content": "Who is Elon Musk?"},
{
"role": "assistant",
"content": main_module._NON_MATH_REDIRECT_RESPONSES[0],
},
],
})
assert response.status_code == 200
assert response.json()["response"] in main_module._NON_MATH_REDIRECT_RESPONSES
mock_chat_async.assert_not_called()
@patch("main.call_hf_chat")
def test_chat_with_history(self, mock_chat):
mock_chat.return_value = "Yes, that's right."
response = client.post("/api/chat", json={
"message": "Is x = 4 correct for 2 + 2 = x?",
"history": [
{"role": "user", "content": "What is 2+2?"},
{"role": "assistant", "content": "4"},
],
})
assert response.status_code == 200
# Verify history was included in messages
call_args = mock_chat.call_args
messages = call_args.args[0] if call_args.args else call_args.kwargs.get("messages", [])
assert len(messages) >= 3 # system + 2 history + 1 current
def test_chat_missing_message_returns_422(self):
response = client.post("/api/chat", json={"history": []})
assert response.status_code == 422
@patch("main.call_hf_chat")
def test_chat_hf_failure_returns_502(self, mock_chat):
mock_chat.side_effect = Exception("HF API down")
response = client.post("/api/chat", json={
"message": "Solve 3x + 1 = 10",
"history": [],
})
assert response.status_code == 502
@patch("main.call_hf_chat")
def test_chat_quadratic_prompt_smoke(self, mock_chat):
mock_chat.return_value = (
"Given x^2 - 5x + 6 = 0, factor to (x-2)(x-3)=0. "
"So x = 2 or x = 3. Final answer: x = 2, x = 3."
)
response = client.post("/api/chat", json={
"message": "Solve quadratic equation xยฒ - 5x + 6 = 0 step-by-step.",
"history": [],
})
assert response.status_code == 200
data = response.json()["response"]
assert "x = 2" in data
assert "x = 3" in data
@patch("main.call_hf_chat_stream")
def test_chat_stream_success(self, mock_stream):
mock_stream.return_value = iter(["Hello", " world"])
with client.stream("POST", "/api/chat/stream", json={
"message": "What is 2 + 2?",
"history": [],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert "event: chunk" in content
assert '"chunk": "Hello"' in content
assert "event: end" in content
@patch("main.call_hf_chat_stream")
def test_chat_stream_emits_error_event(self, mock_stream):
mock_stream.side_effect = Exception("HF stream down")
with client.stream("POST", "/api/chat/stream", json={
"message": "Solve x + 2 = 5",
"history": [],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert "event: error" in content
assert "event: end" in content
@patch("main.call_hf_chat_stream_async")
def test_chat_stream_timeout_emits_error_and_end_events(self, mock_stream_async):
async def _slow_stream(*args, **kwargs):
await asyncio.sleep(0.05)
yield "late chunk"
mock_stream_async.return_value = _slow_stream()
with patch.object(main_module, "CHAT_STREAM_NO_TOKEN_TIMEOUT_SEC", 0.01), patch.object(main_module, "CHAT_STREAM_TOTAL_TIMEOUT_SEC", 0.03):
with client.stream("POST", "/api/chat/stream", json={
"message": "Solve x + 2 = 5",
"history": [],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert "event: error" in content
assert "timed out" in content.lower()
assert "event: end" in content
@patch("main.call_hf_chat_stream_async")
def test_chat_stream_marker_mode_continues_until_marker(self, mock_stream_async):
async def _first_stream(*args, **kwargs):
yield "n=1: x=1\n"
yield "n=2: x=2"
async def _second_stream(*args, **kwargs):
yield "\nn=3: x=3\nEND_MARKER"
mock_stream_async.side_effect = [_first_stream(), _second_stream()]
with patch.object(main_module, "CHAT_STREAM_CONTINUATION_MAX_ROUNDS", 1):
with client.stream("POST", "/api/chat/stream", json={
"message": "Solve x+n=2n for n=1..3 and end with END_MARKER",
"history": [],
"completionMode": "marker",
"expectedEndMarker": "END_MARKER",
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert "END_MARKER" in content
assert "event: end" in content
assert mock_stream_async.call_count == 2
@patch("main.call_hf_chat_stream")
def test_chat_stream_non_math_returns_refusal_and_skips_inference(self, mock_stream):
with client.stream("POST", "/api/chat/stream", json={
"message": "Who is Elon Musk?",
"history": [],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert "event: chunk" in content
assert any(candidate in content for candidate in main_module._NON_MATH_REDIRECT_RESPONSES)
assert "event: end" in content
mock_stream.assert_not_called()
@patch("main.call_hf_chat_stream_async")
def test_chat_stream_allows_contextual_followup_token_and_calls_inference(self, mock_stream_async):
async def _stream(*args, **kwargs):
yield "Sure, continuing with the next step."
mock_stream_async.return_value = _stream()
with client.stream("POST", "/api/chat/stream", json={
"message": "go",
"history": [
{"role": "assistant", "content": "Would you like to continue?"},
],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert "Sure, continuing with the next step." in content
assert "event: end" in content
mock_stream_async.assert_called_once()
@patch("main.call_hf_chat_stream_async")
def test_chat_stream_followup_token_reconstructs_latest_math_intent_and_calls_inference(self, mock_stream_async):
async def _stream(*args, **kwargs):
yield "Continuing the same solution from the previous step."
mock_stream_async.return_value = _stream()
with client.stream("POST", "/api/chat/stream", json={
"message": "more",
"history": [
{"role": "user", "content": "Solve 2x + 3 = 7"},
{"role": "assistant", "content": "We can isolate x now."},
],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert "Continuing the same solution from the previous step." in content
assert "event: end" in content
mock_stream_async.assert_called_once()
@patch("main.call_hf_chat_stream_async")
def test_chat_stream_followup_token_without_context_requests_clarification(self, mock_stream_async):
with client.stream("POST", "/api/chat/stream", json={
"message": "go",
"history": [],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert main_module._CONTINUATION_CONTEXT_CLARIFY_RESPONSE in content
assert "event: end" in content
mock_stream_async.assert_not_called()
@patch("main.call_hf_chat_stream_async")
def test_chat_stream_followup_token_after_refused_request_remains_blocked(self, mock_stream_async):
with client.stream("POST", "/api/chat/stream", json={
"message": "continue",
"history": [
{"role": "user", "content": "Who is Elon Musk?"},
{
"role": "assistant",
"content": main_module._NON_MATH_REDIRECT_RESPONSES[1],
},
],
}) as response:
assert response.status_code == 200
content = "".join(response.iter_text())
assert any(candidate in content for candidate in main_module._NON_MATH_REDIRECT_RESPONSES)
assert "event: end" in content
mock_stream_async.assert_not_called()
class TestChatTransport:
@patch("services.ai_client.get_deepseek_client")
def test_call_hf_chat_uses_deepseek_api(self, mock_ds_fn):
mock_ds = MagicMock()
mock_choice = MagicMock()
mock_choice.message.content = "x = 2 or x = 3"
mock_ds.chat.completions.create.return_value = MagicMock(
choices=[mock_choice]
)
mock_ds_fn.return_value = mock_ds
with patch.object(main_module, "get_inference_client") as mock_get_ic:
ic = MagicMock()
ic.generate_from_messages.return_value = "x = 2 or x = 3"
mock_get_ic.return_value = ic
result = main_module.call_hf_chat(
[{"role": "user", "content": "Solve x^2 - 5x + 6 = 0"}],
max_tokens=256,
temperature=0.2,
top_p=0.9,
)
assert result
class TestInferenceRouting:
def test_chat_strict_model_lock_keeps_single_model_chain(self, monkeypatch):
monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-chat")
monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
client = InferenceClient()
req = InferenceRequest(
messages=[{"role": "user", "content": "Show all steps and prove the result rigorously."}],
task_type="chat",
)
selected_model, source = client._resolve_primary_model(req)
model_chain = client._model_chain_for_task("chat", selected_model)
assert selected_model == "deepseek-chat"
assert "chat_strict_model_only" in source
assert model_chain == ["deepseek-chat"]
def test_chat_env_override_wins_under_model_lock(self, monkeypatch):
monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-chat")
monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-reasoner")
client = InferenceClient()
req = InferenceRequest(
messages=[{"role": "user", "content": "Find the roots and explain why."}],
task_type="chat",
)
selected_model, source = client._resolve_primary_model(req)
model_chain = client._model_chain_for_task("chat", selected_model)
assert selected_model == "deepseek-chat"
assert "chat_override_env" in source
assert model_chain == ["deepseek-chat"]
def test_chat_temp_override_wins_under_model_lock(self, monkeypatch):
monkeypatch.setenv("INFERENCE_CHAT_MODEL_ID", "deepseek-reasoner")
monkeypatch.setenv("INFERENCE_CHAT_MODEL_TEMP_OVERRIDE", "deepseek-chat")
monkeypatch.setenv("INFERENCE_CHAT_STRICT_MODEL_ONLY", "true")
monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-reasoner")
client = InferenceClient()
req = InferenceRequest(
messages=[{"role": "user", "content": "Find the roots and explain why."}],
task_type="chat",
)
selected_model, source = client._resolve_primary_model(req)
model_chain = client._model_chain_for_task("chat", selected_model)
assert selected_model == "deepseek-chat"
assert "chat_temp_override_env" in source
assert model_chain == ["deepseek-chat"]
def test_chat_temp_override_does_not_change_non_chat_task_under_lock(self, monkeypatch):
monkeypatch.setenv("INFERENCE_CHAT_MODEL_TEMP_OVERRIDE", "deepseek-chat")
monkeypatch.setenv("INFERENCE_ENFORCE_LOCK_MODEL", "true")
monkeypatch.setenv("INFERENCE_LOCK_MODEL_ID", "deepseek-reasoner")
client = InferenceClient()
req = InferenceRequest(
messages=[{"role": "user", "content": "Check if my solution is correct."}],
task_type="verify_solution",
)
selected_model, source = client._resolve_primary_model(req)
model_chain = client._model_chain_for_task("verify_solution", selected_model)
assert selected_model == "deepseek-reasoner"
assert "chat_temp_override_env" not in source
assert model_chain == ["deepseek-reasoner"]
# โโโ Risk Prediction โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestRiskPrediction:
@patch("main.get_deepseek_client")
def test_predict_risk_success(self, mock_ds_fn):
mock_ds_fn.return_value = make_deepseek_risk_mock()
response = client.post("/api/predict-risk", json={
"engagementScore": 80,
"avgQuizScore": 75,
"attendance": 90,
"assignmentCompletion": 85,
})
assert response.status_code == 200
data = response.json()
assert data["riskLevel"] in ("High", "Medium", "Low")
assert 0 <= data["confidence"] <= 1
def test_predict_risk_invalid_score_range(self):
response = client.post("/api/predict-risk", json={
"engagementScore": 150,
"avgQuizScore": 75,
"attendance": 90,
"assignmentCompletion": 85,
})
assert response.status_code == 422
def test_predict_risk_negative_score(self):
response = client.post("/api/predict-risk", json={
"engagementScore": -5,
"avgQuizScore": 75,
"attendance": 90,
"assignmentCompletion": 85,
})
assert response.status_code == 422
def test_predict_risk_missing_fields(self):
response = client.post("/api/predict-risk", json={
"engagementScore": 80,
})
assert response.status_code == 422
@patch("main.get_deepseek_client")
def test_predict_risk_ai_failure(self, mock_ds_fn):
mock_client = MagicMock()
mock_client.chat.completions.create.side_effect = Exception("AI down")
mock_ds_fn.return_value = mock_client
response = client.post("/api/predict-risk", json={
"engagementScore": 80,
"avgQuizScore": 75,
"attendance": 90,
"assignmentCompletion": 85,
})
assert response.status_code == 502
@patch("main.get_deepseek_client")
def test_batch_risk_prediction(self, mock_ds_fn):
mock_ds_fn.return_value = make_deepseek_risk_mock()
response = client.post("/api/predict-risk/batch", json={
"students": [
{"engagementScore": 80, "avgQuizScore": 75, "attendance": 90, "assignmentCompletion": 85},
{"engagementScore": 30, "avgQuizScore": 40, "attendance": 50, "assignmentCompletion": 35},
],
})
assert response.status_code == 200
assert len(response.json()) == 2
# โโโ Learning Path โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestLearningPath:
@patch("main.call_hf_chat")
def test_learning_path_success(self, mock_chat):
mock_chat.return_value = "1. Review fractions\n2. Practice decimals"
response = client.post("/api/learning-path", json={
"weaknesses": ["fractions", "decimals"],
"gradeLevel": "Grade 11",
})
assert response.status_code == 200
assert "fractions" in response.json()["learningPath"].lower()
def test_learning_path_missing_weaknesses(self):
response = client.post("/api/learning-path", json={
"gradeLevel": "Grade 11",
})
assert response.status_code == 422
def test_learning_path_missing_grade(self):
response = client.post("/api/learning-path", json={
"weaknesses": ["fractions"],
})
assert response.status_code == 422
@patch("main.call_hf_chat")
def test_learning_path_ai_failure(self, mock_chat):
mock_chat.side_effect = Exception("AI service down")
response = client.post("/api/learning-path", json={
"weaknesses": ["algebra"],
"gradeLevel": "Grade 11",
})
assert response.status_code == 502
# โโโ Daily Insight โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestDailyInsight:
@patch("main.call_hf_chat")
def test_daily_insight_success(self, mock_chat):
mock_chat.return_value = "Class is doing well."
response = client.post("/api/analytics/daily-insight", json={
"students": [
{"name": "Alice", "engagementScore": 80, "avgQuizScore": 75, "attendance": 90, "riskLevel": "Low"},
],
})
assert response.status_code == 200
assert response.json()["insight"]
def test_daily_insight_empty_students(self):
response = client.post("/api/analytics/daily-insight", json={
"students": [],
})
assert response.status_code == 200
assert "No student data" in response.json()["insight"]
# โโโ Quiz Topics โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestQuizTopics:
def test_get_all_topics(self):
response = client.get("/api/quiz/topics")
assert response.status_code == 200
assert "allTopics" in response.json()
def test_get_topics_by_grade(self):
response = client.get("/api/quiz/topics?gradeLevel=Grade%2011")
assert response.status_code == 200
data = response.json()
assert data["gradeLevel"] == "Grade 11"
assert "topics" in data
def test_get_topics_invalid_grade(self):
response = client.get("/api/quiz/topics?gradeLevel=Grade%2099")
assert response.status_code == 404
# โโโ Quiz Generation โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestQuizGeneration:
@patch("main.call_hf_chat")
def test_generate_quiz_success(self, mock_chat):
quiz_json = json.dumps([{
"questionType": "multiple_choice",
"question": "What is 2+2?",
"correctAnswer": "4",
"options": ["A) 3", "B) 4", "C) 5", "D) 6"],
"bloomLevel": "remember",
"difficulty": "easy",
"topic": "Arithmetic",
"points": 1,
"explanation": "2+2=4",
}])
mock_chat.return_value = quiz_json
response = client.post("/api/quiz/generate", json={
"topics": ["Arithmetic"],
"gradeLevel": "Grade 11",
"numQuestions": 1,
})
assert response.status_code == 200
data = response.json()
assert len(data["questions"]) >= 1
assert data["totalPoints"] > 0
def test_generate_quiz_missing_topics(self):
response = client.post("/api/quiz/generate", json={
"gradeLevel": "Grade 11",
})
assert response.status_code == 422
class TestClassRecordImportMapping:
def test_sanitize_column_mapping_drops_none_and_unknown_fields(self):
raw_mapping = {
"Student Name": "name",
"Grade Level": None,
"Section": "",
"General Mathematics": None,
"Custom": "not_a_supported_field",
"Average": "avgQuizScore",
}
sanitized = main_module._sanitize_column_mapping(raw_mapping)
assert sanitized == {
"Student Name": "name",
"Average": "avgQuizScore",
}
@patch("main.call_hf_chat")
def test_generate_quiz_bad_llm_output(self, mock_chat):
mock_chat.return_value = "This is not valid JSON at all."
response = client.post("/api/quiz/generate", json={
"topics": ["Algebra"],
"gradeLevel": "Grade 11",
"numQuestions": 1,
})
assert response.status_code == 500
@patch("main.call_hf_chat")
def test_preview_quiz(self, mock_chat):
quiz_json = json.dumps([{
"questionType": "identification",
"question": "Define slope.",
"correctAnswer": "Rise over run",
"bloomLevel": "remember",
"difficulty": "easy",
"topic": "Algebra",
"points": 1,
"explanation": "Slope = rise/run.",
}])
mock_chat.return_value = quiz_json
response = client.post("/api/quiz/preview", json={
"topics": ["Algebra"],
"gradeLevel": "Grade 11",
})
assert response.status_code == 200
@patch("main.call_hf_chat")
def test_generate_quiz_accepts_new_max_limits(self, mock_chat):
max_questions = main_module.MAX_QUESTIONS_LIMIT
quiz_json = json.dumps([
{
"questionType": "identification",
"question": f"Question {i + 1}",
"correctAnswer": "Answer",
"bloomLevel": "remember",
"difficulty": "easy",
"topic": "Algebra",
"points": 1,
"explanation": "Because.",
}
for i in range(max_questions)
])
mock_chat.return_value = quiz_json
response = client.post("/api/quiz/generate", json={
"topics": [f"Topic {i + 1}" for i in range(main_module.MAX_TOPICS_LIMIT)],
"gradeLevel": "Grade 11",
"numQuestions": max_questions,
})
assert response.status_code == 200
data = response.json()
assert len(data["questions"]) == max_questions
def test_generate_quiz_rejects_over_max_questions(self):
response = client.post("/api/quiz/generate", json={
"topics": ["Algebra"],
"gradeLevel": "Grade 11",
"numQuestions": main_module.MAX_QUESTIONS_LIMIT + 1,
})
assert response.status_code == 422
class TestUploadClassRecordsGuardrails:
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_upload_class_records_rejects_unsupported_dataset_intent(self, _mock_chat):
files = {
"files": ("records.csv", b"name,lrn,email,avgQuizScore,attendance,engagementScore,assignmentCompletion\nAna,1001,ana@example.com,80,90,85,88\n", "text/csv"),
}
response = client.post(
"/api/upload/class-records",
files=files,
data={"datasetIntent": "unsupported_intent"},
)
assert response.status_code == 400
assert "Unsupported datasetIntent" in response.json()["detail"]
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_upload_class_records_warns_when_preferred_core_fields_missing(self, _mock_chat):
files = {
"files": (
"records.csv",
b"name,lrn,email,attendance\nAna,1001,ana@example.com,90\n",
"text/csv",
),
}
response = client.post(
"/api/upload/class-records",
files=files,
data={"datasetIntent": "synthetic_student_records"},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["summary"]["failedFiles"] == 0
assert payload["summary"]["partialSuccessFiles"] == 1
combined_warnings = " ".join(payload.get("warnings", []))
assert "Missing preferred educational columns" in combined_warnings
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_upload_class_records_returns_interpretation_metadata(self, _mock_chat):
files = {
"files": (
"records.csv",
(
b"name,lrn,email,avgQuizScore,attendance,engagementScore,assignmentCompletion,patient_diagnosis\n"
b"Ana,1001,ana@example.com,80,90,85,88,none\n"
),
"text/csv",
),
}
response = client.post(
"/api/upload/class-records",
files=files,
data={"datasetIntent": "synthetic_student_records"},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["datasetIntent"] == "synthetic_student_records"
assert isinstance(payload.get("columnInterpretations"), list)
summary = payload.get("interpretationSummary") or {}
assert summary.get("storageOnlyColumns", 0) >= 1
assert summary.get("domainMismatchWarnings", 0) >= 1
class_metadata = payload.get("classMetadata") or {}
assert class_metadata.get("classSectionId")
assert class_metadata.get("className")
assert class_metadata.get("grade")
assert class_metadata.get("section")
assert class_metadata.get("gradeLevel")
assert class_metadata.get("classification")
patient_column = next(
(item for item in payload["columnInterpretations"] if item.get("columnName") == "patient_diagnosis"),
None,
)
assert patient_column is not None
assert patient_column["usagePolicy"] == "storage_only"
assert patient_column["confidenceBand"] == "low"
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_upload_class_records_accepts_minimal_teacher_schema(self, _mock_chat):
files = {
"files": (
"records.csv",
(
b"name,lrn,avgQuizScore,attendance,engagementScore\n"
b"Ana Cruz,1001,81,92,88\n"
b"Ben Dela,1002,58,70,52\n"
),
"text/csv",
),
}
response = client.post(
"/api/upload/class-records",
files=files,
data={"datasetIntent": "synthetic_student_records"},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["interpretedRows"] == 2
assert payload["rejectedRows"] == 0
assert payload["inferredStateCoverage"]["inferredRows"] == 2
assert payload["inferredStateCoverage"]["coveragePct"] == 100.0
assert all("inferredState" in row for row in payload["students"])
class_metadata = payload.get("classMetadata") or {}
assert class_metadata.get("classSectionId")
assert class_metadata.get("className")
assert class_metadata.get("grade") == "Grade 11"
assert class_metadata.get("section") == "Section A"
assert class_metadata.get("gradeLevel") == "Grade 11"
assert class_metadata.get("classification") == "Senior High School"
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_upload_class_records_reports_explicit_row_rejections(self, _mock_chat):
files = {
"files": (
"records.csv",
(
b"name,lrn,email,avgQuizScore,attendance,engagementScore\n"
b",1001,ana@example.com,81,92,88\n"
b"Ben Dela,,,58,70,52\n"
b"Cara Lim,1003,,77,83,75\n"
),
"text/csv",
),
}
response = client.post(
"/api/upload/class-records",
files=files,
data={"datasetIntent": "synthetic_student_records"},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["interpretedRows"] == 1
assert payload["rejectedRows"] == 2
reasons = payload.get("rejectedReasons") or {}
assert any("missing required field: name" in key for key in reasons.keys())
assert any("missing required identity value: lrn_or_email" in key for key in reasons.keys())
assert len(payload.get("rejectedRowDetails") or []) == 2
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_upload_class_records_degrades_gracefully_when_firestore_adc_missing(self, _mock_chat):
class _FailingFirestoreModule:
def client(self):
raise Exception(
"Your default credentials were not found. "
"To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc"
)
files = {
"files": (
"records.csv",
(
b"name,lrn,avgQuizScore,attendance,engagementScore\n"
b"Ana Cruz,1001,81,92,88\n"
),
"text/csv",
),
}
with patch.object(main_module, "firebase_firestore", _FailingFirestoreModule()), patch.object(main_module, "_firebase_ready", True):
response = client.post(
"/api/upload/class-records",
files=files,
data={"datasetIntent": "synthetic_student_records"},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["persisted"] is False
assert (payload.get("dashboardSync") or {}).get("synced") is False
warnings_blob = " ".join(payload.get("warnings", []))
assert "adc is not configured" in warnings_blob.lower()
class TestImportedOverviewAndTopicMastery:
def test_imported_class_overview_returns_inferred_state_for_realistic_minimal_records(self):
# Ensure teacher role matches mock data
main_module.firebase_auth.verify_id_token = MagicMock(
return_value={
"uid": "test-teacher-uid",
"email": "teacher@example.com",
"role": "teacher",
}
)
firestore = _FakeFirestoreModule(
{
"normalizedClassRecords": [
{
"teacherId": "test-teacher-uid",
"name": "Ana Cruz",
"lrn": "1001",
"classSectionId": "grade11_a",
"className": "Grade 11 - A",
"avgQuizScore": 92,
"attendance": 96,
"engagementScore": 91,
"unknownFields": {},
},
{
"teacherId": "test-teacher-uid",
"name": "Ben Dela",
"lrn": "1002",
"classSectionId": "grade11_a",
"className": "Grade 11 - A",
"avgQuizScore": 68,
"attendance": 82,
"engagementScore": 66,
"unknownFields": {},
},
{
"teacherId": "test-teacher-uid",
"name": "Cara Lim",
"lrn": "1003",
"classSectionId": "grade11_a",
"className": "Grade 11 - A",
"avgQuizScore": 49,
"attendance": 71,
"engagementScore": 50,
"unknownFields": {},
},
]
}
)
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True):
response = client.get("/api/analytics/imported-class-overview?classSectionId=grade11_a&limit=100")
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert len(payload["students"]) == 3
coverage = payload.get("inferredStateCoverage") or {}
assert coverage.get("inferredRows") == 3
assert coverage.get("coveragePct") == 100.0
risk_levels = {student["riskLevel"] for student in payload["students"]}
assert risk_levels == {"Low", "Medium", "High"}
assert all(student.get("inferredState") for student in payload["students"])
assert all("stateConfidence" in student for student in payload["students"])
assert all(student.get("classMetadata") for student in payload["students"])
assert all(student.get("classMetadata", {}).get("classSectionId") == "grade11_a" for student in payload["students"])
assert all(student.get("classMetadata", {}).get("gradeLevel") for student in payload["students"])
assert all(student.get("classMetadata", {}).get("classification") for student in payload["students"])
assert all(classroom.get("classMetadata") for classroom in payload["classrooms"])
assert all(classroom.get("classMetadata", {}).get("classSectionId") == "grade11_a" for classroom in payload["classrooms"])
assert all(classroom.get("classMetadata", {}).get("gradeLevel") for classroom in payload["classrooms"])
assert all(classroom.get("classMetadata", {}).get("classification") for classroom in payload["classrooms"])
def test_imported_class_overview_returns_503_when_firestore_adc_missing(self):
firestore = _FakeFirestoreModule(
{"normalizedClassRecords": []},
stream_error=(
"Your default credentials were not found. "
"To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc"
),
)
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True):
response = client.get("/api/analytics/imported-class-overview?classSectionId=grade11_a&limit=100")
assert response.status_code == 503
detail = str((response.json() or {}).get("detail") or "").lower()
assert "firestore adc is not configured" in detail
assert "google_application_credentials" in detail
def test_topic_mastery_reports_fallback_warning_without_topic_columns(self):
firestore = _FakeFirestoreModule(
{
"normalizedClassRecords": [
{
"teacherId": "test-teacher-uid",
"name": "Ana Cruz",
"lrn": "1001",
"classSectionId": "grade11_a",
"className": "Grade 11 - A",
"avgQuizScore": 84,
"attendance": 92,
"engagementScore": 88,
"assessmentName": "general-assessment",
"unknownFields": {},
}
],
"courseMaterials": [],
}
)
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True):
response = client.get("/api/analytics/topic-mastery?teacherId=test-teacher-uid&classSectionId=grade11_a")
assert response.status_code == 200
payload = response.json()
assert payload["summary"]["totalTopicsTracked"] >= 1
assert payload["summary"].get("fallbackTopicRows") == 1
assert any("fallback topic context" in warning.lower() for warning in payload.get("warnings") or [])
class TestAsyncGenerationTasks:
@patch("main.asyncio.create_task")
def test_quiz_generate_async_submit_status_list_cancel(self, mock_create_task):
main_module._async_tasks.clear()
mock_create_task.side_effect = lambda coro: coro.close()
response = client.post("/api/quiz/generate-async", json={
"topics": ["Algebra"],
"gradeLevel": "Grade 11",
"numQuestions": 1,
})
assert response.status_code == 200
payload = response.json()
task_id = payload["taskId"]
assert payload["status"] == "queued"
assert mock_create_task.called
status_response = client.get(f"/api/tasks/{task_id}")
assert status_response.status_code == 200
status_payload = status_response.json()
assert status_payload["taskId"] == task_id
assert status_payload["status"] in {"queued", "running", "cancelling", "cancelled", "completed", "failed"}
list_response = client.get("/api/tasks?limit=20")
assert list_response.status_code == 200
list_payload = list_response.json()
assert list_payload["count"] >= 1
assert any(item["taskId"] == task_id for item in list_payload["tasks"])
cancel_response = client.post(f"/api/tasks/{task_id}/cancel")
assert cancel_response.status_code == 200
cancel_payload = cancel_response.json()
assert cancel_payload["taskId"] == task_id
assert cancel_payload["status"] in {"cancelled", "cancelling"}
def test_inference_metrics_requires_admin(self):
# Test with a non-admin mock to verify role check works
with patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "teacher-uid",
"email": "teacher@example.com",
"role": "teacher",
}):
response = client.get("/api/ops/inference-metrics")
assert response.status_code == 403
def test_inference_metrics_admin_success(self):
# Set admin role directly to ensure it persists
main_module.firebase_auth.verify_id_token = MagicMock(
return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}
)
response = client.get("/api/ops/inference-metrics")
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert "metrics" in payload
assert "requests_total" in payload["metrics"]
# โโโ Calculator โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestCalculator:
def test_evaluate_simple_expression(self):
response = client.post("/api/calculator/evaluate", json={
"expression": "2 + 3",
})
# sympy may not be installed in test env โ accept 200 or 500
assert response.status_code in (200, 500)
if response.status_code == 200:
data = response.json()
assert data["result"] == "5"
def test_evaluate_with_variables(self):
response = client.post("/api/calculator/evaluate", json={
"expression": "x**2 + 2*x + 1",
})
# Accept 200 (sympy available) or 500 (sympy missing)
assert response.status_code in (200, 500)
def test_evaluate_dangerous_expression(self):
response = client.post("/api/calculator/evaluate", json={
"expression": "__import__('os').system('rm -rf /')",
})
# 400 if validation catches it, 500 if sympy missing or general error
assert response.status_code in (400, 500)
def test_evaluate_empty_expression(self):
response = client.post("/api/calculator/evaluate", json={
"expression": "",
})
assert response.status_code == 422
def test_evaluate_too_long_expression(self):
response = client.post("/api/calculator/evaluate", json={
"expression": "x + " * 200,
})
# 400 if length validation, 422 if pydantic validation, 500 if sympy missing
assert response.status_code in (400, 422, 500)
# โโโ Error Handling โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestErrorHandling:
def test_404_for_unknown_endpoint(self):
response = client.get("/api/nonexistent")
assert response.status_code == 404
def test_method_not_allowed(self):
response = client.get("/api/chat")
assert response.status_code == 405
def test_request_id_in_error_response(self):
response = client.get("/api/nonexistent")
assert "x-request-id" in response.headers
def test_invalid_json_body(self):
response = client.post(
"/api/chat",
content="this is not json",
headers={"Content-Type": "application/json"},
)
assert response.status_code == 422
# โโโ Student Competency โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class TestStudentCompetency:
@patch("main.call_hf_chat")
def test_competency_no_history(self, mock_chat):
mock_chat.return_value = ""
response = client.post("/api/quiz/student-competency", json={
"studentId": "student123",
"quizHistory": [],
})
assert response.status_code == 200
data = response.json()
assert data["studentId"] == "student123"
assert data["competencies"] == []
@patch("main.call_hf_chat")
def test_competency_with_history(self, mock_chat):
mock_chat.return_value = "Good progress overall."
response = client.post("/api/quiz/student-competency", json={
"studentId": "student123",
"quizHistory": [
{"topic": "Algebra", "score": 8, "total": 10, "timeTaken": 300},
{"topic": "Algebra", "score": 9, "total": 10, "timeTaken": 250},
{"topic": "Geometry", "score": 4, "total": 10, "timeTaken": 500},
],
})
assert response.status_code == 200
data = response.json()
assert len(data["competencies"]) > 0
# Algebra should be higher competency than Geometry
algebra = next((c for c in data["competencies"] if c["topic"] == "Algebra"), None)
geometry = next((c for c in data["competencies"] if c["topic"] == "Geometry"), None)
if algebra and geometry:
assert algebra["efficiencyScore"] > geometry["efficiencyScore"]
# โโโ Course Materials Recent Retrieval โโโโโโโโโโโโโโโโโโโโโโโ
class _FakeDocSnapshot:
def __init__(self, doc_id: str, data: Dict[str, Any]):
self.id = doc_id
self._data = data
def to_dict(self) -> Dict[str, Any]:
return self._data
class _FakeQuery:
def __init__(self, docs: List[Dict[str, Any]], fail_order: bool = False, stream_error: str | None = None):
self._docs = docs
self._filters: List[tuple[str, str, Any]] = []
self._limit: int | None = None
self._fail_order = fail_order
self._stream_error = stream_error
def where(self, field: str, op: str, value: Any):
self._filters.append((field, op, value))
return self
def order_by(self, *args, **kwargs):
if self._fail_order:
raise Exception("missing composite index")
return self
def limit(self, value: int):
self._limit = value
return self
def stream(self):
if self._stream_error:
raise Exception(self._stream_error)
filtered: List[Dict[str, Any]] = []
for doc in self._docs:
include = True
for field, op, expected in self._filters:
if op != "==":
continue
if doc.get(field) != expected:
include = False
break
if include:
filtered.append(doc)
if self._limit is not None:
filtered = filtered[: self._limit]
return [_FakeDocSnapshot(str(doc.get("materialId") or "doc"), doc) for doc in filtered]
class _FakeCollection:
def __init__(
self,
name: str,
store: Dict[str, List[Dict[str, Any]]],
audit_logs: List[Dict[str, Any]],
fail_order: bool = False,
stream_error: str | None = None,
):
self._name = name
self._store = store
self._audit_logs = audit_logs
self._fail_order = fail_order
self._stream_error = stream_error
def where(self, field: str, op: str, value: Any):
docs = list(self._store.get(self._name, []))
query = _FakeQuery(docs, fail_order=self._fail_order, stream_error=self._stream_error)
return query.where(field, op, value)
def add(self, payload: Dict[str, Any]):
self._audit_logs.append(payload)
return (None, None)
class _FakeFirestoreClient:
def __init__(self, store: Dict[str, List[Dict[str, Any]]], fail_order: bool = False, stream_error: str | None = None):
self._store = store
self.audit_logs: List[Dict[str, Any]] = []
self._fail_order = fail_order
self._stream_error = stream_error
def collection(self, name: str):
return _FakeCollection(
name,
self._store,
self.audit_logs,
fail_order=self._fail_order,
stream_error=self._stream_error,
)
class _FakeFirestoreModule:
class Query:
DESCENDING = "DESCENDING"
SERVER_TIMESTAMP = object()
def __init__(
self,
store: Dict[str, List[Dict[str, Any]]],
fail_order: bool = False,
stream_error: str | None = None,
):
self._client = _FakeFirestoreClient(store, fail_order=fail_order, stream_error=stream_error)
def client(self):
return self._client
class TestRecentCourseMaterials:
def test_recent_course_materials_respects_class_section_filter(self):
# Ensure teacher role matches mock data
main_module.firebase_auth.verify_id_token = MagicMock(
return_value={
"uid": "test-teacher-uid",
"email": "teacher@example.com",
"role": "teacher",
}
)
now = int(time.time())
firestore = _FakeFirestoreModule(
{
"courseMaterials": [
{
"materialId": "mat-a",
"teacherId": "test-teacher-uid",
"fileName": "algebra-a.pdf",
"fileType": "pdf",
"classSectionId": "grade11_a",
"topics": [{"title": "Linear Equations"}],
"extractedTextLength": 1200,
"retentionDays": 180,
"expiresAtEpoch": now + 3600,
},
{
"materialId": "mat-b",
"teacherId": "test-teacher-uid",
"fileName": "algebra-b.pdf",
"fileType": "pdf",
"classSectionId": "grade11_b",
"topics": [{"title": "Quadratics"}],
"extractedTextLength": 1600,
"retentionDays": 180,
"expiresAtEpoch": now + 3600,
},
]
}
)
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True):
response = client.get("/api/upload/course-materials/recent?classSectionId=grade11_a&limit=10")
assert response.status_code == 200
data = response.json()
assert data["success"] is True
assert data["classSectionId"] == "grade11_a"
assert len(data["materials"]) == 1
assert data["materials"][0]["materialId"] == "mat-a"
assert all(item["classSectionId"] == "grade11_a" for item in data["materials"])
def test_recent_course_materials_reports_retention_exclusions(self):
# Ensure teacher role matches mock data
main_module.firebase_auth.verify_id_token = MagicMock(
return_value={
"uid": "test-teacher-uid",
"email": "teacher@example.com",
"role": "teacher",
}
)
now = int(time.time())
firestore = _FakeFirestoreModule(
{
"courseMaterials": [
{
"materialId": "mat-valid",
"teacherId": "test-teacher-uid",
"fileName": "active.txt",
"fileType": "txt",
"classSectionId": "grade11_a",
"topics": [{"title": "Functions"}],
"extractedTextLength": 900,
"retentionDays": 180,
"expiresAtEpoch": now + 7200,
},
{
"materialId": "mat-expired",
"teacherId": "test-teacher-uid",
"fileName": "expired.txt",
"fileType": "txt",
"classSectionId": "grade11_a",
"topics": [{"title": "Inequalities"}],
"extractedTextLength": 700,
"retentionDays": 30,
"expiresAtEpoch": now - 60,
},
]
},
fail_order=True,
)
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True):
response = client.get("/api/upload/course-materials/recent?classSectionId=grade11_a&limit=10")
assert response.status_code == 200
data = response.json()
assert len(data["materials"]) == 1
assert data["materials"][0]["materialId"] == "mat-valid"
warning_text = " ".join(data.get("warnings", []))
assert "expired course-material artifact" in warning_text.lower()
assert "fallback query path" in warning_text.lower()
# โโโ Student Account Provisioning โโโโโโโโโโโโโโโโโโโโโโโโโโโ
class _ProvisionDocSnapshot:
def __init__(self, doc_id: str, data: Dict[str, Any] | None):
self.id = doc_id
self._data = data
@property
def exists(self) -> bool:
return self._data is not None
def to_dict(self) -> Dict[str, Any]:
return dict(self._data or {})
class _ProvisionDocumentRef:
def __init__(self, store: Dict[str, Dict[str, Dict[str, Any]]], collection_name: str, doc_id: str):
self._store = store
self._collection_name = collection_name
self._doc_id = doc_id
def get(self):
data = self._store.get(self._collection_name, {}).get(self._doc_id)
return _ProvisionDocSnapshot(self._doc_id, data)
def set(self, payload: Dict[str, Any], merge: bool = False):
collection = self._store.setdefault(self._collection_name, {})
existing = dict(collection.get(self._doc_id, {})) if merge else {}
existing.update(payload)
collection[self._doc_id] = existing
def delete(self):
collection = self._store.setdefault(self._collection_name, {})
collection.pop(self._doc_id, None)
class _ProvisionQuery:
def __init__(self, store: Dict[str, Dict[str, Dict[str, Any]]], collection_name: str):
self._store = store
self._collection_name = collection_name
self._filters: List[tuple[str, str, Any]] = []
self._limit: int | None = None
def where(self, field: str, op: str, value: Any):
self._filters.append((field, op, value))
return self
def limit(self, value: int):
self._limit = value
return self
def stream(self):
collection = self._store.get(self._collection_name, {})
docs: List[_ProvisionDocSnapshot] = []
for doc_id, data in collection.items():
include = True
for field, op, expected in self._filters:
if op != "==":
continue
if data.get(field) != expected:
include = False
break
if include:
docs.append(_ProvisionDocSnapshot(doc_id, data))
if self._limit is not None:
docs = docs[: self._limit]
return docs
class _ProvisionCollectionRef:
def __init__(self, store: Dict[str, Dict[str, Dict[str, Any]]], collection_name: str):
self._store = store
self._collection_name = collection_name
def where(self, field: str, op: str, value: Any):
return _ProvisionQuery(self._store, self._collection_name).where(field, op, value)
def limit(self, value: int):
return _ProvisionQuery(self._store, self._collection_name).limit(value)
def stream(self):
collection = self._store.get(self._collection_name, {})
return [_ProvisionDocSnapshot(doc_id, data) for doc_id, data in collection.items()]
def document(self, doc_id: str):
return _ProvisionDocumentRef(self._store, self._collection_name, doc_id)
def add(self, payload: Dict[str, Any]):
collection = self._store.setdefault(self._collection_name, {})
doc_id = f"auto-{len(collection) + 1}"
collection[doc_id] = dict(payload)
return (None, None)
class _ProvisionFirestoreClient:
def __init__(self, store: Dict[str, Dict[str, Dict[str, Any]]]):
self.store = store
def collection(self, name: str):
return _ProvisionCollectionRef(self.store, name)
class _ProvisionFirestoreModule:
class Query:
DESCENDING = "DESCENDING"
SERVER_TIMESTAMP = object()
def __init__(self, seed: Dict[str, Dict[str, Dict[str, Any]]] | None = None):
self._client = _ProvisionFirestoreClient(seed or {})
def client(self):
return self._client
class TestStudentAccountProvisioningImport:
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_preview_student_account_import_returns_validation_summary(self, _mock_chat):
firestore = _ProvisionFirestoreModule(
{
"users": {
"existing-student": {
"email": "existing@student.com",
"lrn": "1002",
"role": "student",
}
}
}
)
def _lookup_user(email: str):
if email == "existing@student.com":
return type("AuthUser", (), {"uid": "auth-existing"})()
raise Exception("user not found")
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=_lookup_user):
response = client.post(
"/api/import/student-accounts/preview",
files={
"file": (
"accounts.csv",
(
b"First Name,Last Name,Student ID,Email,Grade,Section\n"
b"Ana,Cruz,1001,ana@student.com,Grade 11,STEM-A\n"
b"Ben,Dela,1002,existing@student.com,Grade 11,STEM-A\n"
b",Lim,1003,cara@student.com,Grade 11,STEM-A\n"
),
"text/csv",
)
},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload.get("previewToken")
assert payload["summary"]["totalRows"] == 3
assert payload["summary"]["validRows"] == 1
assert payload["summary"]["duplicateRows"] >= 1
assert payload["summary"]["invalidRows"] >= 1
@patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
def test_commit_student_account_import_provisions_profiles(self, _mock_chat):
firestore = _ProvisionFirestoreModule({"users": {}, "managedStudents": {}, "classSectionOwnership": {}, "accessAuditLogs": {}})
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}), patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")), patch.object(main_module.firebase_auth, "create_user", return_value=type("AuthUser", (), {"uid": "auth-created-1"})()):
preview_response = client.post(
"/api/import/student-accounts/preview",
files={
"file": (
"accounts.csv",
b"First Name,Last Name,Student ID,Email,Grade,Section\nAna,Cruz,1001,ana@student.com,Grade 11,STEM-A\n",
"text/csv",
)
},
)
assert preview_response.status_code == 200
preview_payload = preview_response.json()
assert preview_payload["summary"]["validRows"] == 1
commit_response = client.post(
"/api/import/student-accounts/commit",
json={
"previewToken": preview_payload["previewToken"],
"forcePasswordChange": True,
"createAuthUsers": True,
},
)
assert commit_response.status_code == 200
commit_payload = commit_response.json()
assert commit_payload["summary"]["createdRows"] == 1
assert commit_payload["summary"]["failedRows"] == 0
assert len(commit_payload["rows"]) == 1
assert commit_payload["rows"][0]["status"] in {"created", "updated"}
assert commit_payload["rows"][0]["uid"]
users_store = firestore.client().store.get("users", {})
assert len(users_store) == 1
provisioned_profile = next(iter(users_store.values()))
assert provisioned_profile.get("role") == "student"
assert provisioned_profile.get("forcePasswordChange") is True
class _FakeEmailServiceSuccess:
def send_transactional_email(self, _message):
return EmailSendResult(success=True, provider="test_email", message_id="msg-1")
class _FakeEmailServiceFailure:
def send_transactional_email(self, _message):
return EmailSendResult(
success=False,
provider="test_email",
error_code="provider_down",
error_message="Provider unreachable",
retryable=True,
)
class TestAdminCreateUserEndpoint:
def test_create_admin_user_returns_success_when_email_delivered(self):
firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}), patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")), patch.object(main_module.firebase_auth, "create_user", return_value=type("AuthUser", (), {"uid": "new-user-uid"})()), patch.object(main_module, "create_email_service_from_env", return_value=_FakeEmailServiceSuccess()):
response = client.post(
"/api/admin/users",
json={
"name": "Ana & Josรฉ/Lee",
"email": "ana@student.com",
"password": "StrongPass1!",
"confirmPassword": "StrongPass1!",
"role": "Student",
"status": "Active",
"grade": "Grade 11",
"section": "STEM A",
"lrn": "123456789012",
},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["userCreated"] is True
assert payload["emailSent"] is True
assert payload["resultCode"] == "created_and_emailed"
assert payload["uid"] == "new-user-uid"
users_store = firestore.client().store.get("users", {})
assert "new-user-uid" in users_store
assert users_store["new-user-uid"].get("role") == "student"
assert "Ana+%26+Jos%C3%A9%2FLee" in users_store["new-user-uid"].get("photo", "")
def test_create_admin_user_returns_partial_success_when_email_fails(self):
firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}), patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")), patch.object(main_module.firebase_auth, "create_user", return_value=type("AuthUser", (), {"uid": "new-user-uid-2"})()), patch.object(main_module, "create_email_service_from_env", return_value=_FakeEmailServiceFailure()):
response = client.post(
"/api/admin/users",
json={
"name": "Ben Dela",
"email": "ben@student.com",
"password": "StrongPass1!",
"confirmPassword": "StrongPass1!",
"role": "Student",
"status": "Active",
"grade": "Grade 11",
"section": "STEM B",
"lrn": "123456789013",
},
)
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["userCreated"] is True
assert payload["emailSent"] is False
assert payload["resultCode"] == "created_email_failed"
assert payload["uid"] == "new-user-uid-2"
assert isinstance(payload.get("warnings"), list)
assert payload.get("emailError", {}).get("code") == "provider_down"
def test_create_admin_user_rejects_password_without_special_character(self):
firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}):
response = client.post(
"/api/admin/users",
json={
"name": "Cara Diaz",
"email": "cara@student.com",
"password": "StrongPass1",
"confirmPassword": "StrongPass1",
"role": "Student",
"status": "Active",
"grade": "Grade 11",
"section": "STEM C",
"lrn": "123456789014",
},
)
assert response.status_code == 400
payload = response.json()
assert "special character" in payload["detail"].lower()
def test_create_admin_user_rolls_back_auth_user_when_firestore_write_fails(self):
firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
delete_user_mock = MagicMock()
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}), patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")), patch.object(main_module.firebase_auth, "create_user", return_value=type("AuthUser", (), {"uid": "new-user-uid-3"})()), patch.object(main_module.firebase_auth, "delete_user", delete_user_mock), patch.object(_ProvisionDocumentRef, "set", side_effect=Exception("firestore unavailable")):
response = client.post(
"/api/admin/users",
json={
"name": "Dana Flores",
"email": "dana@student.com",
"password": "StrongPass1!",
"confirmPassword": "StrongPass1!",
"role": "Student",
"status": "Active",
"grade": "Grade 11",
"section": "STEM A",
"lrn": "123456789015",
},
)
assert response.status_code == 500
payload = response.json()
assert "firestore" in payload["detail"].lower()
delete_user_mock.assert_called_once_with("new-user-uid-3")
class TestAdminListUsersEndpoint:
def test_get_admin_users_returns_paginated_results(self):
firestore = _ProvisionFirestoreModule(
{
"users": {
"student-a": {
"name": "Alice Student",
"email": "alice@student.com",
"role": "student",
"status": "Active",
"grade": "Grade 11",
"section": "STEM A",
"lrn": "100000000001",
"createdAt": 1710000000,
},
"student-b": {
"name": "Ben Student",
"email": "ben@student.com",
"role": "student",
"status": "Active",
"grade": "Grade 11",
"section": "STEM B",
"lrn": "100000000002",
"createdAt": 1710000100,
},
"teacher-a": {
"name": "Tina Teacher",
"email": "tina@school.com",
"role": "teacher",
"status": "Active",
"department": "Mathematics",
"createdAt": 1710000200,
},
},
"accessAuditLogs": {},
}
)
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}):
response = client.get("/api/admin/users?page=1&pageSize=1&role=student")
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["page"] == 1
assert payload["pageSize"] == 1
assert len(payload["users"]) == 1
assert payload["users"][0]["role"] == "Student"
assert payload["hasMore"] is True
def test_get_admin_users_rejects_invalid_role_filter(self):
firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}):
response = client.get("/api/admin/users?role=guest")
assert response.status_code == 400
assert "role must be one of" in response.json()["detail"].lower()
def test_get_admin_users_rejects_non_admin_role(self):
firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "teacher-uid",
"email": "teacher@example.com",
"role": "teacher",
}):
response = client.get("/api/admin/users?page=1&pageSize=25")
assert response.status_code == 403
assert "forbidden" in response.json()["detail"].lower()
class TestAdminDeleteUserEndpoint:
def test_delete_admin_user_removes_auth_and_profile(self):
firestore = _ProvisionFirestoreModule(
{
"users": {
"target-uid": {
"email": "target@student.com",
"role": "student",
}
},
"accessAuditLogs": {},
}
)
delete_user_mock = MagicMock()
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}), patch.object(main_module.firebase_auth, "delete_user", delete_user_mock):
response = client.delete("/api/admin/users?uid=target-uid")
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["uid"] == "target-uid"
assert payload["authDeleted"] is True
assert payload["profileDeleted"] is True
delete_user_mock.assert_called_once_with("target-uid")
assert "target-uid" not in firestore.client().store.get("users", {})
def test_delete_admin_user_handles_missing_auth_record(self):
firestore = _ProvisionFirestoreModule(
{
"users": {
"target-uid-2": {
"email": "missing-auth@student.com",
"role": "student",
}
},
"accessAuditLogs": {},
}
)
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}), patch.object(main_module.firebase_auth, "delete_user", side_effect=Exception("No user record found for the provided uid")):
response = client.delete("/api/admin/users?uid=target-uid-2")
assert response.status_code == 200
payload = response.json()
assert payload["success"] is True
assert payload["uid"] == "target-uid-2"
assert payload["authDeleted"] is False
assert payload["profileDeleted"] is True
assert any("already missing" in warning.lower() for warning in payload.get("warnings", []))
assert "target-uid-2" not in firestore.client().store.get("users", {})
def test_delete_admin_user_rejects_self_delete(self):
firestore = _ProvisionFirestoreModule({"users": {}, "accessAuditLogs": {}})
with patch.object(main_module, "firebase_firestore", firestore), patch.object(main_module, "_firebase_ready", True), patch.object(main_module.firebase_auth, "verify_id_token", return_value={
"uid": "admin-uid",
"email": "admin@example.com",
"role": "admin",
}):
response = client.delete("/api/admin/users?uid=admin-uid")
assert response.status_code == 400
assert "cannot delete their own account" in response.json()["detail"].lower()
# โโโ Run โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if __name__ == "__main__":
pytest.main([__file__, "-v"])
|