import os import stat from decimal import Decimal from pathlib import Path from application.repositories import ModelRepository from domain import Account, Asset, FinancialModel, Transaction from infrastructure.repositories import JsonFileRepository class TestJsonFileRepository: def test_save_load_roundtrip(self, tmp_path: Path): repo = JsonFileRepository() model = FinancialModel( accounts=[Account(name="Test", balance=Decimal("100.50"))], transactions=[Transaction(amount=Decimal("33.33"), category="income")], ) p = tmp_path / "model.json" repo.save(model, p) assert p.exists() loaded = repo.load(p) assert len(loaded.accounts) == 1 assert loaded.accounts[0].name == "Test" assert loaded.accounts[0].balance == Decimal("100.50") assert loaded.transactions[0].amount == Decimal("33.33") def test_version_field_persisted(self, tmp_path: Path): repo = JsonFileRepository() model = FinancialModel() p = tmp_path / "v.json" repo.save(model, p) import json with open(p) as f: data = json.load(f) assert data["version"] == 2 def test_creates_parent_dirs(self, tmp_path: Path): repo = JsonFileRepository() model = FinancialModel() p = tmp_path / "nested" / "dir" / "model.json" repo.save(model, p) assert p.exists() def test_implements_protocol(self): repo = JsonFileRepository() assert isinstance(repo, ModelRepository) def test_saved_model_has_private_permissions(self, tmp_path: Path): if os.name != "posix": return repo = JsonFileRepository() p = tmp_path / "private.json" repo.save(FinancialModel(), p) assert stat.S_IMODE(p.stat().st_mode) == 0o600 def test_decimal_preserved(self, tmp_path: Path): repo = JsonFileRepository() model = FinancialModel(assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))]) p = tmp_path / "decimal.json" repo.save(model, p) loaded = repo.load(p) assert loaded.assets[0].value == Decimal("12345.67") assert loaded.assets[0].growth_rate == Decimal("8.5")