Files
nifodea/tests/test_model.py
T
oqyude b15533f275 D9: SCHEMA_VERSION объявить как ClassVar[int] + регрессионные тесты
- domain/model.py: `SCHEMA_VERSION: int = 1` в pydantic v2 — это поле, а не
  метаданные класса (значение принималось в конструкторе:
  `FinancialModel(SCHEMA_VERSION=99)`). Теперь `ClassVar[int]` — поле
  исключено из model_fields/model_dump.
- Формат to_dict() и файла состояния НЕ изменился: `version` по-прежнему
  пишется вручную и равен 1 (зафиксировано тестами).
- tests/test_model.py: +6 регрессионных тестов (ClassVar, неизменяемость
  версии, набор ключей to_dict, round-trip to_dict/from_dict, legacy v0,
  отказ от неизвестной версии).
2026-10-25 05:17:32 +03:00

183 lines
6.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from decimal import Decimal
from pathlib import Path
import pytest
from domain import (
Account,
Asset,
ExchangeRate,
FinancialModel,
ForecastScenario,
Liability,
RecurringCashflow,
Transaction,
)
from infrastructure.repositories import JsonFileRepository
_repo = JsonFileRepository()
class TestAccount:
def test_create(self):
a = Account(name="Test", balance=Decimal("100.0"))
assert a.name == "Test"
assert a.balance == Decimal("100.0")
assert a.currency == "USD"
def test_to_dict_roundtrip(self):
a = Account(name="Test", balance=Decimal("100.0"))
d = a.model_dump(mode="json")
a2 = Account.model_validate(d)
assert a2.name == a.name
assert a2.balance == a.balance
assert a2.currency == a.currency
class TestTransaction:
def test_create(self):
t = Transaction(amount=Decimal("500.0"), category="food")
assert t.amount == Decimal("500.0")
def test_roundtrip(self):
t = Transaction(amount=Decimal("-100.0"), category="rent", description="test")
d = t.model_dump(mode="json")
t2 = Transaction.model_validate(d)
assert t2.amount == t.amount
assert t2.category == t.category
assert t2.description == t.description
class TestFinancialModel:
def test_default_base_currency(self):
model = FinancialModel()
assert model.base_currency == "RUB"
def test_base_currency_roundtrip(self, tmp_path: Path):
model = FinancialModel(base_currency="EUR")
p = tmp_path / "model.json"
_repo.save(model, p)
loaded = _repo.load(p)
assert loaded.base_currency == "EUR"
def test_base_currency_backward_compat(self, tmp_path: Path):
import json
p = tmp_path / "legacy.json"
with open(p, "w") as f:
json.dump({"accounts": []}, f)
loaded = _repo.load(p)
assert loaded.base_currency == "RUB"
def test_exchange_rates_default(self):
model = FinancialModel()
assert len(model.exchange_rates) == 1
assert model.exchange_rates[0].from_currency == "USD"
assert model.exchange_rates[0].to_currency == "RUB"
assert model.exchange_rates[0].rate == Decimal("80")
def test_save_load(self, tmp_path: Path):
model = FinancialModel()
model.accounts.append(Account(name="Test", balance=Decimal("100")))
model.transactions.append(Transaction(amount=Decimal("50"), category="income"))
p = tmp_path / "model.json"
_repo.save(model, p)
assert p.exists()
loaded = _repo.load(p)
assert len(loaded.accounts) == 1
assert len(loaded.transactions) == 1
assert loaded.accounts[0].name == "Test"
def test_empty_model(self):
model = FinancialModel()
d = model.to_dict()
assert d["accounts"] == []
assert d["transactions"] == []
assert d["base_currency"] == "RUB"
assert "exchange_rates" in d
def test_all_entities_roundtrip(self, tmp_path: Path):
model = FinancialModel(
accounts=[Account(name="A"), Account(name="B")],
transactions=[Transaction(amount=Decimal("100"))],
recurring=[RecurringCashflow(amount=Decimal("50"))],
assets=[Asset(name="Stock", value=Decimal("1000"))],
liabilities=[Liability(name="Loan", balance=Decimal("500"), interest=Decimal("5"), payment=Decimal("100"))],
scenarios=[ForecastScenario(name="test")],
exchange_rates=[ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))],
)
p = tmp_path / "full.json"
_repo.save(model, p)
loaded = _repo.load(p)
assert len(loaded.accounts) == 2
assert len(loaded.transactions) == 1
assert len(loaded.recurring) == 1
assert len(loaded.assets) == 1
assert len(loaded.liabilities) == 1
assert len(loaded.scenarios) == 1
assert len(loaded.exchange_rates) == 1
class TestSchemaVersion:
"""Регрессии D9: SCHEMA_VERSION — ClassVar, а не поле pydantic.
Формат файла состояния (`to_dict()`) не меняется: там по-прежнему
пишется `{"version": 1, ...}`.
"""
def test_schema_version_is_not_a_pydantic_field(self):
assert "SCHEMA_VERSION" not in FinancialModel.model_fields
assert FinancialModel.SCHEMA_VERSION == 1
def test_schema_version_cannot_be_overridden_at_construction(self):
# Раньше `SCHEMA_VERSION: int = 1` было полем, и значение принималось
# в конструктор. Теперь лишний kwargs игнорируется, версия — 1.
model = FinancialModel(SCHEMA_VERSION=99)
assert FinancialModel.SCHEMA_VERSION == 1
assert model.SCHEMA_VERSION == 1
assert model.to_dict()["version"] == 1
assert "SCHEMA_VERSION" not in model.model_dump()
def test_to_dict_version_and_key_set(self):
d = FinancialModel().to_dict()
assert d["version"] == 1
assert set(d.keys()) == {
"version",
"base_currency",
"accounts",
"transactions",
"recurring",
"assets",
"liabilities",
"scenarios",
"exchange_rates",
}
def test_to_dict_from_dict_roundtrip(self):
model = FinancialModel(
base_currency="EUR",
accounts=[Account(name="A", currency="EUR", balance=Decimal("10.5"))],
transactions=[Transaction(amount=Decimal("-3.25"), category="rent")],
recurring=[RecurringCashflow(amount=Decimal("7"), frequency="weekly")],
assets=[Asset(name="S", value=Decimal("100"), growth_rate=Decimal("8.5"))],
liabilities=[Liability(name="L", balance=Decimal("50"), interest=Decimal("5"), payment=Decimal("1"))],
scenarios=[ForecastScenario(name="sc")],
exchange_rates=[ExchangeRate(from_currency="EUR", to_currency="RUB", rate=Decimal("90"))],
)
restored = FinancialModel.from_dict(model.to_dict())
assert restored.to_dict() == model.to_dict()
assert restored.base_currency == "EUR"
assert restored.accounts[0].balance == Decimal("10.5")
assert restored.transactions[0].amount == Decimal("-3.25")
def test_from_dict_accepts_legacy_without_version(self):
restored = FinancialModel.from_dict({"base_currency": "USD", "accounts": []})
assert restored.base_currency == "USD"
assert restored.accounts == []
def test_from_dict_rejects_unknown_version(self):
with pytest.raises(ValueError):
FinancialModel.from_dict({"version": 2})