Files
nifodea/tests/test_excel_template.py
T
oqyude cdda703b37 T9: Excel as the model authoring surface
- ExcelRepository: canonical columns with ru/en aliases, date/number normalization
  (Excel dates, DD.MM.YYYY, '1 234,56', currency symbols, parentheses), account
  name->UUID resolution, per-row errors with sheet!row, warnings for formulas
  without cached values, duplicate names and default exchange rates
- ExcelTemplate: skeleton generator (number/date formats, dropdowns for currency,
  frequency en/ru and account, 'Инструкция' sheet); ship data/model_template.xlsx
- CLI: cf template-xlsx [--force]; cf import-xlsx --dry-run with rich error table,
  import writes nothing when the file has errors
- RecurringCashflow.account (empty = all accounts) + name/UUID matching in forecast;
  cf config recurring-add --account, account column in info/recurring-list
- Forecast: runs are idempotent, 'Итог: Баланс' sums all accounts of the last month
- README: 'Сборка модели в Excel' section
- ruff check . clean (9 pre-existing import/line-length findings fixed)
- MetaAgent: T9 archived, req-T9 approved, manifest/checkpoints/state synced

118 tests pass
2026-11-11 15:40:37 +03:00

130 lines
4.5 KiB
Python

from pathlib import Path
import pytest
from openpyxl import load_workbook
from domain import FinancialModel
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError, write_template
from infrastructure.repositories.excel_repository import CANONICAL_COLUMNS, SHEET_ORDER
_EXPECTED_SHEETS = list(SHEET_ORDER) + ["Инструкция"]
def _headers(ws) -> list:
return [cell.value for cell in ws[1]]
def _instruction_text(path: Path) -> str:
wb = load_workbook(path)
try:
return "\n".join(
str(cell.value)
for row in wb["Инструкция"].iter_rows()
for cell in row
if cell.value is not None
)
finally:
wb.close()
class TestWriteTemplate:
def test_creates_file(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
assert path == tmp_path / "template.xlsx"
assert path.exists()
def test_sheets_and_canonical_headers(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
assert wb.sheetnames == _EXPECTED_SHEETS
assert _headers(wb["ModelInfo"]) == ["Property", "Value"]
for sheet_name, columns in CANONICAL_COLUMNS.items():
assert _headers(wb[sheet_name]) == list(columns), sheet_name
finally:
wb.close()
def test_template_loads_as_empty_model(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model == FinancialModel()
assert ExcelRepository().load(path) == FinancialModel()
def test_existing_file_requires_force(self, tmp_path: Path):
path = tmp_path / "template.xlsx"
path.write_bytes(b"not an xlsx")
with pytest.raises(ExcelRepositoryError):
write_template(path)
assert path.read_bytes() == b"not an xlsx"
def test_force_overwrites_existing_file(self, tmp_path: Path):
path = tmp_path / "template.xlsx"
path.write_bytes(b"not an xlsx")
returned = write_template(path, force=True)
assert returned == path
wb = load_workbook(path)
try:
assert wb.sheetnames == _EXPECTED_SHEETS
finally:
wb.close()
def test_creates_missing_parent_directories(self, tmp_path: Path):
path = write_template(tmp_path / "nested" / "dir" / "template.xlsx")
assert path.exists()
def test_currency_and_frequency_validations(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
accounts_formulas = " ".join(
validation.formula1 for validation in wb["Accounts"].data_validations.dataValidation
)
assert "RUB" in accounts_formulas
assert "JPY" in accounts_formulas
recurring_formulas = " ".join(
validation.formula1 for validation in wb["Recurring"].data_validations.dataValidation
)
assert "monthly" in recurring_formulas
assert "ежемесячно" in recurring_formulas
transactions_formulas = " ".join(
validation.formula1 for validation in wb["Transactions"].data_validations.dataValidation
)
assert "Accounts!$B$2:$B$500" in transactions_formulas
finally:
wb.close()
def test_instruction_sheet_mentions_workflow_and_sign_convention(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
text = _instruction_text(path)
assert "cf import-xlsx" in text
assert "положительная = доход" in text
assert "id можно оставить пустым" in text
assert "счёт указывается по имени" in text
assert "31.01.2026" in text
for sheet_name in CANONICAL_COLUMNS:
assert sheet_name in text
def test_template_has_no_data_rows(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
for sheet_name in CANONICAL_COLUMNS:
rows = [
row
for row in wb[sheet_name].iter_rows(min_row=2, values_only=True)
if any(value is not None for value in row)
]
assert rows == [], sheet_name
finally:
wb.close()