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_protocol.py377 lines, 14.6 KiBHistoryRawDownload
1"""`hab/2` kablo sozlesmesinin testleri.
2
3Bu paket `aioquic` GEREKTIRMEZ ve ag kullanmaz: `src.protocol` saf Python'dur,
4`src.bridge` buradan hic import edilmez.
5"""
6
7from __future__ import annotations
8
9import json
10import struct
11import unittest
12
13from src import protocol
14
15
16class ProtocolVersionTests(unittest.TestCase):
17 def test_protocol_is_hab_2_not_hab_1(self):
18 # constant.rs:530-531. Podcast ve Celebi `hab/1` kullaniyor ve bu yuzden
19 # ALPN muzakeresinde reddediliyorlar.
20 self.assertEqual(protocol.AI_PROTOCOL, "hab/2")
21 self.assertEqual(protocol.AI_ALPN, "hab/2")
22 self.assertEqual(protocol.AI_PROTOCOL, protocol.AI_ALPN)
23
24 def test_frame_cap_matches_backend(self):
25 # constant.rs:536
26 self.assertEqual(protocol.AI_MAX_FRAME_BYTES, 8 * 1024 * 1024)
27
28 def test_worker_concurrency_bounds_match_backend(self):
29 # constant.rs:547-548
30 self.assertEqual(protocol.AI_MAX_CONCURRENT_PER_WORKER, 64)
31 self.assertEqual(protocol.AI_DEFAULT_CONCURRENT_PER_WORKER, 8)
32
33 def test_keepalive_is_below_idle_timeout(self):
34 # constant.rs:554-555: saglikli ama sessiz bir servis dusurulmemeli.
35 self.assertLess(protocol.AI_KEEPALIVE_SECS, protocol.AI_IDLE_TIMEOUT_SECS)
36
37 def test_greeting_timeout_is_below_backend_handshake_timeout(self):
38 # Reddi biz gormeliyiz; akis altimizdan kesilmemeli (constant.rs:643).
39 self.assertLess(
40 protocol.GREETING_TIMEOUT_SECS, protocol.AI_HANDSHAKE_TIMEOUT_SECS
41 )
42
43
44class FrameCodecTests(unittest.TestCase):
45 def test_round_trip(self):
46 payload = {"id": "01J", "school": "demo", "veri": "cok satirli\nmetin"}
47 self.assertEqual(protocol.decode_frame(protocol.encode_frame(payload)), payload)
48
49 def test_length_prefix_is_big_endian_u32(self):
50 encoded = protocol.encode_frame({"a": 1})
51 (length,) = struct.unpack(">I", encoded[:4])
52 self.assertEqual(length, len(encoded) - 4)
53 self.assertEqual(json.loads(encoded[4:]), {"a": 1})
54
55 def test_back_to_back_frames_stay_aligned(self):
56 first = protocol.encode_frame({"n": 1})
57 second = protocol.encode_frame({"n": 2})
58 buffer = first + second
59 self.assertEqual(protocol.decode_frame(buffer), {"n": 1})
60 self.assertEqual(protocol.decode_frame(buffer[len(first) :]), {"n": 2})
61
62 def test_oversize_write_is_refused(self):
63 with self.assertRaises(protocol.FrameTooLarge):
64 protocol.encode_frame({"x": "a" * (protocol.AI_MAX_FRAME_BYTES + 1)})
65
66 def test_oversize_length_header_is_refused_before_allocating(self):
67 claimed = protocol.AI_MAX_FRAME_BYTES + 1
68 with self.assertRaises(protocol.FrameTooLarge):
69 protocol.decode_frame(struct.pack(">I", claimed))
70
71 def test_garbage_body_is_malformed(self):
72 body = b"hic de json degil"
73 with self.assertRaises(protocol.FrameMalformed):
74 protocol.decode_frame(struct.pack(">I", len(body)) + body)
75
76 def test_non_ascii_survives_the_round_trip(self):
77 payload = {"school": "ataturk-anadolu", "ad": "Ogrenci Cigdem Sisli"}
78 self.assertEqual(protocol.decode_frame(protocol.encode_frame(payload)), payload)
79
80
81class FrameStreamTests(unittest.IsolatedAsyncioTestCase):
82 async def test_frame_split_across_chunks(self):
83 stream = protocol.FrameStream()
84 encoded = protocol.encode_frame({"id": "01J", "school": "demo"})
85 for index in range(0, len(encoded), 3):
86 stream.feed(encoded[index : index + 3], end=False)
87 self.assertEqual(await stream.read_frame(), {"id": "01J", "school": "demo"})
88
89 async def test_raw_bytes_after_a_header_are_not_frames(self):
90 # Blob govdesi HAM bayttir (protocol.rs:26-31); cerceve kapagina tabi degil.
91 stream = protocol.FrameStream()
92 header = protocol.encode_frame(
93 {
94 "status": "ok",
95 "id": "01J",
96 "school": "demo",
97 "name": "ozet.pdf",
98 "content_type": "application/pdf",
99 "size": 5,
100 }
101 )
102 stream.feed(header + b"12345", end=True)
103 parsed = protocol.parse_blob_response(await stream.read_frame())
104 self.assertEqual(parsed.size, 5)
105 self.assertEqual(await stream.read_exact(parsed.size), b"12345")
106
107 async def test_truncated_stream_is_eof(self):
108 stream = protocol.FrameStream()
109 stream.feed(struct.pack(">I", 8) + b'{"a":', end=True)
110 with self.assertRaises(EOFError):
111 await stream.read_frame()
112
113
114class HelloAndGreetingTests(unittest.TestCase):
115 def test_hello_carries_no_school(self):
116 # protocol.rs:82-84: filo paylasimlidir, okul her frame'de gelir.
117 wire = protocol.build_hello("zeka", ["insight.student"], "gizli", 4)
118 self.assertNotIn("school", wire)
119 self.assertEqual(wire["protocol"], "hab/2")
120 self.assertEqual(wire["capabilities"], ["insight.student"])
121 self.assertEqual(wire["max_concurrent"], 4)
122
123 def test_hello_round_trip(self):
124 wire = protocol.build_hello("zeka", ["insight.class"], "gizli", 99)
125 parsed = protocol.Hello.from_wire(wire)
126 self.assertEqual(parsed.service, "zeka")
127 # Backend clamp'i 1..=64 (constant.rs:547); biz de kirpiyoruz.
128 self.assertEqual(parsed.max_concurrent, protocol.AI_MAX_CONCURRENT_PER_WORKER)
129
130 def test_max_concurrent_is_optional_on_the_wire(self):
131 parsed = protocol.Hello.from_wire(
132 {
133 "protocol": "hab/2",
134 "service": "zeka",
135 "capabilities": ["insight.student"],
136 "token": "gizli",
137 }
138 )
139 self.assertIsNone(parsed.max_concurrent)
140
141 def test_welcome_returns_worker_id(self):
142 worker = protocol.parse_greeting(
143 {"type": "welcome", "worker_id": "w1", "protocol": "hab/2"}
144 )
145 self.assertEqual(worker, "w1")
146
147 def test_rejection_carries_its_code(self):
148 with self.assertRaises(protocol.HandshakeRejected) as caught:
149 protocol.parse_greeting(
150 {"type": "rejected", "code": "unsupported_protocol", "message": "eski"}
151 )
152 self.assertEqual(caught.exception.code, protocol.RejectCode.UNSUPPORTED_PROTOCOL)
153 self.assertTrue(caught.exception.permanent)
154
155 def test_welcome_echoing_a_foreign_protocol_is_rejected(self):
156 with self.assertRaises(protocol.HandshakeRejected) as caught:
157 protocol.parse_greeting(
158 {"type": "welcome", "worker_id": "w1", "protocol": "hab/1"}
159 )
160 self.assertEqual(caught.exception.code, protocol.RejectCode.UNSUPPORTED_PROTOCOL)
161
162
163class ApiFrameTests(unittest.TestCase):
164 def test_api_request_wire_names(self):
165 wire = protocol.build_api_request(
166 "01J", "demo", "/notes", query="limit=10", on_behalf_of="user:abc"
167 )
168 self.assertEqual(
169 wire,
170 {
171 "id": "01J",
172 "school": "demo",
173 "path": "/notes",
174 "query": "limit=10",
175 "on_behalf_of": "user:abc",
176 },
177 )
178 self.assertEqual(protocol.ApiRequest.from_wire(wire).path, "/notes")
179
180 def test_school_is_required_with_no_default(self):
181 with self.assertRaises(protocol.ApiRefused) as caught:
182 protocol.build_api_request("01J", "", "/notes")
183 self.assertEqual(caught.exception.code, protocol.ApiErrorCode.MALFORMED)
184
185 def test_query_inside_the_path_is_refused(self):
186 with self.assertRaises(protocol.ApiRefused):
187 protocol.build_api_request("01J", "demo", "/notes?limit=10")
188
189 def test_non_get_method_is_refused_locally(self):
190 with self.assertRaises(protocol.ApiRefused) as caught:
191 protocol.build_api_request("01J", "demo", "/notes", method="POST")
192 self.assertEqual(
193 caught.exception.code, protocol.ApiErrorCode.METHOD_NOT_ALLOWED
194 )
195
196 def test_api_response_tag_is_outcome_and_status_is_http(self):
197 # protocol.rs:449-451: etiket `outcome`, `status` HTTP kodudur.
198 parsed = protocol.parse_api_response(
199 {"outcome": "ok", "id": "1", "school": "demo", "status": 404, "body": None}
200 )
201 self.assertEqual(parsed.status, 404)
202 self.assertFalse(parsed.ok)
203
204 def test_api_error_raises_with_its_code(self):
205 with self.assertRaises(protocol.ApiRefused) as caught:
206 protocol.parse_api_response(
207 {
208 "outcome": "err",
209 "id": "1",
210 "school": "demo",
211 "code": "path_not_allowed",
212 "message": "olmaz",
213 }
214 )
215 self.assertEqual(caught.exception.code, protocol.ApiErrorCode.PATH_NOT_ALLOWED)
216
217
218class BlobFrameTests(unittest.TestCase):
219 def test_blob_request_wire_names(self):
220 wire = protocol.build_blob_request("01J", "demo", "01FILE", "user:abc")
221 self.assertEqual(
222 wire,
223 {"id": "01J", "school": "demo", "file": "01FILE", "on_behalf_of": "user:abc"},
224 )
225
226 def test_blob_and_api_shapes_never_parse_as_each_other(self):
227 # protocol.rs:34: ayirici alan `path` / `file`.
228 blob = protocol.build_blob_request("01J", "demo", "01FILE")
229 self.assertNotIn("path", blob)
230 with self.assertRaises(protocol.FrameMalformed):
231 protocol.ApiRequest.from_wire(blob)
232
233 def test_blob_tag_is_status_not_outcome(self):
234 # protocol.rs:509-511
235 parsed = protocol.parse_blob_response(
236 {
237 "status": "ok",
238 "id": "1",
239 "school": "demo",
240 "name": "ozet.pdf",
241 "content_type": "application/pdf",
242 "size": 204800,
243 }
244 )
245 self.assertEqual(parsed.size, 204800)
246
247 def test_blob_error_raises(self):
248 with self.assertRaises(protocol.BlobRefused) as caught:
249 protocol.parse_blob_response(
250 {
251 "status": "err",
252 "id": "1",
253 "school": "demo",
254 "code": "not_found",
255 "message": "yok",
256 }
257 )
258 self.assertEqual(caught.exception.code, protocol.ApiErrorCode.NOT_FOUND)
259
260
261class RequestResponseTests(unittest.TestCase):
262 def test_request_round_trip_and_deadline_budget(self):
263 request = protocol.Request.from_wire(
264 {
265 "id": "01J",
266 "school": "demo",
267 "capability": "insight.student",
268 "deadline_ms": 30000,
269 "payload": {"user_id": "u1"},
270 }
271 )
272 self.assertEqual(request.capability, "insight.student")
273 # Butceden pay dusulur; gec cevap yerine erken hata.
274 self.assertLess(request.timeout_secs, 30.0)
275 self.assertGreater(request.timeout_secs, 15.0)
276
277 def test_request_without_a_school_is_malformed(self):
278 with self.assertRaises(protocol.FrameMalformed):
279 protocol.Request.from_wire(
280 {"id": "01J", "capability": "insight.student", "deadline_ms": 1000}
281 )
282
283 def test_responses_echo_the_school(self):
284 # protocol.rs:155-169: her cevap okulunu yankilar.
285 self.assertEqual(
286 protocol.ok_response("01J", "demo", {"n": 1}),
287 {"status": "ok", "id": "01J", "school": "demo", "payload": {"n": 1}},
288 )
289 self.assertEqual(
290 protocol.err_response("01J", "demo", "bad_input", "olmaz"),
291 {
292 "status": "err",
293 "id": "01J",
294 "school": "demo",
295 "code": "bad_input",
296 "message": "olmaz",
297 },
298 )
299
300
301class AllowlistTests(unittest.TestCase):
302 #: `constant.rs:656-676` anlik goruntusu. Backend degisirse bu test kirilir
303 #: ve sapma fark edilir -- sessizce `path_not_allowed` toplamak yerine.
304 BACKEND_SNAPSHOT = (
305 "/auth/me",
306 "/users/me/profile",
307 "/users/{id}/profile",
308 "/notes",
309 "/notes/{id}",
310 "/course-notes",
311 "/course-notes/{id}",
312 "/course-notes/{id}/files",
313 "/homework",
314 "/homework/{id}",
315 "/homework/{id}/result",
316 "/homework/{id}/submission",
317 "/homework/report/{user}",
318 "/marks/me",
319 "/marks/{user}",
320 "/attendance/me",
321 "/attendance/{user}",
322 "/pomodoro/me",
323 "/pomodoro/{user}",
324 )
325
326 def test_allowlist_matches_backend_snapshot(self):
327 self.assertEqual(protocol.AI_API_ALLOWLIST, self.BACKEND_SNAPSHOT)
328 self.assertEqual(len(protocol.AI_API_ALLOWLIST), 19)
329
330 def test_literal_path_matches_exactly(self):
331 self.assertTrue(protocol.path_allowed("/auth/me"))
332 self.assertFalse(protocol.path_allowed("/auth/m"))
333 self.assertFalse(protocol.path_allowed("/AUTH/ME"))
334
335 def test_placeholder_takes_exactly_one_segment(self):
336 self.assertTrue(protocol.path_allowed("/notes/note123"))
337 self.assertFalse(protocol.path_allowed("/notes/note123/files"))
338
339 def test_trailing_slash_is_a_different_path(self):
340 self.assertFalse(protocol.path_allowed("/notes/"))
341 self.assertFalse(protocol.path_allowed("/auth/me/"))
342
343 def test_empty_segments_never_fill_a_placeholder(self):
344 self.assertFalse(protocol.path_allowed("/users//profile"))
345 self.assertFalse(protocol.path_allowed("//notes"))
346
347 def test_course_note_blobs_are_not_readable_over_the_api(self):
348 self.assertTrue(protocol.path_allowed("/course-notes/n1/files"))
349 self.assertFalse(protocol.path_allowed("/course-notes/n1/files/f1"))
350
351 def test_forbidden_data_paths_are_not_on_the_list(self):
352 for path in ("/meals", "/payments", "/messages", "/chatbot", "/meals/menu"):
353 self.assertFalse(protocol.path_allowed(path), path)
354
355 def test_template_is_the_pattern_not_the_path(self):
356 self.assertEqual(protocol.route_template("/marks/u1"), "/marks/{user}")
357 self.assertIsNone(protocol.route_template("/users"))
358
359 def test_unlisted_path_never_reaches_the_wire(self):
360 # Reddi tel USTUNDE degil, tele CIKMADAN once veriyoruz.
361 with self.assertRaises(protocol.ApiRefused) as caught:
362 protocol.build_api_request("01J", "demo", "/meals")
363 self.assertEqual(
364 caught.exception.code, protocol.ApiErrorCode.PATH_NOT_ALLOWED
365 )
366
367
368class TraceIdTests(unittest.TestCase):
369 def test_ulid_shape_and_uniqueness(self):
370 first, second = protocol.new_trace_id(), protocol.new_trace_id()
371 self.assertEqual(len(first), 26)
372 self.assertNotEqual(first, second)
373 self.assertTrue(set(first) <= set("0123456789ABCDEFGHJKMNPQRSTVWXYZ"))
374
375
376if __name__ == "__main__":
377 unittest.main()