- транзакция из прошлого уже учтена в балансе счёта — в прогноз не попадает; транзакция будущего попадает в месяц своей даты; без даты — в первый месяц сетки; за горизонтом — игнорируется; - счёт ищется и по UUID, и по имени: операция, заполненная в Excel по имени счёта, больше не выпадает из расчёта молча; - ForecastService.warnings — предупреждения расчёта (счёт не найден). Числа изменились (было → стало, sample_model, 12 мес.): - доход 52149.97 → 19149.96 (зарплата и аренда учитывались в каждом месяце, теперь — только в январе); - итоговый баланс 13087.98 → 13184.84. Тесты: 289 → 296 (новый класс TestTransactionDates, характеристики прогноза и сценариев пересчитаны и проверены вручную).
200 lines
9.3 KiB
Python
200 lines
9.3 KiB
Python
from decimal import Decimal
|
||
|
||
from application.scenarios import DEFAULT_SCENARIOS, ScenarioService
|
||
from domain import Account, FinancialModel, RecurringCashflow
|
||
|
||
_BALANCE = "total_balance"
|
||
_INCOME = "total_income"
|
||
_EXPENSES = "total_expenses"
|
||
|
||
# Месяц старта сетки прогноза для D11-характеристики (совпадает с start_date
|
||
# recurring в sample_model) — числа не зависят от даты запуска тестов (D16b).
|
||
_GRID_START = "2026-01-01"
|
||
|
||
_DESCRIPTIONS = {
|
||
"baseline": "Базовый сценарий без изменений",
|
||
"optimistic": "Оптимистичный: доход +15%, расход -5%, рост активов +20%",
|
||
"pessimistic": "Пессимистичный: доход -15%, расход +10%, рост активов -20%",
|
||
}
|
||
|
||
|
||
class TestScenarioService:
|
||
def test_baseline(self, sample_model):
|
||
service = ScenarioService(sample_model, start_month=_GRID_START)
|
||
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, start_month=_GRID_START)
|
||
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, start_month=_GRID_START)
|
||
result = service.what_if(income_mult=1.2, expense_mult=0.9, months=6)
|
||
assert result["scenario"] == "what-if"
|
||
|
||
|
||
class TestRecurringClassificationBySign:
|
||
"""D16a: сценарии применяют множители к recurring по знаку, не по category."""
|
||
|
||
@staticmethod
|
||
def _model(*recurring: RecurringCashflow) -> FinancialModel:
|
||
return FinancialModel(
|
||
accounts=[Account(name="Счёт", balance=Decimal("0"))],
|
||
recurring=list(recurring),
|
||
)
|
||
|
||
def test_negative_amount_with_income_category_uses_expense_multiplier(self):
|
||
model = self._model(RecurringCashflow(amount=Decimal("-500"), category="income"))
|
||
result = ScenarioService(model).apply(DEFAULT_SCENARIOS["optimistic"], months=1)
|
||
|
||
# Расход -500 × 0.95 = -475 (income-множитель 1.15 не применяется).
|
||
assert result[_INCOME] == Decimal("0")
|
||
assert result[_EXPENSES] == Decimal("475")
|
||
assert result[_BALANCE] == Decimal("-475")
|
||
|
||
def test_positive_amount_with_expense_category_uses_income_multiplier(self):
|
||
model = self._model(RecurringCashflow(amount=Decimal("500"), category="expense"))
|
||
result = ScenarioService(model).apply(DEFAULT_SCENARIOS["optimistic"], months=1)
|
||
|
||
# Доход 500 × 1.15 = 575 (expense-множитель 0.95 не применяется).
|
||
assert result[_INCOME] == Decimal("575")
|
||
assert result[_EXPENSES] == Decimal("0")
|
||
assert result[_BALANCE] == Decimal("575")
|
||
|
||
def test_what_if_classifies_recurring_by_sign(self):
|
||
model = self._model(
|
||
RecurringCashflow(amount=Decimal("500"), category="expense"),
|
||
RecurringCashflow(amount=Decimal("-500"), category="income"),
|
||
)
|
||
result = ScenarioService(model).what_if(income_mult=2, expense_mult=Decimal("0.5"), months=1)
|
||
|
||
assert result[_INCOME] == Decimal("1000")
|
||
assert result[_EXPENSES] == Decimal("250")
|
||
assert result[_BALANCE] == Decimal("750")
|
||
|
||
|
||
class TestScenarioCharacterization:
|
||
"""Фиксация текущих чисел сервиса сценариев.
|
||
|
||
Это характеристика существующего поведения, а не спецификация: числа
|
||
меняются только вместе с изменением самого движка прогноза.
|
||
"""
|
||
|
||
def test_default_scenarios_numbers_6_months(self, sample_model):
|
||
expected = {
|
||
"baseline": (Decimal("11591.11"), Decimal("11033.65"), Decimal("4483.81")),
|
||
"optimistic": (Decimal("12135.36"), Decimal("12798.52"), Decimal("4303.81")),
|
||
"pessimistic": (Decimal("10986.41"), Decimal("9271.49"), Decimal("4843.81")),
|
||
}
|
||
|
||
for name, scenario in DEFAULT_SCENARIOS.items():
|
||
# СВЕЖИЙ ScenarioService на каждый сценарий.
|
||
result = ScenarioService(sample_model, start_month=_GRID_START).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("13184.84"), Decimal("19149.96"), Decimal("7505.87")),
|
||
"optimistic": (Decimal("14241.99"), Decimal("22266.93"), Decimal("7205.87")),
|
||
"pessimistic": (Decimal("12008.32"), Decimal("16045.55"), Decimal("8105.87")),
|
||
}
|
||
|
||
for name, scenario in DEFAULT_SCENARIOS.items():
|
||
# СВЕЖИЙ ScenarioService на каждый сценарий.
|
||
result = ScenarioService(sample_model, start_month=_GRID_START).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: доход x1.2, расход x0.9, рост x1.0"
|
||
|
||
six = ScenarioService(sample_model, start_month=_GRID_START).what_if(
|
||
income_mult=1.2, expense_mult=0.9, months=6
|
||
)
|
||
assert six == {
|
||
_BALANCE: Decimal("12302.52"),
|
||
_INCOME: Decimal("12833.63"),
|
||
_EXPENSES: Decimal("4123.81"),
|
||
"months": 6,
|
||
"scenario": "what-if",
|
||
"scenario_description": description,
|
||
}
|
||
|
||
twelve = ScenarioService(sample_model, start_month=_GRID_START).what_if(
|
||
income_mult=1.2, expense_mult=0.9, months=12
|
||
)
|
||
assert twelve == {
|
||
_BALANCE: Decimal("14616.08"),
|
||
_INCOME: Decimal("22149.98"),
|
||
_EXPENSES: Decimal("6905.87"),
|
||
"months": 12,
|
||
"scenario": "what-if",
|
||
"scenario_description": description,
|
||
}
|
||
|
||
def test_compare_matches_apply(self, sample_model):
|
||
comparison = ScenarioService(sample_model, start_month=_GRID_START).compare(months=12)
|
||
assert set(comparison) == {"baseline", "optimistic", "pessimistic"}
|
||
|
||
for name, scenario in DEFAULT_SCENARIOS.items():
|
||
# apply() на СВЕЖЕМ сервисе даёт те же числа, что и compare().
|
||
single = ScenarioService(sample_model, start_month=_GRID_START).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, start_month=_GRID_START)
|
||
first = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
|
||
second = service.apply(DEFAULT_SCENARIOS["baseline"], months=6)
|
||
|
||
assert first == second
|
||
assert first[_BALANCE] == Decimal("11591.11")
|
||
|
||
|
||
class TestRecurringScheduleInScenarios:
|
||
"""D32: сценарии видят календарные списания и границы recurring."""
|
||
|
||
_GRID = "2026-01-01"
|
||
|
||
@staticmethod
|
||
def _model(*recurring: RecurringCashflow) -> FinancialModel:
|
||
return FinancialModel(
|
||
accounts=[Account(name="Счёт", balance=Decimal("0"))],
|
||
recurring=list(recurring),
|
||
)
|
||
|
||
def test_yearly_amount_is_charged_once_after_multiplier(self):
|
||
# D32: годовой платёж списывается целиком в месяц якорной даты:
|
||
# 1200 × 1.15 (optimistic) = 1380, а не 115 в каждом месяце.
|
||
model = self._model(RecurringCashflow(amount=Decimal("1200"), frequency="yearly"))
|
||
result = ScenarioService(model, start_month=self._GRID).apply(DEFAULT_SCENARIOS["optimistic"], months=1)
|
||
assert result[_INCOME] == Decimal("1380.00")
|
||
assert result[_BALANCE] == Decimal("1380.00")
|
||
|
||
def test_end_date_limits_payments_inside_scenario(self):
|
||
model = self._model(RecurringCashflow(amount=Decimal("500"), end_date="2026-02-28"))
|
||
result = ScenarioService(model, start_month=self._GRID).apply(DEFAULT_SCENARIOS["baseline"], months=6)
|
||
# Платежи только в январе и феврале: 500 + 500.
|
||
assert result[_INCOME] == Decimal("1000.00")
|
||
assert result[_BALANCE] == Decimal("1000.00")
|