D31: схема v2 — валюта у денежных величин + display_currency
- Transaction/RecurringCashflow/Asset/Liability получили поле currency (пусто = наследование: у операции — от счёта, у актива/обязательства — от базовой валюты модели); - Account.currency больше не по умолчанию USD: пусто = базовая валюта модели (новый счёт в рублёвой модели не становился долларовым); - FinancialModel.display_currency — валюта вывода по умолчанию, свойство output_currency; SCHEMA_VERSION 1 → 2, миграция v0/v1; - resolve_currency() в domain/currency.py — единое правило «явный → базовый»; - тесты: контракт схемы обновлён на v2, добавлены тесты миграции v1, display_currency и наследования валюты; - попутно: 3 теста были не платформонезависимы (Windows: разделитель пути в дефолте экспорта и cp1252 в subprocess-декодинге) — исправлены.
This commit is contained in:
1 parent
e26ed28068
commit
4bd19abbe9
12 files changed
+175
-21
No files matched your search
+66
-10
@@ -25,7 +25,10 @@ class TestAccount:
|
||||
a = Account(name="Test", balance=Decimal("100.0"))
|
||||
assert a.name == "Test"
|
||||
assert a.balance == Decimal("100.0")
|
||||
assert a.currency == "USD"
|
||||
# D31: валюта счёта не задана по умолчанию — она наследуется от
|
||||
# базовой валюты модели. Раньше дефолтом был «USD», из-за чего новый
|
||||
# счёт в рублёвой модели молча становился долларовым.
|
||||
assert a.currency == ""
|
||||
|
||||
def test_to_dict_roundtrip(self):
|
||||
a = Account(name="Test", balance=Decimal("100.0"))
|
||||
@@ -202,29 +205,29 @@ class TestValidateAssignment:
|
||||
class TestSchemaVersion:
|
||||
"""Регрессии D9: SCHEMA_VERSION — ClassVar, а не поле pydantic.
|
||||
|
||||
Формат файла состояния (`to_dict()`) не меняется: там по-прежнему
|
||||
пишется `{"version": 1, ...}`.
|
||||
Формат файла состояния (`to_dict()`) — `{"version": 2, ...}` (D31).
|
||||
"""
|
||||
|
||||
def test_schema_version_is_not_a_pydantic_field(self):
|
||||
assert "SCHEMA_VERSION" not in FinancialModel.model_fields
|
||||
assert FinancialModel.SCHEMA_VERSION == 1
|
||||
assert FinancialModel.SCHEMA_VERSION == 2
|
||||
|
||||
def test_schema_version_cannot_be_overridden_at_construction(self):
|
||||
# Раньше `SCHEMA_VERSION: int = 1` было полем, и значение принималось
|
||||
# в конструктор. Теперь лишний kwargs игнорируется, версия — 1.
|
||||
# в конструктор. Теперь лишний kwargs игнорируется, версия — 2.
|
||||
model = FinancialModel(SCHEMA_VERSION=99)
|
||||
assert FinancialModel.SCHEMA_VERSION == 1
|
||||
assert model.SCHEMA_VERSION == 1
|
||||
assert model.to_dict()["version"] == 1
|
||||
assert FinancialModel.SCHEMA_VERSION == 2
|
||||
assert model.SCHEMA_VERSION == 2
|
||||
assert model.to_dict()["version"] == 2
|
||||
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 d["version"] == 2
|
||||
assert set(d.keys()) == {
|
||||
"version",
|
||||
"base_currency",
|
||||
"display_currency",
|
||||
"accounts",
|
||||
"transactions",
|
||||
"recurring",
|
||||
@@ -258,7 +261,60 @@ class TestSchemaVersion:
|
||||
|
||||
def test_from_dict_rejects_unknown_version(self):
|
||||
with pytest.raises(ValueError):
|
||||
FinancialModel.from_dict({"version": 2})
|
||||
FinancialModel.from_dict({"version": 3})
|
||||
|
||||
|
||||
class TestSchemaVersion2:
|
||||
"""D31: схема v2 — валюта у денежных величин + валюта вывода."""
|
||||
|
||||
def test_v1_file_is_migrated(self):
|
||||
# Файл состояния, записанный до D31, читается без ошибок: у операций
|
||||
# просто нет своей валюты — она наследуется от счёта.
|
||||
legacy = {
|
||||
"version": 1,
|
||||
"base_currency": "RUB",
|
||||
"accounts": [
|
||||
{
|
||||
"id": "00000000-0000-0000-0000-000000000001",
|
||||
"name": "Счёт",
|
||||
"currency": "RUB",
|
||||
"balance": "100",
|
||||
}
|
||||
],
|
||||
"transactions": [
|
||||
{
|
||||
"id": "00000000-0000-0000-0000-000000000002",
|
||||
"date": "2026-01-01",
|
||||
"account": "00000000-0000-0000-0000-000000000001",
|
||||
"category": "salary",
|
||||
"amount": "500",
|
||||
"description": "",
|
||||
}
|
||||
],
|
||||
}
|
||||
restored = FinancialModel.from_dict(legacy)
|
||||
assert restored.transactions[0].currency == ""
|
||||
assert restored.transactions[0].amount == Decimal("500")
|
||||
assert restored.output_currency == "RUB"
|
||||
|
||||
def test_display_currency_is_used_for_output(self):
|
||||
assert FinancialModel(base_currency="RUB").output_currency == "RUB"
|
||||
assert FinancialModel(base_currency="RUB", display_currency="USD").output_currency == "USD"
|
||||
|
||||
def test_display_currency_survives_roundtrip(self, tmp_path: Path):
|
||||
repo = JsonFileRepository()
|
||||
model = FinancialModel(base_currency="RUB", display_currency="EUR")
|
||||
p = tmp_path / "model.json"
|
||||
repo.save(model, p)
|
||||
assert repo.load(p).display_currency == "EUR"
|
||||
|
||||
def test_operations_carry_own_currency(self):
|
||||
txn = Transaction(amount=Decimal("10"), currency="usd")
|
||||
assert txn.currency == "USD"
|
||||
rec = RecurringCashflow(amount=Decimal("10"), currency=" eur ")
|
||||
assert rec.currency == "EUR"
|
||||
assert Asset(value=Decimal("1")).currency == ""
|
||||
assert Liability(balance=Decimal("1")).currency == ""
|
||||
|
||||
|
||||
class TestPydanticValidators:
|
||||
|
||||
Reference in new issue
Block a user