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
+219
-12
No files matched your search
+6
-1
@@ -1,10 +1,15 @@
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class Account(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
id: UUID = Field(default_factory=uuid4)
|
||||
name: str = ""
|
||||
currency: str = "USD"
|
||||
|
||||
+6
-1
@@ -1,10 +1,15 @@
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class Asset(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
id: UUID = Field(default_factory=uuid4)
|
||||
name: str = ""
|
||||
value: Decimal = Field(default=Decimal("0"))
|
||||
|
||||
+6
-1
@@ -1,6 +1,6 @@
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
CURRENCY_SYMBOLS = {
|
||||
"RUB": "₽",
|
||||
@@ -42,6 +42,11 @@ DEFAULT_CURRENCY_DECIMALS = 2
|
||||
|
||||
|
||||
class ExchangeRate(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
from_currency: str = "USD"
|
||||
to_currency: str = "RUB"
|
||||
rate: Decimal = Field(default=Decimal("80"))
|
||||
|
||||
+6
-1
@@ -1,10 +1,15 @@
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class Liability(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
id: UUID = Field(default_factory=uuid4)
|
||||
name: str = ""
|
||||
balance: Decimal = Field(default=Decimal("0"))
|
||||
|
||||
+6
-1
@@ -1,6 +1,6 @@
|
||||
from typing import ClassVar
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from domain.account import Account
|
||||
from domain.asset import Asset
|
||||
@@ -12,6 +12,11 @@ from domain.transaction import Transaction
|
||||
|
||||
|
||||
class FinancialModel(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
"""Корневая модель финансового плана.
|
||||
|
||||
Сериализация (save/load) вынесена в `application.repositories.ModelRepository` —
|
||||
|
||||
+6
-1
@@ -1,10 +1,15 @@
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class RecurringCashflow(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
id: UUID = Field(default_factory=uuid4)
|
||||
start_date: str = ""
|
||||
end_date: str = ""
|
||||
|
||||
+6
-1
@@ -1,10 +1,15 @@
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class ForecastScenario(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
id: UUID = Field(default_factory=uuid4)
|
||||
name: str = "baseline"
|
||||
income_multiplier: Decimal = Field(default=Decimal("1"))
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
from decimal import Decimal
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class Transaction(BaseModel):
|
||||
# Валидация при присваивании: любое присваивание полю проверяется
|
||||
# валидатором модели, а значение приводится к объявленному типу
|
||||
# (float в поле Decimal не остаётся float) — D17.
|
||||
model_config = ConfigDict(validate_assignment=True)
|
||||
|
||||
id: UUID = Field(default_factory=uuid4)
|
||||
date: str = ""
|
||||
account: str = ""
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""cf compare — сравнить все сценарии."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
@@ -8,6 +9,7 @@ from infrastructure.cli.services import (
|
||||
build_services,
|
||||
console,
|
||||
convert_value,
|
||||
fail_validation,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
resolve_currency,
|
||||
@@ -25,7 +27,12 @@ def compare(
|
||||
target_curr, symbol = resolve_currency(model, currency)
|
||||
_, scenario_service, _, converter = build_services(model)
|
||||
base_curr = model.base_currency
|
||||
try:
|
||||
results = scenario_service.compare(months)
|
||||
except ValidationError as e:
|
||||
# Сценарий может обнулить суммы (множитель 0) — модель это
|
||||
# отклоняет (валидация при присваивании, D17).
|
||||
fail_validation(e)
|
||||
|
||||
table = Table(title=t("cmd.compare.title", currency=target_curr))
|
||||
table.add_column(t("cmd.compare.col.scenario"), style="cyan")
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
"""cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...)."""
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.table import Table
|
||||
|
||||
from domain import (
|
||||
@@ -13,7 +16,7 @@ from domain import (
|
||||
Transaction,
|
||||
)
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.services import console, load_model, save_model
|
||||
from infrastructure.cli.services import console, fail_validation, load_model, save_model
|
||||
|
||||
app = typer.Typer(name="config", help=t("config.help"))
|
||||
|
||||
@@ -49,19 +52,27 @@ def rate_set(
|
||||
"""Добавить или обновить курс валюты"""
|
||||
model = load_model()
|
||||
fc, tc = from_currency.upper(), to_currency.upper()
|
||||
# Курс пишем Decimal: поле объявлено как Decimal, а float в него класть
|
||||
# нельзя (D17).
|
||||
rate_value = Decimal(str(rate))
|
||||
existing = [r for r in model.exchange_rates if r.from_currency == fc and r.to_currency == tc]
|
||||
try:
|
||||
if existing:
|
||||
existing[0].rate = rate
|
||||
existing[0].rate = rate_value
|
||||
else:
|
||||
model.exchange_rates.append(
|
||||
ExchangeRate(
|
||||
from_currency=fc,
|
||||
to_currency=tc,
|
||||
rate=rate,
|
||||
rate=rate_value,
|
||||
)
|
||||
)
|
||||
except ValidationError as e:
|
||||
# Отрицательный или нулевой курс отклоняет валидатор модели —
|
||||
# показываем понятное сообщение вместо traceback (D17).
|
||||
fail_validation(e)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate)}")
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate_value)}")
|
||||
|
||||
|
||||
@app.command(name="rate-list")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""cf scenario — применить именованный сценарий (baseline/optimistic/pessimistic)."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
|
||||
from application.scenarios import DEFAULT_SCENARIOS
|
||||
from infrastructure.cli.i18n import t
|
||||
@@ -8,6 +9,7 @@ from infrastructure.cli.services import (
|
||||
build_services,
|
||||
console,
|
||||
convert_value,
|
||||
fail_validation,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
resolve_currency,
|
||||
@@ -34,7 +36,12 @@ def scenario(
|
||||
console.print(t("cmd.scenario.err.available", scenarios=", ".join(DEFAULT_SCENARIOS.keys())))
|
||||
raise typer.Exit(1)
|
||||
|
||||
try:
|
||||
result = scenario_service.apply(scenario_obj, months)
|
||||
except ValidationError as e:
|
||||
# Сценарий может обнулить суммы (множитель 0) — модель это
|
||||
# отклоняет (валидация при присваивании, D17).
|
||||
fail_validation(e)
|
||||
balance = convert_value(converter, result["total_balance"], base_curr, target_curr)
|
||||
income = convert_value(converter, result["total_income"], base_curr, target_curr)
|
||||
expenses = convert_value(converter, result["total_expenses"], base_curr, target_curr)
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""cf whatif — what-if анализ с произвольными множителями."""
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.services import (
|
||||
build_services,
|
||||
console,
|
||||
convert_value,
|
||||
fail_validation,
|
||||
fmt_amount,
|
||||
load_model,
|
||||
resolve_currency,
|
||||
@@ -27,7 +29,12 @@ def whatif(
|
||||
target_curr, symbol = resolve_currency(model, currency)
|
||||
_, scenario_service, _, converter = build_services(model)
|
||||
base_curr = model.base_currency
|
||||
try:
|
||||
result = scenario_service.what_if(income, expense, growth, months)
|
||||
except ValidationError as e:
|
||||
# Множитель 0 обнуляет суммы транзакций — модель это отклоняет
|
||||
# (валидация при присваивании, D17). Показываем сообщение, а не traceback.
|
||||
fail_validation(e)
|
||||
|
||||
balance = convert_value(converter, result["total_balance"], base_curr, target_curr)
|
||||
income_v = convert_value(converter, result["total_income"], base_curr, target_curr)
|
||||
|
||||
@@ -253,6 +253,7 @@ _r("cmd.config.liability_remove.err", "Обязательство '{id}' не н
|
||||
# ── global ─────────────────────────────────────────────────────
|
||||
|
||||
_r("global.ok", "OK")
|
||||
_r("global.validation_error", "Ошибка валидации данных: {error}")
|
||||
|
||||
# ── prompts ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -3,13 +3,17 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import NoReturn
|
||||
|
||||
import typer
|
||||
from pydantic import ValidationError
|
||||
from rich.console import Console
|
||||
|
||||
from application.forecast import ForecastService
|
||||
from application.scenarios import ScenarioService
|
||||
from domain import CurrencyConverter, FinancialModel
|
||||
from infrastructure.ai.assistant import AssistantService
|
||||
from infrastructure.cli.i18n import t
|
||||
from infrastructure.cli.paths import MODEL_PATH
|
||||
from infrastructure.repositories import JsonFileRepository
|
||||
|
||||
@@ -18,6 +22,21 @@ console = Console()
|
||||
_json_repo = JsonFileRepository()
|
||||
|
||||
|
||||
def fail_validation(exc: ValidationError) -> NoReturn:
|
||||
"""Показать ошибку валидации понятным сообщением и завершить команду.
|
||||
|
||||
Доменные модели валидируют и при присваивании (D17), поэтому «нельзя
|
||||
положить отрицательный курс» — ожидаемая ошибка ввода, а не сбой
|
||||
программы: пользователь получает понятное сообщение и код возврата 1
|
||||
вместо traceback.
|
||||
"""
|
||||
details = "; ".join(
|
||||
f"{'.'.join(str(part) for part in error['loc']) or 'значение'}: {error['msg']}" for error in exc.errors()
|
||||
)
|
||||
console.print(f"[red]{t('global.validation_error', error=details)}[/red]")
|
||||
raise typer.Exit(1)
|
||||
|
||||
|
||||
def load_model() -> FinancialModel:
|
||||
if MODEL_PATH.exists():
|
||||
return _json_repo.load(MODEL_PATH)
|
||||
|
||||
@@ -181,6 +181,44 @@ class TestCli:
|
||||
assert "Акции" in result.stdout
|
||||
|
||||
|
||||
class TestValidationErrors:
|
||||
"""D17: ошибка валидации — понятное сообщение и код 1, без traceback."""
|
||||
|
||||
def test_config_rate_set_with_negative_rate_fails_cleanly(self):
|
||||
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
|
||||
assert result.exit_code == 1
|
||||
assert "Ошибка валидации" in result.stdout
|
||||
assert "rate must be positive" in result.stdout
|
||||
assert "Traceback" not in result.stdout
|
||||
assert result.exception is None or isinstance(result.exception, SystemExit)
|
||||
|
||||
def test_config_rate_set_with_negative_rate_does_not_save_model(self):
|
||||
runner.invoke(app, ["init"])
|
||||
before = (Path.cwd() / "data" / "model.json").read_text(encoding="utf-8")
|
||||
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
|
||||
assert result.exit_code == 1
|
||||
after = (Path.cwd() / "data" / "model.json").read_text(encoding="utf-8")
|
||||
assert before == after, "Невалидный курс не должен сохраняться в модель"
|
||||
|
||||
def test_config_rate_set_stores_decimal_rate(self):
|
||||
import json
|
||||
|
||||
runner.invoke(app, ["init"])
|
||||
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "90"])
|
||||
assert result.exit_code == 0
|
||||
|
||||
data = json.loads((Path.cwd() / "data" / "model.json").read_text(encoding="utf-8"))
|
||||
rate = data["exchange_rates"][0]["rate"]
|
||||
# Decimal сериализуется строкой, а не числом float.
|
||||
assert isinstance(rate, str)
|
||||
assert rate == "90.0"
|
||||
|
||||
def test_config_rate_set_with_valid_rate_succeeds(self):
|
||||
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "90"])
|
||||
assert result.exit_code == 0
|
||||
assert "Traceback" not in result.stdout
|
||||
|
||||
|
||||
class TestFilesystemIsolation:
|
||||
"""Регрессии D10: CLI-тесты не пишут в дерево репозитория."""
|
||||
|
||||
|
||||
@@ -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