Files
nifodea/tests/test_excel_authoring.py
T
oqyude 6b13a15408 D35, D36: Excel как поверхность сборки модели
Импорт и выгрузка переработаны в полноценную поверхность авторства.

Схема (infrastructure/repositories/excel_schema.py):
- таблица SHEETS описывает листы, русские заголовки, синонимы заголовков
  и типы значений — один источник истины для записи и чтения (D28);
- заголовки русские (D19), синонимы — русские и английские, порядок
  столбцов и регистр не важны;
- новые столбцы: валюта у транзакций/регулярных/активов/обязательств и
  счёт у регулярного платежа.

Импорт (терпимый):
- числа: «1 234,56», «1,234.56», «₽1200», «(100)» = −100;
- даты: датой Excel или текстом (2026-11-01 / 01.11.2026 / 01/11/2026);
- счёт — по имени или UUID; неизвестный счёт — ошибка с адресом лист!строка;
- ошибки строк собираются в отчёт, файл с ошибками не сохраняется;
- предупреждения: неизвестный столбец, повтор имени счёта, формула без
  сохранённого значения, отсутствующий лист;
- cf import-xlsx --dry-run — проверка без записи модели.

Шаблон и выгрузка:
- cf template-xlsx — каркас: русские заголовки, форматы чисел и дат,
  выпадающие списки (валюта, периодичность, счёт), лист «Инструкция»;
- cf export-xlsx пишет тот же шаблон, уже заполненный данными, —
  цикл «выгрузить → поправить в Excel → импортировать» работает;
- перед перезаписью модели сохраняется резервная копия model.json.bak.

Тесты: 302 → 333 (tests/test_excel_authoring.py).
2026-11-15 06:12:41 +03:00

361 lines
14 KiB
Python

