Files
nifodea/tests/test_excel_sync.py
T

273 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from decimal import Decimal
from pathlib import Path
import pytest
from openpyxl import load_workbook
from domain import FinancialModel, ForecastScenario
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
_SCENARIO_FIELDS = ["id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"]
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 == [
"Accounts",
"Transactions",
"Recurring",
"Assets",
"Liabilities",
"ExchangeRates",
"Scenarios",
"ModelInfo",
]
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 == []