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_source.py519 lines, 21.6 KiBHistoryRawDownload
1"""Veri erisim cephesinin testleri.
2
3En onemlisi `ForbiddenSurfaceTests`: cephede yemek, odeme, diyet, mesaj ve
4sohbet yontemi OLMADIGINI dogrular. O test kirilirsa yapisal kapi acilmis
5demektir.
6"""
7
8from __future__ import annotations
9
10import inspect
11import json
12import tempfile
13import unittest
14from pathlib import Path
15
16from src import config, protocol, source
17
18
19class ForbiddenSurfaceTests(unittest.TestCase):
20 def test_no_forbidden_data_methods(self):
21 # Yapisal kapi: hesap modulu yemek/odeme/diyet/mesaj/sohbet verisini
22 # ISTEYEMEZ, cunku cagiracagi fonksiyon yok.
23 for holder in (source.Source, source.BridgeSource, source.FileSource):
24 for name in dir(holder):
25 if name.startswith("_"):
26 continue
27 lowered = name.lower()
28 for term in source.FORBIDDEN_DATA_TERMS:
29 self.assertNotIn(
30 term,
31 lowered,
32 f"{holder.__name__}.{name} yasakli veri terimini ('{term}') tasiyor",
33 )
34
35 def test_surface_is_exactly_the_eight_declared_methods(self):
36 declared = {
37 name
38 for name in dir(source.Source)
39 if not name.startswith("_") and callable(getattr(source.Source, name, None))
40 }
41 self.assertEqual(declared, set(source.SOURCE_METHODS))
42
43 def test_both_implementations_cover_the_whole_surface(self):
44 for holder in (source.BridgeSource, source.FileSource):
45 for name in source.SOURCE_METHODS:
46 method = getattr(holder, name, None)
47 self.assertTrue(
48 callable(method), f"{holder.__name__}.{name} eksik"
49 )
50 self.assertTrue(
51 inspect.iscoroutinefunction(method),
52 f"{holder.__name__}.{name} es zamansiz olmali",
53 )
54
55 def test_signatures_match_the_protocol(self):
56 for name in source.SOURCE_METHODS:
57 expected = inspect.signature(getattr(source.Source, name))
58 for holder in (source.BridgeSource, source.FileSource):
59 self.assertEqual(
60 inspect.signature(getattr(holder, name)),
61 expected,
62 f"{holder.__name__}.{name} imzasi arayuzden sapiyor",
63 )
64
65 def test_every_method_documents_its_allowlist_path(self):
66 for name, template in source._TEMPLATES.items():
67 doc = inspect.getdoc(getattr(source.BridgeSource, name)) or ""
68 self.assertIn(template, doc, f"source.{name} docstring'i yolunu yazmiyor")
69
70 def test_every_template_is_on_the_backend_allowlist(self):
71 for name, template in source._TEMPLATES.items():
72 self.assertIn(
73 template,
74 protocol.AI_API_ALLOWLIST,
75 f"source.{name} izin listesi disinda bir yol kullaniyor",
76 )
77
78
79class _RecordingClient:
80 """Sahte kopru istemcisi: cagrilari kaydeder, hazir cevap doner."""
81
82 def __init__(self, body=None, status: int = 200):
83 self.calls: list[dict] = []
84 self._body = body
85 self._status = status
86
87 async def api_get(self, school, path, query=None, on_behalf_of=None):
88 self.calls.append(
89 {
90 "school": school,
91 "path": path,
92 "query": query,
93 "on_behalf_of": on_behalf_of,
94 }
95 )
96 return protocol.ApiResponse("01J", school, self._status, self._body)
97
98
99class BridgeSourceTests(unittest.IsolatedAsyncioTestCase):
100 async def test_marks_uses_the_allowlisted_path(self):
101 client = _RecordingClient(body={"user": "u1", "courses": [{"average": 88}]})
102 rows = await source.BridgeSource(client).marks("demo", "u1")
103 self.assertEqual(rows, [{"average": 88}])
104 self.assertEqual(client.calls[0]["path"], "/marks/u1")
105 self.assertEqual(client.calls[0]["school"], "demo")
106
107 async def test_page_envelope_is_unwrapped(self):
108 client = _RecordingClient(body={"items": [{"id": "n1"}], "total": 1})
109 rows = await source.BridgeSource(client).notes("demo", "u1")
110 self.assertEqual(rows, [{"id": "n1"}])
111 self.assertEqual(client.calls[0]["on_behalf_of"], "u1")
112
113 async def test_course_notes_sends_the_required_course_query(self):
114 client = _RecordingClient(body={"items": [], "total": 0})
115 await source.BridgeSource(client).course_notes("demo", "c1")
116 self.assertEqual(client.calls[0]["path"], "/course-notes")
117 self.assertEqual(client.calls[0]["query"], "course=c1")
118
119 async def test_course_notes_without_a_course_sends_nothing(self):
120 client = _RecordingClient(body={"items": [], "total": 0})
121 self.assertEqual(await source.BridgeSource(client).course_notes("demo"), [])
122 self.assertEqual(client.calls, [])
123
124 async def test_404_is_an_empty_result_not_an_error(self):
125 client = _RecordingClient(body=None, status=404)
126 self.assertIsNone(await source.BridgeSource(client).profile("demo", "u1"))
127
128 async def test_empty_school_is_refused_before_the_wire(self):
129 client = _RecordingClient(body={"items": []})
130 with self.assertRaises(source.SourceError):
131 await source.BridgeSource(client).marks("", "u1")
132 self.assertEqual(client.calls, [])
133
134 async def test_a_path_outside_the_allowlist_is_blocked(self):
135 # Cephe izin listesi disina cikamaz; ciksa bile ikinci kemer tutar.
136 client = _RecordingClient(body={"items": []})
137 with self.assertRaises(source.SourceError) as caught:
138 await source.BridgeSource(client)._get("marks", "demo", "/meals")
139 self.assertEqual(caught.exception.code, protocol.ApiErrorCode.PATH_NOT_ALLOWED)
140 self.assertEqual(client.calls, [])
141
142 async def test_bridge_refusal_becomes_a_source_error(self):
143 class _Refusing:
144 async def api_get(self, school, path, query=None, on_behalf_of=None):
145 raise protocol.ApiRefused(
146 protocol.ApiErrorCode.UNKNOWN_SCHOOL, "boyle bir okul yok"
147 )
148
149 with self.assertRaises(source.SourceError) as caught:
150 await source.BridgeSource(_Refusing()).marks("yok-boyle", "u1")
151 self.assertEqual(caught.exception.code, protocol.ApiErrorCode.UNKNOWN_SCHOOL)
152
153
154class RealResponseShapeTests(unittest.IsolatedAsyncioTestCase):
155 """Her uc icin backend struct'larindan TURETILMIS gercek bicimli yanitlar.
156
157 Bu sinif, `_as_list()` doneminde kacirilan hatanin nobetcisidir: o surumde
158 `/marks` ve `/attendance` yanitlari `items` tasimadigi icin sessizce `[]`
159 donuyordu. Asagidaki govdelerin her biri backend kaynagindaki struct'in
160 alanlarina birebir uyar.
161 """
162
163 # web/marks.rs:65 MarksReport -> web/marks.rs:50 CourseMarks -> :33 MarkEntry
164 MARKS_REPORT = {
165 "user": "u1",
166 "courses": [
167 {
168 "course": {"id": "c1", "name": "Matematik"},
169 "results": [
170 {
171 "exam": "e1",
172 "title": "1. Yazili",
173 "kind": "yazili",
174 "weight": 2,
175 "mark": 72,
176 "grade": "CB",
177 "graded_by": "t1",
178 }
179 ],
180 "average": 72.0,
181 "average_grade": "CB",
182 },
183 {
184 "course": {"id": "c2", "name": "Fizik"},
185 "results": [],
186 "average": None,
187 "average_grade": None,
188 },
189 ],
190 "overall_average": 72.0,
191 "overall_grade": "CB",
192 }
193
194 # web/attendance.rs:84 AttendanceReport -> :76 CourseAttendance -> :31 StatusCounts
195 ATTENDANCE_REPORT = {
196 "user": "u1",
197 "events": {
198 "present": 3,
199 "absent": 0,
200 "late": 0,
201 "excused": 0,
202 "custom": {},
203 "total": 3,
204 "rate": 1.0,
205 },
206 "sessions": {
207 "present": 40,
208 "absent": 6,
209 "late": 4,
210 "excused": 2,
211 "custom": {"gorevli": 1},
212 "total": 53,
213 "rate": 0.88,
214 },
215 "courses": [
216 {
217 "course": {"id": "c1", "name": "Matematik"},
218 "counts": {
219 "present": 20,
220 "absent": 4,
221 "late": 2,
222 "excused": 1,
223 "custom": {},
224 "total": 27,
225 "rate": 0.8461538461538461,
226 },
227 }
228 ],
229 }
230
231 # web/pomodoro.rs:78 PomodoroLog -> :40 PomodoroResponse
232 POMODORO_LOG = {
233 "items": [
234 {
235 "id": "p1",
236 "user": "u1",
237 "started_at": 1776067200000,
238 "finished_at": 1776068700000,
239 "duration_ms": 1500000,
240 "counted": True,
241 },
242 {
243 "id": "p2",
244 "user": "u1",
245 "started_at": 1776070000000,
246 "finished_at": None,
247 "duration_ms": None,
248 "counted": None,
249 },
250 ],
251 "total": 256,
252 "limit": 100,
253 "offset": 0,
254 "total_focus_ms": 384000000,
255 }
256
257 # web/homework.rs:1206 Page<HomeworkReportEntry> -> :1166 HomeworkReportEntry
258 HOMEWORK_REPORT_PAGE = {
259 "items": [
260 {
261 "course": "c1",
262 "homework": "h1",
263 "title": "Turev calisma kagidi",
264 "subject": "s1",
265 "due_at": 1776067200000,
266 "submitted": True,
267 "late": False,
268 "missing": False,
269 "result": {"mark": 85},
270 }
271 ],
272 "total": 1,
273 "limit": None,
274 "offset": 0,
275 }
276
277 # web/users.rs:707 ProfileResponse
278 PROFILE = {
279 "id": "u1",
280 "username": "ada",
281 "display_name": "Ada Lovelace",
282 "stats": {"pomodoro_total": 128, "study_streak_current": 4},
283 }
284
285 async def test_marks_unwraps_the_courses_block_not_items(self):
286 # REGRESYON: `_as_list()` burada `[]` donuyordu -- MarksReport'ta
287 # `items` yok, `courses` var (web/marks.rs:65).
288 client = _RecordingClient(body=self.MARKS_REPORT)
289 rows = await source.BridgeSource(client).marks("demo", "u1")
290 self.assertEqual(len(rows), 2)
291 self.assertEqual(rows[0]["course"]["id"], "c1")
292 self.assertEqual(rows[0]["results"][0]["mark"], 72)
293 self.assertEqual(rows[1]["average"], None)
294
295 async def test_attendance_unwraps_the_courses_block_not_items(self):
296 # REGRESYON: aynisi AttendanceReport icin (web/attendance.rs:84).
297 client = _RecordingClient(body=self.ATTENDANCE_REPORT)
298 rows = await source.BridgeSource(client).attendance("demo", "u1")
299 self.assertEqual(len(rows), 1)
300 self.assertEqual(rows[0]["course"]["id"], "c1")
301 # Ders basina SAYAC dondurur, satir/tarih degil.
302 self.assertEqual(rows[0]["counts"]["absent"], 4)
303 self.assertNotIn("date", rows[0])
304
305 async def test_pomodoro_unwraps_items_from_the_pomodoro_log(self):
306 client = _RecordingClient(body=self.POMODORO_LOG)
307 rows = await source.BridgeSource(client).pomodoro("demo", "u1")
308 self.assertEqual(len(rows), 2)
309 self.assertEqual(rows[0]["duration_ms"], 1500000)
310 # Devam eden seansta `counted` null.
311 self.assertIsNone(rows[1]["counted"])
312
313 async def test_homework_report_returns_the_whole_page_envelope(self):
314 client = _RecordingClient(body=self.HOMEWORK_REPORT_PAGE)
315 report = await source.BridgeSource(client).homework_report("demo", "u1")
316 self.assertEqual(report["total"], 1)
317 self.assertEqual(report["items"][0]["homework"], "h1")
318
319 async def test_profile_returns_the_plain_object(self):
320 client = _RecordingClient(body=self.PROFILE)
321 profile = await source.BridgeSource(client).profile("demo", "u1")
322 self.assertEqual(profile["username"], "ada")
323 self.assertEqual(profile["stats"]["pomodoro_total"], 128)
324
325 async def test_page_envelope_endpoints_unwrap_items(self):
326 page = {"items": [{"id": "x1"}], "total": 1, "limit": None, "offset": 0}
327 bridge = source.BridgeSource(_RecordingClient(body=page))
328 self.assertEqual(await bridge.notes("demo", "u1"), [{"id": "x1"}])
329 self.assertEqual(await bridge.homework_list("demo", "u1"), [{"id": "x1"}])
330 self.assertEqual(await bridge.course_notes("demo", "c1"), [{"id": "x1"}])
331
332
333class SilentEmptyGuardTests(unittest.IsolatedAsyncioTestCase):
334 """Beklenmeyen bicim SESSIZCE BOS DONMEZ.
335
336 Sessiz bos, bu projede en pahali hata sinifidir: hesap bosalir, hata
337 cikmaz, gunluk sessiz kalir. Her sapma ayirt edilebilir bir
338 `unexpected_shape` uretmek zorunda.
339 """
340
341 def _assert_shape_error(self, error: source.SourceError, needle: str) -> None:
342 self.assertEqual(error.code, "unexpected_shape")
343 self.assertIn(needle, str(error))
344
345 async def test_marks_with_an_items_envelope_is_not_silently_empty(self):
346 # Tam da eski hatanin tersi: `items` gelirse de fark edilsin.
347 client = _RecordingClient(body={"items": [{"course": "c1"}], "total": 1})
348 with self.assertRaises(source.SourceError) as caught:
349 await source.BridgeSource(client).marks("demo", "u1")
350 self._assert_shape_error(caught.exception, "courses")
351
352 async def test_attendance_without_courses_is_not_silently_empty(self):
353 client = _RecordingClient(body={"user": "u1", "events": {}, "sessions": {}})
354 with self.assertRaises(source.SourceError) as caught:
355 await source.BridgeSource(client).attendance("demo", "u1")
356 self._assert_shape_error(caught.exception, "courses")
357
358 async def test_pomodoro_without_items_is_not_silently_empty(self):
359 client = _RecordingClient(body={"sessions": [], "total_focus_ms": 0})
360 with self.assertRaises(source.SourceError) as caught:
361 await source.BridgeSource(client).pomodoro("demo", "u1")
362 self._assert_shape_error(caught.exception, "items")
363
364 async def test_notes_without_items_is_not_silently_empty(self):
365 client = _RecordingClient(body={"rows": []})
366 with self.assertRaises(source.SourceError) as caught:
367 await source.BridgeSource(client).notes("demo", "u1")
368 self._assert_shape_error(caught.exception, "items")
369
370 async def test_homework_report_without_items_is_not_silently_empty(self):
371 client = _RecordingClient(body={"total": 0, "limit": None, "offset": 0})
372 with self.assertRaises(source.SourceError) as caught:
373 await source.BridgeSource(client).homework_report("demo", "u1")
374 self._assert_shape_error(caught.exception, "items")
375
376 async def test_profile_without_an_id_is_not_silently_half(self):
377 client = _RecordingClient(body={"username": "ada"})
378 with self.assertRaises(source.SourceError) as caught:
379 await source.BridgeSource(client).profile("demo", "u1")
380 self._assert_shape_error(caught.exception, "id")
381
382 async def test_a_scalar_body_is_refused(self):
383 client = _RecordingClient(body="beklenmedik")
384 with self.assertRaises(source.SourceError) as caught:
385 await source.BridgeSource(client).marks("demo", "u1")
386 self.assertEqual(caught.exception.code, "unexpected_shape")
387
388 async def test_a_bare_list_is_accepted_but_warned(self):
389 # Belgelenen bicim zarf; duz liste sapma isaretidir ama veri kullanilir.
390 client = _RecordingClient(body=[{"course": "c1"}])
391 with self.assertLogs_bridge() as logs:
392 rows = await source.BridgeSource(client).marks("demo", "u1")
393 self.assertEqual(rows, [{"course": "c1"}])
394 self.assertTrue(any("duz liste" in line for line in logs))
395
396 def assertLogs_bridge(self):
397 """`config.log` ASCII `print` kullanir, `logging` degil -- yakalayalim."""
398
399 class _Capture:
400 def __init__(self):
401 self.lines: list[str] = []
402
403 def __enter__(self):
404 self._original = config.log
405
406 def spy(level, message):
407 self.lines.append(message)
408
409 config.log = spy
410 return self.lines
411
412 def __exit__(self, *exc):
413 config.log = self._original
414 return False
415
416 return _Capture()
417
418 async def test_404_stays_an_empty_result_for_every_endpoint(self):
419 # 404 bir bicim sorunu DEGILDIR: router calisti ve "yok" dedi.
420 bridge = source.BridgeSource(_RecordingClient(body=None, status=404))
421 self.assertEqual(await bridge.marks("demo", "u1"), [])
422 self.assertEqual(await bridge.attendance("demo", "u1"), [])
423 self.assertEqual(await bridge.pomodoro("demo", "u1"), [])
424 self.assertEqual(await bridge.notes("demo", "u1"), [])
425 self.assertIsNone(await bridge.profile("demo", "u1"))
426 self.assertIsNone(await bridge.homework_report("demo", "u1"))
427
428
429class FileSourceTests(unittest.IsolatedAsyncioTestCase):
430 def setUp(self):
431 self._tmp = tempfile.TemporaryDirectory()
432 self.root = Path(self._tmp.name)
433 self.addCleanup(self._tmp.cleanup)
434 self.src = source.FileSource(self.root)
435
436 def _write(self, school: str, kind: str, key: str, body) -> None:
437 target = self.root / school / source.FileSource.DIRECTORIES[kind]
438 target.mkdir(parents=True, exist_ok=True)
439 with (target / f"{key}.json").open("w", encoding="utf-8") as handle:
440 json.dump(body, handle, ensure_ascii=False)
441
442 async def test_end_to_end_read_of_one_student_from_bare_lists(self):
443 # Elle yazilan kucuk fiksturler duz liste olabilir; bu bicim uyari
444 # uretmeden kabul edilir (fikstur yazilmistir, telden gelmemistir).
445 self._write("demo", "profile", "u1", {"id": "u1", "grade": "11-A"})
446 self._write("demo", "marks", "u1", [{"course": "mat", "average": 72}])
447 self._write("demo", "attendance", "u1", [{"course": "mat", "counts": {}}])
448 self._write("demo", "pomodoro", "u1", [{"id": "p1", "duration_ms": 1500000}])
449 self._write("demo", "homework_report", "u1", {"items": [{"homework": "h1"}]})
450 self._write("demo", "homework_list", "u1", [{"id": "h1"}])
451 self._write("demo", "notes", "u1", [{"id": "n1"}])
452 self._write("demo", "course_notes", "c1", [{"id": "cn1"}])
453
454 self.assertEqual((await self.src.profile("demo", "u1"))["grade"], "11-A")
455 self.assertEqual(
456 await self.src.marks("demo", "u1"), [{"course": "mat", "average": 72}]
457 )
458 self.assertEqual(
459 await self.src.attendance("demo", "u1"), [{"course": "mat", "counts": {}}]
460 )
461 self.assertEqual(
462 await self.src.pomodoro("demo", "u1"),
463 [{"id": "p1", "duration_ms": 1500000}],
464 )
465 report = await self.src.homework_report("demo", "u1")
466 self.assertEqual(report["items"][0]["homework"], "h1")
467 self.assertEqual(await self.src.homework_list("demo", "u1"), [{"id": "h1"}])
468 self.assertEqual(await self.src.notes("demo", "u1"), [{"id": "n1"}])
469 self.assertEqual(await self.src.course_notes("demo", "c1"), [{"id": "cn1"}])
470
471 async def test_a_real_response_saved_verbatim_works_as_a_fixture(self):
472 # Gercek bir cevabi dosyaya oldugu gibi kaydetmek calismali: kopru ve
473 # fikstur ayni zarflari acar.
474 real = RealResponseShapeTests
475 self._write("demo", "marks", "u1", real.MARKS_REPORT)
476 self._write("demo", "attendance", "u1", real.ATTENDANCE_REPORT)
477 self._write("demo", "pomodoro", "u1", real.POMODORO_LOG)
478 self._write("demo", "homework_report", "u1", real.HOMEWORK_REPORT_PAGE)
479 self._write("demo", "profile", "u1", real.PROFILE)
480
481 marks = await self.src.marks("demo", "u1")
482 self.assertEqual([row["course"]["id"] for row in marks], ["c1", "c2"])
483 attendance = await self.src.attendance("demo", "u1")
484 self.assertEqual(attendance[0]["counts"]["absent"], 4)
485 self.assertEqual(len(await self.src.pomodoro("demo", "u1")), 2)
486 self.assertEqual((await self.src.homework_report("demo", "u1"))["total"], 1)
487 self.assertEqual((await self.src.profile("demo", "u1"))["username"], "ada")
488
489 async def test_a_fixture_with_the_wrong_envelope_key_is_not_silently_empty(self):
490 self._write("demo", "marks", "u1", {"items": [{"course": "mat"}]})
491 with self.assertRaises(source.SourceError) as caught:
492 await self.src.marks("demo", "u1")
493 self.assertEqual(caught.exception.code, "unexpected_shape")
494
495 async def test_missing_fixture_is_empty_not_an_error(self):
496 self.assertIsNone(await self.src.profile("demo", "yok"))
497 self.assertEqual(await self.src.marks("demo", "yok"), [])
498
499 async def test_other_schools_are_not_visible(self):
500 self._write("demo", "marks", "u1", [{"value": 1}])
501 self.assertEqual(await self.src.marks("baska-okul", "u1"), [])
502
503 async def test_path_traversal_in_an_id_cannot_escape_the_root(self):
504 self._write("demo", "marks", "u1", [{"value": 1}])
505 self.assertEqual(await self.src.marks("demo", "../../u1"), [])
506
507 async def test_homework_list_without_a_user_reads_the_service_fixture(self):
508 self._write("demo", "homework_list", "_service", [{"id": "h0"}])
509 self.assertEqual(await self.src.homework_list("demo"), [{"id": "h0"}])
510
511 async def test_fixture_source_is_the_same_class(self):
512 self.assertIs(source.FixtureSource, source.FileSource)
513
514 async def test_file_source_satisfies_the_protocol(self):
515 self.assertIsInstance(self.src, source.Source)
516
517
518if __name__ == "__main__":
519 unittest.main()