Вместо «месячной доли» (D16b: amount/30.4, amount/4.33, amount/12) регулярный платёж раскладывается по календарю: сколько и каких списаний выпадает в конкретный месяц. - domain/recurrence.py — планировщик на dateutil.rrule: daily/weekly/monthly/ yearly, якорь даты старта сохраняется, end_date ограничивает окно, разбор дат в пользовательских форматах, русские синонимы периодичности; - domain/recurring.py — amount_in_month(month_start, month_end, default_start) вместо monthly_amount()/is_active_in_month(); amount теперь — сумма ОДНОГО списания; периодичность нормализуется при валидации; - application/forecast.py — платёж раскладывается по месяцам сетки. Числа изменились (было → стало): - yearly 1200: 100.00/мес, итог 1200.00 → 1200.00 в месяц якоря, итог 1200.00; - weekly 100: 23.09/мес, итог 277.14 → по календарю (янв 500, фев 400, …); - daily 1: 0.03/мес, итог 0.39 → по числу дней месяца (31, 28, 31, …). Тесты: 255 → 289 (новый tests/test_recurrence.py, переписаны тесты D16b).
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("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, 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("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, 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("12231.75"),
|
||
_INCOME: Decimal("30833.63"),
|
||
_EXPENSES: Decimal("9523.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("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, 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("11527.64")
|
||
|
||
|
||
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")
|