forge
Explore
Log in

Don't you dare go Hollow

hezarfen_zeka

Clone
★ 0

0 watching0 forksPython1.9 MiBe01a4faAhmet Kaan Gümüş2 months ago25 commits

test_report_capability.py476 lines, 19.1 KiBHistoryRawDownload
1"""`insight.report` -- the school report document, end to end over the table.
2
3What is proven here, in the order it matters:
4
51. The fail-pre-fix fact, for the fourth served name: with an empty handler
6 table the dispatch answers `unknown_capability`; `handlers.wire()` makes the
7 same call reach a real handler, and the boot self-check counts the name
8 dispatchable -- and refuses to boot when it is not.
92. The whole point of the seam: row lists shaped EXACTLY like what the backend
10 sends -- built here by the very writers that wrote them in production
11 (`store.summary_rows` / `recommendation_rows` / `profile_rows` / `run_row`),
12 with NO `school` key anywhere (ZEKA never wrote one; the frame carries it) --
13 render the school report HTML: the display name, the student count, the
14 per-student attention lines, the class NAMES (never the raw ids), and only
15 the roles the `okul` report may show.
163. Refusals are typed and leave no half-built document behind: an empty row set
17 (`insufficient_rows`), an unserved kind or a payload that breaks the contract
18 (`bad_request`), a package failure (`internal`), an over-cap document
19 (`document_too_large`) -- never a truncated HTML file.
20"""
21
22from __future__ import annotations
23
24import re
25import time
26import unittest
27from typing import Any
28from unittest.mock import patch
29
30from src import capabilities, handlers, protocol
31from src.compute import clock
32from src.compute.model import (
33 Audience,
34 Confidence,
35 Recommendation,
36 StudentSegmentProfile,
37 StudentSummary,
38)
39from src.protocol import CapabilityError
40from src.store import profile_rows, recommendation_rows, run_row, summary_rows
41
42SCHOOL = "demo-okul"
43DISPLAY = "Demo Anadolu Lisesi"
44NOW = int(time.time() * 1000)
45DAY = clock.DAY_MS
46RUN_DAY = clock.tr_date_key(NOW)
47
48FACT_A = "Son 30 günde 4 ödev teslim edilmedi"
49FACT_B = "Not eğilimi son üç sınavda düştü"
50
51#: Şube KİMLİKLERİ (satırlarda `marks.classes` olarak giden şey) ve GÖRÜNEN
52#: adları (payload'ın `classes` haritasından gelen şey). İkisinin sırası
53#: KASITLI olarak farklıdır (kimlikte A<B, adda "10-B"<"9-A"): tablonun
54#: kimliğe göre değil ADA göre sıralandığı böyle görünür.
55CLASS_A_ID = "01a0b1a6-f984-7483-94ee-7643d137fe08"
56CLASS_B_ID = "01a0b1a6-f984-7483-94ee-7643d137fe09"
57CLASS_A_NAME = "9-A"
58CLASS_B_NAME = "10-B"
59CLASS_LABEL_UNKNOWN = "Adı bilinmeyen şube"
60
61
62def _marks(course: str, title: str, band: str, class_id: str) -> dict[str, Any]:
63 """One course's evidence block, in the shape `marks.py` writes."""
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
86def _attention(trigger: str, fact: str) -> dict[str, Any]:
87 """One attention item, in the shape `attention.py` writes."""
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
98def summaries() -> list[dict[str, Any]]:
99 """`zeka_student_summary` rows, exactly as ZEKA writes them (no `school`)."""
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
138def recommendations() -> list[dict[str, Any]]:
139 """`zeka_recommendation` rows: teacher, student and parent cards.
140
141 The parent card is the gate witness: `allowed_roles("okul")` is
142 `STAFF_ROLES | STUDENT_FACING_ROLES` (`report/gate.py`), so teacher and
143 student cards show in the school report and the parent card must not.
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
193def profiles() -> list[dict[str, Any]]:
194 """`zeka_student_segment_profile` rows."""
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
225def runs() -> list[dict[str, Any]]:
226 """`zeka_run` rows, keyed the way the store writes them."""
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
248def payload(**over: Any) -> dict[str, Any]:
249 """The request exactly as the backend builds it (`## insight.report`)."""
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 # Sibling key, read whole from the school's own class table: the rows
256 # carry class IDS, and the document must print NAMES.
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
270class ReportCase(unittest.IsolatedAsyncioTestCase):
271 """Wired table, one school, and the payload the backend will send."""
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
283class 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() # a clean bill: no raise
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
304class 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 # 1) a self-contained HTML document, not an error page
310 self.assertTrue(html.startswith("<!DOCTYPE html>"))
311 # 2) the DISPLAY name the payload carried is the title
312 self.assertIn(DISPLAY, html)
313 # 3) the student count is the number of summaries the backend sent --
314 # rows carry no `school`, so this also proves the frame's stamp
315 self.assertIn('<td>Öğrenci</td><td class="num">3</td>', html)
316 # 3b) the Şube cells print the MAPPED NAMES, never the raw ids, and the
317 # class count is unchanged by the labelling
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 # ...and the tables read in NAME order, not id order (the fixture's
324 # names sort the other way round from its ids on purpose)
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 # 4) one line per student's attention item, with the student's id and
332 # the student's class NAME in the same row
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 # 5) the role gate ran: teacher and student cards show (the `okul`
339 # report allows both), the parent card does not
340 self.assertIn("T4.homework", html)
341 self.assertIn("O1.review_band", html)
342 self.assertNotIn("V1.parent_only", html)
343
344 # The answer's own contract
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 # The limitation notes are the package's own sentences, not invented ones
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 """The `class_names: {<id>: name}` fallback shape works as well."""
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 """A class the map lacks is a label, and the numbers do not move."""
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 # Labelling is not counting: 2 classes, 3 students, both unchanged.
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 """An older backend sends no map: the document builds, labelled."""
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
405class 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"}, # no row lists at all
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 # Backend dropped ReportSchool.slug. A leftover key must not refuse
431 # and must not become a second identity.
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 # A container that is not a list, and an entry with no usable id
444 # (an id is what the mapping keys on; swallowing it would strip every
445 # label silently).
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 # The document rides INSIDE the JSON frame: half the cap is the room
471 # the rest of the frame (and JSON escaping) needs.
472 self.assertEqual(handlers._MAX_HTML_BYTES * 2, protocol.AI_MAX_FRAME_BYTES)
473
474
475if __name__ == "__main__":
476 unittest.main()