Files
nifodea/tests/test_model.py
T
oqyude c702818d43 D17: validate_assignment=True — присваивание проверяется, курс пишется Decimal
- domain/*: на всех моделях домена (FinancialModel, Account, Transaction,
  RecurringCashflow, Asset, Liability, ForecastScenario, ExchangeRate)
  включён model_config = ConfigDict(validate_assignment=True). Раньше
  присваивание шло мимо валидаторов: `r.rate = -5` принимался, а
  config_cmd.py писал в поле Decimal значение типа float.
- infrastructure/cli/commands/config_cmd.py: rate_set пишет
  Decimal(str(rate)) вместо float.
- infrastructure/cli/services.py: хелпер fail_validation() — печатает
  понятное сообщение (t("global.validation_error")) и завершает команду
  кодом 1 вместо traceback.
- infrastructure/cli/i18n.py: добавлен ключ global.validation_error.
- infrastructure/cli/commands/{whatif,scenario,compare}.py: тот же обработчик
  для случая «множитель 0 обнуляет сумму» — иначе D17 вводил бы новый traceback.
- tests/test_model.py: +9 тестов (отклонение отрицательного/нулевого курса,
  float в поле Decimal не остаётся float, отклонение по всем валидаторам).
- tests/test_cli.py: +4 теста (ненулевой код без traceback, модель не
  сохраняется, курс сохраняется строкой-Decimal, валидный курс проходит).

Было → стало:
  cf config rate-set USD RUB -- -5   принимался, «OK Курс USD → RUB = -5.0»,
                                     курс сохранялся float (-5.0) + warning
                                  → «Ошибка валидации данных: rate: Value error,
                                     rate must be positive», код 1, без traceback
  cf whatif --income 0                работал (суммы обнулялись молча)
                                  → «Ошибка валидации данных: amount: Value error,
                                     amount must be non-zero», код 1
2026-10-25 14:55:40 +03:00

429 lines
18 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
from uuid import UUID
import pytest
from pydantic import ValidationError
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 TestValidateAssignment:
"""D17: модели домена валидируют присваивание (validate_assignment=True).
Раньше `r.rate = -5` молча принимался, а `config_cmd.py` писал в поле
Decimal значение типа float — валидатор при этом не срабатывал.
"""
def test_negative_rate_is_rejected_on_assignment(self):
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))
with pytest.raises(ValidationError) as exc_info:
rate.rate = Decimal("-5")
assert "rate must be positive" in str(exc_info.value)
# Значение не изменилось — невалидное присваивание отклонено целиком.
assert rate.rate == Decimal("80")
def test_zero_rate_is_rejected_on_assignment(self):
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))
with pytest.raises(ValidationError):
rate.rate = Decimal("0")
assert rate.rate == Decimal("80")
def test_float_in_decimal_field_does_not_stay_float(self):
# Присваивание float в поле Decimal не «проходит» как float:
# значение приводится к объявленному типу (Decimal) валидатором.
rate = ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("80"))
rate.rate = 90.5
assert isinstance(rate.rate, Decimal)
assert not isinstance(rate.rate, float)
assert rate.rate == Decimal("90.5")
def test_account_balance_rejected_on_assignment(self):
account = Account(name="A", balance=Decimal("100"))
with pytest.raises(ValidationError) as exc_info:
account.balance = Decimal("-1")
assert "balance must be non-negative" in str(exc_info.value)
assert account.balance == Decimal("100")
def test_transaction_amount_rejected_on_assignment(self):
txn = Transaction(amount=Decimal("100"))
with pytest.raises(ValidationError) as exc_info:
txn.amount = Decimal("0")
assert "amount must be non-zero" in str(exc_info.value)
assert txn.amount == Decimal("100")
def test_recurring_amount_and_frequency_rejected_on_assignment(self):
recurring = RecurringCashflow(amount=Decimal("100"), frequency="monthly")
with pytest.raises(ValidationError):
recurring.amount = Decimal("0")
with pytest.raises(ValidationError):
recurring.frequency = "hourly"
assert recurring.amount == Decimal("100")
assert recurring.frequency == "monthly"
def test_liability_interest_and_payment_rejected_on_assignment(self):
liability = Liability(name="L", balance=Decimal("100"), interest=Decimal("5"), payment=Decimal("10"))
with pytest.raises(ValidationError):
liability.interest = Decimal("-1")
with pytest.raises(ValidationError):
liability.payment = Decimal("-1")
assert liability.interest == Decimal("5")
assert liability.payment == Decimal("10")
def test_scenario_multiplier_rejected_on_assignment(self):
scenario = ForecastScenario(name="s", income_multiplier=Decimal("1"))
with pytest.raises(ValidationError):
scenario.income_multiplier = Decimal("-1")
assert scenario.income_multiplier == Decimal("1")
def test_financial_model_assignment_is_validated(self):
model = FinancialModel()
model.base_currency = "EUR"
assert model.base_currency == "EUR"
with pytest.raises(ValidationError):
model.exchange_rates = [ExchangeRate(from_currency="USD", to_currency="RUB", rate=Decimal("-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})
class TestPydanticValidators:
"""Фиксация текущего поведения всех 7 валидаторов pydantic в домене (D11).
Это тесты-характеристики: они фиксируют ТЕКУЩЕЕ поведение как есть.
Валидаторы НЕ «чинятся» — если текст ошибки изменится, тесты нужно будет
переписать осознанно.
Проверяется и сообщение об ошибке, чтобы из `ValidationError` было видно,
какой именно валидатор сработал.
"""
# --- 1. Account.balance — неотрицательный ---
def test_account_balance_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Account(balance=Decimal("-1"))
assert "balance must be non-negative" in str(exc_info.value)
def test_account_balance_allows_zero(self):
assert Account(balance=Decimal("0")).balance == Decimal("0")
def test_account_balance_rejects_small_negative(self):
with pytest.raises(ValidationError) as exc_info:
Account(balance=Decimal("-0.01"))
assert "balance must be non-negative" in str(exc_info.value)
# --- 2. Transaction.amount — ненулевой (отрицательные разрешены) ---
def test_transaction_amount_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
Transaction(amount=Decimal("0"))
assert "amount must be non-zero" in str(exc_info.value)
def test_transaction_amount_allows_negative(self):
# Расходы записываются отрицательными суммами — это валидное значение.
assert Transaction(amount=Decimal("-0.01")).amount == Decimal("-0.01")
# --- 3. RecurringCashflow.frequency — из фиксированного множества ---
def test_recurring_frequency_allows_known_value(self):
assert RecurringCashflow(frequency="monthly").frequency == "monthly"
def test_recurring_frequency_rejects_unknown_value(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(frequency="hourly")
assert "unknown frequency: hourly" in str(exc_info.value)
def test_recurring_frequency_rejects_empty_string(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(frequency="")
assert "unknown frequency:" in str(exc_info.value)
# --- 4. RecurringCashflow.amount — ненулевой ---
def test_recurring_amount_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(amount=Decimal("0"))
assert "amount must be non-zero" in str(exc_info.value)
def test_recurring_amount_allows_non_zero(self):
assert RecurringCashflow(amount=Decimal("1")).amount == Decimal("1")
# --- 5. Liability.interest / Liability.payment — неотрицательные ---
def test_liability_interest_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Liability(interest=Decimal("-1"))
text = str(exc_info.value)
assert "must be non-negative" in text
assert "interest" in text
def test_liability_payment_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
Liability(payment=Decimal("-1"))
text = str(exc_info.value)
assert "must be non-negative" in text
assert "payment" in text
def test_liability_allows_zero_interest_and_payment(self):
liab = Liability(interest=Decimal("0"), payment=Decimal("0"))
assert liab.interest == Decimal("0")
assert liab.payment == Decimal("0")
# --- 6. ForecastScenario — множители неотрицательные ---
def test_scenario_income_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(income_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "income_multiplier" in text
def test_scenario_expense_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(expense_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "expense_multiplier" in text
def test_scenario_growth_multiplier_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ForecastScenario(growth_multiplier=Decimal("-1"))
text = str(exc_info.value)
assert "multiplier must be non-negative" in text
assert "growth_multiplier" in text
def test_scenario_allows_zero_multipliers(self):
scenario = ForecastScenario(
income_multiplier=Decimal("0"),
expense_multiplier=Decimal("0"),
growth_multiplier=Decimal("0"),
)
assert scenario.income_multiplier == Decimal("0")
assert scenario.expense_multiplier == Decimal("0")
assert scenario.growth_multiplier == Decimal("0")
# --- 7. ExchangeRate.rate — строго положительный ---
def test_exchange_rate_rejects_zero(self):
with pytest.raises(ValidationError) as exc_info:
ExchangeRate(rate=Decimal("0"))
assert "rate must be positive" in str(exc_info.value)
def test_exchange_rate_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ExchangeRate(rate=Decimal("-1"))
assert "rate must be positive" in str(exc_info.value)
def test_exchange_rate_allows_small_positive(self):
assert ExchangeRate(rate=Decimal("0.01")).rate == Decimal("0.01")
class TestDecimalCoercionAndIds:
"""Приведение типов и идентификаторы сущностей — текущее поведение (D11)."""
def test_decimal_fields_accept_strings(self):
# pydantic v2 в нестрогом режиме приводит строку к Decimal без потери
# точности (Decimal("100.50"), а не float).
assert Account(balance="100.50").balance == Decimal("100.50")
assert Transaction(amount="-12.34").amount == Decimal("-12.34")
assert RecurringCashflow(amount="7.25").amount == Decimal("7.25")
assert Asset(value="1000.5").value == Decimal("1000.5")
assert Liability(balance="500.75").balance == Decimal("500.75")
assert ForecastScenario(income_multiplier="1.5").income_multiplier == Decimal("1.5")
assert ExchangeRate(rate="90.25").rate == Decimal("90.25")
def test_entities_have_uuid_ids(self):
# У всех сущностей, кроме ExchangeRate, есть поле id типа UUID.
for entity in (
Account(),
Transaction(),
RecurringCashflow(),
Asset(),
Liability(),
ForecastScenario(),
):
assert isinstance(entity.id, UUID)
# str(UUID) — валидный UUID, который можно разобрать обратно.
assert UUID(str(entity.id)) == entity.id
def test_exchange_rate_has_no_id_field(self):
# В отличие от остальных сущностей, у ExchangeRate поля id нет
# (в листе ExchangeRates тоже нет колонки id — только from/to/rate).
assert "id" not in ExchangeRate.model_fields
assert not hasattr(ExchangeRate(), "id")