"""Тесты Excel-поверхности сборки модели (D35, D36)."""
from decimal import Decimal
from pathlib import Path
import pytest
from openpyxl import Workbook, load_workbook
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
from infrastructure.repositories.excel_template import write_template
def _write_sheets(path: Path, sheets: dict[str, list[list]]) -> Path:
"""Создать .xlsx с заданными листами (как будто пользователь заполнил файл)."""
wb = Workbook()
wb.remove(wb.active)
for name, rows in sheets.items():
ws = wb.create_sheet(title=name)
for row in rows:
ws.append(row)
wb.save(path)
wb.close()
return path
class TestTemplate:
"""D36: каркас шаблона."""
def test_template_has_all_sheets_and_instruction(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
assert wb.sheetnames == [
"Accounts",
"Transactions",
"Recurring",
"Assets",
"Liabilities",
"ExchangeRates",
"Scenarios",
"ModelInfo",
"Инструкция",
]
finally:
wb.close()
def test_template_headers_are_russian(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
assert [cell.value for cell in wb["Accounts"][1]] == ["ID", "Название", "Валюта", "Баланс"]
assert [cell.value for cell in wb["Transactions"][1]] == [
"ID",
"Дата",
"Счёт",
"Категория",
"Сумма",
"Описание",
"Валюта",
]
finally:
wb.close()
def test_template_has_dropdowns(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
validations = wb["Transactions"].data_validations.dataValidation
assert validations
# Валюта и счёт — с выпадающими списками.
formulas = {validation.formula1 for validation in validations}
assert any("Accounts" in formula for formula in formulas)
assert any("RUB" in formula for formula in formulas)
recurring_validations = wb["Recurring"].data_validations.dataValidation
assert any("monthly" in v.formula1 for v in recurring_validations)
finally:
wb.close()
def test_instruction_sheet_describes_columns(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
wb = load_workbook(path)
try:
ws = wb["Инструкция"]
text = "\n".join(
str(cell.value) for row in ws.iter_rows() for cell in row if cell.value is not None
)
assert "Порядок работы" in text
assert "Счёт" in text
assert "Периодичность" in text
finally:
wb.close()
def test_template_is_imported_without_errors(self, tmp_path: Path):
path = write_template(tmp_path / "template.xlsx")
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts == []
def test_existing_file_is_not_overwritten(self, tmp_path: Path):
path = tmp_path / "template.xlsx"
write_template(path)
with pytest.raises(Exception):
write_template(path)
def test_force_overwrites(self, tmp_path: Path):
path = tmp_path / "template.xlsx"
write_template(path)
write_template(path, force=True)
assert path.exists()
class TestTolerantImport:
"""D35: импорт принимает то, что пишет человек."""
def test_russian_headers_and_text_numbers(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [
["Название", "Валюта", "Баланс"],
["Основной", "RUB", "1 234,56"],
],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts[0].name == "Основной"
assert result.model.accounts[0].balance == Decimal("1234.56")
def test_english_headers_are_accepted(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [
["name", "currency", "balance"],
["Main", "RUB", 100],
],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts[0].name == "Main"
def test_column_order_does_not_matter(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [
["Баланс", "Название", "Валюта"],
[500, "Main", "RUB"],
],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.accounts[0].name == "Main"
assert result.model.accounts[0].balance == Decimal("500")
@pytest.mark.parametrize(
("value", "expected"),
[
("1 234,56", Decimal("1234.56")),
("1,234.56", Decimal("1234.56")),
("₽1 200,50", Decimal("1200.50")),
("(100)", Decimal("-100")),
("-1200", Decimal("-1200")),
],
)
def test_number_formats(self, tmp_path: Path, value, expected):
# Отрицательные суммы — в столбце «Сумма» регулярного платежа:
# баланс счёта отрицательным быть не может (правило модели).
path = _write_sheets(
tmp_path / "model.xlsx",
{"Recurring": [["Сумма"], [value]]},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.recurring[0].amount == expected
@pytest.mark.parametrize(
("value", "expected"),
[
("2026-11-01", "2026-11-01"),
("01.11.2026", "2026-11-01"),
("01/11/2026", "2026-11-01"),
],
)
def test_date_formats(self, tmp_path: Path, value, expected):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Transactions": [["Дата", "Счёт", "Сумма"], [value, "Счёт", 100]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.transactions[0].date == expected
def test_account_is_resolved_by_name(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название", "Валюта", "Баланс"], ["Основной", "RUB", 100]],
"Transactions": [["Дата", "Счёт", "Сумма"], ["2026-11-01", "Основной", 500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.transactions[0].account == str(result.model.accounts[0].id)
def test_unknown_account_is_an_error_with_address(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Основной"]],
"Transactions": [["Дата", "Счёт", "Сумма"], ["2026-11-01", "Нет такого", 500]],
},
)
result = ExcelRepository().load_report(path)
assert len(result.errors) == 1
error = result.errors[0]
assert error.sheet == "Transactions"
assert error.row == 2
assert "Нет такого" in error.message
def test_load_raises_on_errors(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{"Accounts": [["Название", "Баланс"], ["Счёт", "не число"]]},
)
with pytest.raises(ExcelRepositoryError):
ExcelRepository().load(path)
def test_unknown_column_is_a_warning(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{"Accounts": [["Название", "Баланс", "Пожелание"], ["Счёт", 100, "хочу миллион"]]},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert any("Пожелание" in warning for warning in result.warnings)
def test_duplicate_account_names_are_a_warning(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{"Accounts": [["Название", "Баланс"], ["Счёт", 100], ["счёт", 200]]},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert any("повторяется" in warning for warning in result.warnings)
def test_russian_frequency_is_normalized(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Recurring": [["Периодичность", "Сумма"], ["ежемесячно", -1500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.recurring[0].frequency == "monthly"
def test_empty_periodicity_falls_back_to_monthly(self, tmp_path: Path):
# Пустая ячейка в Excel — это «не задано», а не ошибка: период по
# умолчанию задаёт сама модель.
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Recurring": [["Периодичность", "Сумма"], ["", -1500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors == []
assert result.model.recurring[0].frequency == "monthly"
def test_unknown_periodicity_is_an_error(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"Accounts": [["Название"], ["Счёт"]],
"Recurring": [["Периодичность", "Сумма"], ["hourly", -1500]],
},
)
result = ExcelRepository().load_report(path)
assert result.errors
assert "периодичность" in result.errors[0].message.lower()
def test_model_info_accepts_russian_labels(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"ModelInfo": [
["Свойство", "Значение"],
["Базовая валюта", "EUR"],
["Валюта вывода", "USD"],
],
"Accounts": [["Название"], ["Счёт"]],
},
)
result = ExcelRepository().load_report(path)
assert result.model.base_currency == "EUR"
assert result.model.display_currency == "USD"
def test_empty_model_info_cell_is_not_the_word_none(self, tmp_path: Path):
path = _write_sheets(
tmp_path / "model.xlsx",
{
"ModelInfo": [
["Свойство", "Значение"],
["Базовая валюта", "RUB"],
["Валюта вывода", None],
],
},
)
result = ExcelRepository().load_report(path)
assert result.model.display_currency == ""
class TestExportIsEditable:
"""D36: выгруженный файл — это шаблон с данными."""
def test_export_contains_instruction_and_validations(self, sample_model, tmp_path: Path):
path = tmp_path / "exported.xlsx"
ExcelRepository().save(sample_model, path)
wb = load_workbook(path)
try:
assert "Инструкция" in wb.sheetnames
assert wb["Transactions"].data_validations.dataValidation
assert [cell.value for cell in wb["Accounts"][1]] == ["ID", "Название", "Валюта", "Баланс"]
finally:
wb.close()
def test_exported_file_can_be_imported_back(self, sample_model, tmp_path: Path):
path = tmp_path / "exported.xlsx"
ExcelRepository().save(sample_model, path)
loaded = ExcelRepository().load(path)
assert [a.name for a in loaded.accounts] == ["Основной счёт", "Сбережения"]
assert loaded.accounts[0].balance == Decimal("5000")
assert loaded.transactions[0].date == "2026-01-01"
def test_export_preserves_own_currency_of_operations(self, tmp_path: Path):
from domain import Account, FinancialModel, Transaction
model = FinancialModel(
accounts=[Account(name="Доллары", currency="USD", balance=Decimal("100"))],
transactions=[
Transaction(date="2026-01-01", account="Доллары", amount=Decimal("5"), currency="EUR")
],
)
path = tmp_path / "currencies.xlsx"
ExcelRepository().save(model, path)
loaded = ExcelRepository().load(path)
assert loaded.transactions[0].currency == "EUR"
assert loaded.accounts[0].currency == "USD"