| 1 | import asyncio |
| 2 | import base64 |
| 3 | import hashlib |
| 4 | import json |
| 5 | import struct |
| 6 | import tempfile |
| 7 | import threading |
| 8 | import unittest |
| 9 | from unittest import mock |
| 10 | |
| 11 | from src import protocol |
| 12 | from tests.regress.regress_unanswered_stream import ( |
| 13 | FakeQuic, |
| 14 | decode_frame, |
| 15 | install_fake_aioquic, |
| 16 | ) |
| 17 | |
| 18 | |
| 19 | class FramingTests(unittest.TestCase): |
| 20 | def test_length_prefix_is_four_byte_big_endian(self) -> None: |
| 21 | self.assertEqual( |
| 22 | protocol.encode_frame({})[:4], |
| 23 | b"\x00\x00\x00\x02", |
| 24 | "uzunluk oneki 4 bayt big-endian olmali", |
| 25 | ) |
| 26 | |
| 27 | def test_body_is_utf8_json_without_ascii_escaping(self) -> None: |
| 28 | frame = protocol.encode_frame({"k": "cok"}) |
| 29 | self.assertEqual(json.loads(frame[4:].decode("utf-8")), {"k": "cok"}) |
| 30 | |
| 31 | def test_encode_frame_raises_frame_too_large_above_eight_mib(self) -> None: |
| 32 | large = {"payload": "a" * (protocol.MAX_FRAME_BYTES + 16)} |
| 33 | with self.assertRaises(protocol.CapabilityError) as raised: |
| 34 | protocol.encode_frame(large) |
| 35 | self.assertEqual( |
| 36 | raised.exception.code, |
| 37 | "frame_too_large", |
| 38 | "8 MiB ustu cerceve 'frame_too_large' kodu ile reddedilmeli", |
| 39 | ) |
| 40 | |
| 41 | def test_round_trip_survives_split_across_chunk_boundary(self) -> None: |
| 42 | message = protocol.build_hello("podcast", ["podcast.submit"], "gizli", 2) |
| 43 | |
| 44 | async def round_trip() -> object: |
| 45 | stream = protocol.FrameStream() |
| 46 | encoded = protocol.encode_frame(message) |
| 47 | stream.feed(encoded[:3], end=False) |
| 48 | stream.feed(encoded[3:7], end=False) |
| 49 | stream.feed(encoded[7:], end=True) |
| 50 | return await stream.read_frame() |
| 51 | |
| 52 | self.assertEqual( |
| 53 | asyncio.run(round_trip()), |
| 54 | message, |
| 55 | "cerceve parcali beslendiginde gidis-donus bozulmamali", |
| 56 | ) |
| 57 | |
| 58 | def test_declared_length_above_limit_is_rejected_before_body_read(self) -> None: |
| 59 | async def run() -> None: |
| 60 | stream = protocol.FrameStream() |
| 61 | stream.feed(struct.pack(">I", protocol.MAX_FRAME_BYTES + 1), end=True) |
| 62 | await stream.read_frame() |
| 63 | |
| 64 | with self.assertRaises(protocol.CapabilityError) as raised: |
| 65 | asyncio.run(run()) |
| 66 | self.assertEqual(raised.exception.code, "frame_too_large") |
| 67 | |
| 68 | def test_truncated_frame_raises_eof_not_silent_none(self) -> None: |
| 69 | async def run() -> None: |
| 70 | stream = protocol.FrameStream() |
| 71 | stream.feed(struct.pack(">I", 32) + b"{", end=True) |
| 72 | await stream.read_frame() |
| 73 | |
| 74 | with self.assertRaises(EOFError): |
| 75 | asyncio.run(run()) |
| 76 | |
| 77 | |
| 78 | class HelloAndGreetingTests(unittest.TestCase): |
| 79 | def test_hello_carries_protocol_service_capabilities_token_and_concurrency(self) -> None: |
| 80 | hello = protocol.build_hello("podcast", ["a", "b"], "sir", 3) |
| 81 | self.assertEqual( |
| 82 | hello, |
| 83 | { |
| 84 | "protocol": protocol.PROTOCOL, |
| 85 | "service": "podcast", |
| 86 | "capabilities": ["a", "b"], |
| 87 | "token": "sir", |
| 88 | "max_concurrent": 3, |
| 89 | }, |
| 90 | ) |
| 91 | |
| 92 | def test_protocol_identifier_is_hab_two(self) -> None: |
| 93 | self.assertEqual( |
| 94 | protocol.PROTOCOL, |
| 95 | "hab/2", |
| 96 | "backend hem ALPN'de hem Hello'da hab/2 disini reddediyor; " |
| 97 | "hab/1 ile servis uretimde oludur", |
| 98 | ) |
| 99 | |
| 100 | def test_welcome_greeting_returns_worker_id(self) -> None: |
| 101 | greeting = {"type": "welcome", "worker_id": "w7", "protocol": protocol.PROTOCOL} |
| 102 | self.assertEqual(protocol.parse_greeting(greeting), "w7") |
| 103 | |
| 104 | def test_welcome_with_wrong_protocol_is_rejected_as_unsupported_protocol(self) -> None: |
| 105 | for wrong in ("hab/9", "hab/1", "HAB/2", ""): |
| 106 | with self.subTest(protocol=wrong): |
| 107 | with self.assertRaises(protocol.HandshakeRejected) as raised: |
| 108 | protocol.parse_greeting({"type": "welcome", "protocol": wrong}) |
| 109 | self.assertEqual(raised.exception.code, "unsupported_protocol") |
| 110 | |
| 111 | def test_non_welcome_greeting_propagates_backend_error_code(self) -> None: |
| 112 | with self.assertRaises(protocol.HandshakeRejected) as raised: |
| 113 | protocol.parse_greeting({"code": "unauthorized", "message": "kotu token"}) |
| 114 | self.assertEqual(raised.exception.code, "unauthorized") |
| 115 | |
| 116 | def test_non_object_greeting_is_rejected_as_malformed(self) -> None: |
| 117 | for greeting in ([], "welcome", 3, None): |
| 118 | with self.subTest(greeting=greeting): |
| 119 | with self.assertRaises(protocol.HandshakeRejected) as raised: |
| 120 | protocol.parse_greeting(greeting) |
| 121 | self.assertEqual(raised.exception.code, "malformed") |
| 122 | |
| 123 | def test_unauthorized_and_unsupported_protocol_are_permanent_rejects(self) -> None: |
| 124 | self.assertTrue(protocol.HandshakeRejected("unauthorized", "x").permanent) |
| 125 | self.assertTrue( |
| 126 | protocol.HandshakeRejected("unsupported_protocol", "x").permanent |
| 127 | ) |
| 128 | self.assertFalse(protocol.HandshakeRejected("malformed", "x").permanent) |
| 129 | |
| 130 | |
| 131 | class SchoolEchoTests(unittest.TestCase): |
| 132 | def test_ok_response_echoes_the_school(self) -> None: |
| 133 | self.assertEqual( |
| 134 | protocol.ok_response("r1", "ataturk-ortaokulu", {"job_id": "J"}), |
| 135 | { |
| 136 | "status": "ok", |
| 137 | "id": "r1", |
| 138 | "school": "ataturk-ortaokulu", |
| 139 | "payload": {"job_id": "J"}, |
| 140 | }, |
| 141 | "backend Response::Ok 'school' alanini ZORUNLU tutuyor; " |
| 142 | "yankilanmazsa cevap okunamaz", |
| 143 | ) |
| 144 | |
| 145 | def test_err_response_echoes_the_school(self) -> None: |
| 146 | self.assertEqual( |
| 147 | protocol.err_response("r1", "ataturk-ortaokulu", "busy", "dolu"), |
| 148 | { |
| 149 | "status": "err", |
| 150 | "id": "r1", |
| 151 | "school": "ataturk-ortaokulu", |
| 152 | "code": "busy", |
| 153 | "message": "dolu", |
| 154 | }, |
| 155 | ) |
| 156 | |
| 157 | def test_api_request_carries_the_school(self) -> None: |
| 158 | request = protocol.build_api_request("r1", "ataturk-ortaokulu", "/auth/me") |
| 159 | self.assertEqual( |
| 160 | request["school"], |
| 161 | "ataturk-ortaokulu", |
| 162 | "hab/2 ApiRequest 'school' istiyor; yoksa backend 'malformed' doner", |
| 163 | ) |
| 164 | self.assertEqual(request["id"], "r1") |
| 165 | self.assertEqual(request["path"], "/auth/me") |
| 166 | |
| 167 | def test_api_request_without_a_school_is_refused(self) -> None: |
| 168 | for school in ("", " ", None, 7): |
| 169 | with self.subTest(school=school): |
| 170 | with self.assertRaises(protocol.ApiRefused) as raised: |
| 171 | protocol.build_api_request("r1", school, "/auth/me") |
| 172 | self.assertEqual(raised.exception.code, "malformed") |
| 173 | |
| 174 | def test_api_response_exposes_the_echoed_school(self) -> None: |
| 175 | answer = protocol.parse_api_response( |
| 176 | {"outcome": "ok", "id": "r1", "school": "ataturk-ortaokulu", "status": 200} |
| 177 | ) |
| 178 | self.assertEqual(answer.school, "ataturk-ortaokulu") |
| 179 | with self.assertRaises(protocol.ApiRefused) as raised: |
| 180 | protocol.parse_api_response( |
| 181 | { |
| 182 | "outcome": "err", |
| 183 | "id": "r1", |
| 184 | "school": "ataturk-ortaokulu", |
| 185 | "code": "path_not_allowed", |
| 186 | "message": "x", |
| 187 | } |
| 188 | ) |
| 189 | self.assertEqual(raised.exception.school, "ataturk-ortaokulu") |
| 190 | |
| 191 | |
| 192 | class RequestParsingTests(unittest.TestCase): |
| 193 | def test_valid_request_is_unpacked(self) -> None: |
| 194 | parsed = protocol.parse_request( |
| 195 | { |
| 196 | "id": "r1", |
| 197 | "school": "ataturk-ortaokulu", |
| 198 | "capability": "podcast.status", |
| 199 | "payload": {"job_id": "J"}, |
| 200 | } |
| 201 | ) |
| 202 | self.assertEqual(parsed[0], "r1") |
| 203 | self.assertEqual(parsed[1], "ataturk-ortaokulu") |
| 204 | self.assertEqual(parsed[2], "podcast.status") |
| 205 | self.assertEqual(parsed[3], {"job_id": "J"}) |
| 206 | self.assertIsNone(parsed[4], "deadline_ms yoksa zaman asimi None olmali") |
| 207 | |
| 208 | def test_unparseable_frames_raise_bad_request(self) -> None: |
| 209 | for frame in ( |
| 210 | [], |
| 211 | "istek", |
| 212 | None, |
| 213 | {}, |
| 214 | {"id": 7, "school": "o", "capability": "podcast.status"}, |
| 215 | {"id": "r1", "school": "o", "capability": 7}, |
| 216 | {"school": "o", "capability": "podcast.status"}, |
| 217 | {"id": "r1", "capability": "podcast.status"}, |
| 218 | ): |
| 219 | with self.subTest(frame=frame): |
| 220 | with self.assertRaises(protocol.CapabilityError) as raised: |
| 221 | protocol.parse_request(frame) |
| 222 | self.assertEqual( |
| 223 | raised.exception.code, |
| 224 | "bad_request", |
| 225 | "ayristirilamayan istek 'bad_request' ile reddedilmeli", |
| 226 | ) |
| 227 | |
| 228 | def test_a_request_without_a_school_is_rejected_instead_of_guessed(self) -> None: |
| 229 | for school in (None, "", " ", 7, ["o"]): |
| 230 | with self.subTest(school=school): |
| 231 | with self.assertRaises(protocol.CapabilityError) as raised: |
| 232 | protocol.parse_request( |
| 233 | { |
| 234 | "id": "r1", |
| 235 | "school": school, |
| 236 | "capability": "podcast.status", |
| 237 | "payload": {}, |
| 238 | } |
| 239 | ) |
| 240 | self.assertEqual(raised.exception.code, "bad_request") |
| 241 | |
| 242 | def test_deadline_margin_is_subtracted_so_answer_beats_backend_timeout(self) -> None: |
| 243 | timeout = protocol.parse_request( |
| 244 | { |
| 245 | "id": "r1", |
| 246 | "school": "o", |
| 247 | "capability": "podcast.status", |
| 248 | "deadline_ms": 60000, |
| 249 | } |
| 250 | )[4] |
| 251 | self.assertIsNotNone(timeout) |
| 252 | self.assertLess( |
| 253 | timeout, 60.0, "deadline payi birakilmali; cevap backend'in tavanindan once gitmeli" |
| 254 | ) |
| 255 | self.assertAlmostEqual(timeout, 60.0 - protocol.DEADLINE_MARGIN_SECS, places=6) |
| 256 | |
| 257 | def test_short_deadline_keeps_at_least_half_the_budget(self) -> None: |
| 258 | timeout = protocol.parse_request( |
| 259 | { |
| 260 | "id": "r1", |
| 261 | "school": "o", |
| 262 | "capability": "podcast.status", |
| 263 | "deadline_ms": 100, |
| 264 | } |
| 265 | )[4] |
| 266 | self.assertAlmostEqual(timeout, 0.05, places=6) |
| 267 | self.assertGreater(timeout, 0.0, "kisa deadline negatif zaman asimi uretmemeli") |
| 268 | |
| 269 | def test_non_positive_or_boolean_deadline_yields_no_timeout(self) -> None: |
| 270 | for value in (0, -1, True, False, "60000", None, [60000]): |
| 271 | with self.subTest(deadline_ms=value): |
| 272 | self.assertIsNone( |
| 273 | protocol.parse_request( |
| 274 | { |
| 275 | "id": "r1", |
| 276 | "school": "o", |
| 277 | "capability": "podcast.status", |
| 278 | "deadline_ms": value, |
| 279 | } |
| 280 | )[4] |
| 281 | ) |
| 282 | |
| 283 | |
| 284 | class ConstantTests(unittest.TestCase): |
| 285 | def test_wire_constants_match_the_documented_contract(self) -> None: |
| 286 | self.assertEqual(protocol.MAX_FRAME_BYTES, 8 * 1024 * 1024) |
| 287 | self.assertEqual(protocol.CERTIFICATE_PATH, "/ai/certificate") |
| 288 | self.assertEqual(protocol.KEEPALIVE_SECS, 10) |
| 289 | self.assertEqual(protocol.IDLE_TIMEOUT_SECS, 30.0) |
| 290 | self.assertLess( |
| 291 | protocol.KEEPALIVE_SECS, |
| 292 | protocol.IDLE_TIMEOUT_SECS, |
| 293 | "keepalive araligi idle timeout'tan kisa olmali", |
| 294 | ) |
| 295 | |
| 296 | |
| 297 | class _BridgeSettings: |
| 298 | def __init__(self, job_root: str) -> None: |
| 299 | self.job_root = job_root |
| 300 | self.service = "podcast" |
| 301 | self.token = "sir" |
| 302 | self.max_concurrent = 4 |
| 303 | self.backend_url = "http://127.0.0.1:1" |
| 304 | self.host = "127.0.0.1" |
| 305 | self.port = 1 |
| 306 | self.server_name = "localhost" |
| 307 | self.tls_fingerprint = "" |
| 308 | self.reconnect_secs = 0.05 |
| 309 | self.reconnect_max_secs = 1.0 |
| 310 | |
| 311 | def summary(self) -> str: |
| 312 | return "test ayarlari" |
| 313 | |
| 314 | |
| 315 | class _RegisteringQuic(FakeQuic): |
| 316 | def __init__(self, proto, greeting: dict) -> None: |
| 317 | super().__init__() |
| 318 | self._proto = proto |
| 319 | self._greeting = greeting |
| 320 | |
| 321 | def get_next_available_stream_id(self) -> int: |
| 322 | return 0 |
| 323 | |
| 324 | def send_stream_data(self, sid: int, data: bytes, end_stream: bool) -> None: |
| 325 | super().send_stream_data(sid, data, end_stream) |
| 326 | if not end_stream: |
| 327 | self._proto._streams[sid].feed( |
| 328 | protocol.encode_frame(self._greeting), end=True |
| 329 | ) |
| 330 | |
| 331 | |
| 332 | class BridgeRegistrationPath(unittest.TestCase): |
| 333 | @classmethod |
| 334 | def setUpClass(cls) -> None: |
| 335 | install_fake_aioquic() |
| 336 | from src import bridge |
| 337 | |
| 338 | cls.bridge = bridge |
| 339 | |
| 340 | def setUp(self) -> None: |
| 341 | from src import config |
| 342 | |
| 343 | self._log_level = config._active_level |
| 344 | config.set_log_level("error") |
| 345 | self._root = tempfile.TemporaryDirectory(prefix="podcast-hab2-") |
| 346 | self.settings = _BridgeSettings(self._root.name) |
| 347 | self.quic = FakeQuic() |
| 348 | self.proto = self.bridge.BridgeProtocol(settings=self.settings) |
| 349 | self.proto._quic = self.quic |
| 350 | |
| 351 | def tearDown(self) -> None: |
| 352 | from src import config |
| 353 | |
| 354 | config._active_level = self._log_level |
| 355 | self._root.cleanup() |
| 356 | |
| 357 | def test_the_registration_path_announces_hab_two_on_the_control_stream(self) -> None: |
| 358 | quic = _RegisteringQuic( |
| 359 | self.proto, |
| 360 | {"type": "welcome", "worker_id": "w1", "protocol": "hab/2"}, |
| 361 | ) |
| 362 | self.proto._quic = quic |
| 363 | asyncio.run(self.proto.register()) |
| 364 | sid, data, end = quic.written[0] |
| 365 | hello = decode_frame(data) |
| 366 | self.assertEqual( |
| 367 | hello["protocol"], |
| 368 | "hab/2", |
| 369 | "Hello hab/2 bildirmeli; backend sozlesmeyi ALPN'den SONRA burada da dogruluyor", |
| 370 | ) |
| 371 | self.assertEqual(hello["service"], "podcast") |
| 372 | self.assertEqual(hello["token"], "sir") |
| 373 | self.assertFalse( |
| 374 | end, "kontrol akisi kapatilmamali; kapanmasi backend icin kayittan dusmedir" |
| 375 | ) |
| 376 | |
| 377 | def test_a_response_frame_echoes_the_inbound_school(self) -> None: |
| 378 | from src import capabilities |
| 379 | |
| 380 | seen: list[str] = [] |
| 381 | |
| 382 | def handler(school: str, payload: dict) -> dict: |
| 383 | seen.append(school) |
| 384 | return {"job_id": "J"} |
| 385 | |
| 386 | capabilities.REGISTRY["podcast.okul"] = handler |
| 387 | try: |
| 388 | self.serve( |
| 389 | { |
| 390 | "id": "r-1", |
| 391 | "school": "ataturk-ortaokulu", |
| 392 | "capability": "podcast.okul", |
| 393 | "payload": {}, |
| 394 | } |
| 395 | ) |
| 396 | finally: |
| 397 | capabilities.REGISTRY.pop("podcast.okul", None) |
| 398 | response = decode_frame(self.quic.written[0][1]) |
| 399 | self.assertEqual(response["status"], "ok") |
| 400 | self.assertEqual(response["school"], "ataturk-ortaokulu") |
| 401 | self.assertEqual( |
| 402 | seen, ["ataturk-ortaokulu"], "okul isleyiciye ulasmali; payload'a gomulmemeli" |
| 403 | ) |
| 404 | |
| 405 | def test_an_err_frame_echoes_the_school_of_a_malformed_request(self) -> None: |
| 406 | self.serve({"id": "r-2", "school": "ataturk-ortaokulu", "capability": 7}) |
| 407 | response = decode_frame(self.quic.written[0][1]) |
| 408 | self.assertEqual(response["status"], "err") |
| 409 | self.assertEqual(response["code"], "bad_request") |
| 410 | self.assertEqual( |
| 411 | response["school"], |
| 412 | "ataturk-ortaokulu", |
| 413 | "cozulemeyen istekte bile okul yankilanmali; backend hangi okulun " |
| 414 | "istegi oldugunu ancak boyle anlar", |
| 415 | ) |
| 416 | |
| 417 | def test_an_unknown_capability_still_echoes_the_school(self) -> None: |
| 418 | self.serve( |
| 419 | { |
| 420 | "id": "r-3", |
| 421 | "school": "ataturk-ortaokulu", |
| 422 | "capability": "podcast.yok", |
| 423 | "payload": {}, |
| 424 | } |
| 425 | ) |
| 426 | response = decode_frame(self.quic.written[0][1]) |
| 427 | self.assertEqual(response["code"], "unsupported_capability") |
| 428 | self.assertEqual(response["school"], "ataturk-ortaokulu") |
| 429 | |
| 430 | def serve(self, frame: dict, sid: int = 1) -> None: |
| 431 | stream = protocol.FrameStream() |
| 432 | stream.feed(protocol.encode_frame(frame), end=True) |
| 433 | self.proto._streams[sid] = stream |
| 434 | asyncio.run(self.proto._serve_request(sid, stream)) |
| 435 | |
| 436 | |
| 437 | class _FakeHttpResponse: |
| 438 | def __init__(self, payload: dict) -> None: |
| 439 | self._body = json.dumps(payload).encode("utf-8") |
| 440 | |
| 441 | def __enter__(self) -> "_FakeHttpResponse": |
| 442 | return self |
| 443 | |
| 444 | def __exit__(self, *exc: object) -> bool: |
| 445 | return False |
| 446 | |
| 447 | def read(self) -> bytes: |
| 448 | return self._body |
| 449 | |
| 450 | |
| 451 | class CertificatePinTests(unittest.TestCase): |
| 452 | @classmethod |
| 453 | def setUpClass(cls) -> None: |
| 454 | install_fake_aioquic() |
| 455 | from src import bridge |
| 456 | |
| 457 | cls.bridge = bridge |
| 458 | |
| 459 | def setUp(self) -> None: |
| 460 | from src import config |
| 461 | |
| 462 | self._log_level = config._active_level |
| 463 | config.set_log_level("error") |
| 464 | |
| 465 | def tearDown(self) -> None: |
| 466 | from src import config |
| 467 | |
| 468 | config._active_level = self._log_level |
| 469 | |
| 470 | def certificate(self) -> tuple[str, str]: |
| 471 | der = b"\x30\x82\x01\x00" + bytes(range(64)) |
| 472 | body = base64.b64encode(der).decode("ascii") |
| 473 | pem = "-----BEGIN CERTIFICATE-----\n" + body + "\n-----END CERTIFICATE-----\n" |
| 474 | return pem, hashlib.sha256(der).hexdigest() |
| 475 | |
| 476 | def fetch(self, pem: str, reported: str, expected: str = "") -> str: |
| 477 | payload = {"certificate_pem": pem, "fingerprint_sha256": reported} |
| 478 | with mock.patch.object( |
| 479 | self.bridge.urllib.request, |
| 480 | "urlopen", |
| 481 | lambda url, timeout: _FakeHttpResponse(payload), |
| 482 | ): |
| 483 | return self.bridge.fetch_certificate("http://backend:8080", expected) |
| 484 | |
| 485 | def test_the_pin_is_compared_against_the_sha256_of_the_pems_own_der(self) -> None: |
| 486 | pem, fingerprint = self.certificate() |
| 487 | self.assertEqual( |
| 488 | self.fetch(pem, fingerprint, fingerprint), |
| 489 | pem, |
| 490 | "pin PEM'in DER'inden hesaplanan SHA-256 ile karsilastirilmali", |
| 491 | ) |
| 492 | |
| 493 | def test_a_pin_that_does_not_match_refuses_to_connect(self) -> None: |
| 494 | pem, fingerprint = self.certificate() |
| 495 | with self.assertRaises(RuntimeError) as raised: |
| 496 | self.fetch(pem, fingerprint, "0" * 64) |
| 497 | self.assertIn("PINLENEN", str(raised.exception)) |
| 498 | |
| 499 | def test_a_server_reporting_a_fingerprint_for_another_pem_is_refused(self) -> None: |
| 500 | pem, _ = self.certificate() |
| 501 | with self.assertRaises(RuntimeError): |
| 502 | self.fetch(pem, "0" * 64) |
| 503 | |
| 504 | def test_without_a_pin_the_certificate_is_trusted_on_first_use(self) -> None: |
| 505 | pem, fingerprint = self.certificate() |
| 506 | self.assertEqual(self.fetch(pem, fingerprint), pem) |
| 507 | |
| 508 | def test_a_missing_pem_is_an_error_not_an_empty_trust_store(self) -> None: |
| 509 | with self.assertRaises(RuntimeError): |
| 510 | self.fetch("", "0" * 64) |
| 511 | |
| 512 | |
| 513 | class ReconnectLoop(unittest.TestCase): |
| 514 | @classmethod |
| 515 | def setUpClass(cls) -> None: |
| 516 | install_fake_aioquic() |
| 517 | from src import bridge |
| 518 | |
| 519 | cls.bridge = bridge |
| 520 | |
| 521 | def setUp(self) -> None: |
| 522 | from src import config |
| 523 | |
| 524 | self._log_level = config._active_level |
| 525 | config.set_log_level("error") |
| 526 | self._root = tempfile.TemporaryDirectory(prefix="podcast-hab2-") |
| 527 | self.settings = _BridgeSettings(self._root.name) |
| 528 | |
| 529 | def tearDown(self) -> None: |
| 530 | from src import config |
| 531 | |
| 532 | config._active_level = self._log_level |
| 533 | self._root.cleanup() |
| 534 | |
| 535 | def test_backoff_doubles_and_stops_at_the_configured_ceiling(self) -> None: |
| 536 | self.settings.reconnect_secs = 3.0 |
| 537 | self.settings.reconnect_max_secs = 120.0 |
| 538 | self.assertEqual(self.bridge.next_backoff(3.0, self.settings), 6.0) |
| 539 | self.assertEqual(self.bridge.next_backoff(6.0, self.settings), 12.0) |
| 540 | self.assertEqual(self.bridge.next_backoff(100.0, self.settings), 120.0) |
| 541 | self.assertEqual( |
| 542 | self.bridge.next_backoff(120.0, self.settings), |
| 543 | self.settings.reconnect_max_secs, |
| 544 | "geri cekilme tavani asmamali; jitter de tavani kaydirmamali", |
| 545 | ) |
| 546 | |
| 547 | def test_a_permanent_reject_keeps_the_loop_retrying_instead_of_exiting(self) -> None: |
| 548 | attempts: list[int] = [] |
| 549 | |
| 550 | async def fake_run_once(settings) -> None: |
| 551 | attempts.append(1) |
| 552 | raise protocol.HandshakeRejected("unauthorized", "kotu token") |
| 553 | |
| 554 | async def scenario() -> None: |
| 555 | with mock.patch.object(self.bridge, "run_once", fake_run_once): |
| 556 | task = asyncio.ensure_future(self.bridge.run_forever(self.settings)) |
| 557 | await asyncio.sleep(0.2) |
| 558 | self.assertFalse( |
| 559 | task.done(), |
| 560 | "kalici red donguden CIKMAMALI: restart: unless-stopped ile " |
| 561 | "exit 2 sonsuz crash-loop olur ve backend duzelince servis " |
| 562 | "kendiliginden toparlanmaz", |
| 563 | ) |
| 564 | self.assertEqual(len(attempts), 1, "kalici red sonrasi sikistirmali deneme") |
| 565 | task.cancel() |
| 566 | await asyncio.sleep(0) |
| 567 | |
| 568 | asyncio.run(scenario()) |
| 569 | |
| 570 | def test_a_retryable_reject_schedules_the_next_attempt(self) -> None: |
| 571 | attempts: list[int] = [] |
| 572 | |
| 573 | async def fake_run_once(settings) -> None: |
| 574 | attempts.append(1) |
| 575 | raise protocol.HandshakeRejected("malformed", "bozuk greeting") |
| 576 | |
| 577 | async def scenario() -> None: |
| 578 | with mock.patch.object(self.bridge, "run_once", fake_run_once): |
| 579 | task = asyncio.ensure_future(self.bridge.run_forever(self.settings)) |
| 580 | await asyncio.sleep(0.6) |
| 581 | task.cancel() |
| 582 | await asyncio.sleep(0) |
| 583 | |
| 584 | asyncio.run(scenario()) |
| 585 | self.assertGreaterEqual( |
| 586 | len(attempts), 2, "gecici red sonrasi bir sonraki deneme zamanlanmali" |
| 587 | ) |
| 588 | |
| 589 | |
| 590 | def _report_record(**extra: object) -> dict: |
| 591 | record = { |
| 592 | "job_id": "j1", |
| 593 | "source_id": "ders.pdf", |
| 594 | "format": "duz_okuma", |
| 595 | "user_id": "u1", |
| 596 | "state": "done", |
| 597 | "stage": "done", |
| 598 | "progress": 1.0, |
| 599 | "error_code": None, |
| 600 | } |
| 601 | record.update(extra) |
| 602 | return record |
| 603 | |
| 604 | |
| 605 | def _reported_payload(record: dict) -> dict: |
| 606 | from src import backend |
| 607 | |
| 608 | seen: list[dict] = [] |
| 609 | |
| 610 | class Proto: |
| 611 | async def call_capability(self, school, capability, payload): |
| 612 | seen.append(dict(payload)) |
| 613 | return {"ok": True} |
| 614 | |
| 615 | loop = asyncio.new_event_loop() |
| 616 | ready = threading.Event() |
| 617 | |
| 618 | def spin() -> None: |
| 619 | asyncio.set_event_loop(loop) |
| 620 | ready.set() |
| 621 | loop.run_forever() |
| 622 | |
| 623 | thread = threading.Thread(target=spin, daemon=True) |
| 624 | thread.start() |
| 625 | if not ready.wait(2): |
| 626 | raise RuntimeError("olay dongusu acilmadi") |
| 627 | try: |
| 628 | backend.BackendClient(loop, Proto()).report("okul-a", record) |
| 629 | finally: |
| 630 | loop.call_soon_threadsafe(loop.stop) |
| 631 | thread.join(timeout=2) |
| 632 | loop.close() |
| 633 | if len(seen) != 1: |
| 634 | raise AssertionError(f"rapor cercevesi gitmedi: {seen}") |
| 635 | return seen[0] |
| 636 | |
| 637 | |
| 638 | class TranscriptFrameTests(unittest.TestCase): |
| 639 | def test_a_missing_transcript_stays_empty_and_the_frame_encodes(self) -> None: |
| 640 | payload = _reported_payload(_report_record()) |
| 641 | self.assertEqual(payload["transcript"], "") |
| 642 | frame = protocol.encode_frame( |
| 643 | { |
| 644 | "id": "1", |
| 645 | "school": "okul-a", |
| 646 | "capability": protocol.PODCAST_REPORT_CAPABILITY, |
| 647 | "payload": payload, |
| 648 | } |
| 649 | ) |
| 650 | decoded = json.loads(frame[4:]) |
| 651 | self.assertEqual(decoded["payload"]["transcript"], "") |
| 652 | |
| 653 | def test_an_empty_transcript_stays_empty_and_the_frame_encodes(self) -> None: |
| 654 | payload = _reported_payload(_report_record(transcript="")) |
| 655 | self.assertEqual(payload["transcript"], "") |
| 656 | frame = protocol.encode_frame({"payload": payload}) |
| 657 | decoded = json.loads(frame[4:]) |
| 658 | self.assertEqual(decoded["payload"]["transcript"], "") |
| 659 | |
| 660 | def test_the_done_report_frame_carries_the_transcript(self) -> None: |
| 661 | text = "ilk bolum\n\nikinci bolum" |
| 662 | payload = _reported_payload(_report_record(transcript=text)) |
| 663 | self.assertEqual(payload["transcript"], text) |
| 664 | frame = protocol.encode_frame( |
| 665 | { |
| 666 | "id": "2", |
| 667 | "school": "okul-a", |
| 668 | "capability": protocol.PODCAST_REPORT_CAPABILITY, |
| 669 | "payload": payload, |
| 670 | } |
| 671 | ) |
| 672 | decoded = json.loads(frame[4:]) |
| 673 | self.assertEqual(decoded["payload"]["transcript"], text) |
| 674 | self.assertLess(len(frame), protocol.MAX_FRAME_BYTES) |
| 675 | |
| 676 | |
| 677 | |
| 678 | if __name__ == "__main__": |
| 679 | unittest.main() |