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
This commit is contained in:
1 parent
43ab5685ec
commit
c702818d43
16 files changed
+229
-22
No files matched your search
@@ -122,6 +122,83 @@ class TestFinancialModel:
|
||||
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.
|
||||
|
||||
|
||||
Reference in new issue
Block a user