- infrastructure/repositories/excel_repository.py: ExcelRepository.save() создаёт
родительский каталог файла (parents=True, exist_ok=True) перед сохранением;
ошибки создания каталога и записи файла оборачиваются в ExcelRepositoryError
с понятным сообщением вместо сырого FileNotFoundError из openpyxl.
- tests/test_excel_sync.py: +3 теста (создание каталога, экспорт в bare
filename, доменная ошибка когда родительский путь занят файлом).
- tests/test_cli.py: +3 теста (экспорт в несуществующий каталог, дефолтный
exports/forecast.xlsx, понятная ошибка без traceback).
Было → стало:
cf export-xlsx /tmp/nifodea-check/out.xlsx FileNotFoundError (traceback)
→ «Модель экспортирована в
/tmp/nifodea-check/out.xlsx», код 0
cf export-xlsx (каталога exports/ нет) FileNotFoundError (traceback)
→ каталог создан, файл записан, код 0
каталог создать нельзя (путь занят файлом) FileNotFoundError (traceback)
→ «Ошибка экспорта: Не удалось создать
каталог …», код 1, без traceback
193 lines
8.3 KiB
Python
193 lines
8.3 KiB
Python
from decimal import Decimal
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
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 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",
|
||
"ModelInfo",
|
||
]
|
||
finally:
|
||
wb.close()
|