D16b: месячная доля recurring по frequency и учёт start_date/end_date
amount — итог за период frequency: daily /30.4, weekly /4.33, monthly /1, yearly /12 (делители — именованные константы domain/recurring.py). Платёж учитывается в месяце сетки прогноза, если start_date <= конец месяца и end_date >= начало месяца; сравнение по ISO-строкам, пустые даты — без границ. Сетка прогноза привязана к start_month (по умолчанию текущий календарный месяц), округление — только в точке отображения.
This commit is contained in:
1 parent
abcd84c0fa
commit
f50106ca96
6 files changed
+259
-32
No files matched your search
+123
-16
@@ -4,32 +4,43 @@ import pytest
|
||||
|
||||
from application.forecast import ForecastError, ForecastService
|
||||
from domain import Account, FinancialModel, RecurringCashflow
|
||||
from domain.recurring import (
|
||||
DAYS_PER_MONTH,
|
||||
FREQUENCY_MONTHLY_DIVISOR,
|
||||
MONTHS_PER_YEAR,
|
||||
WEEKS_PER_MONTH,
|
||||
)
|
||||
|
||||
_MAIN_ACCOUNT = "Основной счёт"
|
||||
_SAVINGS_ACCOUNT = "Сбережения"
|
||||
|
||||
# Месяц старта сетки прогноза для D11-характеристики: он совпадает с
|
||||
# `start_date` recurring в `sample_model`, поэтому числа не зависят от того,
|
||||
# когда именно запущены тесты (D16b).
|
||||
_GRID_START = "2026-01-01"
|
||||
|
||||
|
||||
class TestForecastService:
|
||||
def test_forecast_returns_results(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
results = service.forecast_cashflow(months=12)
|
||||
assert len(results) > 0
|
||||
assert "balance" in results[0]
|
||||
assert "month" in results[0]
|
||||
|
||||
def test_forecast_12_months(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
results = service.forecast_cashflow(months=12)
|
||||
months = set(r["month"] for r in results)
|
||||
assert max(months) == 12
|
||||
|
||||
def test_invalid_months(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
with pytest.raises(ForecastError):
|
||||
service.forecast_cashflow(months=0)
|
||||
|
||||
def test_summary(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
s = service.summary(months=6)
|
||||
assert "total_balance" in s
|
||||
assert "total_income" in s
|
||||
@@ -92,7 +103,7 @@ class TestForecastCharacterization:
|
||||
"""
|
||||
|
||||
def test_forecast_cashflow_12_months_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
results = service.forecast_cashflow(months=12)
|
||||
|
||||
# Порядок строк: сначала все 12 месяцев «Основного счёта»,
|
||||
@@ -129,7 +140,7 @@ class TestForecastCharacterization:
|
||||
assert actual == expected
|
||||
|
||||
def test_summary_6_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
assert service.summary(months=6) == {
|
||||
"total_balance": Decimal("11527.64"),
|
||||
"total_income": Decimal("26033.66"),
|
||||
@@ -138,7 +149,7 @@ class TestForecastCharacterization:
|
||||
}
|
||||
|
||||
def test_summary_12_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
assert service.summary(months=12) == {
|
||||
"total_balance": Decimal("13087.98"),
|
||||
"total_income": Decimal("52149.97"),
|
||||
@@ -151,7 +162,7 @@ class TestForecastCharacterization:
|
||||
# повторный forecast_cashflow на ТОМ ЖЕ экземпляре сервиса даёт
|
||||
# идентичный результат. До D14 второй вызов давал 13649.62 вместо
|
||||
# 13087.98 (сумма 368465.98 вместо 361041.88).
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
first = service.forecast_cashflow(months=12)
|
||||
second = service.forecast_cashflow(months=12)
|
||||
|
||||
@@ -163,7 +174,7 @@ class TestForecastCharacterization:
|
||||
|
||||
def test_forecast_does_not_mutate_model(self, sample_model):
|
||||
# D14: модель сервиса после прогноза байт-в-байт та же, что до.
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
before = service.model.model_dump_json()
|
||||
service.forecast_cashflow(months=12)
|
||||
service.summary(months=12)
|
||||
@@ -172,14 +183,14 @@ class TestForecastCharacterization:
|
||||
# И модель, переданная в сервис, тоже не меняется (сервис работает
|
||||
# на копии — и не трогает оригинал).
|
||||
original = sample_model.model_dump_json()
|
||||
ForecastService(sample_model).forecast_cashflow(months=12)
|
||||
ForecastService(sample_model, start_month=_GRID_START).forecast_cashflow(months=12)
|
||||
assert sample_model.model_dump_json() == original
|
||||
|
||||
def test_summary_after_forecast_matches_summary_alone(self, sample_model):
|
||||
# D14: сводка больше не расходится с прогнозом. До D14 после двух
|
||||
# прогнозов summary давал 13730.60 / 52867.46 / 19200.00 вместо
|
||||
# 13087.98 / 52149.97 / 20705.87.
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
service.forecast_cashflow(months=12)
|
||||
service.forecast_cashflow(months=12)
|
||||
summary = service.summary(months=12)
|
||||
@@ -191,13 +202,13 @@ class TestForecastCharacterization:
|
||||
}
|
||||
|
||||
# На свежем экземпляре — те же числа.
|
||||
fresh = ForecastService(sample_model)
|
||||
fresh = ForecastService(sample_model, start_month=_GRID_START)
|
||||
assert fresh.summary(months=12)["total_balance"] == Decimal("13087.98")
|
||||
|
||||
def test_summary_total_balance_is_last_table_row(self, sample_model):
|
||||
# D14: «Итог» в CLI обязан совпадать с последней строкой таблицы —
|
||||
# сводка считается по тому же набору результатов.
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
results = service.forecast_cashflow(months=12)
|
||||
summary = service.summary(months=12, results=results)
|
||||
assert summary["total_balance"] == results[-1]["balance"]
|
||||
@@ -209,7 +220,7 @@ class TestForecastCharacterization:
|
||||
# D15: округление в прогнозе осталось только в точке сериализации
|
||||
# (`_q()`), поэтому JSON-вывод стабилен: все денежные значения —
|
||||
# ровно два знака после запятой.
|
||||
service = ForecastService(sample_model)
|
||||
service = ForecastService(sample_model, start_month=_GRID_START)
|
||||
results = service.forecast_cashflow(months=12)
|
||||
assert results
|
||||
for row in results:
|
||||
@@ -224,8 +235,104 @@ class TestForecastCharacterization:
|
||||
# Стоимость обязательства амортизируется по одному вызову на каждый
|
||||
# (счёт × месяц), поэтому суммарное число вызовов зависит от
|
||||
# горизонта — это текущее поведение (Tier 2, D16).
|
||||
six = ForecastService(sample_model).summary(months=6)
|
||||
twelve = ForecastService(sample_model).summary(months=12)
|
||||
six = ForecastService(sample_model, start_month=_GRID_START).summary(months=6)
|
||||
twelve = ForecastService(sample_model, start_month=_GRID_START).summary(months=12)
|
||||
|
||||
assert six["total_balance"] == Decimal("11527.64")
|
||||
assert twelve["total_balance"] == Decimal("13087.98")
|
||||
|
||||
|
||||
class TestRecurringSchedule:
|
||||
"""D16b: периодичность и границы recurring.
|
||||
|
||||
`amount` — итог за период `frequency`; в каждый месяц сетки прогноза
|
||||
попадает месячная доля (amount / делитель), а `start_date`/`end_date`
|
||||
ограничивают месяцы, в которых платёж вообще учитывается.
|
||||
"""
|
||||
|
||||
_GRID = "2026-01-01"
|
||||
|
||||
@staticmethod
|
||||
def _model(amount: str, frequency: str = "monthly", start_date: str = "", end_date: str = "") -> FinancialModel:
|
||||
return FinancialModel(
|
||||
accounts=[Account(name="Счёт", balance=Decimal("0"))],
|
||||
recurring=[
|
||||
RecurringCashflow(
|
||||
amount=Decimal(amount),
|
||||
frequency=frequency,
|
||||
start_date=start_date,
|
||||
end_date=end_date,
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
def _incomes(self, model: FinancialModel, months: int = 6) -> list[Decimal]:
|
||||
rows = ForecastService(model, start_month=self._GRID).forecast_cashflow(months)
|
||||
return [row["income"] for row in rows]
|
||||
|
||||
def test_frequency_divisors_cover_exactly_the_allowed_frequencies(self):
|
||||
assert set(FREQUENCY_MONTHLY_DIVISOR) == {"daily", "weekly", "monthly", "yearly"}
|
||||
assert FREQUENCY_MONTHLY_DIVISOR["daily"] == DAYS_PER_MONTH == Decimal("30.4")
|
||||
assert FREQUENCY_MONTHLY_DIVISOR["weekly"] == WEEKS_PER_MONTH == Decimal("4.33")
|
||||
assert FREQUENCY_MONTHLY_DIVISOR["monthly"] == Decimal("1")
|
||||
assert FREQUENCY_MONTHLY_DIVISOR["yearly"] == MONTHS_PER_YEAR == Decimal("12")
|
||||
|
||||
def test_monthly_without_bounds_pays_every_month(self):
|
||||
# Как было до D16b: monthly без границ — вся сумма в каждом месяце.
|
||||
assert self._incomes(self._model("500")) == [Decimal("500.00")] * 6
|
||||
|
||||
def test_empty_start_date_means_from_the_beginning(self):
|
||||
assert self._incomes(self._model("500", start_date="")) == [Decimal("500.00")] * 6
|
||||
|
||||
def test_monthly_start_date_inside_horizon(self):
|
||||
# Старт 10 апреля: январь–март без платежа, апрель–июнь — платёж.
|
||||
incomes = self._incomes(self._model("500", start_date="2026-04-10"))
|
||||
assert incomes == [Decimal("0.00")] * 3 + [Decimal("500.00")] * 3
|
||||
|
||||
def test_monthly_start_date_exactly_on_month_start(self):
|
||||
# Граница включительная: start_date == начало марта → март уже платит.
|
||||
incomes = self._incomes(self._model("500", start_date="2026-03-01"))
|
||||
assert incomes == [Decimal("0.00")] * 2 + [Decimal("500.00")] * 4
|
||||
|
||||
def test_monthly_start_date_exactly_on_month_end(self):
|
||||
# start_date == конец февраля → февраль уже платит (start ≤ конец месяца).
|
||||
incomes = self._incomes(self._model("500", start_date="2026-02-28"))
|
||||
assert incomes == [Decimal("0.00")] + [Decimal("500.00")] * 5
|
||||
|
||||
def test_monthly_end_date_stops_payments(self):
|
||||
incomes = self._incomes(self._model("500", end_date="2026-03-15"))
|
||||
assert incomes == [Decimal("500.00")] * 3 + [Decimal("0.00")] * 3
|
||||
|
||||
def test_monthly_end_date_exactly_on_month_start(self):
|
||||
# Граница включительная: end_date == начало марта → март ещё платит.
|
||||
incomes = self._incomes(self._model("500", end_date="2026-03-01"))
|
||||
assert incomes == [Decimal("500.00")] * 3 + [Decimal("0.00")] * 3
|
||||
|
||||
def test_end_date_before_grid_pays_nothing(self):
|
||||
incomes = self._incomes(self._model("500", end_date="2025-12-31"))
|
||||
assert incomes == [Decimal("0.00")] * 6
|
||||
|
||||
def test_yearly_amount_is_split_by_12(self):
|
||||
model = self._model("1200", frequency="yearly")
|
||||
assert self._incomes(model, months=12) == [Decimal("100.00")] * 12
|
||||
# Итог за год сохраняется: 12 × 100 = 1200.
|
||||
assert ForecastService(model, start_month=self._GRID).summary(months=12)["total_income"] == Decimal("1200.00")
|
||||
|
||||
def test_weekly_amount_is_split_by_4_33(self):
|
||||
assert self._incomes(self._model("43.3", frequency="weekly")) == [Decimal("10.00")] * 6
|
||||
|
||||
def test_daily_amount_is_split_by_30_4(self):
|
||||
assert self._incomes(self._model("30.4", frequency="daily")) == [Decimal("1.00")] * 6
|
||||
|
||||
def test_weekly_share_keeps_full_decimal_precision(self):
|
||||
item = RecurringCashflow(amount=Decimal("100"), frequency="weekly")
|
||||
assert item.monthly_amount() == Decimal("100") / Decimal("4.33")
|
||||
# В строке прогноза — округление до копеек при отображении.
|
||||
assert self._incomes(self._model("100", frequency="weekly"), months=1) == [Decimal("23.09")]
|
||||
|
||||
def test_rounding_happens_only_on_display(self):
|
||||
# daily amount=1: доля 1/30.4 не квантуется, поэтому баланс за 12
|
||||
# месяцев — 12 × (1/30.4) = 0.3947… → 0.39. Если бы каждая доля
|
||||
# округлялась до 0.03, вышло бы 0.36.
|
||||
rows = ForecastService(self._model("1", frequency="daily"), start_month=self._GRID).forecast_cashflow(12)
|
||||
assert rows[-1]["balance"] == Decimal("0.39")
|
||||
+45
-10
@@ -7,6 +7,10 @@ _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%",
|
||||
@@ -16,20 +20,20 @@ _DESCRIPTIONS = {
|
||||
|
||||
class TestScenarioService:
|
||||
def test_baseline(self, sample_model):
|
||||
service = ScenarioService(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)
|
||||
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)
|
||||
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"
|
||||
|
||||
@@ -90,7 +94,7 @@ class TestScenarioCharacterization:
|
||||
|
||||
for name, scenario in DEFAULT_SCENARIOS.items():
|
||||
# СВЕЖИЙ ScenarioService на каждый сценарий.
|
||||
result = ScenarioService(sample_model).apply(scenario, months=6)
|
||||
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
|
||||
@@ -109,7 +113,7 @@ class TestScenarioCharacterization:
|
||||
|
||||
for name, scenario in DEFAULT_SCENARIOS.items():
|
||||
# СВЕЖИЙ ScenarioService на каждый сценарий.
|
||||
result = ScenarioService(sample_model).apply(scenario, months=12)
|
||||
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
|
||||
@@ -122,7 +126,9 @@ class TestScenarioCharacterization:
|
||||
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)
|
||||
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"),
|
||||
@@ -132,7 +138,9 @@ class TestScenarioCharacterization:
|
||||
"scenario_description": description,
|
||||
}
|
||||
|
||||
twelve = ScenarioService(sample_model).what_if(income_mult=1.2, expense_mult=0.9, months=12)
|
||||
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"),
|
||||
@@ -143,21 +151,48 @@ class TestScenarioCharacterization:
|
||||
}
|
||||
|
||||
def test_compare_matches_apply(self, sample_model):
|
||||
comparison = ScenarioService(sample_model).compare(months=12)
|
||||
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).apply(scenario, months=12)
|
||||
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)
|
||||
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:
|
||||
"""D16b: сценарии видят месячную долю и границы 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_divided_by_12_after_multiplier(self):
|
||||
# 1200 за год × 1.15 (optimistic) / 12 = 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("115.00")
|
||||
assert result[_BALANCE] == Decimal("115.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")
|
||||
Reference in new issue
Block a user