| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | from __future__ import annotations |
| 23 | |
| 24 | import re |
| 25 | import time |
| 26 | import unittest |
| 27 | from typing import Any |
| 28 | from unittest.mock import patch |
| 29 | |
| 30 | from src import capabilities, handlers, protocol |
| 31 | from src.compute import clock |
| 32 | from src.compute.model import ( |
| 33 | Audience, |
| 34 | Confidence, |
| 35 | Recommendation, |
| 36 | StudentSegmentProfile, |
| 37 | StudentSummary, |
| 38 | ) |
| 39 | from src.protocol import CapabilityError |
| 40 | from src.store import profile_rows, recommendation_rows, run_row, summary_rows |
| 41 | |
| 42 | SCHOOL = "demo-okul" |
| 43 | DISPLAY = "Demo Anadolu Lisesi" |
| 44 | NOW = int(time.time() * 1000) |
| 45 | DAY = clock.DAY_MS |
| 46 | RUN_DAY = clock.tr_date_key(NOW) |
| 47 | |
| 48 | FACT_A = "Son 30 günde 4 ödev teslim edilmedi" |
| 49 | FACT_B = "Not eğilimi son üç sınavda düştü" |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | CLASS_A_ID = "01a0b1a6-f984-7483-94ee-7643d137fe08" |
| 56 | CLASS_B_ID = "01a0b1a6-f984-7483-94ee-7643d137fe09" |
| 57 | CLASS_A_NAME = "9-A" |
| 58 | CLASS_B_NAME = "10-B" |
| 59 | CLASS_LABEL_UNKNOWN = "Adı bilinmeyen şube" |
| 60 | |
| 61 | |
| 62 | def _marks(course: str, title: str, band: str, class_id: str) -> dict[str, Any]: |
| 63 | |
| 64 | return { |
| 65 | "classes": [class_id], |
| 66 | "courses": { |
| 67 | course: { |
| 68 | "course": course, |
| 69 | "course_title": title, |
| 70 | "n_marks": 6, |
| 71 | "average": 42.5, |
| 72 | "trend": {"available": True, "dropped": True, "rising": False}, |
| 73 | "placement": { |
| 74 | "band": band, |
| 75 | "confidence": "stable", |
| 76 | "z": -1.8, |
| 77 | "class_average": 68.0, |
| 78 | "class_sd": 9.0, |
| 79 | "cohort_n": 12, |
| 80 | }, |
| 81 | } |
| 82 | }, |
| 83 | } |
| 84 | |
| 85 | |
| 86 | def _attention(trigger: str, fact: str) -> dict[str, Any]: |
| 87 | |
| 88 | return { |
| 89 | "trigger": trigger, |
| 90 | "course": "course-1", |
| 91 | "fact": fact, |
| 92 | "window_from": NOW - 30 * DAY, |
| 93 | "window_to": NOW, |
| 94 | "evidence": {"missing": 4, "cohort_median": 1}, |
| 95 | } |
| 96 | |
| 97 | |
| 98 | def summaries() -> list[dict[str, Any]]: |
| 99 | |
| 100 | return summary_rows( |
| 101 | [ |
| 102 | StudentSummary( |
| 103 | school=SCHOOL, |
| 104 | student="ogrenci-a", |
| 105 | computed_at=NOW, |
| 106 | marks=_marks("course-1", "Matematik", "review", CLASS_A_ID), |
| 107 | attendance={"overall": {"rate": 0.82}, "courses": {}}, |
| 108 | submission={"overall": {"n": 12, "n_submitted": 9, "n_missing": 3}}, |
| 109 | study={"recent_28d": {"n_stints": 11, "active_days": 7}}, |
| 110 | attention=[_attention("homework", FACT_A)], |
| 111 | confidence=Confidence.STABLE, |
| 112 | ), |
| 113 | StudentSummary( |
| 114 | school=SCHOOL, |
| 115 | student="ogrenci-b", |
| 116 | computed_at=NOW, |
| 117 | marks=_marks("course-2", "Fen Bilimleri", "on_track", CLASS_B_ID), |
| 118 | attendance={"overall": {"rate": 0.95}, "courses": {}}, |
| 119 | submission={"overall": {"n": 11, "n_submitted": 11, "n_missing": 0}}, |
| 120 | study={"recent_28d": {"n_stints": 15, "active_days": 9}}, |
| 121 | attention=[_attention("mark_trend", FACT_B)], |
| 122 | confidence=Confidence.STABLE, |
| 123 | ), |
| 124 | StudentSummary( |
| 125 | school=SCHOOL, |
| 126 | student="ogrenci-c", |
| 127 | computed_at=NOW, |
| 128 | marks=_marks("course-1", "Matematik", "insufficient_data", CLASS_A_ID), |
| 129 | attendance={"overall": {"rate": 1.0}, "courses": {}}, |
| 130 | submission={"overall": {"n": 10, "n_submitted": 10, "n_missing": 0}}, |
| 131 | study={"recent_28d": {"n_stints": 8, "active_days": 6}}, |
| 132 | confidence=Confidence.EXPLORATORY, |
| 133 | ), |
| 134 | ] |
| 135 | ) |
| 136 | |
| 137 | |
| 138 | def recommendations() -> list[dict[str, Any]]: |
| 139 | |
| 140 | |
| 141 | |
| 142 | |
| 143 | |
| 144 | |
| 145 | rows, rejected = recommendation_rows( |
| 146 | [ |
| 147 | Recommendation( |
| 148 | school=SCHOOL, |
| 149 | audience="ogretmen-1", |
| 150 | audience_role=Audience.TEACHER, |
| 151 | product="T4", |
| 152 | rule_id="T4.homework", |
| 153 | about="ogrenci-a", |
| 154 | course="course-1", |
| 155 | evidence={"missing": 4, "cohort_median": 1}, |
| 156 | limitation="Teslim anı bilinmiyor.", |
| 157 | confidence=Confidence.STABLE, |
| 158 | computed_at=NOW, |
| 159 | expires_at=NOW + 7 * DAY, |
| 160 | ), |
| 161 | Recommendation( |
| 162 | school=SCHOOL, |
| 163 | audience="ogrenci-a", |
| 164 | audience_role=Audience.STUDENT, |
| 165 | product="O1", |
| 166 | rule_id="O1.review_band", |
| 167 | course="course-1", |
| 168 | evidence={"student_average": 42.5, "class_average": 68.0}, |
| 169 | limitation="Konu kırılımı yok.", |
| 170 | confidence=Confidence.STABLE, |
| 171 | computed_at=NOW, |
| 172 | expires_at=NOW + 7 * DAY, |
| 173 | ), |
| 174 | Recommendation( |
| 175 | school=SCHOOL, |
| 176 | audience="veli-1", |
| 177 | audience_role=Audience.PARENT, |
| 178 | product="V1", |
| 179 | rule_id="V1.parent_only", |
| 180 | about="ogrenci-a", |
| 181 | evidence={"n": 3}, |
| 182 | limitation="Veli kartı okul raporunda gösterilmez.", |
| 183 | confidence=Confidence.STABLE, |
| 184 | computed_at=NOW, |
| 185 | expires_at=NOW + 7 * DAY, |
| 186 | ), |
| 187 | ] |
| 188 | ) |
| 189 | assert rejected == 0, "fixture rows must carry evidence" |
| 190 | return rows |
| 191 | |
| 192 | |
| 193 | def profiles() -> list[dict[str, Any]]: |
| 194 | |
| 195 | return profile_rows( |
| 196 | [ |
| 197 | StudentSegmentProfile( |
| 198 | school=SCHOOL, |
| 199 | student="ogrenci-a", |
| 200 | dimension="bilissel_talep", |
| 201 | label="analiz", |
| 202 | n_answers=120, |
| 203 | n_correct=60, |
| 204 | overall_n_answers=400, |
| 205 | overall_accuracy=0.61, |
| 206 | computed_at=NOW, |
| 207 | confidence=Confidence.STABLE, |
| 208 | ), |
| 209 | StudentSegmentProfile( |
| 210 | school=SCHOOL, |
| 211 | student="ogrenci-b", |
| 212 | dimension="dikkat_tuzagi", |
| 213 | label="var", |
| 214 | n_answers=150, |
| 215 | n_correct=90, |
| 216 | overall_n_answers=400, |
| 217 | overall_accuracy=0.61, |
| 218 | computed_at=NOW, |
| 219 | confidence=Confidence.EXPLORATORY, |
| 220 | ), |
| 221 | ] |
| 222 | ) |
| 223 | |
| 224 | |
| 225 | def runs() -> list[dict[str, Any]]: |
| 226 | |
| 227 | return [ |
| 228 | run_row( |
| 229 | { |
| 230 | "started_at": NOW - 3600_000, |
| 231 | "finished_at": NOW, |
| 232 | "status": "ok", |
| 233 | "students_total": 3, |
| 234 | "students_ok": 3, |
| 235 | "students_failed": 0, |
| 236 | "students_skipped": 0, |
| 237 | "rows_written": 9, |
| 238 | "budget_exceeded": False, |
| 239 | "budget_ms": 60_000, |
| 240 | "pending_students": [], |
| 241 | "failed_modules": [], |
| 242 | }, |
| 243 | f"{SCHOOL}_{RUN_DAY}", |
| 244 | ) |
| 245 | ] |
| 246 | |
| 247 | |
| 248 | def payload(**over: Any) -> dict[str, Any]: |
| 249 | |
| 250 | sent: dict[str, Any] = { |
| 251 | "kind": "okul", |
| 252 | "run_day": RUN_DAY, |
| 253 | "requested_by": "mudur-1", |
| 254 | "school": {"id": "01990000-0000-7000-8000-000000000001", "name": DISPLAY}, |
| 255 | |
| 256 | |
| 257 | "classes": [ |
| 258 | {"id": CLASS_A_ID, "name": CLASS_A_NAME}, |
| 259 | {"id": CLASS_B_ID, "name": CLASS_B_NAME}, |
| 260 | ], |
| 261 | "summaries": summaries(), |
| 262 | "recommendations": recommendations(), |
| 263 | "profiles": profiles(), |
| 264 | "runs": runs(), |
| 265 | } |
| 266 | sent.update(over) |
| 267 | return sent |
| 268 | |
| 269 | |
| 270 | class ReportCase(unittest.IsolatedAsyncioTestCase): |
| 271 | |
| 272 | |
| 273 | def setUp(self) -> None: |
| 274 | handlers.wire() |
| 275 | |
| 276 | def tearDown(self) -> None: |
| 277 | capabilities._handlers.clear() |
| 278 | |
| 279 | async def dispatch(self, sent: dict[str, Any]) -> dict[str, Any]: |
| 280 | return await capabilities.dispatch("insight.report", SCHOOL, sent) |
| 281 | |
| 282 | |
| 283 | class DispatchTests(ReportCase): |
| 284 | async def test_report_is_unknown_until_wire_registers_it(self) -> None: |
| 285 | capabilities._handlers.clear() |
| 286 | with self.assertRaises(CapabilityError) as caught: |
| 287 | await self.dispatch(payload()) |
| 288 | self.assertEqual(caught.exception.code, "unknown_capability") |
| 289 | |
| 290 | handlers.wire() |
| 291 | answer = await self.dispatch(payload()) |
| 292 | self.assertEqual(answer["format"], "html") |
| 293 | |
| 294 | def test_the_boot_self_check_counts_it_dispatchable(self) -> None: |
| 295 | self.assertIn("insight.report", capabilities.dispatchable_names()) |
| 296 | capabilities.verify_dispatchable() |
| 297 | |
| 298 | capabilities._handlers.pop("insight.report") |
| 299 | with self.assertRaises(capabilities.RegistrationError) as caught: |
| 300 | capabilities.verify_dispatchable() |
| 301 | self.assertIn("insight.report", str(caught.exception)) |
| 302 | |
| 303 | |
| 304 | class DocumentTests(ReportCase): |
| 305 | async def test_the_html_carries_name_count_and_per_student_lines(self) -> None: |
| 306 | answer = await self.dispatch(payload()) |
| 307 | html = answer["html"] |
| 308 | |
| 309 | |
| 310 | self.assertTrue(html.startswith("<!DOCTYPE html>")) |
| 311 | |
| 312 | self.assertIn(DISPLAY, html) |
| 313 | |
| 314 | |
| 315 | self.assertIn('<td>Öğrenci</td><td class="num">3</td>', html) |
| 316 | |
| 317 | |
| 318 | self.assertIn('<td>Şube</td><td class="num">2</td>', html) |
| 319 | self.assertIn(f"<td>{CLASS_A_NAME}</td>", html) |
| 320 | self.assertIn(f"<td>{CLASS_B_NAME}</td>", html) |
| 321 | self.assertNotIn(CLASS_A_ID, html) |
| 322 | self.assertNotIn(CLASS_B_ID, html) |
| 323 | |
| 324 | |
| 325 | pairs = [ |
| 326 | (label, course) |
| 327 | for label, course in re.findall(r"<tr><td>([^<]+)</td><td>([^<]+)</td>", html) |
| 328 | if label in (CLASS_A_NAME, CLASS_B_NAME, CLASS_LABEL_UNKNOWN) |
| 329 | ] |
| 330 | self.assertEqual(pairs, sorted(pairs)) |
| 331 | |
| 332 | |
| 333 | self.assertIn("<td>ogrenci-a</td>", html) |
| 334 | self.assertIn(f"<td>ogrenci-a</td><td>{CLASS_A_NAME}</td>", html) |
| 335 | self.assertIn(FACT_A, html) |
| 336 | self.assertIn("<td>ogrenci-b</td>", html) |
| 337 | self.assertIn(FACT_B, html) |
| 338 | |
| 339 | |
| 340 | self.assertIn("T4.homework", html) |
| 341 | self.assertIn("O1.review_band", html) |
| 342 | self.assertNotIn("V1.parent_only", html) |
| 343 | |
| 344 | |
| 345 | self.assertEqual(answer["kind"], "okul") |
| 346 | self.assertEqual(answer["format"], "html") |
| 347 | self.assertEqual(answer["run_day"], RUN_DAY) |
| 348 | self.assertIs(answer["truncated"], False) |
| 349 | self.assertEqual(answer["byte_size"], len(html.encode("utf-8"))) |
| 350 | self.assertEqual( |
| 351 | answer["coverage"]["rows"], |
| 352 | {"summaries": 3, "recommendations": 3, "profiles": 2, "runs": 1}, |
| 353 | ) |
| 354 | self.assertIs(answer["coverage"]["empty"], False) |
| 355 | |
| 356 | self.assertTrue(answer["notes"]) |
| 357 | self.assertTrue( |
| 358 | all(isinstance(note, str) and note for note in answer["notes"]) |
| 359 | ) |
| 360 | self.assertTrue(any("sıralama yoktur" in note for note in answer["notes"])) |
| 361 | |
| 362 | async def test_run_day_falls_back_to_the_newest_run_row(self) -> None: |
| 363 | sent = payload() |
| 364 | del sent["run_day"] |
| 365 | answer = await self.dispatch(sent) |
| 366 | self.assertEqual(answer["run_day"], RUN_DAY) |
| 367 | |
| 368 | async def test_class_names_mapping_shape_labels_too(self) -> None: |
| 369 | |
| 370 | sent = payload() |
| 371 | sent.pop("classes") |
| 372 | sent["class_names"] = {CLASS_A_ID: CLASS_A_NAME, CLASS_B_ID: CLASS_B_NAME} |
| 373 | html = (await self.dispatch(sent))["html"] |
| 374 | self.assertIn(f"<td>{CLASS_A_NAME}</td>", html) |
| 375 | self.assertIn(f"<td>{CLASS_B_NAME}</td>", html) |
| 376 | self.assertNotIn(CLASS_A_ID, html) |
| 377 | self.assertNotIn(CLASS_B_ID, html) |
| 378 | |
| 379 | async def test_an_unmapped_class_gets_the_label_never_the_id(self) -> None: |
| 380 | |
| 381 | sent = payload(classes=[{"id": CLASS_A_ID, "name": CLASS_A_NAME}]) |
| 382 | answer = await self.dispatch(sent) |
| 383 | html = answer["html"] |
| 384 | self.assertIn(f"<td>{CLASS_A_NAME}</td>", html) |
| 385 | self.assertIn(CLASS_LABEL_UNKNOWN, html) |
| 386 | self.assertNotIn(CLASS_B_ID, html) |
| 387 | |
| 388 | self.assertIn('<td>Şube</td><td class="num">2</td>', html) |
| 389 | self.assertIn('<td>Öğrenci</td><td class="num">3</td>', html) |
| 390 | |
| 391 | async def test_a_backend_without_a_class_map_still_builds(self) -> None: |
| 392 | |
| 393 | sent = payload() |
| 394 | sent.pop("classes") |
| 395 | answer = await self.dispatch(sent) |
| 396 | html = answer["html"] |
| 397 | self.assertTrue(html.startswith("<!DOCTYPE html>")) |
| 398 | self.assertIn(CLASS_LABEL_UNKNOWN, html) |
| 399 | self.assertNotIn(CLASS_A_ID, html) |
| 400 | self.assertNotIn(CLASS_B_ID, html) |
| 401 | self.assertIn('<td>Öğrenci</td><td class="num">3</td>', html) |
| 402 | self.assertIn('<td>Şube</td><td class="num">2</td>', html) |
| 403 | |
| 404 | |
| 405 | class RefusalTests(ReportCase): |
| 406 | async def test_an_empty_row_set_is_refused_not_rendered(self) -> None: |
| 407 | for sent in ( |
| 408 | payload(summaries=[], recommendations=[], profiles=[], runs=[]), |
| 409 | {"kind": "okul"}, |
| 410 | ): |
| 411 | with self.assertRaises(CapabilityError) as caught: |
| 412 | await self.dispatch(sent) |
| 413 | self.assertEqual(caught.exception.code, "insufficient_rows") |
| 414 | |
| 415 | async def test_a_kind_this_capability_does_not_serve_is_refused(self) -> None: |
| 416 | for kind in ("ogrenci", "ogretmen", "ham", "rapor", ""): |
| 417 | with self.assertRaises(CapabilityError) as caught: |
| 418 | await self.dispatch(payload(kind=kind)) |
| 419 | self.assertEqual(caught.exception.code, "bad_request") |
| 420 | |
| 421 | async def test_a_row_claiming_another_school_is_refused(self) -> None: |
| 422 | sent = payload() |
| 423 | sent["summaries"] = [{**sent["summaries"][0], "school": "baska-okul"}] |
| 424 | with self.assertRaises(CapabilityError) as caught: |
| 425 | await self.dispatch(sent) |
| 426 | self.assertEqual(caught.exception.code, "bad_request") |
| 427 | self.assertIn("baska-okul", str(caught.exception)) |
| 428 | |
| 429 | async def test_a_stray_school_slug_is_ignored(self) -> None: |
| 430 | |
| 431 | |
| 432 | answer = await self.dispatch( |
| 433 | payload(school={"id": "x", "slug": "baska-okul", "name": "Başka"}) |
| 434 | ) |
| 435 | self.assertIn("Başka", answer["html"]) |
| 436 | |
| 437 | async def test_a_malformed_row_list_is_refused(self) -> None: |
| 438 | with self.assertRaises(CapabilityError) as caught: |
| 439 | await self.dispatch(payload(profiles={"student": "ogrenci-a"})) |
| 440 | self.assertEqual(caught.exception.code, "bad_request") |
| 441 | |
| 442 | async def test_a_malformed_class_list_is_refused(self) -> None: |
| 443 | |
| 444 | |
| 445 | |
| 446 | for bad in ({"id": CLASS_A_ID}, ["9-A"], [{"name": CLASS_A_NAME}]): |
| 447 | with self.assertRaises(CapabilityError) as caught: |
| 448 | await self.dispatch(payload(classes=bad)) |
| 449 | self.assertEqual(caught.exception.code, "bad_request") |
| 450 | |
| 451 | async def test_a_render_failure_is_a_typed_refusal(self) -> None: |
| 452 | with patch.object( |
| 453 | handlers.report_render, "to_html", side_effect=RuntimeError("çizim düştü") |
| 454 | ): |
| 455 | with self.assertRaises(CapabilityError) as caught: |
| 456 | await self.dispatch(payload()) |
| 457 | self.assertEqual(caught.exception.code, "internal") |
| 458 | self.assertIn("çizim düştü", str(caught.exception)) |
| 459 | |
| 460 | async def test_an_oversize_document_is_refused_not_truncated(self) -> None: |
| 461 | cap = protocol.AI_MAX_FRAME_BYTES // 2 |
| 462 | with patch.object( |
| 463 | handlers.report_render, "to_html", return_value="x" * (cap + 1) |
| 464 | ): |
| 465 | with self.assertRaises(CapabilityError) as caught: |
| 466 | await self.dispatch(payload()) |
| 467 | self.assertEqual(caught.exception.code, "document_too_large") |
| 468 | |
| 469 | def test_the_html_cap_is_half_the_frame_cap(self) -> None: |
| 470 | |
| 471 | |
| 472 | self.assertEqual(handlers._MAX_HTML_BYTES * 2, protocol.AI_MAX_FRAME_BYTES) |
| 473 | |
| 474 | |
| 475 | if __name__ == "__main__": |
| 476 | unittest.main() |