| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | import json |
| 8 | import tempfile |
| 9 | import unittest |
| 10 | from pathlib import Path |
| 11 | from unittest import mock |
| 12 | |
| 13 | from src.segment.cache import NullCache, ResponseCache |
| 14 | from src.segment.config import ( |
| 15 | DEFAULT_MODEL_IDS, |
| 16 | SegmentConfig, |
| 17 | SegmentConfigError, |
| 18 | ) |
| 19 | from src.segment.provider import ( |
| 20 | LIVE_MODELS, |
| 21 | MODEL_ALIASES, |
| 22 | PRICING, |
| 23 | BaseProvider, |
| 24 | BudgetExceeded, |
| 25 | BudgetGuard, |
| 26 | ChatResult, |
| 27 | DeepSeekProvider, |
| 28 | MockProvider, |
| 29 | ProviderError, |
| 30 | RateLimiter, |
| 31 | Usage, |
| 32 | build_provider, |
| 33 | cost_usd, |
| 34 | parse_item_from_prompt, |
| 35 | ) |
| 36 | from src.segment import provider as provider_mod |
| 37 | from src.segment.schema import parse_label_json |
| 38 | |
| 39 | |
| 40 | ITEM = { |
| 41 | "question_id": "q1", |
| 42 | "text": "Kalitim konusunda cekinik fenotipin gorulme kosulu hangisidir?", |
| 43 | "choices": ["Çekinik fenotip yalnız aa genotipinde görülür", |
| 44 | "Aa genotipinde de çekinik fenotip görülür", |
| 45 | "(12, 5)", "(7, -3)"], |
| 46 | "subject_name": "Kalıtım", |
| 47 | "course_name": "Biyoloji", |
| 48 | } |
| 49 | |
| 50 | |
| 51 | def cfg(**over): |
| 52 | c = SegmentConfig() |
| 53 | c.cache_enabled = False |
| 54 | c.rpm = 10 ** 6 |
| 55 | for k, v in over.items(): |
| 56 | setattr(c, k, v) |
| 57 | return c |
| 58 | |
| 59 | |
| 60 | class TestUsageAndCost(unittest.TestCase): |
| 61 | |
| 62 | def test_cache_alani_yoksa_hepsi_miss_sayilir(self): |
| 63 | u = Usage.from_api({"prompt_tokens": 100, "completion_tokens": 20}) |
| 64 | self.assertEqual((u.input_cache_hit, u.input_cache_miss, u.output), |
| 65 | (0, 100, 20)) |
| 66 | |
| 67 | def test_maliyet_hesabi(self): |
| 68 | u = Usage(input_cache_hit=0, input_cache_miss=1_000_000, output=1_000_000) |
| 69 | |
| 70 | self.assertAlmostEqual(cost_usd("deepseek-flash", u), 0.44 + 1.32, places=9) |
| 71 | self.assertAlmostEqual(cost_usd("deepseek-v4-pro", u), 1.32 + 3.96, places=9) |
| 72 | |
| 73 | def test_bilinmeyen_model_en_pahali_tarifeyle_ucretlenir(self): |
| 74 | u = Usage(input_cache_miss=1_000_000, output=0) |
| 75 | self.assertGreater(cost_usd("bilinmeyen-model", u), 0.0) |
| 76 | |
| 77 | |
| 78 | class TestModelCatalogRegression(unittest.TestCase): |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | def test_her_rol_modelinin_fiyat_satiri_var(self): |
| 90 | for role, model in DEFAULT_MODEL_IDS.items(): |
| 91 | with self.subTest(role=role, model=model): |
| 92 | key = MODEL_ALIASES.get(model, model) |
| 93 | self.assertIn(key, PRICING, |
| 94 | f"'{role}' rolunun modeli {model!r} fiyat " |
| 95 | "tablosunda yok -> en pahali tarifeye duser.") |
| 96 | |
| 97 | def test_uctaki_modellerin_fiyat_satiri_var(self): |
| 98 | for model in LIVE_MODELS: |
| 99 | self.assertIn(MODEL_ALIASES.get(model, model), PRICING) |
| 100 | |
| 101 | def test_olu_model_adlari_temizlendi(self): |
| 102 | for dead in ("deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash"): |
| 103 | self.assertNotIn(dead, PRICING) |
| 104 | self.assertNotIn(dead, MODEL_ALIASES) |
| 105 | self.assertNotIn(dead, DEFAULT_MODEL_IDS.values()) |
| 106 | |
| 107 | def test_rol_modelleri_uctaki_katalogun_icinde(self): |
| 108 | self.assertTrue(set(DEFAULT_MODEL_IDS.values()) <= set(LIVE_MODELS)) |
| 109 | |
| 110 | def test_bilinmeyen_model_hala_en_pahali_tarifeye_duser(self): |
| 111 | |
| 112 | u = Usage(input_cache_miss=1_000_000) |
| 113 | worst = max(PRICING.values(), key=lambda p: p["out"])["in_miss"] |
| 114 | self.assertAlmostEqual(cost_usd("uydurma-model", u), worst, places=9) |
| 115 | self.assertGreater(cost_usd("uydurma-model", u), |
| 116 | cost_usd("deepseek-flash", u)) |
| 117 | |
| 118 | |
| 119 | class TestThinking(unittest.TestCase): |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | |
| 126 | def _payload(self, **over): |
| 127 | c = cfg(api_key="sahte", **over) |
| 128 | p = DeepSeekProvider(c, budget=BudgetGuard(10.0), sleep=lambda _s: None) |
| 129 | return p, c |
| 130 | |
| 131 | def test_thinking_nesne_olarak_konur_metin_degil(self): |
| 132 | p, c = self._payload(thinking="enabled") |
| 133 | body = p.build_payload("soru", None, 0.0, "deepseek-v4-pro") |
| 134 | self.assertEqual(body["thinking"], {"type": "enabled"}) |
| 135 | self.assertNotIsInstance(body["thinking"], str) |
| 136 | |
| 137 | def test_disabled_da_nesne(self): |
| 138 | p, _ = self._payload(thinking="disabled") |
| 139 | body = p.build_payload("soru", None, 0.0, "deepseek-v4-pro") |
| 140 | self.assertEqual(body["thinking"], {"type": "disabled"}) |
| 141 | |
| 142 | def test_bos_deger_uca_hic_gonderilmez(self): |
| 143 | p, _ = self._payload(thinking="") |
| 144 | body = p.build_payload("soru", None, 0.0, "deepseek-v4-pro") |
| 145 | self.assertNotIn("thinking", body) |
| 146 | |
| 147 | def test_rol_varsayilanlari(self): |
| 148 | |
| 149 | p, _ = self._payload() |
| 150 | self.assertEqual( |
| 151 | p.build_payload("s", None, 0.0, "deepseek-v4-pro", |
| 152 | role="reasoner")["thinking"], {"type": "enabled"}) |
| 153 | self.assertEqual( |
| 154 | p.build_payload("s", None, 0.0, "deepseek-v4-pro", |
| 155 | role="pro")["thinking"], {"type": "disabled"}) |
| 156 | self.assertNotIn("thinking", |
| 157 | p.build_payload("s", None, 0.0, "deepseek-flash", |
| 158 | role="flash")) |
| 159 | |
| 160 | def test_reasoning_effort(self): |
| 161 | p, _ = self._payload(reasoning_effort="high") |
| 162 | body = p.build_payload("s", None, 0.0, "deepseek-v4-pro") |
| 163 | self.assertEqual(body["reasoning_effort"], "high") |
| 164 | p2, _ = self._payload() |
| 165 | self.assertNotIn("reasoning_effort", |
| 166 | p2.build_payload("s", None, 0.0, "deepseek-flash")) |
| 167 | |
| 168 | def test_gecersiz_degerler_reddedilir(self): |
| 169 | for bad in ("max", "high", "on"): |
| 170 | with self.assertRaises(SegmentConfigError): |
| 171 | cfg(thinking=bad).validate() |
| 172 | with self.assertRaises(SegmentConfigError): |
| 173 | cfg(reasoning_effort="asiri").validate() |
| 174 | |
| 175 | def test_json_zorlamasi_yalniz_etiket_cagrilarinda(self): |
| 176 | p, _ = self._payload() |
| 177 | self.assertIn("response_format", |
| 178 | p.build_payload("s", None, 0.0, "deepseek-flash", kind="label")) |
| 179 | self.assertNotIn("response_format", |
| 180 | p.build_payload("s", None, 0.0, "deepseek-flash", |
| 181 | kind="paraphrase")) |
| 182 | |
| 183 | def test_reasoning_content_semaya_girmez(self): |
| 184 | |
| 185 | from src.segment.labelers import BaselineLabeler |
| 186 | |
| 187 | class Thinker(MockProvider): |
| 188 | def _call(self, prompt, system, temperature, model, **kw): |
| 189 | res = super()._call(prompt, system, temperature, model, **kw) |
| 190 | res.reasoning_content = "once sunu dusundum, sonra bunu" |
| 191 | return res |
| 192 | |
| 193 | c = cfg() |
| 194 | seg = BaselineLabeler(Thinker(c, budget=BudgetGuard(5.0)), c).label_item(ITEM) |
| 195 | self.assertEqual(seg.reasoning_content, "once sunu dusundum, sonra bunu") |
| 196 | self.assertNotIn("dusundum", seg.rationale) |
| 197 | self.assertEqual(seg.to_dict()["reasoning_chars"], |
| 198 | len("once sunu dusundum, sonra bunu")) |
| 199 | |
| 200 | def test_thinking_onbellek_anahtarinin_parcasi(self): |
| 201 | |
| 202 | with tempfile.TemporaryDirectory() as td: |
| 203 | cache = ResponseCache(Path(td)) |
| 204 | c1 = cfg(thinking="enabled") |
| 205 | c1.cache_enabled = True |
| 206 | MockProvider(c1, cache=cache, budget=BudgetGuard(10.0)).chat("ayni istem") |
| 207 | c2 = cfg(thinking="disabled") |
| 208 | c2.cache_enabled = True |
| 209 | r = MockProvider(c2, cache=cache, budget=BudgetGuard(10.0)).chat("ayni istem") |
| 210 | self.assertFalse(r.cached) |
| 211 | |
| 212 | |
| 213 | class TestUsageFromApi(unittest.TestCase): |
| 214 | |
| 215 | |
| 216 | def test_cache_hit_miss_ayri_tarifelenir(self): |
| 217 | u = Usage.from_api({"prompt_tokens": 1_000_000, |
| 218 | "prompt_cache_hit_tokens": 900_000, |
| 219 | "prompt_cache_miss_tokens": 100_000, |
| 220 | "completion_tokens": 500, |
| 221 | "completion_tokens_details": {"reasoning_tokens": 300}}) |
| 222 | self.assertEqual(u.input_cache_hit, 900_000) |
| 223 | self.assertEqual(u.input_cache_miss, 100_000) |
| 224 | self.assertEqual(u.reasoning, 300) |
| 225 | |
| 226 | beklenen = (900_000 * 0.014 + 100_000 * 0.44 + 500 * 1.32) / 1_000_000 |
| 227 | self.assertAlmostEqual(cost_usd("deepseek-flash", u), beklenen, places=12) |
| 228 | |
| 229 | def test_dusunce_token_i_iki_kez_sayilmaz(self): |
| 230 | |
| 231 | a = Usage(output=1000, reasoning=800) |
| 232 | b = Usage(output=1000, reasoning=0) |
| 233 | self.assertEqual(cost_usd("deepseek-v4-pro", a), |
| 234 | cost_usd("deepseek-v4-pro", b)) |
| 235 | |
| 236 | def test_cache_alani_yoksa_hepsi_miss(self): |
| 237 | u = Usage.from_api({"prompt_tokens": 1000, "completion_tokens": 10}) |
| 238 | self.assertEqual((u.input_cache_hit, u.input_cache_miss), (0, 1000)) |
| 239 | |
| 240 | |
| 241 | class TestBudgetGuard(unittest.TestCase): |
| 242 | |
| 243 | def test_tavan_asilinca_durdurur(self): |
| 244 | g = BudgetGuard(0.001) |
| 245 | g.charge(Usage(input_cache_miss=10), 0.0005) |
| 246 | with self.assertRaises(BudgetExceeded): |
| 247 | g.charge(Usage(input_cache_miss=10), 0.0006) |
| 248 | |
| 249 | with self.assertRaises(BudgetExceeded): |
| 250 | g.check() |
| 251 | |
| 252 | def test_saglayici_butce_tavaninda_durur(self): |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | |
| 258 | |
| 259 | c = cfg() |
| 260 | c.model_ids["flash"] = "deepseek-flash" |
| 261 | |
| 262 | class Fake(BaseProvider): |
| 263 | name = "fake" |
| 264 | |
| 265 | def _call(self, prompt, system, temperature, model, **kw): |
| 266 | |
| 267 | return ChatResult(text="{}", usage=Usage(input_cache_miss=1_000_000), |
| 268 | model=model) |
| 269 | |
| 270 | p = Fake(c, budget=BudgetGuard(0.5), sleep=lambda _s: None) |
| 271 | p.chat("ilk") |
| 272 | with self.assertRaises(BudgetExceeded): |
| 273 | p.chat("ikinci") |
| 274 | with self.assertRaises(BudgetExceeded): |
| 275 | p.chat("ucuncu") |
| 276 | |
| 277 | def test_butce_gercekten_ucretlenir(self): |
| 278 | c = cfg() |
| 279 | c.model_ids["flash"] = "deepseek-flash" |
| 280 | |
| 281 | class Fake(BaseProvider): |
| 282 | name = "fake" |
| 283 | |
| 284 | def _call(self, prompt, system, temperature, model, **kw): |
| 285 | return ChatResult(text="{}", usage=Usage(input_cache_miss=1_000_000, |
| 286 | output=0), model=model) |
| 287 | |
| 288 | p = Fake(c, budget=BudgetGuard(10.0), sleep=lambda _s: None) |
| 289 | res = p.chat("x") |
| 290 | self.assertAlmostEqual(res.cost, 0.44, places=6) |
| 291 | self.assertAlmostEqual(p.budget.spent, 0.44, places=6) |
| 292 | |
| 293 | |
| 294 | class TestRateLimiterAndRetry(unittest.TestCase): |
| 295 | |
| 296 | def test_hiz_siniri_bekletir(self): |
| 297 | now = [0.0] |
| 298 | slept = [] |
| 299 | rl = RateLimiter(60, clock=lambda: now[0], sleep=slept.append) |
| 300 | rl.acquire() |
| 301 | rl.acquire() |
| 302 | self.assertEqual(slept, [1.0]) |
| 303 | |
| 304 | def test_ustel_geri_cekilme(self): |
| 305 | slept = [] |
| 306 | calls = [] |
| 307 | |
| 308 | class Flaky(BaseProvider): |
| 309 | name = "flaky" |
| 310 | |
| 311 | def _call(self, prompt, system, temperature, model, **kw): |
| 312 | calls.append(1) |
| 313 | if len(calls) < 3: |
| 314 | raise OSError("gecici ag hatasi") |
| 315 | return ChatResult(text="ok", usage=Usage(), model=model) |
| 316 | |
| 317 | p = Flaky(cfg(max_retry=4, retry_base_s=0.5), budget=BudgetGuard(1.0), |
| 318 | sleep=slept.append) |
| 319 | res = p.chat("x") |
| 320 | self.assertEqual(res.text, "ok") |
| 321 | |
| 322 | |
| 323 | self.assertEqual([s for s in slept if s >= 0.1], [0.5, 1.0]) |
| 324 | |
| 325 | def test_kalici_hata_provider_error(self): |
| 326 | class Dead(BaseProvider): |
| 327 | name = "dead" |
| 328 | |
| 329 | def _call(self, *a, **kw): |
| 330 | raise OSError("kapali") |
| 331 | |
| 332 | p = Dead(cfg(max_retry=2), budget=BudgetGuard(1.0), sleep=lambda _s: None) |
| 333 | with self.assertRaises(ProviderError): |
| 334 | p.chat("x") |
| 335 | |
| 336 | |
| 337 | class TestCache(unittest.TestCase): |
| 338 | |
| 339 | def test_yazma_okuma_ve_atomikligi(self): |
| 340 | with tempfile.TemporaryDirectory() as td: |
| 341 | c = ResponseCache(Path(td)) |
| 342 | c.put("abcdef", {"text": "merhaba", "usage": {}}) |
| 343 | self.assertEqual(c.get("abcdef")["text"], "merhaba") |
| 344 | |
| 345 | c2 = ResponseCache(Path(td)) |
| 346 | self.assertEqual(c2.get("abcdef")["text"], "merhaba") |
| 347 | self.assertIsNone(c2.get("yokboyle")) |
| 348 | self.assertEqual(c2.stats()["hits"], 1) |
| 349 | self.assertEqual(c2.stats()["misses"], 1) |
| 350 | |
| 351 | def test_bozuk_girdi_yok_sayilir(self): |
| 352 | with tempfile.TemporaryDirectory() as td: |
| 353 | c = ResponseCache(Path(td)) |
| 354 | c.put("ffeedd", {"text": "x", "usage": {}}) |
| 355 | p = Path(td) / "ff" / "ffeedd.json" |
| 356 | p.write_text("{bozuk", encoding="utf-8") |
| 357 | self.assertIsNone(ResponseCache(Path(td)).get("ffeedd")) |
| 358 | |
| 359 | def test_onbellek_ikinci_cagriyi_bedava_yapar(self): |
| 360 | with tempfile.TemporaryDirectory() as td: |
| 361 | c = SegmentConfig() |
| 362 | c.cache_enabled = True |
| 363 | c.rpm = 10 ** 6 |
| 364 | cache = ResponseCache(Path(td)) |
| 365 | p = MockProvider(c, cache=cache, budget=BudgetGuard(10.0)) |
| 366 | prompt = ("Ders: Matematik\nKonu: x\nSoru kokü: 2+2 kactir?\n" |
| 367 | "Siklar (0-tabanli indeksli):\n [0] 4\n [1] 5\n\n") |
| 368 | r1 = p.chat(prompt) |
| 369 | r2 = p.chat(prompt) |
| 370 | self.assertFalse(r1.cached) |
| 371 | self.assertTrue(r2.cached) |
| 372 | self.assertEqual(r1.text, r2.text) |
| 373 | self.assertEqual(r2.cost, 0.0) |
| 374 | self.assertEqual(p.budget.calls, 1) |
| 375 | |
| 376 | def test_farkli_istem_surumu_farkli_anahtar(self): |
| 377 | |
| 378 | with tempfile.TemporaryDirectory() as td: |
| 379 | c = SegmentConfig() |
| 380 | c.cache_enabled = True |
| 381 | c.rpm = 10 ** 6 |
| 382 | p = MockProvider(c, cache=ResponseCache(Path(td)), budget=BudgetGuard(10.0)) |
| 383 | p.chat("istem A") |
| 384 | r = p.chat("istem B") |
| 385 | self.assertFalse(r.cached) |
| 386 | self.assertEqual(p.budget.calls, 2) |
| 387 | |
| 388 | def test_null_cache(self): |
| 389 | c = NullCache() |
| 390 | c.put("x", {"a": 1}) |
| 391 | self.assertIsNone(c.get("x")) |
| 392 | |
| 393 | |
| 394 | class TestMockProvider(unittest.TestCase): |
| 395 | |
| 396 | def _prompt(self, item=ITEM): |
| 397 | from src.segment import prompts |
| 398 | return prompts.get("v1").render(item, course_name=item.get("course_name")) |
| 399 | |
| 400 | def test_istemden_madde_geri_cikarilir(self): |
| 401 | stem, choices = parse_item_from_prompt(self._prompt()) |
| 402 | self.assertIn("Kalitim", stem) |
| 403 | self.assertEqual(choices, ITEM["choices"]) |
| 404 | |
| 405 | def test_belirlenimci(self): |
| 406 | p = MockProvider(cfg(), budget=BudgetGuard(10.0)) |
| 407 | a = p.chat(self._prompt(), temperature=0.3).text |
| 408 | q = MockProvider(cfg(), budget=BudgetGuard(10.0)) |
| 409 | b = q.chat(self._prompt(), temperature=0.3).text |
| 410 | self.assertEqual(a, b) |
| 411 | |
| 412 | def test_sema_uyumlu_cikti_uretir(self): |
| 413 | p = MockProvider(cfg(), budget=BudgetGuard(10.0)) |
| 414 | seg = parse_label_json(p.chat(self._prompt()).text, question_id="q1", |
| 415 | choices=ITEM["choices"], prompt_version="v1", |
| 416 | model="mock", variant="baseline") |
| 417 | self.assertIn(seg.label("dikkat_tuzagi"), ("var", "yok")) |
| 418 | |
| 419 | def test_sicaklik_sifir_tam_belirlenimci(self): |
| 420 | |
| 421 | |
| 422 | |
| 423 | |
| 424 | |
| 425 | p = MockProvider(cfg(), budget=BudgetGuard(10.0)) |
| 426 | outs = set() |
| 427 | for i in range(5): |
| 428 | data = json.loads(p.chat(self._prompt(), temperature=0.0, |
| 429 | cache_key_extra=str(i), nonce=str(i)).text) |
| 430 | outs.add(tuple(sorted((k, v["etiket"]) |
| 431 | for k, v in data["boyutlar"].items()))) |
| 432 | self.assertEqual(len(outs), 1) |
| 433 | |
| 434 | def test_ikiz_sik_tuzak_olarak_isaretlenir(self): |
| 435 | |
| 436 | p = MockProvider(cfg(), budget=BudgetGuard(10.0)) |
| 437 | data = json.loads(p.chat(self._prompt(), temperature=0.0).text) |
| 438 | self.assertEqual(data["boyutlar"]["dikkat_tuzagi"]["etiket"], "var") |
| 439 | self.assertIn(data["tuzak_sik_index"], (0, 1)) |
| 440 | |
| 441 | def test_yalnizca_sayisal_siklarda_tuzak_yok(self): |
| 442 | item = dict(ITEM, choices=["24", "18", "36", "12"], |
| 443 | text="12 + 12 kactir?") |
| 444 | p = MockProvider(cfg(), budget=BudgetGuard(10.0)) |
| 445 | data = json.loads(p.chat(self._prompt(item), temperature=0.0).text) |
| 446 | self.assertEqual(data["boyutlar"]["dikkat_tuzagi"]["etiket"], "yok") |
| 447 | self.assertIsNone(data["tuzak_sik_index"]) |
| 448 | |
| 449 | |
| 450 | class TestDeepSeekProvider(unittest.TestCase): |
| 451 | |
| 452 | def test_anahtarsiz_cagri_hata_verir_ag_a_cikilmaz(self): |
| 453 | c = cfg(api_key=None, max_retry=1) |
| 454 | p = DeepSeekProvider(c, budget=BudgetGuard(10.0), sleep=lambda _s: None) |
| 455 | with self.assertRaises(ProviderError) as ctx: |
| 456 | p.chat("x") |
| 457 | self.assertIn("LLM_API_KEY", str(ctx.exception)) |
| 458 | |
| 459 | def test_anahtar_yoksa_build_provider_mocka_duser(self): |
| 460 | p = build_provider(cfg(api_key=None), mock=False) |
| 461 | self.assertEqual(p.name, "mock") |
| 462 | |
| 463 | def test_anahtar_varsa_deepseek_secilir(self): |
| 464 | p = build_provider(cfg(api_key="sahte-anahtar"), mock=False) |
| 465 | self.assertEqual(p.name, "deepseek") |
| 466 | |
| 467 | |
| 468 | def _yanit(payload): |
| 469 | |
| 470 | class _R: |
| 471 | def read(self_inner): |
| 472 | return json.dumps(payload).encode() |
| 473 | |
| 474 | def __enter__(self_inner): |
| 475 | return self_inner |
| 476 | |
| 477 | def __exit__(self_inner, *a): |
| 478 | return False |
| 479 | |
| 480 | return _R() |
| 481 | |
| 482 | |
| 483 | class TestGatewayBodyError(unittest.TestCase): |
| 484 | |
| 485 | |
| 486 | |
| 487 | |
| 488 | |
| 489 | |
| 490 | |
| 491 | |
| 492 | _SECENEK = {"choices": [{"message": {"content": "{\"etiket\": \"dogru\"}"}}], |
| 493 | "usage": {}} |
| 494 | |
| 495 | def _provider(self, yanitlar, **over): |
| 496 | cagri = {"n": 0} |
| 497 | |
| 498 | def _say(req, timeout=None): |
| 499 | cagri["n"] += 1 |
| 500 | yanit = yanitlar[cagri["n"] - 1] |
| 501 | if isinstance(yanit, BaseException): |
| 502 | raise yanit |
| 503 | return yanit |
| 504 | |
| 505 | c = cfg(api_key="sahte-anahtar", **over) |
| 506 | p = DeepSeekProvider(c, budget=BudgetGuard(10.0), sleep=lambda _s: None) |
| 507 | return p, cagri, mock.patch("src.segment.provider.urllib.request.urlopen", |
| 508 | side_effect=_say) |
| 509 | |
| 510 | def test_govdede_gecici_hata_yeniden_denenir(self): |
| 511 | |
| 512 | yanitlar = [_yanit({"error": {"message": "Upstream error from Nvidia: " |
| 513 | "Service temporarily overloaded", |
| 514 | "code": 503}}), |
| 515 | _yanit(self._SECENEK)] |
| 516 | p, cagri, yama = self._provider(yanitlar) |
| 517 | with yama: |
| 518 | res = p.chat("x") |
| 519 | self.assertEqual(cagri["n"], 2) |
| 520 | self.assertIn("dogru", res.text) |
| 521 | |
| 522 | def test_govdede_kalici_hata_ilk_denemede_saglayicinin_mesajiyla_biter(self): |
| 523 | |
| 524 | yanitlar = [_yanit({"error": {"message": "model bulunamadi", "code": 400}})] |
| 525 | p, cagri, yama = self._provider(yanitlar, max_retry=4) |
| 526 | |
| 527 | |
| 528 | beklenen = getattr(provider_mod, "ProviderRejection", ProviderError) |
| 529 | with yama: |
| 530 | with self.assertRaises(beklenen) as ctx: |
| 531 | p.chat("x") |
| 532 | self.assertEqual(cagri["n"], 1) |
| 533 | self.assertIn("model bulunamadi", str(ctx.exception)) |
| 534 | |
| 535 | def test_govdede_dizge_bicimi_hata_gecici_sayilir(self): |
| 536 | yanitlar = [_yanit({"error": "temporary upstream failure"}), |
| 537 | _yanit(self._SECENEK)] |
| 538 | p, cagri, yama = self._provider(yanitlar) |
| 539 | with yama: |
| 540 | p.chat("x") |
| 541 | self.assertEqual(cagri["n"], 2) |
| 542 | |
| 543 | def test_gercek_http_5xx_hala_yeniden_denenir(self): |
| 544 | |
| 545 | import urllib.error |
| 546 | yanitlar = [urllib.error.HTTPError("u", 503, "m", {}, None), |
| 547 | _yanit(self._SECENEK)] |
| 548 | p, cagri, yama = self._provider(yanitlar) |
| 549 | with yama: |
| 550 | p.chat("x") |
| 551 | self.assertEqual(cagri["n"], 2) |
| 552 | |
| 553 | |
| 554 | class TestConfig(unittest.TestCase): |
| 555 | |
| 556 | def test_gecersiz_butce_reddedilir(self): |
| 557 | with self.assertRaises(SegmentConfigError): |
| 558 | cfg(budget_usd=0).validate() |
| 559 | |
| 560 | def test_tek_tekrar_reddedilir(self): |
| 561 | with self.assertRaises(SegmentConfigError): |
| 562 | cfg(intra_replicates=1).validate() |
| 563 | |
| 564 | def test_model_rolleri(self): |
| 565 | c = SegmentConfig() |
| 566 | self.assertEqual(set(c.model_ids), {"pro", "flash", "reasoner"}) |
| 567 | |
| 568 | |
| 569 | |
| 570 | self.assertEqual(c.model_id("reasoner"), "deepseek-v4-pro") |
| 571 | self.assertEqual(c.model_id("flash"), "deepseek-flash") |
| 572 | self.assertEqual(c.thinking_for("reasoner"), "enabled") |
| 573 | self.assertEqual(c.thinking_for("pro"), "disabled") |
| 574 | |
| 575 | def test_ozet_anahtari_sizdirmaz(self): |
| 576 | c = cfg(api_key="cok-gizli-anahtar") |
| 577 | self.assertNotIn("cok-gizli", c.summary()) |
| 578 | self.assertIn("tanimli", c.summary()) |
| 579 | |
| 580 | |
| 581 | if __name__ == "__main__": |
| 582 | unittest.main() |