Гейт `ruff format --check .` в .github/workflows/ci.yml был красным на dev до слияния веток: application/forecast.py, tests/test_excel_authoring.py, tests/test_forecast.py — разница только в раскладке выражений по строкам (ruff 0.17.2 переносит длинные однострочные списки в одну строку при line-length = 120). Изменение чисто форматное: 354 теста зелёные до и после, ruff check чистый.
428 lines
17 KiB
Python
428 lines
17 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:
|
|
# D40: названия листов — русские, чтобы было видно, что где.
|
|
assert wb.sheetnames == [
|
|
"Счета",
|
|
"Транзакции",
|
|
"Регулярные платежи",
|
|
"Активы",
|
|
"Обязательства",
|
|
"Курсы валют",
|
|
"Сценарии",
|
|
"Настройки модели",
|
|
"Инструкция",
|
|
]
|
|
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["Счета"][1]] == ["ID", "Название", "Валюта", "Баланс"]
|
|
assert [cell.value for cell in wb["Транзакции"][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["Транзакции"].data_validations.dataValidation
|
|
assert validations
|
|
# Валюта и счёт — с выпадающими списками.
|
|
formulas = {validation.formula1 for validation in validations}
|
|
assert any("Счета" in formula for formula in formulas)
|
|
assert any("RUB" in formula for formula in formulas)
|
|
recurring_validations = wb["Регулярные платежи"].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["Транзакции"].data_validations.dataValidation
|
|
assert [cell.value for cell in wb["Счета"][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"
|
|
|
|
|
|
class TestRussianSheetNames:
|
|
"""D40: названия листов — русские, старые английские файлы читаются как раньше."""
|
|
|
|
def test_russian_sheet_names_are_imported(self, tmp_path: Path):
|
|
path = _write_sheets(
|
|
tmp_path / "russian.xlsx",
|
|
{
|
|
"Счета": [["Название", "Баланс"], ["Зарплатный", 120000]],
|
|
"Транзакции": [["Дата", "Счёт", "Сумма"], ["2026-02-01", "Зарплатный", -5000]],
|
|
"Настройки модели": [["Свойство", "Значение"], ["Базовая валюта", "RUB"]],
|
|
},
|
|
)
|
|
|
|
result = ExcelRepository().load_report(path)
|
|
|
|
assert result.errors == []
|
|
assert [a.name for a in result.model.accounts] == ["Зарплатный"]
|
|
assert result.model.accounts[0].balance == Decimal("120000")
|
|
assert len(result.model.transactions) == 1
|
|
assert result.model.base_currency == "RUB"
|
|
|
|
def test_english_sheet_names_still_work(self, tmp_path: Path):
|
|
# Файлы, созданные до D40, лежат у пользователей — они читаются.
|
|
path = _write_sheets(
|
|
tmp_path / "english.xlsx",
|
|
{
|
|
"Accounts": [["Название", "Баланс"], ["Зарплатный", 120000]],
|
|
"Transactions": [["Дата", "Счёт", "Сумма"], ["2026-02-01", "Зарплатный", -5000]],
|
|
"ModelInfo": [["Свойство", "Значение"], ["Базовая валюта", "RUB"]],
|
|
},
|
|
)
|
|
|
|
result = ExcelRepository().load_report(path)
|
|
|
|
assert result.errors == []
|
|
assert [a.name for a in result.model.accounts] == ["Зарплатный"]
|
|
assert len(result.model.transactions) == 1
|
|
assert result.model.base_currency == "RUB"
|
|
|
|
def test_sheet_name_matching_ignores_case_and_spaces(self, tmp_path: Path):
|
|
path = _write_sheets(
|
|
tmp_path / "case.xlsx",
|
|
{
|
|
"счета ": [["Название", "Баланс"], ["Зарплатный", 120000]],
|
|
"РЕГУЛЯРНЫЕ ПЛАТЕЖИ": [["Сумма", "Периодичность"], [-1200, "monthly"]],
|
|
},
|
|
)
|
|
|
|
result = ExcelRepository().load_report(path)
|
|
|
|
assert result.errors == []
|
|
assert len(result.model.accounts) == 1
|
|
assert len(result.model.recurring) == 1
|
|
|
|
def test_error_address_uses_the_sheet_name_from_the_file(self, tmp_path: Path):
|
|
path = _write_sheets(
|
|
tmp_path / "broken.xlsx",
|
|
{
|
|
"Счета": [["Название", "Баланс"], ["Зарплатный", 120000]],
|
|
"Транзакции": [["Дата", "Счёт", "Сумма"], ["2026-02-01", "Нет такого", -5000]],
|
|
},
|
|
)
|
|
|
|
result = ExcelRepository().load_report(path)
|
|
|
|
assert result.errors
|
|
assert result.errors[0].sheet == "Транзакции"
|
|
assert result.errors[0].row == 2
|