from decimal import Decimal from pathlib import Path from openpyxl import load_workbook from domain import FinancialModel from infrastructure.repositories import ExcelRepository, ExcelRepositoryError # ВНИМАНИЕ: лист Scenarios НЕ поддерживается при экспорте/импорте .xlsx — # сценарии прогноза теряются при round-trip. Это известное поведение, # изменение — Tier 2 (D18). Намеренно здесь НЕ проверяется. class TestExcelRepository: def test_export_creates_file(self, sample_model, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "test.xlsx" repo.save(sample_model, p) assert p.exists() def test_export_import_roundtrip(self, sample_model, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "roundtrip.xlsx" repo.save(sample_model, p) loaded = repo.load(p) assert len(loaded.accounts) == len(sample_model.accounts) assert len(loaded.transactions) == len(sample_model.transactions) assert len(loaded.recurring) == len(sample_model.recurring) assert len(loaded.assets) == len(sample_model.assets) assert len(loaded.liabilities) == len(sample_model.liabilities) assert len(loaded.exchange_rates) == len(sample_model.exchange_rates) def test_roundtrip_preserves_base_currency(self, tmp_path: Path): repo = ExcelRepository() model = FinancialModel(base_currency="EUR") p = tmp_path / "eur_model.xlsx" repo.save(model, p) loaded = repo.load(p) assert loaded.base_currency == "EUR" def test_import_missing_file(self): repo = ExcelRepository() try: repo.load("nonexistent.xlsx") assert False, "Expected ExcelRepositoryError" except ExcelRepositoryError: pass def test_export_empty_model(self, tmp_path: Path): repo = ExcelRepository() model = FinancialModel() p = tmp_path / "empty.xlsx" repo.save(model, p) assert p.exists() class TestExcelRoundTripByValues: """Round-trip .xlsx ПО ЗНАЧЕНИЯМ, а не только по количеству строк (D11). Тесты-характеристики: фиксируют текущее поведение ExcelRepository. Числа сравниваются по значению (Decimal("5000") == Decimal("5000.00")), а не по записи (числу знаков/экспоненте). """ @staticmethod def _roundtrip(sample_model, tmp_path: Path): """Сохранить модель в .xlsx и прочитать её обратно.""" repo = ExcelRepository() p = tmp_path / "values.xlsx" repo.save(sample_model, p) return repo.load(p) def test_base_currency_value(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert loaded.base_currency == "RUB" def test_accounts_values(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert len(loaded.accounts) == 2 assert [a.name for a in loaded.accounts] == ["Основной счёт", "Сбережения"] assert [a.currency for a in loaded.accounts] == ["RUB", "RUB"] # Сравнение по значению: Decimal("5000") == Decimal("5000.00"). assert loaded.accounts[0].balance == Decimal("5000") assert loaded.accounts[1].balance == Decimal("10000") def test_account_id_is_preserved(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert str(loaded.accounts[0].id) == str(sample_model.accounts[0].id) def test_transactions_values(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert len(loaded.transactions) == 2 assert [t.date for t in loaded.transactions] == ["2026-01-01", "2026-01-05"] assert [t.category for t in loaded.transactions] == ["income", "rent"] assert loaded.transactions[0].amount == Decimal("3000") assert loaded.transactions[1].amount == Decimal("-1200") assert [t.description for t in loaded.transactions] == ["Зарплата", "Аренда"] # Ссылка на счёт хранится строкой с UUID основного счёта. assert loaded.transactions[0].account == str(sample_model.accounts[0].id) assert loaded.transactions[1].account == str(sample_model.accounts[0].id) def test_recurring_values(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert len(loaded.recurring) == 2 assert [r.frequency for r in loaded.recurring] == ["monthly", "monthly"] assert loaded.recurring[0].amount == Decimal("500") assert loaded.recurring[1].amount == Decimal("-200") assert [r.category for r in loaded.recurring] == ["income", "subscription"] assert [r.start_date for r in loaded.recurring] == ["2026-01-01", "2026-01-01"] assert [r.end_date for r in loaded.recurring] == ["", ""] def test_assets_values(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert len(loaded.assets) == 1 assert loaded.assets[0].name == "Акции" assert loaded.assets[0].value == Decimal("50000") assert loaded.assets[0].growth_rate == Decimal("8") def test_liabilities_values(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert len(loaded.liabilities) == 1 assert loaded.liabilities[0].name == "Кредит" assert loaded.liabilities[0].balance == Decimal("20000") assert loaded.liabilities[0].interest == Decimal("5") assert loaded.liabilities[0].payment == Decimal("500") def test_exchange_rates_values(self, sample_model, tmp_path: Path): loaded = self._roundtrip(sample_model, tmp_path) assert len(loaded.exchange_rates) == 1 assert loaded.exchange_rates[0].from_currency == "USD" assert loaded.exchange_rates[0].to_currency == "RUB" assert loaded.exchange_rates[0].rate == Decimal("80") def test_written_sheet_names(self, sample_model, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "sheets.xlsx" repo.save(sample_model, p) wb = load_workbook(p) try: assert wb.sheetnames == [ "Accounts", "Transactions", "Recurring", "Assets", "Liabilities", "ExchangeRates", "ModelInfo", ] finally: wb.close()