| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | import asyncio |
| 14 | import json |
| 15 | import struct |
| 16 | import unittest |
| 17 | |
| 18 | from src.bridge.contract import (AI_CHAT_CAPABILITY, AI_ALPN, |
| 19 | AI_MAX_CONCURRENT_PER_WORKER, AI_MAX_FRAME_BYTES, |
| 20 | AI_PROTOCOL, AI_RAG_CHAT_CAPABILITY, |
| 21 | AI_RAG_INDEX_CAPABILITY, |
| 22 | AI_RAG_QUESTIONS_CAPABILITY, |
| 23 | AI_RAG_SUMMARIZE_CAPABILITY, ApiError, ApiRequest, |
| 24 | ASSIGNABLE_ROLES, BlobRequest, ChatReplyPayload, |
| 25 | ChatRequestPayload, ChatTurn, FrameStream, |
| 26 | FrameTooLarge, HandshakeRejected, RagFile, |
| 27 | RagIndexPayload, RagIndexReply, |
| 28 | RagIndexReplyFile, RagQuestion, |
| 29 | RagQuestionsReplyPayload, |
| 30 | RagQuestionsRequestPayload, RagScope, |
| 31 | RagScopePair, RagSummarizeReplyPayload, |
| 32 | RagSummarizeRequestPayload, RagSummaryCitation, |
| 33 | build_hello, decode_api_response, encode_frame, |
| 34 | parse_greeting) |
| 35 | |
| 36 | |
| 37 | class YetenekAdlariTests(unittest.TestCase): |
| 38 | def test_capability_strings(self): |
| 39 | self.assertEqual(AI_CHAT_CAPABILITY, "chat.reply") |
| 40 | self.assertEqual(AI_RAG_INDEX_CAPABILITY, "rag.index") |
| 41 | self.assertEqual(AI_RAG_CHAT_CAPABILITY, "rag.chat") |
| 42 | self.assertEqual(AI_RAG_SUMMARIZE_CAPABILITY, "rag.summarize") |
| 43 | self.assertEqual(AI_RAG_QUESTIONS_CAPABILITY, "rag.questions") |
| 44 | |
| 45 | def test_protocol_name(self): |
| 46 | self.assertEqual(AI_PROTOCOL, "hab/2") |
| 47 | |
| 48 | def test_ai_is_not_an_assignable_role(self): |
| 49 | |
| 50 | self.assertNotIn("ai", ASSIGNABLE_ROLES) |
| 51 | self.assertEqual(ASSIGNABLE_ROLES, |
| 52 | ("parent", "student", "teacher", "manager", "admin")) |
| 53 | |
| 54 | |
| 55 | class RagIndexTelBicimiTests(unittest.TestCase): |
| 56 | def test_keys_match_the_rust_test_exactly(self): |
| 57 | p = RagIndexPayload(course_note="01NOTE", course="01COURSE", |
| 58 | author="01AUTHOR", title="Chapter 3", |
| 59 | content="quadratics", |
| 60 | files=[RagFile("01FILE", "recap.pdf", |
| 61 | "application/pdf", 12)]) |
| 62 | self.assertEqual(p.to_wire(), { |
| 63 | "course_note": "01NOTE", "course": "01COURSE", "author": "01AUTHOR", |
| 64 | "title": "Chapter 3", "content": "quadratics", |
| 65 | "files": [{"id": "01FILE", "name": "recap.pdf", |
| 66 | "content_type": "application/pdf", "size": 12}]}) |
| 67 | |
| 68 | def test_files_is_optional_on_the_wire(self): |
| 69 | |
| 70 | |
| 71 | p = RagIndexPayload.from_wire({"course_note": "01NOTE", "course": "01C", |
| 72 | "author": "01A", "title": "t", "content": "c"}) |
| 73 | self.assertEqual(p.files, []) |
| 74 | |
| 75 | def test_index_reply_keys_are_id_and_doc_id(self): |
| 76 | |
| 77 | |
| 78 | |
| 79 | r = RagIndexReply(files=[RagIndexReplyFile(id="01FILE", doc_id="5eda1f0a9c32")]) |
| 80 | self.assertEqual(r.to_wire(), { |
| 81 | "files": [{"id": "01FILE", "doc_id": "5eda1f0a9c32"}]}) |
| 82 | |
| 83 | def test_index_reply_round_trips(self): |
| 84 | w = {"files": [{"id": "01A", "doc_id": "d1"}, {"id": "01B", "doc_id": "d2"}]} |
| 85 | r = RagIndexReply.from_wire(w) |
| 86 | self.assertEqual(r.to_wire(), w) |
| 87 | self.assertEqual(RagIndexReply.from_wire({}).files, []) |
| 88 | |
| 89 | def test_scope_pair_keys_are_sinif_and_ders(self): |
| 90 | |
| 91 | |
| 92 | |
| 93 | self.assertEqual(RagScopePair(sinif="10", ders="biyoloji").to_wire(), |
| 94 | {"sinif": "10", "ders": "biyoloji"}) |
| 95 | self.assertEqual(RagScopePair.from_wire({"sinif": "", "ders": "satranc"}).to_wire(), |
| 96 | {"sinif": None, "ders": "satranc"}) |
| 97 | self.assertEqual(RagScopePair.from_wire({"ders": "satranc"}).sinif, None) |
| 98 | |
| 99 | |
| 100 | class RagOzetSoruTelBicimiTests(unittest.TestCase): |
| 101 | |
| 102 | |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | def test_scope_keys_match_the_contract(self): |
| 108 | s = RagScope(ders="biyoloji", sinif="10", pages=[16, 17], |
| 109 | span_ids=[], scope_label="DNA") |
| 110 | self.assertEqual(s.to_wire(), {"sinif": "10", "ders": "biyoloji", |
| 111 | "pages": [16, 17], "span_ids": [], |
| 112 | "scope_label": "DNA"}) |
| 113 | self.assertEqual(RagScope.from_wire({"sinif": "", "ders": "satranc"}).sinif, |
| 114 | None) |
| 115 | |
| 116 | def test_summarize_request_keys(self): |
| 117 | p = RagSummarizeRequestPayload.from_wire({ |
| 118 | "scope": {"sinif": "10", "ders": "biyoloji", "pages": [16], |
| 119 | "span_ids": [], "scope_label": "DNA"}, |
| 120 | "asker": "U-1", "asker_role": "teacher"}) |
| 121 | self.assertEqual(p.to_wire(), { |
| 122 | "scope": {"sinif": "10", "ders": "biyoloji", "pages": [16], |
| 123 | "span_ids": [], "scope_label": "DNA"}, |
| 124 | "asker": "U-1", "asker_role": "teacher", "scope_pairs": []}) |
| 125 | |
| 126 | def test_questions_request_defaults_and_keys(self): |
| 127 | |
| 128 | |
| 129 | p = RagQuestionsRequestPayload.from_wire({ |
| 130 | "scope": {"ders": "biyoloji", "pages": [16]}, |
| 131 | "asker": "U-1", "asker_role": "student"}) |
| 132 | self.assertEqual(p.n, 5) |
| 133 | self.assertEqual(p.difficulty, "orta") |
| 134 | self.assertIsNone(p.seed_question) |
| 135 | self.assertEqual(p.to_wire()["seed_question"], None) |
| 136 | |
| 137 | def test_summarize_reply_keys(self): |
| 138 | r = RagSummarizeReplyPayload( |
| 139 | text="özet", citations=[RagSummaryCitation(n=1, span_ids=["s1"], |
| 140 | pages=[16, 17])], |
| 141 | scope_pages=[16, 17], hierarchical=True) |
| 142 | self.assertEqual(r.to_wire(), { |
| 143 | "text": "özet", "abstained": False, "reason": "", |
| 144 | "citations": [{"n": 1, "span_ids": ["s1"], "pages": [16, 17]}], |
| 145 | "scope_pages": [16, 17], "hierarchical": True}) |
| 146 | |
| 147 | def test_refusal_dicts_parse_with_missing_optionals(self): |
| 148 | |
| 149 | |
| 150 | |
| 151 | ozet = RagSummarizeReplyPayload.from_wire({ |
| 152 | "text": "", "abstained": True, "reason": "empty_scope"}) |
| 153 | self.assertTrue(ozet.abstained) |
| 154 | self.assertEqual(ozet.citations, []) |
| 155 | self.assertEqual(ozet.scope_pages, []) |
| 156 | self.assertFalse(ozet.hierarchical) |
| 157 | |
| 158 | soru = RagQuestionsReplyPayload.from_wire( |
| 159 | {"items": [], "span_ids": [], "pages": []}) |
| 160 | self.assertEqual(soru.items, []) |
| 161 | self.assertFalse(soru.abstained) |
| 162 | self.assertEqual(soru.reason, "") |
| 163 | |
| 164 | def test_questions_reply_mirrors_service_keys_verbatim(self): |
| 165 | r = RagQuestionsReplyPayload.from_wire({ |
| 166 | "items": [{"soru": "s", "cevap": "c", "zorluk": "zor"}], |
| 167 | "abstained": False, "reason": "", "span_ids": ["s1"], "pages": [16]}) |
| 168 | self.assertEqual(r.to_wire()["items"], |
| 169 | [{"soru": "s", "cevap": "c", "zorluk": "zor"}]) |
| 170 | self.assertEqual(RagQuestion.from_wire({}).to_wire(), |
| 171 | {"soru": "", "cevap": "", "zorluk": ""}) |
| 172 | |
| 173 | |
| 174 | class ChatTelBicimiTests(unittest.TestCase): |
| 175 | def test_request_keys(self): |
| 176 | p = ChatRequestPayload(message="merhaba", asker_role="student", |
| 177 | history=[ChatTurn("user", "önceki"), |
| 178 | ChatTurn("assistant", "cevap")]) |
| 179 | self.assertEqual(p.to_wire(), { |
| 180 | "message": "merhaba", "asker_role": "student", |
| 181 | "history": [{"role": "user", "content": "önceki"}, |
| 182 | {"role": "assistant", "content": "cevap"}]}) |
| 183 | |
| 184 | def test_history_is_optional(self): |
| 185 | p = ChatRequestPayload.from_wire({"message": "hi", "asker_role": "student"}) |
| 186 | self.assertEqual(p.history, []) |
| 187 | |
| 188 | def test_history_is_oldest_first(self): |
| 189 | |
| 190 | |
| 191 | |
| 192 | p = ChatRequestPayload.from_wire({ |
| 193 | "message": "3.", "asker_role": "student", |
| 194 | "history": [{"role": "user", "content": "1."}, |
| 195 | {"role": "assistant", "content": "2."}]}) |
| 196 | self.assertEqual([t.content for t in p.history], ["1.", "2."]) |
| 197 | |
| 198 | def test_reply_carries_text_only(self): |
| 199 | |
| 200 | |
| 201 | |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | self.assertEqual(ChatReplyPayload(text="cevap").to_wire(), {"text": "cevap"}) |
| 207 | |
| 208 | def test_request_has_no_asker_identity(self): |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | alanlar = set(ChatRequestPayload(message="m", asker_role="student").to_wire()) |
| 214 | self.assertEqual(alanlar, {"message", "asker_role", "history"}) |
| 215 | for yasak in ("user", "user_id", "asker", "student", "class", "course"): |
| 216 | self.assertNotIn(yasak, alanlar) |
| 217 | |
| 218 | |
| 219 | class ApiOkumaTests(unittest.TestCase): |
| 220 | def test_minimal_request_omits_optional_keys(self): |
| 221 | r = ApiRequest(id="01T", school="demo", path="/users/me") |
| 222 | self.assertEqual(r.to_wire(), {"id": "01T", "school": "demo", |
| 223 | "path": "/users/me"}) |
| 224 | |
| 225 | def test_on_behalf_of_and_query_are_carried(self): |
| 226 | r = ApiRequest(id="01T", school="demo", path="/notes", |
| 227 | query="limit=10&offset=0", on_behalf_of="01USER") |
| 228 | self.assertEqual(r.to_wire()["query"], "limit=10&offset=0") |
| 229 | self.assertEqual(r.to_wire()["on_behalf_of"], "01USER") |
| 230 | |
| 231 | def test_blob_request_shape(self): |
| 232 | b = BlobRequest(id="01T", school="demo", file="01FILE", |
| 233 | on_behalf_of="01AUTHOR") |
| 234 | self.assertEqual(b.to_wire(), {"id": "01T", "school": "demo", |
| 235 | "file": "01FILE", "on_behalf_of": "01AUTHOR"}) |
| 236 | |
| 237 | def test_404_is_an_ok_outcome_not_an_error(self): |
| 238 | |
| 239 | |
| 240 | status, body = decode_api_response({"outcome": "ok", "id": "1", |
| 241 | "school": "demo", "status": 404, |
| 242 | "body": None}) |
| 243 | self.assertEqual(status, 404) |
| 244 | self.assertIsNone(body) |
| 245 | |
| 246 | def test_bridge_refusal_raises(self): |
| 247 | with self.assertRaises(ApiError): |
| 248 | decode_api_response({"outcome": "err", "id": "1", "school": "demo", |
| 249 | "code": "forbidden_path", "message": "no"}) |
| 250 | |
| 251 | |
| 252 | class ElSikismaTelBicimiTests(unittest.TestCase): |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | def test_alpn_is_hab2(self): |
| 259 | |
| 260 | self.assertEqual(AI_ALPN, "hab/2") |
| 261 | |
| 262 | def test_hello_keys_are_the_wire_names(self): |
| 263 | hello = build_hello("rag", ("rag.chat", "rag.index"), "tok", 4) |
| 264 | self.assertEqual(sorted(hello), ["capabilities", "max_concurrent", |
| 265 | "protocol", "service", "token"]) |
| 266 | self.assertEqual(hello["protocol"], AI_PROTOCOL) |
| 267 | self.assertEqual(hello["capabilities"], ["rag.chat", "rag.index"]) |
| 268 | self.assertNotIn("school", hello) |
| 269 | |
| 270 | def test_hello_max_concurrent_is_clamped(self): |
| 271 | |
| 272 | self.assertEqual(build_hello("rag", ("rag.chat",), "t", 999)["max_concurrent"], |
| 273 | AI_MAX_CONCURRENT_PER_WORKER) |
| 274 | self.assertEqual(build_hello("rag", ("rag.chat",), "t", 0)["max_concurrent"], 1) |
| 275 | |
| 276 | def test_greeting_welcome_returns_worker_id(self): |
| 277 | self.assertEqual( |
| 278 | parse_greeting({"type": "welcome", "worker_id": "W1", |
| 279 | "protocol": AI_PROTOCOL}), "W1") |
| 280 | |
| 281 | def test_greeting_rejection_carries_code_and_permanence(self): |
| 282 | with self.assertRaises(HandshakeRejected) as ctx: |
| 283 | parse_greeting({"type": "rejected", "code": "unauthorized", |
| 284 | "message": "invalid token"}) |
| 285 | self.assertEqual(ctx.exception.code, "unauthorized") |
| 286 | self.assertTrue(ctx.exception.permanent) |
| 287 | |
| 288 | def test_greeting_version_mismatch_is_rejected(self): |
| 289 | |
| 290 | with self.assertRaises(HandshakeRejected) as ctx: |
| 291 | parse_greeting({"type": "welcome", "worker_id": "W1", |
| 292 | "protocol": "hab/1"}) |
| 293 | self.assertEqual(ctx.exception.code, "unsupported_protocol") |
| 294 | |
| 295 | def test_frame_is_length_prefixed_json(self): |
| 296 | ham = encode_frame({"a": 1}) |
| 297 | uzunluk = int.from_bytes(ham[:4], "big") |
| 298 | self.assertEqual(uzunluk, len(ham) - 4) |
| 299 | self.assertEqual(json.loads(ham[4:]), {"a": 1}) |
| 300 | |
| 301 | def test_oversize_length_prefix_is_refused_before_the_body(self): |
| 302 | |
| 303 | |
| 304 | async def senaryo() -> None: |
| 305 | akis = FrameStream() |
| 306 | |
| 307 | akis.feed(struct.pack(">I", AI_MAX_FRAME_BYTES + 1), end=False) |
| 308 | with self.assertRaises(FrameTooLarge): |
| 309 | await akis.read_frame() |
| 310 | |
| 311 | asyncio.run(senaryo()) |
| 312 | |
| 313 | def test_partial_stream_raises_eof(self): |
| 314 | async def senaryo() -> None: |
| 315 | akis = FrameStream() |
| 316 | akis.feed(encode_frame({"x": "y"})[:6], end=True) |
| 317 | with self.assertRaises(EOFError): |
| 318 | await akis.read_frame() |
| 319 | |
| 320 | asyncio.run(senaryo()) |
| 321 | |
| 322 | |
| 323 | if __name__ == "__main__": |
| 324 | unittest.main() |