import ast from decimal import Decimal from pathlib import Path import pytest from openpyxl import load_workbook import infrastructure.repositories.excel_repository as excel_repository from domain import Account, FinancialModel, ForecastScenario from infrastructure.repositories import ExcelRepository, ExcelRepositoryError from infrastructure.repositories.excel_repository import InfoSheetSpec, SheetSpec _SCENARIO_FIELDS = ["id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"] _EXPECTED_SHEETS = [ "Accounts", "Transactions", "Recurring", "Assets", "Liabilities", "ExchangeRates", "Scenarios", "ModelInfo", ] 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 TestExportCreatesParentDir: """D19: экспорт в несуществующий каталог создаёт каталог и пишет файл. Раньше `cf export-xlsx exports/report.xlsx` в каталоге без `exports/` падал с сырым `FileNotFoundError` из openpyxl. """ def test_save_creates_missing_parent_dir(self, sample_model, tmp_path: Path): repo = ExcelRepository() target = tmp_path / "nested" / "deeper" / "out.xlsx" assert not target.parent.exists() repo.save(sample_model, target) assert target.parent.is_dir() assert target.exists() def test_save_to_bare_filename_in_cwd(self, sample_model, tmp_path: Path, monkeypatch): repo = ExcelRepository() monkeypatch.chdir(tmp_path) repo.save(sample_model, "out.xlsx") assert (tmp_path / "out.xlsx").exists() def test_save_reports_unreadable_parent_as_domain_error(self, sample_model, tmp_path: Path): # Родительский путь занят файлом — каталог создать нельзя. blocker = tmp_path / "blocker" blocker.write_text("not a directory", encoding="utf-8") repo = ExcelRepository() with pytest.raises(ExcelRepositoryError) as exc_info: repo.save(sample_model, blocker / "out.xlsx") message = str(exc_info.value) assert "Не удалось создать каталог" in message assert "blocker" in message assert not isinstance(exc_info.value, FileNotFoundError) 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 == _EXPECTED_SHEETS finally: wb.close() class TestScenariosSheet: """D18: лист Scenarios переживает round-trip .xlsx.""" @staticmethod def _model_with_scenarios() -> FinancialModel: return FinancialModel( scenarios=[ ForecastScenario( name="baseline", income_multiplier=Decimal("1.0"), expense_multiplier=Decimal("1.0"), growth_multiplier=Decimal("1.0"), description="Базовый сценарий без изменений", ), ForecastScenario( name="optimistic", income_multiplier=Decimal("1.15"), expense_multiplier=Decimal("0.95"), growth_multiplier=Decimal("1.2"), description="Оптимистичный", ), ] ) def test_roundtrip_preserves_all_scenario_fields(self, tmp_path: Path): model = self._model_with_scenarios() repo = ExcelRepository() p = tmp_path / "scenarios.xlsx" repo.save(model, p) loaded = repo.load(p) assert len(loaded.scenarios) == len(model.scenarios) for source, result in zip(model.scenarios, loaded.scenarios, strict=True): assert result.id == source.id assert result.name == source.name assert result.income_multiplier == source.income_multiplier assert result.expense_multiplier == source.expense_multiplier assert result.growth_multiplier == source.growth_multiplier assert result.description == source.description def test_scenario_multipliers_keep_decimal_precision(self, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "scenario_decimals.xlsx" repo.save(self._model_with_scenarios(), p) loaded = repo.load(p) assert loaded.scenarios[1].income_multiplier == Decimal("1.15") assert loaded.scenarios[1].expense_multiplier == Decimal("0.95") assert loaded.scenarios[1].growth_multiplier == Decimal("1.2") def test_old_file_without_scenarios_sheet_loads_empty_list(self, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "old.xlsx" repo.save(self._model_with_scenarios(), p) # Эмулируем файл, созданный до D18: листа Scenarios в нём нет. wb = load_workbook(p) wb.remove(wb["Scenarios"]) wb.save(p) wb.close() loaded = repo.load(p) assert loaded.scenarios == [] def test_empty_scenarios_list_writes_empty_sheet(self, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "empty_scenarios.xlsx" repo.save(FinancialModel(), p) wb = load_workbook(p) try: assert "Scenarios" in wb.sheetnames ws = wb["Scenarios"] assert ws.max_row == 1 assert [cell.value for cell in ws[1]] == _SCENARIO_FIELDS finally: wb.close() assert repo.load(p).scenarios == [] class TestSheetSpecIsSingleSource: """D28: запись и чтение выводятся из одной декларативной таблицы `SHEETS`.""" def test_spec_covers_every_sheet_in_order(self): assert [spec.name for spec in excel_repository.SHEETS] == _EXPECTED_SHEETS def test_collection_specs_point_to_existing_model_fields(self): model = FinancialModel() collection_specs = [spec for spec in excel_repository.SHEETS if isinstance(spec, SheetSpec)] assert len(collection_specs) == 7 for spec in collection_specs: assert hasattr(model, spec.collection), f"{spec.name}: нет поля {spec.collection}" assert isinstance(getattr(model, spec.collection), list) def test_written_headers_are_taken_from_spec(self, sample_model, tmp_path: Path): repo = ExcelRepository() p = tmp_path / "headers.xlsx" repo.save(sample_model, p) wb = load_workbook(p) try: for spec in excel_repository.SHEETS: headers = [cell.value for cell in wb[spec.name][1]] if isinstance(spec, InfoSheetSpec): assert headers == ["Property", "Value"] else: assert headers == list(spec.fields), f"{spec.name}: заголовки не из спецификации" finally: wb.close() def test_new_spec_gets_write_and_read_without_code_changes( self, sample_model, tmp_path: Path, monkeypatch: pytest.MonkeyPatch ): # Генерическая запись/чтение: лист, которого нет в боевой таблице, # но который добавлен в спецификацию, сохраняется и читается сам. copy_sheet = SheetSpec("AccountsCopy", ("id", "name", "currency", "balance"), Account, "accounts") monkeypatch.setattr(excel_repository, "SHEETS", (copy_sheet, InfoSheetSpec())) repo = ExcelRepository() p = tmp_path / "spec_driven.xlsx" repo.save(sample_model, p) wb = load_workbook(p) try: assert wb.sheetnames == ["AccountsCopy", "ModelInfo"] finally: wb.close() loaded = repo.load(p) assert [account.name for account in loaded.accounts] == ["Основной счёт", "Сбережения"] assert loaded.accounts[0].balance == Decimal("5000") def test_no_manual_branches_by_sheet_name_remain(self): # В коде репозитория не должно остаться ручных веток по именам листов: # имена живут только в `SHEETS`. source = Path(excel_repository.__file__).read_text(encoding="utf-8") tree = ast.parse(source) comparisons = [ node for node in ast.walk(tree) if isinstance(node, ast.Compare) and any( isinstance(operand, ast.Name) and operand.id == "sheet_name" for operand in (node.left, *node.comparators) ) ] assert comparisons == [], "остались ручные сравнения по имени листа" assert "_SHEET_CONFIG" not in source