- domain/*: на всех моделях домена (FinancialModel, Account, Transaction,
RecurringCashflow, Asset, Liability, ForecastScenario, ExchangeRate)
включён model_config = ConfigDict(validate_assignment=True). Раньше
присваивание шло мимо валидаторов: `r.rate = -5` принимался, а
config_cmd.py писал в поле Decimal значение типа float.
- infrastructure/cli/commands/config_cmd.py: rate_set пишет
Decimal(str(rate)) вместо float.
- infrastructure/cli/services.py: хелпер fail_validation() — печатает
понятное сообщение (t("global.validation_error")) и завершает команду
кодом 1 вместо traceback.
- infrastructure/cli/i18n.py: добавлен ключ global.validation_error.
- infrastructure/cli/commands/{whatif,scenario,compare}.py: тот же обработчик
для случая «множитель 0 обнуляет сумму» — иначе D17 вводил бы новый traceback.
- tests/test_model.py: +9 тестов (отклонение отрицательного/нулевого курса,
float в поле Decimal не остаётся float, отклонение по всем валидаторам).
- tests/test_cli.py: +4 теста (ненулевой код без traceback, модель не
сохраняется, курс сохраняется строкой-Decimal, валидный курс проходит).
Было → стало:
cf config rate-set USD RUB -- -5 принимался, «OK Курс USD → RUB = -5.0»,
курс сохранялся float (-5.0) + warning
→ «Ошибка валидации данных: rate: Value error,
rate must be positive», код 1, без traceback
cf whatif --income 0 работал (суммы обнулялись молча)
→ «Ошибка валидации данных: amount: Value error,
amount must be non-zero», код 1
239 lines
8.1 KiB
Python
239 lines
8.1 KiB
Python
from pathlib import Path
|
|
|
|
from typer.testing import CliRunner
|
|
|
|
from infrastructure.cli.app import app
|
|
|
|
runner = CliRunner()
|
|
|
|
|
|
class TestCli:
|
|
def test_init(self):
|
|
result = runner.invoke(app, ["init"])
|
|
assert result.exit_code == 0
|
|
assert "Пустая модель" in result.stdout
|
|
|
|
def test_forecast_after_init(self):
|
|
runner.invoke(app, ["init"])
|
|
result = runner.invoke(app, ["forecast", "--months", "3"])
|
|
assert result.exit_code == 0
|
|
|
|
def test_forecast_with_currency(self):
|
|
runner.invoke(app, ["init"])
|
|
result = runner.invoke(app, ["forecast", "--months", "3", "--currency", "USD"])
|
|
assert result.exit_code == 0
|
|
assert "$" in result.stdout
|
|
|
|
def test_unknown_scenario(self):
|
|
result = runner.invoke(app, ["scenario", "unknown"])
|
|
assert result.exit_code != 0
|
|
|
|
def test_help(self):
|
|
result = runner.invoke(app, ["--help"])
|
|
assert result.exit_code == 0
|
|
|
|
def test_info_empty(self):
|
|
runner.invoke(app, ["init"])
|
|
result = runner.invoke(app, ["info"])
|
|
assert result.exit_code == 0
|
|
assert "Базовая валюта" in result.stdout
|
|
|
|
def test_config_base_currency_set(self):
|
|
runner.invoke(app, ["init"])
|
|
result = runner.invoke(app, ["config", "base-currency", "EUR"])
|
|
assert result.exit_code == 0
|
|
assert "EUR" in result.stdout
|
|
|
|
info = runner.invoke(app, ["info"])
|
|
assert "EUR" in info.stdout
|
|
|
|
def test_config_base_currency_show(self):
|
|
runner.invoke(app, ["init"])
|
|
result = runner.invoke(app, ["config", "base-currency"])
|
|
assert result.exit_code == 0
|
|
assert "RUB" in result.stdout
|
|
|
|
def test_config_account_crud(self):
|
|
runner.invoke(app, ["init"])
|
|
|
|
args = ["config", "account-add", "--name", "Тестовый", "--balance", "1000"]
|
|
add = runner.invoke(app, args)
|
|
assert add.exit_code == 0
|
|
assert "Тестовый" in add.stdout
|
|
|
|
lst = runner.invoke(app, ["config", "account-list"])
|
|
assert "Тестовый" in lst.stdout
|
|
|
|
remove = runner.invoke(app, ["config", "account-remove", "Тестовый"])
|
|
assert remove.exit_code == 0
|
|
|
|
lst2 = runner.invoke(app, ["config", "account-list"])
|
|
assert "Тестовый" not in lst2.stdout
|
|
|
|
def test_config_transaction_crud(self):
|
|
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",
|
|
"Зарплата",
|
|
],
|
|
)
|
|
assert add.exit_code == 0
|
|
assert "доход" in add.stdout
|
|
|
|
lst = runner.invoke(app, ["config", "transaction-list"])
|
|
assert "Зарплата" in lst.stdout
|
|
|
|
def test_config_asset_crud(self):
|
|
runner.invoke(app, ["init"])
|
|
|
|
add = runner.invoke(
|
|
app,
|
|
[
|
|
"config",
|
|
"asset-add",
|
|
"--name",
|
|
"Квартира",
|
|
"--value",
|
|
"5000000",
|
|
"--growth",
|
|
"5",
|
|
],
|
|
)
|
|
assert add.exit_code == 0
|
|
assert "Квартира" in add.stdout
|
|
|
|
lst = runner.invoke(app, ["config", "asset-list"])
|
|
assert "Квартира" in lst.stdout
|
|
|
|
def test_config_liability_crud(self):
|
|
runner.invoke(app, ["init"])
|
|
|
|
add = runner.invoke(
|
|
app,
|
|
[
|
|
"config",
|
|
"liability-add",
|
|
"--name",
|
|
"Кредит",
|
|
"--balance",
|
|
"100000",
|
|
"--interest",
|
|
"10",
|
|
"--payment",
|
|
"5000",
|
|
],
|
|
)
|
|
assert add.exit_code == 0
|
|
assert "Кредит" in add.stdout
|
|
|
|
def test_config_recurring_crud(self):
|
|
runner.invoke(app, ["init"])
|
|
|
|
add = runner.invoke(
|
|
app,
|
|
[
|
|
"config",
|
|
"recurring-add",
|
|
"--amount",
|
|
"-500",
|
|
"--category",
|
|
"аренда",
|
|
"--frequency",
|
|
"monthly",
|
|
],
|
|
)
|
|
assert add.exit_code == 0
|
|
|
|
lst = runner.invoke(app, ["config", "recurring-list"])
|
|
assert "аренда" in lst.stdout
|
|
|
|
def test_config_rate_crud(self):
|
|
runner.invoke(app, ["init"])
|
|
|
|
set_r = runner.invoke(app, ["config", "rate-set", "EUR", "RUB", "90"])
|
|
assert set_r.exit_code == 0
|
|
|
|
lst = runner.invoke(app, ["config", "rate-list"])
|
|
assert "EUR" in lst.stdout
|
|
assert "90" in lst.stdout
|
|
|
|
def test_info_with_data(self):
|
|
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"]
|
|
runner.invoke(app, asset_args)
|
|
|
|
result = runner.invoke(app, ["info"])
|
|
assert "Основной" in result.stdout
|
|
assert "Акции" in result.stdout
|
|
|
|
|
|
class TestValidationErrors:
|
|
"""D17: ошибка валидации — понятное сообщение и код 1, без traceback."""
|
|
|
|
def test_config_rate_set_with_negative_rate_fails_cleanly(self):
|
|
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
|
|
assert result.exit_code == 1
|
|
assert "Ошибка валидации" in result.stdout
|
|
assert "rate must be positive" in result.stdout
|
|
assert "Traceback" not in result.stdout
|
|
assert result.exception is None or isinstance(result.exception, SystemExit)
|
|
|
|
def test_config_rate_set_with_negative_rate_does_not_save_model(self):
|
|
runner.invoke(app, ["init"])
|
|
before = (Path.cwd() / "data" / "model.json").read_text(encoding="utf-8")
|
|
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "--", "-5"])
|
|
assert result.exit_code == 1
|
|
after = (Path.cwd() / "data" / "model.json").read_text(encoding="utf-8")
|
|
assert before == after, "Невалидный курс не должен сохраняться в модель"
|
|
|
|
def test_config_rate_set_stores_decimal_rate(self):
|
|
import json
|
|
|
|
runner.invoke(app, ["init"])
|
|
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "90"])
|
|
assert result.exit_code == 0
|
|
|
|
data = json.loads((Path.cwd() / "data" / "model.json").read_text(encoding="utf-8"))
|
|
rate = data["exchange_rates"][0]["rate"]
|
|
# Decimal сериализуется строкой, а не числом float.
|
|
assert isinstance(rate, str)
|
|
assert rate == "90.0"
|
|
|
|
def test_config_rate_set_with_valid_rate_succeeds(self):
|
|
result = runner.invoke(app, ["config", "rate-set", "USD", "RUB", "90"])
|
|
assert result.exit_code == 0
|
|
assert "Traceback" not in result.stdout
|
|
|
|
|
|
class TestFilesystemIsolation:
|
|
"""Регрессии D10: CLI-тесты не пишут в дерево репозитория."""
|
|
|
|
def test_cli_writes_model_into_tmp_cwd(self, isolated_cwd: Path):
|
|
result = runner.invoke(app, ["init"])
|
|
assert result.exit_code == 0
|
|
assert (isolated_cwd / "data" / "model.json").exists()
|
|
|
|
def test_cli_does_not_touch_tracked_repo_files(self, repo_root: Path, isolated_cwd: Path):
|
|
tracked = repo_root / "data" / "model.json"
|
|
before = tracked.read_bytes() if tracked.exists() else None
|
|
|
|
result = runner.invoke(app, ["init"])
|
|
assert result.exit_code == 0
|
|
|
|
after = tracked.read_bytes() if tracked.exists() else None
|
|
assert before == after, "CLI-тест изменил отслеживаемый data/model.json в дереве репозитория"
|