Переведены все английские тексты, которые видит пользователь: 13 сообщений исключений (ExcelRepositoryError, CurrencyError, ForecastError, ValueError в domain/ и from_dict) и 7 сообщений pydantic-валидаторов. What-if описание сценария — по-русски. fail_validation() срезает английский префикс pydantic «Value error, » и берёт запасную подпись поля из нового ключа global.value (ключи i18n не переименованы, en.py не тронут). Инвариант tests/test_language.py: словарь ru, тексты raise(...) и прямые строковые литералы console.print не содержат английских маркеров; end-to-end проверки ошибок export/import/валидации.
199 lines
9.1 KiB
Python
199 lines
9.1 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:
|
||
"""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")
|