| 1 | |
| 2 | import unittest |
| 3 | from dataclasses import dataclass, field |
| 4 | |
| 5 | from src.context import apply_token_budget, reorder_lost_in_middle, pack_contexts |
| 6 | |
| 7 | |
| 8 | @dataclass |
| 9 | class _Ctx: |
| 10 | chunk_id: str |
| 11 | text: str |
| 12 | score: float = 1.0 |
| 13 | parent_text: str | None = None |
| 14 | |
| 15 | |
| 16 | def _mk(n, words_each=100): |
| 17 | |
| 18 | return [_Ctx(f"c{i}", " ".join(["kelime"] * words_each), score=1.0 - i * 0.1) |
| 19 | for i in range(n)] |
| 20 | |
| 21 | |
| 22 | class TokenBudgetTests(unittest.TestCase): |
| 23 | def test_budget_drops_low_score_tail(self): |
| 24 | ctxs = _mk(5, words_each=100) |
| 25 | kept = apply_token_budget(ctxs, max_tokens=300) |
| 26 | self.assertLess(len(kept), 5) |
| 27 | self.assertGreaterEqual(len(kept), 1) |
| 28 | self.assertEqual(kept[0].chunk_id, "c0") |
| 29 | |
| 30 | def test_always_keeps_at_least_one(self): |
| 31 | ctxs = _mk(3, words_each=5000) |
| 32 | kept = apply_token_budget(ctxs, max_tokens=10) |
| 33 | self.assertEqual(len(kept), 1) |
| 34 | self.assertEqual(kept[0].chunk_id, "c0") |
| 35 | |
| 36 | def test_all_fit_under_budget(self): |
| 37 | ctxs = _mk(3, words_each=10) |
| 38 | kept = apply_token_budget(ctxs, max_tokens=100000) |
| 39 | self.assertEqual(len(kept), 3) |
| 40 | |
| 41 | def test_empty(self): |
| 42 | self.assertEqual(apply_token_budget([], 100), []) |
| 43 | |
| 44 | |
| 45 | class LostInMiddleTests(unittest.TestCase): |
| 46 | def test_strong_at_ends_weak_in_middle(self): |
| 47 | ctxs = _mk(5) |
| 48 | out = [c.chunk_id for c in reorder_lost_in_middle(ctxs)] |
| 49 | self.assertEqual(out, ["c0", "c2", "c4", "c3", "c1"]) |
| 50 | self.assertEqual(out[0], "c0") |
| 51 | self.assertEqual(out[-1], "c1") |
| 52 | self.assertEqual(out[len(out) // 2], "c4") |
| 53 | |
| 54 | def test_two_or_fewer_unchanged(self): |
| 55 | ctxs = _mk(2) |
| 56 | self.assertEqual([c.chunk_id for c in reorder_lost_in_middle(ctxs)], ["c0", "c1"]) |
| 57 | self.assertEqual(reorder_lost_in_middle([]), []) |
| 58 | |
| 59 | def test_pack_combines_budget_and_reorder(self): |
| 60 | ctxs = _mk(5, words_each=10) |
| 61 | out = [c.chunk_id for c in pack_contexts(ctxs, max_tokens=100000, reorder=True)] |
| 62 | self.assertEqual(out, ["c0", "c2", "c4", "c3", "c1"]) |
| 63 | |
| 64 | def test_pack_no_reorder(self): |
| 65 | ctxs = _mk(4, words_each=10) |
| 66 | out = [c.chunk_id for c in pack_contexts(ctxs, max_tokens=100000, reorder=False)] |
| 67 | self.assertEqual(out, ["c0", "c1", "c2", "c3"]) |
| 68 | |
| 69 | def test_parent_text_counts_toward_budget(self): |
| 70 | |
| 71 | c = _Ctx("c0", "kısa", score=1.0, parent_text=" ".join(["uzun"] * 5000)) |
| 72 | kept = apply_token_budget([c, _Ctx("c1", "kısa2", 0.9)], max_tokens=50) |
| 73 | self.assertEqual(len(kept), 1) |
| 74 | |
| 75 | |
| 76 | if __name__ == "__main__": |
| 77 | unittest.main() |