| 1 | |
| 2 | import unittest |
| 3 | |
| 4 | from src.service import RagService |
| 5 | from src.generate.generator import GroundedAnswer |
| 6 | from src.summarize.summarizer import GroundedSummary |
| 7 | from src.generate.question_gen import GeneratedQuestionSet, GeneratedQuestion |
| 8 | from src.ingest.canonical import CanonicalDoc, CanonicalUnit |
| 9 | from src.guard.roles import Role |
| 10 | |
| 11 | |
| 12 | class _GenStub: |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | def __init__(self, ans): |
| 22 | self.ans = ans |
| 23 | self.last_role = "UNSET" |
| 24 | self.last_trace = None |
| 25 | |
| 26 | def answer(self, query, *, history=None, top_n=6, candidate_n=40, |
| 27 | role_ctx="UNSET", trace=None, **kw): |
| 28 | self.last_role = role_ctx |
| 29 | self.last_trace = trace |
| 30 | return self.ans |
| 31 | |
| 32 | |
| 33 | class _SumStub: |
| 34 | def __init__(self, res): self.res = res; self.last_units = None |
| 35 | def summarize(self, units, *, scope_label=""): self.last_units = units; return self.res |
| 36 | |
| 37 | |
| 38 | class _QGStub: |
| 39 | def __init__(self, res): self.res = res |
| 40 | def generate(self, units, *, n=5, difficulty="orta", seed_question=None): return self.res |
| 41 | |
| 42 | |
| 43 | def _doc(): |
| 44 | u = [CanonicalUnit(span_id=f"d#{p}.0", doc_id="d", sinif="12", ders="biyoloji", |
| 45 | kaynak_turu="ders_kitabi", page=p, bbox=(0, 0, 1, 1), block_no=0, |
| 46 | kind="paragraph", text=f"metin {p}", page_visual="mixed", |
| 47 | retrieval_disi=False) for p in (10, 11)] |
| 48 | return CanonicalDoc(source_path="d", doc_id="d", source_version="v", sinif="12", |
| 49 | ders="biyoloji", kaynak_turu="ders_kitabi", page_count=11, units=u) |
| 50 | |
| 51 | |
| 52 | _ANS = GroundedAnswer(text="Cevap [1].", citations=[{"n": 1, "chunk_id": "c1", |
| 53 | "span_ids": ["d#10.0"], "pages": [10], "ders": "biyoloji", |
| 54 | "doc_id": "d"}], |
| 55 | used_source_ids=["c1"], abstained=False, reason="", cost_usd=0.001) |
| 56 | |
| 57 | |
| 58 | class ChatTests(unittest.TestCase): |
| 59 | def test_chat_maps_answer_and_role(self): |
| 60 | g = _GenStub(_ANS) |
| 61 | svc = RagService(g) |
| 62 | out = svc.chat({"query": "DNA nedir", "role": {"role": "student", "sinif": "12", |
| 63 | "ders_list": ["biyoloji"]}}) |
| 64 | self.assertEqual(out["text"], "Cevap [1].") |
| 65 | self.assertFalse(out["abstained"]) |
| 66 | self.assertEqual(out["citations"][0]["pages"], [10]) |
| 67 | |
| 68 | |
| 69 | self.assertEqual(out["citations"][0]["doc_id"], "d") |
| 70 | self.assertEqual(g.last_role.role, Role.STUDENT) |
| 71 | self.assertEqual(g.last_role.ders_list, ["biyoloji"]) |
| 72 | |
| 73 | def test_empty_query_no_generator_call(self): |
| 74 | g = _GenStub(_ANS) |
| 75 | out = RagService(g).chat({"query": " "}) |
| 76 | self.assertTrue(out["abstained"]) |
| 77 | self.assertEqual(out["reason"], "empty_query") |
| 78 | self.assertEqual(g.last_role, "UNSET") |
| 79 | |
| 80 | def test_greeting_is_not_insufficient_data(self): |
| 81 | g = _GenStub(_ANS) |
| 82 | svc = RagService(g) |
| 83 | for q in ("selam", "merhaba"): |
| 84 | out = svc.chat({"query": q}) |
| 85 | self.assertNotEqual(out["reason"], "insufficient_data", q) |
| 86 | self.assertFalse(out["abstained"], q) |
| 87 | self.assertEqual(out["reason"], "", q) |
| 88 | self.assertEqual(out["citations"], [], q) |
| 89 | self.assertEqual(out["cost_usd"], 0.0, q) |
| 90 | self.assertFalse(out["cache_hit"], q) |
| 91 | self.assertTrue(out["text"].strip(), q) |
| 92 | self.assertNotIn("bulunamadı", out["text"]) |
| 93 | self.assertEqual(g.last_role, "UNSET") |
| 94 | |
| 95 | def test_non_greeting_question_still_calls_generator(self): |
| 96 | g = _GenStub(_ANS) |
| 97 | out = RagService(g).chat({ |
| 98 | "query": "Fotosentez nedir?", |
| 99 | "role": {"role": "student", "sinif": "12", "ders_list": ["biyoloji"]}, |
| 100 | }) |
| 101 | self.assertNotEqual(g.last_role, "UNSET") |
| 102 | self.assertEqual(g.last_role.role, Role.STUDENT) |
| 103 | self.assertEqual(out["text"], "Cevap [1].") |
| 104 | self.assertFalse(out["abstained"]) |
| 105 | |
| 106 | def test_invalid_role_becomes_none(self): |
| 107 | g = _GenStub(_ANS) |
| 108 | RagService(g).chat({"query": "q", "role": {"role": "hacker"}}) |
| 109 | self.assertIsNone(g.last_role) |
| 110 | |
| 111 | |
| 112 | class SummarizeTests(unittest.TestCase): |
| 113 | def _svc(self): |
| 114 | res = GroundedSummary(text="Özet [1].", citations=[{"n": 1, "span_ids": ["d#10.0"], |
| 115 | "pages": [10]}], scope_pages=[10, 11], cost_usd=0.02) |
| 116 | return RagService(_GenStub(_ANS), doc=_doc(), summarizer=_SumStub(res), ders="biyoloji") |
| 117 | |
| 118 | def test_summarize_scope(self): |
| 119 | out = self._svc().summarize({"scope": {"pages": [10, 11], "scope_label": "x"}, |
| 120 | "role": {"role": "student", "sinif": "12", "ders_list": ["biyoloji"]}}) |
| 121 | self.assertEqual(out["text"], "Özet [1].") |
| 122 | self.assertEqual(out["scope_pages"], [10, 11]) |
| 123 | |
| 124 | def test_summarize_empty_scope(self): |
| 125 | out = self._svc().summarize({"scope": {}}) |
| 126 | self.assertTrue(out["abstained"]); self.assertEqual(out["reason"], "empty_scope") |
| 127 | |
| 128 | def test_summarize_role_denied_wrong_ders(self): |
| 129 | out = self._svc().summarize({"scope": {"pages": [10]}, |
| 130 | "role": {"role": "student", "sinif": "12", "ders_list": ["kimya"]}}) |
| 131 | self.assertTrue(out["abstained"]); self.assertEqual(out["reason"], "role_denied") |
| 132 | |
| 133 | |
| 134 | class QuestionsTests(unittest.TestCase): |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | def _svc(self): |
| 143 | qres = GeneratedQuestionSet(items=[GeneratedQuestion("s1", "c1", "kolay")], |
| 144 | span_ids=["d#10.0"], pages=[10], cost_usd=0.01) |
| 145 | return RagService(_GenStub(_ANS), doc=_doc(), question_gen=_QGStub(qres), |
| 146 | ders="biyoloji") |
| 147 | |
| 148 | def test_generate_questions(self): |
| 149 | out = self._svc().generate_questions( |
| 150 | {"scope": {"pages": [10]}, "n": 3, |
| 151 | "role": {"role": "student", "sinif": "12", "ders_list": ["biyoloji"]}}) |
| 152 | self.assertEqual(len(out["items"]), 1) |
| 153 | self.assertEqual(out["items"][0]["soru"], "s1") |
| 154 | self.assertEqual(out["pages"], [10]) |
| 155 | |
| 156 | def test_generate_questions_without_role_is_denied(self): |
| 157 | out = self._svc().generate_questions({"scope": {"pages": [10]}, "n": 3}) |
| 158 | self.assertTrue(out["abstained"]) |
| 159 | self.assertEqual(out["reason"], "role_required") |
| 160 | self.assertEqual(out["items"], []) |
| 161 | |
| 162 | |
| 163 | class BudgetWiringTests(unittest.TestCase): |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | |
| 173 | @staticmethod |
| 174 | def _ans(cost: float) -> GroundedAnswer: |
| 175 | return GroundedAnswer(text="Cevap [1].", citations=[], used_source_ids=[], |
| 176 | abstained=False, reason="", cost_usd=cost) |
| 177 | |
| 178 | @staticmethod |
| 179 | def _gate(**kw): |
| 180 | from src.budget import BudgetGate |
| 181 | return BudgetGate(**kw) |
| 182 | |
| 183 | def test_school_cap_fires_and_is_per_school(self): |
| 184 | svc = RagService(_GenStub(self._ans(0.30)), |
| 185 | budget=self._gate(user_daily_usd=0.0, tenant_monthly_usd=0.50)) |
| 186 | req = {"query": "soru", "school": "okul-a"} |
| 187 | self.assertEqual(svc.chat(req)["reason"], "") |
| 188 | self.assertAlmostEqual(svc.budget.spent(tenant="okul-a"), 0.30) |
| 189 | self.assertEqual(svc.chat(req)["reason"], "") |
| 190 | red = svc.chat(req) |
| 191 | self.assertEqual(red["reason"], "budget_exceeded") |
| 192 | self.assertTrue(red["abstained"]) |
| 193 | self.assertEqual(red["cost_usd"], 0.0) |
| 194 | self.assertEqual(red["citations"], []) |
| 195 | |
| 196 | self.assertEqual(svc.chat({"query": "soru", "school": "okul-b"})["reason"], "") |
| 197 | self.assertAlmostEqual(svc.budget.spent(tenant="okul-b"), 0.30) |
| 198 | |
| 199 | def test_legacy_tenant_field_cannot_bypass_the_school_cap(self): |
| 200 | |
| 201 | svc = RagService(_GenStub(self._ans(0.30)), |
| 202 | budget=self._gate(user_daily_usd=0.0, tenant_monthly_usd=0.50)) |
| 203 | svc.budget.record(0.60, tenant="okul-a") |
| 204 | out = svc.chat({"query": "soru", "school": "okul-a", "tenant": "baska-okul"}) |
| 205 | self.assertEqual(out["reason"], "budget_exceeded") |
| 206 | |
| 207 | def test_summarize_and_questions_record_against_the_school(self): |
| 208 | |
| 209 | res = GroundedSummary(text="Özet [1].", citations=[], scope_pages=[10], cost_usd=0.30) |
| 210 | qres = GeneratedQuestionSet(items=[GeneratedQuestion("s1", "c1", "kolay")], |
| 211 | span_ids=["d#10.0"], pages=[10], cost_usd=0.30) |
| 212 | svc = RagService(_GenStub(_ANS), doc=_doc(), summarizer=_SumStub(res), |
| 213 | question_gen=_QGStub(qres), ders="biyoloji", |
| 214 | budget=self._gate(user_daily_usd=0.0, tenant_monthly_usd=0.50)) |
| 215 | req = {"school": "okul-a", "scope": {"pages": [10], "scope_label": "x"}, |
| 216 | "role": {"role": "student", "sinif": "12", "ders_list": ["biyoloji"]}} |
| 217 | ozet = svc.summarize(req) |
| 218 | self.assertEqual(ozet["reason"], "") |
| 219 | self.assertAlmostEqual(svc.budget.spent(tenant="okul-a"), 0.30) |
| 220 | soru = svc.generate_questions({**req, "n": 1}) |
| 221 | self.assertEqual(soru["reason"], "") |
| 222 | self.assertAlmostEqual(svc.budget.spent(tenant="okul-a"), 0.60) |
| 223 | red = svc.summarize(req) |
| 224 | self.assertEqual(red["reason"], "budget_exceeded") |
| 225 | self.assertTrue(red["abstained"]) |
| 226 | |
| 227 | |
| 228 | class ScopePairTests(unittest.TestCase): |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | def test_single_pair_matches_the_old_shape(self): |
| 234 | from src.service.handler import _role_ctx |
| 235 | from src.guard.roles import can_access |
| 236 | eski = _role_ctx({"role": "student", "sinif": "10", "ders_list": ["biyoloji"]}) |
| 237 | yeni = _role_ctx({"role": "student"}, [{"sinif": "10", "ders": "biyoloji"}]) |
| 238 | self.assertEqual((yeni.sinif, yeni.ders_list), (eski.sinif, eski.ders_list)) |
| 239 | korpuslar = [("10", "biyoloji"), ("10", "satranc"), ("11", "biyoloji")] |
| 240 | self.assertEqual([can_access(yeni, sinif=s, ders=d) for s, d in korpuslar], |
| 241 | [can_access(eski, sinif=s, ders=d) for s, d in korpuslar]) |
| 242 | self.assertEqual([can_access(yeni, sinif=s, ders=d) for s, d in korpuslar], |
| 243 | [True, False, False]) |
| 244 | |
| 245 | def test_pairs_do_not_open_the_cross_product(self): |
| 246 | |
| 247 | |
| 248 | from src.service.handler import _role_ctx |
| 249 | from src.guard.roles import can_access |
| 250 | ctx = _role_ctx({"role": "student"}, |
| 251 | [{"sinif": "10", "ders": "biyoloji"}, |
| 252 | {"sinif": None, "ders": "satranc"}]) |
| 253 | self.assertTrue(can_access(ctx, sinif="10", ders="biyoloji")) |
| 254 | self.assertTrue(can_access(ctx, sinif="", ders="satranc")) |
| 255 | self.assertFalse(can_access(ctx, sinif="11", ders="satranc")) |
| 256 | self.assertFalse(can_access(ctx, sinif="10", ders="satranc")) |
| 257 | self.assertFalse(can_access(ctx, sinif="10", ders="kimya")) |
| 258 | |
| 259 | def test_chat_uses_pairs_when_present(self): |
| 260 | g = _GenStub(_ANS) |
| 261 | out = RagService(g).chat({"query": "x", "role": {"role": "student"}, |
| 262 | "scope": [{"sinif": "10", "ders": "biyoloji"}]}) |
| 263 | self.assertFalse(out["abstained"]) |
| 264 | self.assertEqual(g.last_role.ders_list, ["biyoloji"]) |
| 265 | self.assertEqual(g.last_role.sinif, "10") |
| 266 | |
| 267 | def test_legacy_dict_scope_is_not_a_grant(self): |
| 268 | |
| 269 | |
| 270 | from src.service.handler import _role_ctx |
| 271 | ctx = _role_ctx({"role": "student", "sinif": "10", "ders_list": ["biyoloji"]}, |
| 272 | {"sinif": "10", "ders": "satranc"}) |
| 273 | self.assertIsNone(ctx.scope_pairs) |
| 274 | self.assertEqual(ctx.ders_list, ["biyoloji"]) |
| 275 | |
| 276 | def test_registry_routes_the_pair_shape(self): |
| 277 | |
| 278 | |
| 279 | from src.service.registry import CorpusRegistry |
| 280 | r = CorpusRegistry() |
| 281 | r.register(object(), school="okul-a", sinif="10", ders="biyoloji") |
| 282 | svc, sebep = r.resolve({"school": "okul-a", "scope": [{"sinif": "10", "ders": "biyoloji"}]}) |
| 283 | self.assertIsNotNone(svc) |
| 284 | self.assertEqual(sebep, "") |
| 285 | svc2, sebep2 = r.resolve({"school": "okul-a", "scope": [{"sinif": "10", "ders": "kimya"}]}) |
| 286 | self.assertIsNone(svc2) |
| 287 | self.assertEqual(sebep2, "no_corpus") |
| 288 | |
| 289 | |
| 290 | if __name__ == "__main__": |
| 291 | unittest.main() |