D11: тесты-характеристики — фиксация текущего поведения
+71 тест (81 → 160). Характеристики фиксируют существующее поведение как есть; их правка — вместе с изменением поведения (Tier 2, D14–D16). - tests/test_forecast.py: TestForecastCharacterization — точные 24 строки forecast_cashflow(12), summary(6)/summary(12), неидемпотентность повторного прогноза (Tier 2, D14), расхождение summary после прогноза, влияние горизонта - tests/test_scenarios.py: TestScenarioCharacterization — числа baseline/ optimistic/pessimistic на 6 и 12 мес., what_if, совпадение compare() с apply() - tests/test_ai.py: TestAssistantCompareScenarios — точный текст промпта compare_scenarios (251 символ), display_currency, подстановка JSON - tests/test_model.py: TestPydanticValidators — все 7 валидаторов домена (balance, amount×2, frequency, interest/payment, множители×3, rate) с проверкой текста ошибки; TestDecimalCoercionAndIds - tests/test_currency.py: TestRoundingBoundaries — 18 границ .5 для format_money (USD/JPY/BHD/CHF/RUB, отрицательные) и 5 для convert() - tests/test_excel_sync.py: TestExcelRoundTripByValues — round-trip по значениям всех 6 листов + ModelInfo, 7 листов в файле Проверено мутацией: смена режима округления роняет 11 тестов test_currency.py.
This commit is contained in:
1 parent
60ac9252ec
commit
2f02a5de63
6 files changed
+619
No files matched your search
@@ -1,7 +1,9 @@
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from domain import (
|
||||
Account,
|
||||
@@ -180,3 +182,170 @@ class TestSchemaVersion:
|
||||
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")
|
||||
Reference in new issue
Block a user