D11: тесты-характеристики — фиксация текущего поведения
+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.
This commit is contained in:
1 parent
60ac9252ec
commit
2f02a5de63
6 files changed
+619
No files matched your search
@@ -17,3 +17,51 @@ class TestAssistantService:
|
||||
result = assistant.advice("Как мне сэкономить?", months=6)
|
||||
assert "prompt" in result
|
||||
assert "ai_response" in result
|
||||
|
||||
|
||||
class TestAssistantCompareScenarios:
|
||||
"""Фиксация точного текста промпта сравнения сценариев.
|
||||
|
||||
Это характеристика существующего поведения: промпт меняется только
|
||||
вместе с изменением шаблона в infrastructure/ai/prompts.py.
|
||||
"""
|
||||
|
||||
def test_compare_scenarios_prompt_exact(self, sample_model):
|
||||
assistant = AssistantService(sample_model, forecast_service=ForecastService(sample_model))
|
||||
result = assistant.compare_scenarios('{"baseline": {"total_balance": "100.00"}}')
|
||||
|
||||
assert set(result) == {"prompt", "ai_response"}
|
||||
assert result["ai_response"] is None
|
||||
|
||||
expected = (
|
||||
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
|
||||
"\n"
|
||||
"### Результаты сценариев:\n"
|
||||
'{"baseline": {"total_balance": "100.00"}}\n'
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: RUB\n"
|
||||
"Отображаемая валюта: RUB\n"
|
||||
"\n"
|
||||
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
|
||||
)
|
||||
assert result["prompt"] == expected
|
||||
assert len(result["prompt"]) == 251
|
||||
|
||||
def test_compare_scenarios_uses_display_currency(self, sample_model):
|
||||
assistant = AssistantService(
|
||||
sample_model,
|
||||
forecast_service=ForecastService(sample_model),
|
||||
display_currency="USD",
|
||||
)
|
||||
prompt = assistant.compare_scenarios('{"baseline": {"total_balance": "100.00"}}')["prompt"]
|
||||
|
||||
assert "Отображаемая валюта: USD" in prompt
|
||||
assert "Базовая валюта модели: RUB" in prompt
|
||||
|
||||
def test_compare_scenarios_embeds_given_json(self, sample_model):
|
||||
scenarios_json = '{"optimistic": {"total_balance": "1.00"}, "pessimistic": {"total_balance": "2.00"}}'
|
||||
assistant = AssistantService(sample_model, forecast_service=ForecastService(sample_model))
|
||||
prompt = assistant.compare_scenarios(scenarios_json)["prompt"]
|
||||
|
||||
assert scenarios_json in prompt
|
||||
@@ -110,3 +110,79 @@ class TestFormatMoney:
|
||||
def test_case_insensitive_currency_code(self, sample_converter):
|
||||
# Defensive: lower-case codes are accepted; storage stays upper-case.
|
||||
assert sample_converter.format_money(Decimal("100"), "usd") == "$100.00"
|
||||
|
||||
|
||||
class TestRoundingBoundaries:
|
||||
"""Границы округления `.5` — текущее поведение (D11).
|
||||
|
||||
Режим округления — ROUND_HALF_UP (0.5 → 1, а не «к чётному»).
|
||||
|
||||
* `format_money` квантизует по числу знаков ISO 4217:
|
||||
JPY — 0 знаков, BHD/KWD/OMR — 3 знака, остальные — 2;
|
||||
неизвестный код → 2 знака (`DEFAULT_CURRENCY_DECIMALS`).
|
||||
* `convert()` квантует результат до 2 знаков ROUND_HALF_UP
|
||||
независимо от числа знаков целевой валюты (см. Tier 2 (D15) ниже).
|
||||
"""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("amount", "currency", "expected"),
|
||||
[
|
||||
# USD — 2 знака, ROUND_HALF_UP
|
||||
(Decimal("0.005"), "USD", "$0.01"),
|
||||
(Decimal("0.015"), "USD", "$0.02"),
|
||||
(Decimal("0.025"), "USD", "$0.03"),
|
||||
(Decimal("1.005"), "USD", "$1.01"),
|
||||
(Decimal("2.675"), "USD", "$2.68"),
|
||||
(Decimal("100.999"), "USD", "$101.00"),
|
||||
(Decimal("100.995"), "USD", "$101.00"),
|
||||
# JPY — 0 знаков
|
||||
(Decimal("0.5"), "JPY", "¥1"),
|
||||
(Decimal("1.5"), "JPY", "¥2"),
|
||||
(Decimal("2.5"), "JPY", "¥3"),
|
||||
(Decimal("-0.5"), "JPY", "-¥1"),
|
||||
# BHD — 3 знака, символа нет → префикс с пробелом
|
||||
(Decimal("0.0005"), "BHD", "BHD 0.001"),
|
||||
(Decimal("1.2345"), "BHD", "BHD 1.235"),
|
||||
# Неизвестный код (CHF) — 2 знака по умолчанию
|
||||
(Decimal("0.125"), "CHF", "CHF 0.13"),
|
||||
# Знак минуса — перед символом
|
||||
(Decimal("-0.005"), "USD", "-$0.01"),
|
||||
(Decimal("-1.005"), "USD", "-$1.01"),
|
||||
# RUB — 2 знака
|
||||
(Decimal("0.5"), "RUB", "₽0.50"),
|
||||
(Decimal("0.05"), "RUB", "₽0.05"),
|
||||
],
|
||||
)
|
||||
def test_format_money_half_up_boundaries(self, amount, currency, expected):
|
||||
assert CurrencyConverter.format_money(amount, currency) == expected
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("amount", "expected"),
|
||||
[
|
||||
(Decimal("0.005"), Decimal("0.40")),
|
||||
(Decimal("0.015"), Decimal("1.20")),
|
||||
(Decimal("0.125"), Decimal("10.00")),
|
||||
(Decimal("2.675"), Decimal("214.00")),
|
||||
(Decimal("1"), Decimal("80.00")),
|
||||
],
|
||||
)
|
||||
def test_convert_half_up_boundaries(self, sample_converter, amount, expected):
|
||||
# USD→RUB, курс 80: multiply, затем quantize(0.01, ROUND_HALF_UP).
|
||||
assert sample_converter.convert(amount, "USD", "RUB") == expected
|
||||
|
||||
def test_convert_always_quantizes_to_two_decimals(self, sample_converter):
|
||||
"""Текущее поведение: convert() квантует до 2 знаков независимо от валюты.
|
||||
|
||||
Изменение — Tier 2 (D15): результат должен учитывать число знаков
|
||||
ISO 4217 целевой валюты (для JPY — 0 знаков).
|
||||
"""
|
||||
assert sample_converter.convert(Decimal("100"), "USD", "RUB") == Decimal("8000.00")
|
||||
|
||||
def test_convert_to_jpy_keeps_two_decimals(self):
|
||||
"""Текущее поведение: USD→JPY квантуется до 2 знаков.
|
||||
|
||||
0.1 USD по курсу 80 → 8.00 (а не «8» — как было бы при 0 знаках JPY).
|
||||
Изменение — Tier 2 (D15).
|
||||
"""
|
||||
converter = CurrencyConverter([ExchangeRate(from_currency="USD", to_currency="JPY", rate=Decimal("80"))])
|
||||
assert converter.convert(Decimal("0.1"), "USD", "JPY") == Decimal("8.00")
|
||||
@@ -1,8 +1,15 @@
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from domain import FinancialModel
|
||||
from infrastructure.repositories import ExcelRepository, ExcelRepositoryError
|
||||
|
||||
# ВНИМАНИЕ: лист Scenarios НЕ поддерживается при экспорте/импорте .xlsx —
|
||||
# сценарии прогноза теряются при round-trip. Это известное поведение,
|
||||
# изменение — Tier 2 (D18). Намеренно здесь НЕ проверяется.
|
||||
|
||||
|
||||
class TestExcelRepository:
|
||||
def test_export_creates_file(self, sample_model, tmp_path: Path):
|
||||
@@ -47,3 +54,100 @@ class TestExcelRepository:
|
||||
p = tmp_path / "empty.xlsx"
|
||||
repo.save(model, p)
|
||||
assert p.exists()
|
||||
|
||||
|
||||
class TestExcelRoundTripByValues:
|
||||
"""Round-trip .xlsx ПО ЗНАЧЕНИЯМ, а не только по количеству строк (D11).
|
||||
|
||||
Тесты-характеристики: фиксируют текущее поведение ExcelRepository.
|
||||
Числа сравниваются по значению (Decimal("5000") == Decimal("5000.00")),
|
||||
а не по записи (числу знаков/экспоненте).
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def _roundtrip(sample_model, tmp_path: Path):
|
||||
"""Сохранить модель в .xlsx и прочитать её обратно."""
|
||||
repo = ExcelRepository()
|
||||
p = tmp_path / "values.xlsx"
|
||||
repo.save(sample_model, p)
|
||||
return repo.load(p)
|
||||
|
||||
def test_base_currency_value(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert loaded.base_currency == "RUB"
|
||||
|
||||
def test_accounts_values(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert len(loaded.accounts) == 2
|
||||
assert [a.name for a in loaded.accounts] == ["Основной счёт", "Сбережения"]
|
||||
assert [a.currency for a in loaded.accounts] == ["RUB", "RUB"]
|
||||
# Сравнение по значению: Decimal("5000") == Decimal("5000.00").
|
||||
assert loaded.accounts[0].balance == Decimal("5000")
|
||||
assert loaded.accounts[1].balance == Decimal("10000")
|
||||
|
||||
def test_account_id_is_preserved(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert str(loaded.accounts[0].id) == str(sample_model.accounts[0].id)
|
||||
|
||||
def test_transactions_values(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert len(loaded.transactions) == 2
|
||||
assert [t.date for t in loaded.transactions] == ["2026-01-01", "2026-01-05"]
|
||||
assert [t.category for t in loaded.transactions] == ["income", "rent"]
|
||||
assert loaded.transactions[0].amount == Decimal("3000")
|
||||
assert loaded.transactions[1].amount == Decimal("-1200")
|
||||
assert [t.description for t in loaded.transactions] == ["Зарплата", "Аренда"]
|
||||
# Ссылка на счёт хранится строкой с UUID основного счёта.
|
||||
assert loaded.transactions[0].account == str(sample_model.accounts[0].id)
|
||||
assert loaded.transactions[1].account == str(sample_model.accounts[0].id)
|
||||
|
||||
def test_recurring_values(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert len(loaded.recurring) == 2
|
||||
assert [r.frequency for r in loaded.recurring] == ["monthly", "monthly"]
|
||||
assert loaded.recurring[0].amount == Decimal("500")
|
||||
assert loaded.recurring[1].amount == Decimal("-200")
|
||||
assert [r.category for r in loaded.recurring] == ["income", "subscription"]
|
||||
assert [r.start_date for r in loaded.recurring] == ["2026-01-01", "2026-01-01"]
|
||||
assert [r.end_date for r in loaded.recurring] == ["", ""]
|
||||
|
||||
def test_assets_values(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert len(loaded.assets) == 1
|
||||
assert loaded.assets[0].name == "Акции"
|
||||
assert loaded.assets[0].value == Decimal("50000")
|
||||
assert loaded.assets[0].growth_rate == Decimal("8")
|
||||
|
||||
def test_liabilities_values(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert len(loaded.liabilities) == 1
|
||||
assert loaded.liabilities[0].name == "Кредит"
|
||||
assert loaded.liabilities[0].balance == Decimal("20000")
|
||||
assert loaded.liabilities[0].interest == Decimal("5")
|
||||
assert loaded.liabilities[0].payment == Decimal("500")
|
||||
|
||||
def test_exchange_rates_values(self, sample_model, tmp_path: Path):
|
||||
loaded = self._roundtrip(sample_model, tmp_path)
|
||||
assert len(loaded.exchange_rates) == 1
|
||||
assert loaded.exchange_rates[0].from_currency == "USD"
|
||||
assert loaded.exchange_rates[0].to_currency == "RUB"
|
||||
assert loaded.exchange_rates[0].rate == Decimal("80")
|
||||
|
||||
def test_written_sheet_names(self, sample_model, tmp_path: Path):
|
||||
repo = ExcelRepository()
|
||||
p = tmp_path / "sheets.xlsx"
|
||||
repo.save(sample_model, p)
|
||||
|
||||
wb = load_workbook(p)
|
||||
try:
|
||||
assert wb.sheetnames == [
|
||||
"Accounts",
|
||||
"Transactions",
|
||||
"Recurring",
|
||||
"Assets",
|
||||
"Liabilities",
|
||||
"ExchangeRates",
|
||||
"ModelInfo",
|
||||
]
|
||||
finally:
|
||||
wb.close()
|
||||
@@ -1,7 +1,12 @@
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from application.forecast import ForecastError, ForecastService
|
||||
|
||||
_MAIN_ACCOUNT = "Основной счёт"
|
||||
_SAVINGS_ACCOUNT = "Сбережения"
|
||||
|
||||
|
||||
class TestForecastService:
|
||||
def test_forecast_returns_results(self, sample_model):
|
||||
@@ -34,3 +39,119 @@ class TestForecastService:
|
||||
service = ForecastService(empty_model)
|
||||
results = service.forecast_cashflow(months=3)
|
||||
assert results == []
|
||||
|
||||
|
||||
class TestForecastCharacterization:
|
||||
"""Фиксация текущих чисел движка прогноза.
|
||||
|
||||
Это характеристика существующего поведения, а не спецификация: числа
|
||||
меняются только вместе с изменением самого движка. Движок мутирует
|
||||
свои assets/liabilities (известная проблема Tier 2, D14), поэтому все
|
||||
проверки ниже выполняются на СВЕЖЕМ экземпляре ForecastService.
|
||||
"""
|
||||
|
||||
def test_forecast_cashflow_12_months_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
results = service.forecast_cashflow(months=12)
|
||||
|
||||
# Порядок строк: сначала все 12 месяцев «Основного счёта»,
|
||||
# затем все 12 месяцев «Сбережений».
|
||||
expected = [
|
||||
(_MAIN_ACCOUNT, 1, Decimal("7152.22"), Decimal("3635.55"), Decimal("1483.33")),
|
||||
(_MAIN_ACCOUNT, 2, Decimal("9190.44"), Decimal("3655.37"), Decimal("1481.60")),
|
||||
(_MAIN_ACCOUNT, 3, Decimal("11226.72"), Decimal("3671.50"), Decimal("1479.85")),
|
||||
(_MAIN_ACCOUNT, 4, Decimal("13262.08"), Decimal("3684.97"), Decimal("1478.10")),
|
||||
(_MAIN_ACCOUNT, 5, Decimal("15297.25"), Decimal("3696.48"), Decimal("1476.35")),
|
||||
(_MAIN_ACCOUNT, 6, Decimal("17332.67"), Decimal("3706.48"), Decimal("1474.58")),
|
||||
(_MAIN_ACCOUNT, 7, Decimal("19368.69"), Decimal("3715.31"), Decimal("1472.81")),
|
||||
(_MAIN_ACCOUNT, 8, Decimal("21405.57"), Decimal("3723.22"), Decimal("1471.03")),
|
||||
(_MAIN_ACCOUNT, 9, Decimal("23443.48"), Decimal("3730.37"), Decimal("1469.24")),
|
||||
(_MAIN_ACCOUNT, 10, Decimal("25482.59"), Decimal("3736.92"), Decimal("1467.45")),
|
||||
(_MAIN_ACCOUNT, 11, Decimal("27522.98"), Decimal("3742.96"), Decimal("1465.64")),
|
||||
(_MAIN_ACCOUNT, 12, Decimal("29564.76"), Decimal("3748.57"), Decimal("1463.83")),
|
||||
(_SAVINGS_ACCOUNT, 1, Decimal("10435.76"), Decimal("697.78"), Decimal("262.02")),
|
||||
(_SAVINGS_ACCOUNT, 2, Decimal("10657.97"), Decimal("680.18"), Decimal("260.19")),
|
||||
(_SAVINGS_ACCOUNT, 3, Decimal("10885.72"), Decimal("666.29"), Decimal("258.36")),
|
||||
(_SAVINGS_ACCOUNT, 4, Decimal("11117.99"), Decimal("655.07"), Decimal("256.52")),
|
||||
(_SAVINGS_ACCOUNT, 5, Decimal("11354.08"), Decimal("645.83"), Decimal("254.67")),
|
||||
(_SAVINGS_ACCOUNT, 6, Decimal("11593.54"), Decimal("638.11"), Decimal("252.81")),
|
||||
(_SAVINGS_ACCOUNT, 7, Decimal("11836.06"), Decimal("631.58"), Decimal("250.95")),
|
||||
(_SAVINGS_ACCOUNT, 8, Decimal("12081.39"), Decimal("625.99"), Decimal("249.08")),
|
||||
(_SAVINGS_ACCOUNT, 9, Decimal("12329.36"), Decimal("621.16"), Decimal("247.20")),
|
||||
(_SAVINGS_ACCOUNT, 10, Decimal("12579.84"), Decimal("616.96"), Decimal("245.32")),
|
||||
(_SAVINGS_ACCOUNT, 11, Decimal("12832.74"), Decimal("613.28"), Decimal("243.42")),
|
||||
(_SAVINGS_ACCOUNT, 12, Decimal("13087.98"), Decimal("610.04"), Decimal("241.52")),
|
||||
]
|
||||
|
||||
actual = [(r["account"], r["month"], r["balance"], r["income"], r["expenses"]) for r in results]
|
||||
assert len(results) == 24
|
||||
assert actual == expected
|
||||
|
||||
def test_summary_6_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
assert service.summary(months=6) == {
|
||||
"total_balance": Decimal("11527.64"),
|
||||
"total_income": Decimal("26033.66"),
|
||||
"total_expenses": Decimal("10483.81"),
|
||||
"months": 6,
|
||||
}
|
||||
|
||||
def test_summary_12_exact_values(self, sample_model):
|
||||
service = ForecastService(sample_model)
|
||||
assert service.summary(months=12) == {
|
||||
"total_balance": Decimal("13087.98"),
|
||||
"total_income": Decimal("52149.97"),
|
||||
"total_expenses": Decimal("20705.87"),
|
||||
"months": 12,
|
||||
}
|
||||
|
||||
def test_repeated_forecast_is_not_idempotent(self, sample_model):
|
||||
# Фиксация текущего (известного, Tier 2 D14) поведения: движок
|
||||
# мутирует свои assets/liabilities, поэтому второй вызов
|
||||
# forecast_cashflow на ТОМ ЖЕ экземпляре сервиса даёт другие числа.
|
||||
# Тест должен измениться вместе с исправлением (Tier 2, D14).
|
||||
service = ForecastService(sample_model)
|
||||
first = service.forecast_cashflow(months=12)
|
||||
second = service.forecast_cashflow(months=12)
|
||||
|
||||
assert first[-1]["balance"] == Decimal("13087.98")
|
||||
assert second[-1]["balance"] == Decimal("13649.62")
|
||||
assert sum(r["balance"] for r in first) == Decimal("361041.88")
|
||||
assert sum(r["balance"] for r in second) == Decimal("368465.98")
|
||||
|
||||
def test_summary_after_forecast_differs_from_summary_alone(self, sample_model):
|
||||
# Расхождение summary() после прогноза и summary() на свежем
|
||||
# экземпляре — известный эффект мутаций движка (Tier 2, D14):
|
||||
# каждый вызов forecast_cashflow (в том числе внутри summary)
|
||||
# амортизирует обязательство и «подращивает» активы.
|
||||
service = ForecastService(sample_model)
|
||||
service.forecast_cashflow(months=12)
|
||||
service.forecast_cashflow(months=12)
|
||||
summary = service.summary(months=12)
|
||||
assert summary == {
|
||||
"total_balance": Decimal("13730.60"),
|
||||
"total_income": Decimal("52867.46"),
|
||||
"total_expenses": Decimal("19200.00"),
|
||||
"months": 12,
|
||||
}
|
||||
|
||||
# Один предварительный forecast_cashflow(12) + summary(12) — это
|
||||
# всего два вызова движка, поэтому числа ещё меньше.
|
||||
once = ForecastService(sample_model)
|
||||
once.forecast_cashflow(months=12)
|
||||
assert once.summary(months=12)["total_balance"] == Decimal("13649.62")
|
||||
|
||||
# На свежом экземпляре service summary(12) даёт другое total_balance
|
||||
# (см. test_summary_12_exact_values).
|
||||
fresh = ForecastService(sample_model)
|
||||
assert fresh.summary(months=12)["total_balance"] == Decimal("13087.98")
|
||||
|
||||
def test_horizon_changes_numbers(self, sample_model):
|
||||
# Стоимость обязательства амортизируется по одному вызову на каждый
|
||||
# (счёт × месяц), поэтому суммарное число вызовов зависит от
|
||||
# горизонта — это текущее поведение (Tier 2, D14/D16).
|
||||
six = ForecastService(sample_model).summary(months=6)
|
||||
twelve = ForecastService(sample_model).summary(months=12)
|
||||
|
||||
assert six["total_balance"] == Decimal("11527.64")
|
||||
assert twelve["total_balance"] == Decimal("13087.98")
|
||||
@@ -1,7 +1,9 @@
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from domain import (
|
||||
Account,
|
||||
@@ -180,3 +182,170 @@ class TestSchemaVersion:
|
||||
def test_from_dict_rejects_unknown_version(self):
|
||||
with pytest.raises(ValueError):
|
||||
FinancialModel.from_dict({"version": 2})
|
||||
|
||||
|
||||
class TestPydanticValidators:
|
||||
"""Фиксация текущего поведения всех 7 валидаторов pydantic в домене (D11).
|
||||
|
||||
Это тесты-характеристики: они фиксируют ТЕКУЩЕЕ поведение как есть.
|
||||
Валидаторы НЕ «чинятся» — если текст ошибки изменится, тесты нужно будет
|
||||
переписать осознанно.
|
||||
|
||||
Проверяется и сообщение об ошибке, чтобы из `ValidationError` было видно,
|
||||
какой именно валидатор сработал.
|
||||
"""
|
||||
|
||||
# --- 1. Account.balance — неотрицательный ---
|
||||
|
||||
def test_account_balance_rejects_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
Account(balance=Decimal("-1"))
|
||||
assert "balance must be non-negative" in str(exc_info.value)
|
||||
|
||||
def test_account_balance_allows_zero(self):
|
||||
assert Account(balance=Decimal("0")).balance == Decimal("0")
|
||||
|
||||
def test_account_balance_rejects_small_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
Account(balance=Decimal("-0.01"))
|
||||
assert "balance must be non-negative" in str(exc_info.value)
|
||||
|
||||
# --- 2. Transaction.amount — ненулевой (отрицательные разрешены) ---
|
||||
|
||||
def test_transaction_amount_rejects_zero(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
Transaction(amount=Decimal("0"))
|
||||
assert "amount must be non-zero" in str(exc_info.value)
|
||||
|
||||
def test_transaction_amount_allows_negative(self):
|
||||
# Расходы записываются отрицательными суммами — это валидное значение.
|
||||
assert Transaction(amount=Decimal("-0.01")).amount == Decimal("-0.01")
|
||||
|
||||
# --- 3. RecurringCashflow.frequency — из фиксированного множества ---
|
||||
|
||||
def test_recurring_frequency_allows_known_value(self):
|
||||
assert RecurringCashflow(frequency="monthly").frequency == "monthly"
|
||||
|
||||
def test_recurring_frequency_rejects_unknown_value(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
RecurringCashflow(frequency="hourly")
|
||||
assert "unknown frequency: hourly" in str(exc_info.value)
|
||||
|
||||
def test_recurring_frequency_rejects_empty_string(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
RecurringCashflow(frequency="")
|
||||
assert "unknown frequency:" in str(exc_info.value)
|
||||
|
||||
# --- 4. RecurringCashflow.amount — ненулевой ---
|
||||
|
||||
def test_recurring_amount_rejects_zero(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
RecurringCashflow(amount=Decimal("0"))
|
||||
assert "amount must be non-zero" in str(exc_info.value)
|
||||
|
||||
def test_recurring_amount_allows_non_zero(self):
|
||||
assert RecurringCashflow(amount=Decimal("1")).amount == Decimal("1")
|
||||
|
||||
# --- 5. Liability.interest / Liability.payment — неотрицательные ---
|
||||
|
||||
def test_liability_interest_rejects_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
Liability(interest=Decimal("-1"))
|
||||
text = str(exc_info.value)
|
||||
assert "must be non-negative" in text
|
||||
assert "interest" in text
|
||||
|
||||
def test_liability_payment_rejects_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
Liability(payment=Decimal("-1"))
|
||||
text = str(exc_info.value)
|
||||
assert "must be non-negative" in text
|
||||
assert "payment" in text
|
||||
|
||||
def test_liability_allows_zero_interest_and_payment(self):
|
||||
liab = Liability(interest=Decimal("0"), payment=Decimal("0"))
|
||||
assert liab.interest == Decimal("0")
|
||||
assert liab.payment == Decimal("0")
|
||||
|
||||
# --- 6. ForecastScenario — множители неотрицательные ---
|
||||
|
||||
def test_scenario_income_multiplier_rejects_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ForecastScenario(income_multiplier=Decimal("-1"))
|
||||
text = str(exc_info.value)
|
||||
assert "multiplier must be non-negative" in text
|
||||
assert "income_multiplier" in text
|
||||
|
||||
def test_scenario_expense_multiplier_rejects_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ForecastScenario(expense_multiplier=Decimal("-1"))
|
||||
text = str(exc_info.value)
|
||||
assert "multiplier must be non-negative" in text
|
||||
assert "expense_multiplier" in text
|
||||
|
||||
def test_scenario_growth_multiplier_rejects_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ForecastScenario(growth_multiplier=Decimal("-1"))
|
||||
text = str(exc_info.value)
|
||||
assert "multiplier must be non-negative" in text
|
||||
assert "growth_multiplier" in text
|
||||
|
||||
def test_scenario_allows_zero_multipliers(self):
|
||||
scenario = ForecastScenario(
|
||||
income_multiplier=Decimal("0"),
|
||||
expense_multiplier=Decimal("0"),
|
||||
growth_multiplier=Decimal("0"),
|
||||
)
|
||||
assert scenario.income_multiplier == Decimal("0")
|
||||
assert scenario.expense_multiplier == Decimal("0")
|
||||
assert scenario.growth_multiplier == Decimal("0")
|
||||
|
||||
# --- 7. ExchangeRate.rate — строго положительный ---
|
||||
|
||||
def test_exchange_rate_rejects_zero(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ExchangeRate(rate=Decimal("0"))
|
||||
assert "rate must be positive" in str(exc_info.value)
|
||||
|
||||
def test_exchange_rate_rejects_negative(self):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ExchangeRate(rate=Decimal("-1"))
|
||||
assert "rate must be positive" in str(exc_info.value)
|
||||
|
||||
def test_exchange_rate_allows_small_positive(self):
|
||||
assert ExchangeRate(rate=Decimal("0.01")).rate == Decimal("0.01")
|
||||
|
||||
|
||||
class TestDecimalCoercionAndIds:
|
||||
"""Приведение типов и идентификаторы сущностей — текущее поведение (D11)."""
|
||||
|
||||
def test_decimal_fields_accept_strings(self):
|
||||
# pydantic v2 в нестрогом режиме приводит строку к Decimal без потери
|
||||
# точности (Decimal("100.50"), а не float).
|
||||
assert Account(balance="100.50").balance == Decimal("100.50")
|
||||
assert Transaction(amount="-12.34").amount == Decimal("-12.34")
|
||||
assert RecurringCashflow(amount="7.25").amount == Decimal("7.25")
|
||||
assert Asset(value="1000.5").value == Decimal("1000.5")
|
||||
assert Liability(balance="500.75").balance == Decimal("500.75")
|
||||
assert ForecastScenario(income_multiplier="1.5").income_multiplier == Decimal("1.5")
|
||||
assert ExchangeRate(rate="90.25").rate == Decimal("90.25")
|
||||
|
||||
def test_entities_have_uuid_ids(self):
|
||||
# У всех сущностей, кроме ExchangeRate, есть поле id типа UUID.
|
||||
for entity in (
|
||||
Account(),
|
||||
Transaction(),
|
||||
RecurringCashflow(),
|
||||
Asset(),
|
||||
Liability(),
|
||||
ForecastScenario(),
|
||||
):
|
||||
assert isinstance(entity.id, UUID)
|
||||
# str(UUID) — валидный UUID, который можно разобрать обратно.
|
||||
assert UUID(str(entity.id)) == entity.id
|
||||
|
||||
def test_exchange_rate_has_no_id_field(self):
|
||||
# В отличие от остальных сущностей, у ExchangeRate поля id нет
|
||||
# (в листе ExchangeRates тоже нет колонки id — только from/to/rate).
|
||||
assert "id" not in ExchangeRate.model_fields
|
||||
assert not hasattr(ExchangeRate(), "id")
|
||||
@@ -1,5 +1,17 @@
|
||||
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):
|
||||
@@ -19,3 +31,92 @@ class TestScenarioService:
|
||||
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")
|
||||
Reference in new issue
Block a user