Skip to content

Commit 74f2617

Browse files
committed
Test LedgerLite validation and persistence
1 parent 03c077b commit 74f2617

1 file changed

Lines changed: 48 additions & 0 deletions

File tree

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""Unit tests for LedgerLite; run with python -m unittest."""
2+
3+
import json
4+
import tempfile
5+
import unittest
6+
from pathlib import Path
7+
8+
from ledgerlite import add_entry, load_entries, save_entries
9+
10+
11+
class LedgerLiteTests(unittest.TestCase):
12+
def test_add_entry_trims_text_and_stores_amount(self):
13+
entries = []
14+
entry = add_entry(entries, 12.5, " lunch ", " food ")
15+
self.assertEqual(entry["description"], "lunch")
16+
self.assertEqual(entry["category"], "food")
17+
self.assertEqual(entry["amount"], 12.5)
18+
self.assertEqual(len(entries), 1)
19+
20+
def test_rejects_non_positive_amount(self):
21+
with self.assertRaises(ValueError):
22+
add_entry([], 0, "coffee", "food")
23+
24+
def test_rejects_blank_description(self):
25+
with self.assertRaises(ValueError):
26+
add_entry([], 2, " ", "food")
27+
28+
def test_save_and_load_round_trip(self):
29+
with tempfile.TemporaryDirectory() as directory:
30+
path = Path(directory) / "nested" / "ledger.json"
31+
entries = [add_entry([], 4.25, "bus", "transport")]
32+
save_entries(path, entries)
33+
self.assertEqual(load_entries(path), entries)
34+
35+
def test_missing_file_is_empty_ledger(self):
36+
with tempfile.TemporaryDirectory() as directory:
37+
self.assertEqual(load_entries(Path(directory) / "missing.json"), [])
38+
39+
def test_invalid_json_reports_error(self):
40+
with tempfile.TemporaryDirectory() as directory:
41+
path = Path(directory) / "broken.json"
42+
path.write_text("{not json", encoding="utf-8")
43+
with self.assertRaises(ValueError):
44+
load_entries(path)
45+
46+
47+
if __name__ == "__main__":
48+
unittest.main()

0 commit comments

Comments
 (0)