Files
nifodea/tests/test_model.py
T
oqyude 7aed61f21b D19: единый язык пользовательских сообщений — русский
Переведены все английские тексты, которые видит пользователь:
13 сообщений исключений (ExcelRepositoryError, CurrencyError,
ForecastError, ValueError в domain/ и from_dict) и 7 сообщений
pydantic-валидаторов. What-if описание сценария — по-русски.

fail_validation() срезает английский префикс pydantic «Value error, »
и берёт запасную подпись поля из нового ключа global.value (ключи
i18n не переименованы, en.py не тронут).

Инвариант tests/test_language.py: словарь ru, тексты raise(...) и
прямые строковые литералы console.print не содержат английских
маркеров; end-to-end проверки ошибок export/import/валидации.
2026-10-25 19:50:31 +03:00

429 lines
19 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` молча принимался, а команда `cf config rate-set`
писала в поле 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 "курс должен быть положительным" 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 "баланс не может быть отрицательным" 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 "сумма не может быть нулевой" 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 "баланс не может быть отрицательным" 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 "баланс не может быть отрицательным" 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 "сумма не может быть нулевой" 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 "неизвестная периодичность: hourly" in str(exc_info.value)
def test_recurring_frequency_rejects_empty_string(self):
with pytest.raises(ValidationError) as exc_info:
RecurringCashflow(frequency="")
assert "неизвестная периодичность:" 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 "сумма не может быть нулевой" 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 "значение не может быть отрицательным" 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 "значение не может быть отрицательным" 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 "множитель не может быть отрицательным" 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 "множитель не может быть отрицательным" 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 "множитель не может быть отрицательным" 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 "курс должен быть положительным" in str(exc_info.value)
def test_exchange_rate_rejects_negative(self):
with pytest.raises(ValidationError) as exc_info:
ExchangeRate(rate=Decimal("-1"))
assert "курс должен быть положительным" 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")