D28: одна декларативная спецификация листов Excel (SheetSpec)
SHEETS в infrastructure/repositories/excel_repository.py описывает имя листа, порядок полей, класс модели и поле FinancialModel; save()/load() идут по этой таблице, ручные ветки по именам листов и _SHEET_CONFIG удалены. ModelInfo описан отдельным InfoSheetSpec. Поведение и порядок листов/колонок не изменились; добавлены тесты, что добавление спецификации автоматически даёт запись и чтение.
This commit is contained in:
1 parent
f50106ca96
commit
f41fc19cc9
3 files changed
+224
-118
No files matched your search
+88
-11
@@ -1,14 +1,28 @@
|
||||
import ast
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from domain import FinancialModel, ForecastScenario
|
||||
import infrastructure.repositories.excel_repository as excel_repository
|
||||
from domain import Account, FinancialModel, ForecastScenario
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
|
||||
from infrastructure.repositories.excel_repository import InfoSheetSpec, SheetSpec
|
||||
|
||||
_SCENARIO_FIELDS = ["id", "name", "income_multiplier", "expense_multiplier", "growth_multiplier", "description"]
|
||||
|
||||
_EXPECTED_SHEETS = [
|
||||
"Accounts",
|
||||
"Transactions",
|
||||
"Recurring",
|
||||
"Assets",
|
||||
"Liabilities",
|
||||
"ExchangeRates",
|
||||
"Scenarios",
|
||||
"ModelInfo",
|
||||
]
|
||||
|
||||
|
||||
class TestExcelRepository:
|
||||
def test_export_creates_file(self, sample_model, tmp_path: Path):
|
||||
@@ -177,16 +191,7 @@ class TestExcelRoundTripByValues:
|
||||
|
||||
wb = load_workbook(p)
|
||||
try:
|
||||
assert wb.sheetnames == [
|
||||
"Accounts",
|
||||
"Transactions",
|
||||
"Recurring",
|
||||
"Assets",
|
||||
"Liabilities",
|
||||
"ExchangeRates",
|
||||
"Scenarios",
|
||||
"ModelInfo",
|
||||
]
|
||||
assert wb.sheetnames == _EXPECTED_SHEETS
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
@@ -270,3 +275,75 @@ class TestScenariosSheet:
|
||||
wb.close()
|
||||
|
||||
assert repo.load(p).scenarios == []
|
||||
|
||||
|
||||
class TestSheetSpecIsSingleSource:
|
||||
"""D28: запись и чтение выводятся из одной декларативной таблицы `SHEETS`."""
|
||||
|
||||
def test_spec_covers_every_sheet_in_order(self):
|
||||
assert [spec.name for spec in excel_repository.SHEETS] == _EXPECTED_SHEETS
|
||||
|
||||
def test_collection_specs_point_to_existing_model_fields(self):
|
||||
model = FinancialModel()
|
||||
collection_specs = [spec for spec in excel_repository.SHEETS if isinstance(spec, SheetSpec)]
|
||||
|
||||
assert len(collection_specs) == 7
|
||||
for spec in collection_specs:
|
||||
assert hasattr(model, spec.collection), f"{spec.name}: нет поля {spec.collection}"
|
||||
assert isinstance(getattr(model, spec.collection), list)
|
||||
|
||||
def test_written_headers_are_taken_from_spec(self, sample_model, tmp_path: Path):
|
||||
repo = ExcelRepository()
|
||||
p = tmp_path / "headers.xlsx"
|
||||
repo.save(sample_model, p)
|
||||
|
||||
wb = load_workbook(p)
|
||||
try:
|
||||
for spec in excel_repository.SHEETS:
|
||||
headers = [cell.value for cell in wb[spec.name][1]]
|
||||
if isinstance(spec, InfoSheetSpec):
|
||||
assert headers == ["Property", "Value"]
|
||||
else:
|
||||
assert headers == list(spec.fields), f"{spec.name}: заголовки не из спецификации"
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
def test_new_spec_gets_write_and_read_without_code_changes(
|
||||
self, sample_model, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
):
|
||||
# Генерическая запись/чтение: лист, которого нет в боевой таблице,
|
||||
# но который добавлен в спецификацию, сохраняется и читается сам.
|
||||
copy_sheet = SheetSpec("AccountsCopy", ("id", "name", "currency", "balance"), Account, "accounts")
|
||||
monkeypatch.setattr(excel_repository, "SHEETS", (copy_sheet, InfoSheetSpec()))
|
||||
|
||||
repo = ExcelRepository()
|
||||
p = tmp_path / "spec_driven.xlsx"
|
||||
repo.save(sample_model, p)
|
||||
|
||||
wb = load_workbook(p)
|
||||
try:
|
||||
assert wb.sheetnames == ["AccountsCopy", "ModelInfo"]
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
loaded = repo.load(p)
|
||||
assert [account.name for account in loaded.accounts] == ["Основной счёт", "Сбережения"]
|
||||
assert loaded.accounts[0].balance == Decimal("5000")
|
||||
|
||||
def test_no_manual_branches_by_sheet_name_remain(self):
|
||||
# В коде репозитория не должно остаться ручных веток по именам листов:
|
||||
# имена живут только в `SHEETS`.
|
||||
source = Path(excel_repository.__file__).read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
|
||||
comparisons = [
|
||||
node
|
||||
for node in ast.walk(tree)
|
||||
if isinstance(node, ast.Compare)
|
||||
and any(
|
||||
isinstance(operand, ast.Name) and operand.id == "sheet_name"
|
||||
for operand in (node.left, *node.comparators)
|
||||
)
|
||||
]
|
||||
assert comparisons == [], "остались ручные сравнения по имени листа"
|
||||
assert "_SHEET_CONFIG" not in source
|
||||
Reference in new issue
Block a user