style: привести код к ruff format (line-length 120)
Обнаружено на шаге 0: `ruff format --check .` НЕ был чистым в baseline (24 файла расходились с форматом ruff). `ruff check .` был чистым. Изменение только косметическое (переносы, пустая строка после docstring модуля, склейка вызовов в пределах line-length=120 из [tool.ruff]); поведение не меняется — pytest 81/81 зелёные, `ruff check .` — без ошибок. Нужно, чтобы `ruff format --check .` стал рабочим гейтом (D13 CI).
This commit is contained in:
1 parent
9b53b25a91
commit
af01efc41a
24 files changed
+219
-160
No files matched your search
+17
-16
@@ -26,20 +26,19 @@ class ForecastService:
|
||||
for account in self.model.accounts:
|
||||
monthly = self._project_account(account, months)
|
||||
for m in range(months):
|
||||
results.append({
|
||||
"account": account.name,
|
||||
"month": m + 1,
|
||||
"balance": monthly[m]["balance"],
|
||||
"income": monthly[m]["income"],
|
||||
"expenses": monthly[m]["expenses"],
|
||||
})
|
||||
results.append(
|
||||
{
|
||||
"account": account.name,
|
||||
"month": m + 1,
|
||||
"balance": monthly[m]["balance"],
|
||||
"income": monthly[m]["income"],
|
||||
"expenses": monthly[m]["expenses"],
|
||||
}
|
||||
)
|
||||
|
||||
# Asset growth — once per month, distributed across accounts proportionally
|
||||
for m in range(months):
|
||||
total_growth = sum(
|
||||
a.value * a.growth_rate / _HUNDRED / _TWELVE
|
||||
for a in self.model.assets
|
||||
)
|
||||
total_growth = sum(a.value * a.growth_rate / _HUNDRED / _TWELVE for a in self.model.assets)
|
||||
month_rows = [r for r in results if r["month"] == m + 1]
|
||||
total_bal = sum(r["balance"] for r in month_rows) or _ONE
|
||||
for r in month_rows:
|
||||
@@ -77,11 +76,13 @@ class ForecastService:
|
||||
|
||||
balance = balance + income - expenses
|
||||
|
||||
monthly.append({
|
||||
"balance": _q(balance),
|
||||
"income": _q(income),
|
||||
"expenses": _q(expenses),
|
||||
})
|
||||
monthly.append(
|
||||
{
|
||||
"balance": _q(balance),
|
||||
"income": _q(income),
|
||||
"expenses": _q(expenses),
|
||||
}
|
||||
)
|
||||
return monthly
|
||||
|
||||
def _liability_cost(self, account: Account) -> Decimal:
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
Определяет контракт: load(path) -> FinancialModel, save(model, path) -> None.
|
||||
Реализации: JsonFileRepository, ExcelRepository.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
@@ -83,9 +83,6 @@ class ScenarioService:
|
||||
income_multiplier=to_d(income_mult),
|
||||
expense_multiplier=to_d(expense_mult),
|
||||
growth_multiplier=to_d(growth_mult),
|
||||
description=(
|
||||
f"What-if: income x{income_mult}, "
|
||||
f"expense x{expense_mult}, growth x{growth_mult}"
|
||||
),
|
||||
description=(f"What-if: income x{income_mult}, expense x{expense_mult}, growth x{growth_mult}"),
|
||||
)
|
||||
return self.apply(scenario, months)
|
||||
+1
-3
@@ -25,9 +25,7 @@ class FinancialModel(BaseModel):
|
||||
assets: list[Asset] = Field(default_factory=list)
|
||||
liabilities: list[Liability] = Field(default_factory=list)
|
||||
scenarios: list[ForecastScenario] = Field(default_factory=list)
|
||||
exchange_rates: list[ExchangeRate] = Field(
|
||||
default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES]
|
||||
)
|
||||
exchange_rates: list[ExchangeRate] = Field(default_factory=lambda: [r.model_copy() for r in DEFAULT_RATES])
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""Сериализация в dict с version и UUID-as-str (для JSON)."""
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Entry point приложения cf. Регистрирует все команды."""
|
||||
|
||||
import sys
|
||||
|
||||
import typer
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf analyze — AI-анализ финансовой модели (заглушка)."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf compare — сравнить все сценарии."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf config — подкоманды для редактирования модели (базовая валюта, счета, транзакции, ...)."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
@@ -52,11 +53,13 @@ def rate_set(
|
||||
if existing:
|
||||
existing[0].rate = rate
|
||||
else:
|
||||
model.exchange_rates.append(ExchangeRate(
|
||||
from_currency=fc,
|
||||
to_currency=tc,
|
||||
rate=rate,
|
||||
))
|
||||
model.exchange_rates.append(
|
||||
ExchangeRate(
|
||||
from_currency=fc,
|
||||
to_currency=tc,
|
||||
rate=rate,
|
||||
)
|
||||
)
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_set.ok', fc=fc, tc=tc, rate=rate)}")
|
||||
|
||||
@@ -86,10 +89,7 @@ def rate_remove(
|
||||
model = load_model()
|
||||
fc, tc = from_currency.upper(), to_currency.upper()
|
||||
initial = len(model.exchange_rates)
|
||||
model.exchange_rates = [
|
||||
r for r in model.exchange_rates
|
||||
if not (r.from_currency == fc and r.to_currency == tc)
|
||||
]
|
||||
model.exchange_rates = [r for r in model.exchange_rates if not (r.from_currency == fc and r.to_currency == tc)]
|
||||
if len(model.exchange_rates) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.rate_remove.ok', fc=fc, tc=tc)}")
|
||||
@@ -143,10 +143,7 @@ def account_remove(
|
||||
"""Удалить счёт по ID или названию"""
|
||||
model = load_model()
|
||||
initial = len(model.accounts)
|
||||
model.accounts = [
|
||||
a for a in model.accounts
|
||||
if str(a.id) != identifier and a.name != identifier
|
||||
]
|
||||
model.accounts = [a for a in model.accounts if str(a.id) != identifier and a.name != identifier]
|
||||
if len(model.accounts) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.account_remove.ok', id=identifier)}")
|
||||
@@ -204,12 +201,14 @@ def transaction_list() -> None:
|
||||
table.add_column(t("table.transactions.col.description"))
|
||||
for tx in model.transactions:
|
||||
account_name = _account_name(model, tx.account)
|
||||
amount_str = CurrencyConverter.format_money(
|
||||
tx.amount, _account_currency(model, tx.account)
|
||||
)
|
||||
amount_str = CurrencyConverter.format_money(tx.amount, _account_currency(model, tx.account))
|
||||
table.add_row(
|
||||
str(tx.id)[:8], tx.date, account_name, tx.category,
|
||||
amount_str, tx.description,
|
||||
str(tx.id)[:8],
|
||||
tx.date,
|
||||
account_name,
|
||||
tx.category,
|
||||
amount_str,
|
||||
tx.description,
|
||||
)
|
||||
console.print(table)
|
||||
|
||||
@@ -244,8 +243,11 @@ def recurring_add(
|
||||
"""Добавить регулярный платёж"""
|
||||
model = load_model()
|
||||
rc = RecurringCashflow(
|
||||
start_date=start_date or "", end_date=end_date or "",
|
||||
frequency=frequency, amount=amount, category=category,
|
||||
start_date=start_date or "",
|
||||
end_date=end_date or "",
|
||||
frequency=frequency,
|
||||
amount=amount,
|
||||
category=category,
|
||||
)
|
||||
model.recurring.append(rc)
|
||||
save_model(model)
|
||||
@@ -334,10 +336,7 @@ def asset_remove(
|
||||
"""Удалить актив по ID или названию"""
|
||||
model = load_model()
|
||||
initial = len(model.assets)
|
||||
model.assets = [
|
||||
a for a in model.assets
|
||||
if str(a.id) != identifier and a.name != identifier
|
||||
]
|
||||
model.assets = [a for a in model.assets if str(a.id) != identifier and a.name != identifier]
|
||||
if len(model.assets) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.asset_remove.ok', id=identifier)}")
|
||||
@@ -392,10 +391,7 @@ def liability_remove(
|
||||
"""Удалить обязательство по ID или названию"""
|
||||
model = load_model()
|
||||
initial = len(model.liabilities)
|
||||
model.liabilities = [
|
||||
li for li in model.liabilities
|
||||
if str(li.id) != identifier and li.name != identifier
|
||||
]
|
||||
model.liabilities = [li for li in model.liabilities if str(li.id) != identifier and li.name != identifier]
|
||||
if len(model.liabilities) < initial:
|
||||
save_model(model)
|
||||
console.print(f"[green]{t('global.ok')}[/green] {t('cmd.config.liability_remove.ok', id=identifier)}")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf export-xlsx — экспорт модели в Excel."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf forecast — прогноз денежных потоков."""
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
@@ -37,7 +38,8 @@ def forecast(
|
||||
|
||||
for r in results:
|
||||
table.add_row(
|
||||
r["account"], str(r["month"]),
|
||||
r["account"],
|
||||
str(r["month"]),
|
||||
fmt_amount(convert_value(converter, r["balance"], base_curr, target_curr), target_curr, symbol),
|
||||
fmt_amount(convert_value(converter, r["income"], base_curr, target_curr), target_curr, symbol),
|
||||
fmt_amount(convert_value(converter, r["expenses"], base_curr, target_curr), target_curr, symbol),
|
||||
@@ -47,7 +49,11 @@ def forecast(
|
||||
cb = convert_value(converter, summary["total_balance"], base_curr, target_curr)
|
||||
ci = convert_value(converter, summary["total_income"], base_curr, target_curr)
|
||||
ce = convert_value(converter, summary["total_expenses"], base_curr, target_curr)
|
||||
console.print(t("cmd.forecast.total",
|
||||
balance=fmt_amount(cb, target_curr, symbol),
|
||||
income=fmt_amount(ci, target_curr, symbol),
|
||||
expenses=fmt_amount(ce, target_curr, symbol)))
|
||||
console.print(
|
||||
t(
|
||||
"cmd.forecast.total",
|
||||
balance=fmt_amount(cb, target_curr, symbol),
|
||||
income=fmt_amount(ci, target_curr, symbol),
|
||||
expenses=fmt_amount(ce, target_curr, symbol),
|
||||
)
|
||||
)
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf import-xlsx — импорт данных из Excel."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
@@ -15,12 +16,16 @@ def import_xlsx(
|
||||
try:
|
||||
model = _repo.load(path)
|
||||
save_model(model)
|
||||
console.print(t("cmd.import.ok",
|
||||
accounts=len(model.accounts),
|
||||
transactions=len(model.transactions),
|
||||
recurring=len(model.recurring),
|
||||
assets=len(model.assets),
|
||||
liabilities=len(model.liabilities)))
|
||||
console.print(
|
||||
t(
|
||||
"cmd.import.ok",
|
||||
accounts=len(model.accounts),
|
||||
transactions=len(model.transactions),
|
||||
recurring=len(model.recurring),
|
||||
assets=len(model.assets),
|
||||
liabilities=len(model.liabilities),
|
||||
)
|
||||
)
|
||||
console.print(t("cmd.import.base_currency", currency=model.base_currency))
|
||||
except ExcelRepositoryError as e:
|
||||
console.print(f"[red]{t('cmd.import.err', error=str(e))}[/red]")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf info — сводка всей финансовой модели."""
|
||||
|
||||
from rich.table import Table
|
||||
|
||||
from domain import CurrencyConverter
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf scenario — применить именованный сценарий (baseline/optimistic/pessimistic)."""
|
||||
|
||||
import typer
|
||||
|
||||
from application.scenarios import DEFAULT_SCENARIOS
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""cf whatif — what-if анализ с произвольными множителями."""
|
||||
|
||||
import typer
|
||||
|
||||
from infrastructure.cli.i18n import t
|
||||
|
||||
+62
-51
@@ -68,9 +68,11 @@ _r("cmd.compare.col.scenario", "Сценарий")
|
||||
|
||||
_r("cmd.import.help", "Импорт данных из Excel")
|
||||
_r("cmd.import.arg.path", "Путь к .xlsx файлу")
|
||||
_r("cmd.import.ok",
|
||||
"Импортировано: {accounts} счетов, {transactions} транзакций, "
|
||||
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств")
|
||||
_r(
|
||||
"cmd.import.ok",
|
||||
"Импортировано: {accounts} счетов, {transactions} транзакций, "
|
||||
"{recurring} регулярных платежей, {assets} активов, {liabilities} обязательств",
|
||||
)
|
||||
_r("cmd.import.base_currency", "Базовая валюта: {currency}")
|
||||
_r("cmd.import.err", "Ошибка импорта: {error}")
|
||||
|
||||
@@ -254,56 +256,65 @@ _r("global.ok", "OK")
|
||||
|
||||
# ── prompts ───────────────────────────────────────────────────
|
||||
|
||||
_r("prompt.analyze", (
|
||||
"Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n"
|
||||
"\n"
|
||||
"### Модель (JSON):\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз на {months} месяцев:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай анализ по пунктам:\n"
|
||||
"1. Общее финансовое состояние\n"
|
||||
"2. Тренд денежного потока (рост/падение)\n"
|
||||
"3. Достаточность ликвидности\n"
|
||||
"4. Рекомендации по улучшению"
|
||||
))
|
||||
_r(
|
||||
"prompt.analyze",
|
||||
(
|
||||
"Ты — финансовый AI-ассистент. Проанализируй финансовую модель пользователя.\n"
|
||||
"\n"
|
||||
"### Модель (JSON):\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз на {months} месяцев:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай анализ по пунктам:\n"
|
||||
"1. Общее финансовое состояние\n"
|
||||
"2. Тренд денежного потока (рост/падение)\n"
|
||||
"3. Достаточность ликвидности\n"
|
||||
"4. Рекомендации по улучшению"
|
||||
),
|
||||
)
|
||||
|
||||
_r("prompt.advice", (
|
||||
"Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n"
|
||||
"\n"
|
||||
"### Модель:\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Вопрос пользователя: {question}\n"
|
||||
"\n"
|
||||
"Ответь как опытный финансовый консультант."
|
||||
))
|
||||
_r(
|
||||
"prompt.advice",
|
||||
(
|
||||
"Ты — финансовый AI-ассистент. Дай персональные рекомендации.\n"
|
||||
"\n"
|
||||
"### Модель:\n"
|
||||
"{model_json}\n"
|
||||
"\n"
|
||||
"### Прогноз:\n"
|
||||
"{forecast_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Вопрос пользователя: {question}\n"
|
||||
"\n"
|
||||
"Ответь как опытный финансовый консультант."
|
||||
),
|
||||
)
|
||||
|
||||
_r("prompt.scenario_comparison", (
|
||||
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
|
||||
"\n"
|
||||
"### Результаты сценариев:\n"
|
||||
"{scenarios_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
|
||||
))
|
||||
_r(
|
||||
"prompt.scenario_comparison",
|
||||
(
|
||||
"Ты — финансовый AI-ассистент. Сравни сценарии прогноза.\n"
|
||||
"\n"
|
||||
"### Результаты сценариев:\n"
|
||||
"{scenarios_json}\n"
|
||||
"\n"
|
||||
"### Валюта:\n"
|
||||
"Базовая валюта модели: {base_currency}\n"
|
||||
"Отображаемая валюта: {display_currency}\n"
|
||||
"\n"
|
||||
"Дай рекомендацию: какой сценарий наиболее вероятен и почему."
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
_current_lang = "ru"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Пути к данным и экспортам."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
DATA_DIR: Path = Path("data")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Composition root + общие хелперы для CLI-команд."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
@@ -34,9 +35,7 @@ def build_services(
|
||||
converter = CurrencyConverter(model.exchange_rates)
|
||||
forecast_service = ForecastService(model)
|
||||
scenario_service = ScenarioService(model)
|
||||
assistant_service = AssistantService(
|
||||
model, forecast_service=forecast_service, converter=converter
|
||||
)
|
||||
assistant_service = AssistantService(model, forecast_service=forecast_service, converter=converter)
|
||||
return forecast_service, scenario_service, assistant_service, converter
|
||||
|
||||
|
||||
@@ -47,9 +46,7 @@ def resolve_currency(model: FinancialModel, currency: str | None) -> tuple[str,
|
||||
return target, symbol
|
||||
|
||||
|
||||
def convert_value(
|
||||
converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str
|
||||
) -> Decimal:
|
||||
def convert_value(converter: CurrencyConverter, amount: Decimal, from_curr: str, to_curr: str) -> Decimal:
|
||||
if to_curr == from_curr:
|
||||
return amount
|
||||
return converter.convert(amount, from_curr, to_curr)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""ExcelRepository — хранит FinancialModel в .xlsx (5 листов + ModelInfo)."""
|
||||
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
@@ -107,8 +108,7 @@ class ExcelRepository(ModelRepository):
|
||||
ws.append(config["fields"])
|
||||
for item in items:
|
||||
row = [
|
||||
str(getattr(item, f)) if isinstance(getattr(item, f), UUID)
|
||||
else getattr(item, f)
|
||||
str(getattr(item, f)) if isinstance(getattr(item, f), UUID) else getattr(item, f)
|
||||
for f in config["fields"]
|
||||
]
|
||||
ws.append(row)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""JsonFileRepository — хранит FinancialModel в .json (включая version)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
+16
-8
@@ -25,24 +25,32 @@ def sample_model() -> FinancialModel:
|
||||
],
|
||||
transactions=[
|
||||
Transaction(
|
||||
date="2026-01-01", account=str(acc_id),
|
||||
category="income", amount=3000.0,
|
||||
date="2026-01-01",
|
||||
account=str(acc_id),
|
||||
category="income",
|
||||
amount=3000.0,
|
||||
description="Зарплата",
|
||||
),
|
||||
Transaction(
|
||||
date="2026-01-05", account=str(acc_id),
|
||||
category="rent", amount=-1200.0,
|
||||
date="2026-01-05",
|
||||
account=str(acc_id),
|
||||
category="rent",
|
||||
amount=-1200.0,
|
||||
description="Аренда",
|
||||
),
|
||||
],
|
||||
recurring=[
|
||||
RecurringCashflow(
|
||||
start_date="2026-01-01", frequency="monthly",
|
||||
amount=500.0, category="income",
|
||||
start_date="2026-01-01",
|
||||
frequency="monthly",
|
||||
amount=500.0,
|
||||
category="income",
|
||||
),
|
||||
RecurringCashflow(
|
||||
start_date="2026-01-01", frequency="monthly",
|
||||
amount=-200.0, category="subscription",
|
||||
start_date="2026-01-01",
|
||||
frequency="monthly",
|
||||
amount=-200.0,
|
||||
category="subscription",
|
||||
),
|
||||
],
|
||||
assets=[
|
||||
|
||||
+57
-28
@@ -86,13 +86,21 @@ class TestCli:
|
||||
runner.invoke(app, ["init"])
|
||||
runner.invoke(app, ["config", "account-add", "--name", "Счёт", "--balance", "0"])
|
||||
|
||||
add = runner.invoke(app, [
|
||||
"config", "transaction-add",
|
||||
"--account", "Счёт",
|
||||
"--amount", "5000",
|
||||
"--category", "income",
|
||||
"--description", "Зарплата",
|
||||
])
|
||||
add = runner.invoke(
|
||||
app,
|
||||
[
|
||||
"config",
|
||||
"transaction-add",
|
||||
"--account",
|
||||
"Счёт",
|
||||
"--amount",
|
||||
"5000",
|
||||
"--category",
|
||||
"income",
|
||||
"--description",
|
||||
"Зарплата",
|
||||
],
|
||||
)
|
||||
assert add.exit_code == 0
|
||||
assert "доход" in add.stdout
|
||||
|
||||
@@ -103,12 +111,19 @@ class TestCli:
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
add = runner.invoke(app, [
|
||||
"config", "asset-add",
|
||||
"--name", "Квартира",
|
||||
"--value", "5000000",
|
||||
"--growth", "5",
|
||||
])
|
||||
add = runner.invoke(
|
||||
app,
|
||||
[
|
||||
"config",
|
||||
"asset-add",
|
||||
"--name",
|
||||
"Квартира",
|
||||
"--value",
|
||||
"5000000",
|
||||
"--growth",
|
||||
"5",
|
||||
],
|
||||
)
|
||||
assert add.exit_code == 0
|
||||
assert "Квартира" in add.stdout
|
||||
|
||||
@@ -119,13 +134,21 @@ class TestCli:
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
add = runner.invoke(app, [
|
||||
"config", "liability-add",
|
||||
"--name", "Кредит",
|
||||
"--balance", "100000",
|
||||
"--interest", "10",
|
||||
"--payment", "5000",
|
||||
])
|
||||
add = runner.invoke(
|
||||
app,
|
||||
[
|
||||
"config",
|
||||
"liability-add",
|
||||
"--name",
|
||||
"Кредит",
|
||||
"--balance",
|
||||
"100000",
|
||||
"--interest",
|
||||
"10",
|
||||
"--payment",
|
||||
"5000",
|
||||
],
|
||||
)
|
||||
assert add.exit_code == 0
|
||||
assert "Кредит" in add.stdout
|
||||
|
||||
@@ -133,12 +156,19 @@ class TestCli:
|
||||
_cleanup()
|
||||
runner.invoke(app, ["init"])
|
||||
|
||||
add = runner.invoke(app, [
|
||||
"config", "recurring-add",
|
||||
"--amount", "-500",
|
||||
"--category", "аренда",
|
||||
"--frequency", "monthly",
|
||||
])
|
||||
add = runner.invoke(
|
||||
app,
|
||||
[
|
||||
"config",
|
||||
"recurring-add",
|
||||
"--amount",
|
||||
"-500",
|
||||
"--category",
|
||||
"аренда",
|
||||
"--frequency",
|
||||
"monthly",
|
||||
],
|
||||
)
|
||||
assert add.exit_code == 0
|
||||
|
||||
lst = runner.invoke(app, ["config", "recurring-list"])
|
||||
@@ -160,8 +190,7 @@ class TestCli:
|
||||
runner.invoke(app, ["init"])
|
||||
acc_args = ["config", "account-add", "--name", "Основной", "--balance", "50000"]
|
||||
runner.invoke(app, acc_args)
|
||||
asset_args = ["config", "asset-add", "--name", "Акции",
|
||||
"--value", "100000", "--growth", "8.0"]
|
||||
asset_args = ["config", "asset-add", "--name", "Акции", "--value", "100000", "--growth", "8.0"]
|
||||
runner.invoke(app, asset_args)
|
||||
|
||||
result = runner.invoke(app, ["info"])
|
||||
|
||||
@@ -6,6 +6,7 @@ CLI (D3 — удаление мёртвых typer.Typer(), D25 — разбие
|
||||
на пакет): если набор изменился, поведение CLI изменилось без
|
||||
согласования — тест обязан упасть.
|
||||
"""
|
||||
|
||||
import typer
|
||||
from typer.main import get_command
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ class TestFinancialModel:
|
||||
|
||||
def test_base_currency_backward_compat(self, tmp_path: Path):
|
||||
import json
|
||||
|
||||
p = tmp_path / "legacy.json"
|
||||
with open(p, "w") as f:
|
||||
json.dump({"accounts": []}, f)
|
||||
|
||||
@@ -29,6 +29,7 @@ class TestJsonFileRepository:
|
||||
p = tmp_path / "v.json"
|
||||
repo.save(model, p)
|
||||
import json
|
||||
|
||||
with open(p) as f:
|
||||
data = json.load(f)
|
||||
assert data["version"] == 1
|
||||
@@ -46,9 +47,7 @@ class TestJsonFileRepository:
|
||||
|
||||
def test_decimal_preserved(self, tmp_path: Path):
|
||||
repo = JsonFileRepository()
|
||||
model = FinancialModel(
|
||||
assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))]
|
||||
)
|
||||
model = FinancialModel(assets=[Asset(name="Stocks", value=Decimal("12345.67"), growth_rate=Decimal("8.5"))])
|
||||
p = tmp_path / "decimal.json"
|
||||
repo.save(model, p)
|
||||
loaded = repo.load(p)
|
||||
|
||||
Reference in new issue
Block a user