+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.
123 lines
5.4 KiB
Python
123 lines
5.4 KiB
Python
from decimal import Decimal
|
|
|
|
from application.scenarios import DEFAULT_SCENARIOS, ScenarioService
|
|
|
|
_BALANCE = "total_balance"
|
|
_INCOME = "total_income"
|
|
_EXPENSES = "total_expenses"
|
|
|
|
_DESCRIPTIONS = {
|
|
"baseline": "Базовый сценарий без изменений",
|
|
"optimistic": "Оптимистичный: доход +15%, расход -5%, рост активов +20%",
|
|
"pessimistic": "Пессимистичный: доход -15%, расход +10%, рост активов -20%",
|
|
}
|
|
|
|
|
|
class TestScenarioService:
|
|
def test_baseline(self, sample_model):
|
|
service = ScenarioService(sample_model)
|
|
result = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
|
|
assert result["scenario"] == "baseline"
|
|
assert result["total_balance"] is not None
|
|
|
|
def test_compare_returns_three(self, sample_model):
|
|
service = ScenarioService(sample_model)
|
|
results = service.compare(months=6)
|
|
assert "baseline" in results
|
|
assert "optimistic" in results
|
|
assert "pessimistic" in results
|
|
|
|
def test_what_if(self, sample_model):
|
|
service = ScenarioService(sample_model)
|
|
result = service.what_if(income_mult=1.2, expense_mult=0.9, months=6)
|
|
assert result["scenario"] == "what-if"
|
|
|
|
|
|
class TestScenarioCharacterization:
|
|
"""Фиксация текущих чисел сервиса сценариев.
|
|
|
|
Это характеристика существующего поведения, а не спецификация: числа
|
|
меняются только вместе с изменением самого движка прогноза.
|
|
"""
|
|
|
|
def test_default_scenarios_numbers_6_months(self, sample_model):
|
|
expected = {
|
|
"baseline": (Decimal("11527.64"), Decimal("26033.66"), Decimal("10483.81")),
|
|
"optimistic": (Decimal("12051.96"), Decimal("30048.49"), Decimal("10003.81")),
|
|
"pessimistic": (Decimal("10943.69"), Decimal("22021.49"), Decimal("11443.81")),
|
|
}
|
|
|
|
for name, scenario in DEFAULT_SCENARIOS.items():
|
|
# СВЕЖИЙ ScenarioService на каждый сценарий.
|
|
result = ScenarioService(sample_model).apply(scenario, months=6)
|
|
assert result["scenario"] == name
|
|
assert result["scenario_description"] == _DESCRIPTIONS[name]
|
|
assert result["months"] == 6
|
|
assert (
|
|
result[_BALANCE],
|
|
result[_INCOME],
|
|
result[_EXPENSES],
|
|
) == expected[name]
|
|
|
|
def test_default_scenarios_numbers_12_months(self, sample_model):
|
|
expected = {
|
|
"baseline": (Decimal("13087.98"), Decimal("52149.97"), Decimal("20705.87")),
|
|
"optimistic": (Decimal("14119.08"), Decimal("60216.93"), Decimal("19745.87")),
|
|
"pessimistic": (Decimal("11938.83"), Decimal("44095.56"), Decimal("22625.87")),
|
|
}
|
|
|
|
for name, scenario in DEFAULT_SCENARIOS.items():
|
|
# СВЕЖИЙ ScenarioService на каждый сценарий.
|
|
result = ScenarioService(sample_model).apply(scenario, months=12)
|
|
assert result["scenario"] == name
|
|
assert result["scenario_description"] == _DESCRIPTIONS[name]
|
|
assert result["months"] == 12
|
|
assert (
|
|
result[_BALANCE],
|
|
result[_INCOME],
|
|
result[_EXPENSES],
|
|
) == expected[name]
|
|
|
|
def test_what_if_numbers(self, sample_model):
|
|
description = "What-if: income x1.2, expense x0.9, growth x1.0"
|
|
|
|
six = ScenarioService(sample_model).what_if(income_mult=1.2, expense_mult=0.9, months=6)
|
|
assert six == {
|
|
_BALANCE: Decimal("12231.75"),
|
|
_INCOME: Decimal("30833.63"),
|
|
_EXPENSES: Decimal("9523.81"),
|
|
"months": 6,
|
|
"scenario": "what-if",
|
|
"scenario_description": description,
|
|
}
|
|
|
|
twelve = ScenarioService(sample_model).what_if(income_mult=1.2, expense_mult=0.9, months=12)
|
|
assert twelve == {
|
|
_BALANCE: Decimal("14514.02"),
|
|
_INCOME: Decimal("61749.97"),
|
|
_EXPENSES: Decimal("18785.87"),
|
|
"months": 12,
|
|
"scenario": "what-if",
|
|
"scenario_description": description,
|
|
}
|
|
|
|
def test_compare_matches_apply(self, sample_model):
|
|
comparison = ScenarioService(sample_model).compare(months=12)
|
|
assert set(comparison) == {"baseline", "optimistic", "pessimistic"}
|
|
|
|
for name, scenario in DEFAULT_SCENARIOS.items():
|
|
# apply() на СВЕЖЕМ сервисе даёт те же числа, что и compare().
|
|
single = ScenarioService(sample_model).apply(scenario, months=12)
|
|
for key in (_BALANCE, _INCOME, _EXPENSES):
|
|
assert comparison[name][key] == single[key]
|
|
|
|
def test_scenario_service_is_not_mutated_by_apply(self, sample_model):
|
|
# apply() работает на копии модели, поэтому сервис не «тратит»
|
|
# обязательство: повторный apply() того же сценария даёт те же числа.
|
|
service = ScenarioService(sample_model)
|
|
first = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
|
|
second = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
|
|
|
|
assert first == second
|
|
assert first[_BALANCE] == Decimal("11527.64")
|