| 1 | |
| 2 | |
| 3 | import os |
| 4 | import tempfile |
| 5 | import unittest |
| 6 | import warnings |
| 7 | |
| 8 | import src.costlog as costlog |
| 9 | from src.pricing import Usage |
| 10 | |
| 11 | |
| 12 | class CostlogTests(unittest.TestCase): |
| 13 | def _paths(self, d): |
| 14 | return os.path.join(d, "runs.jsonl"), os.path.join(d, "Maliyet.md") |
| 15 | |
| 16 | def test_sequential_ids_and_unit_cost(self): |
| 17 | with tempfile.TemporaryDirectory() as d: |
| 18 | L, M = self._paths(d) |
| 19 | r1 = costlog.record("ozet", "deepseek-chat", |
| 20 | Usage(input_cache_miss=1000, output=500), items=10, |
| 21 | ledger=L, maliyet=M) |
| 22 | r2 = costlog.record("chat", "deepseek-chat", |
| 23 | Usage(input_cache_miss=1000, output=500), items=1, |
| 24 | ledger=L, maliyet=M) |
| 25 | self.assertEqual(r1["run_id"], "R0001") |
| 26 | self.assertEqual(r2["run_id"], "R0002") |
| 27 | self.assertAlmostEqual(r1["unit_cost_usd"], round(r1["cost_usd"] / 10, 6)) |
| 28 | |
| 29 | |
| 30 | |
| 31 | |
| 32 | |
| 33 | self.assertTrue(os.path.exists(L)) |
| 34 | self.assertFalse(os.path.exists(M), "render istek yolunda kaldı") |
| 35 | |
| 36 | def test_unknown_model_does_not_crash_or_drop(self): |
| 37 | with tempfile.TemporaryDirectory() as d: |
| 38 | L, M = self._paths(d) |
| 39 | with warnings.catch_warnings(): |
| 40 | warnings.simplefilter("ignore") |
| 41 | r = costlog.record("ozet", "gpt-yok", Usage(output=1), ledger=L, maliyet=M) |
| 42 | self.assertEqual(r["cost_usd"], 0.0) |
| 43 | self.assertEqual(costlog._load(L)[0]["run_id"], "R0001") |
| 44 | |
| 45 | def test_render_atomic_no_tmp_leftover(self): |
| 46 | with tempfile.TemporaryDirectory() as d: |
| 47 | L, M = self._paths(d) |
| 48 | costlog.record("ozet", "deepseek-chat", Usage(output=1), ledger=L, maliyet=M) |
| 49 | leftovers = [f for f in os.listdir(d) if f.endswith(".tmp")] |
| 50 | self.assertEqual(leftovers, []) |
| 51 | |
| 52 | def test_corrupt_line_skipped(self): |
| 53 | with tempfile.TemporaryDirectory() as d: |
| 54 | L, _ = self._paths(d) |
| 55 | with open(L, "w", encoding="utf-8") as f: |
| 56 | f.write('{"run_id":"R1","cost_usd":0.1}\n') |
| 57 | f.write('YARIM {bozuk\n') |
| 58 | f.write('{"run_id":"R2","cost_usd":0.2}\n') |
| 59 | with warnings.catch_warnings(): |
| 60 | warnings.simplefilter("ignore") |
| 61 | rows = costlog._load(L) |
| 62 | self.assertEqual([r["run_id"] for r in rows], ["R1", "R2"]) |
| 63 | |
| 64 | def test_next_id_after_corrupt(self): |
| 65 | with tempfile.TemporaryDirectory() as d: |
| 66 | L, M = self._paths(d) |
| 67 | with open(L, "w", encoding="utf-8") as f: |
| 68 | f.write('{"run_id":"R0007"}\nBOZUK\n') |
| 69 | with warnings.catch_warnings(): |
| 70 | warnings.simplefilter("ignore") |
| 71 | r = costlog.record("ozet", "deepseek-chat", Usage(output=1), ledger=L, maliyet=M) |
| 72 | self.assertEqual(r["run_id"], "R0008") |
| 73 | |
| 74 | |
| 75 | if __name__ == "__main__": |
| 76 | unittest.main() |