From f66a76279640ee30c821f8d296fd3ac5e0e4790b Mon Sep 17 00:00:00 2001 From: oqyude Date: Fri, 23 Oct 2026 12:57:08 +0300 Subject: [PATCH] =?UTF-8?q?D3:=20=D1=83=D0=B1=D1=80=D0=B0=D1=82=D1=8C=20?= =?UTF-8?q?=D0=BC=D1=91=D1=80=D1=82=D0=B2=D1=8B=D0=B5=20typer.Typer()=20?= =?UTF-8?q?=D0=B8=D0=B7=209=20=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D0=B5=D0=B9?= =?UTF-8?q?=20=D0=BA=D0=BE=D0=BC=D0=B0=D0=BD=D0=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Регистрация CLI идёт через infrastructure/cli/app.py:30-38, где вешается «сырая» функция. Поэтому в каждом из 9 одно-командных модулей стоял свой typer.Typer() с декоратором @app.command() — регистрация, которая никогда не читалась. Убраны: commands/analyze.py, compare.py, export_xlsx.py, forecast.py, import_xlsx.py, info.py, init.py, scenario.py, whatif.py commands/config_cmd.py НЕ тронут: его app — настоящий sub-typer, регистрируемый в app.py:41. Страховка (написана и проверена ДО правки, проходит и после): - новый tests/test_cli_contract.py — инвариант поверхности CLI: 9 команд верхнего уровня + 19 подкоманд config, у каждой leaf-команды есть callback, дефолт export-xlsx = "exports/forecast.xlsx". Тест защищает и будущий рефакторинг D25 (разбиение config_cmd.py на пакет). - сверка вывода `cf --help`, `cf config --help`, `cf export-xlsx --help`, `cf forecast --help` с pristine-копией HEAD — побайтово идентично. Проверка: 81/81 тестов зелёные (75 + 6 новых), ruff check . — All checks passed. --- infrastructure/cli/commands/analyze.py | 3 - infrastructure/cli/commands/compare.py | 3 - infrastructure/cli/commands/export_xlsx.py | 2 - infrastructure/cli/commands/forecast.py | 3 - infrastructure/cli/commands/import_xlsx.py | 2 - infrastructure/cli/commands/info.py | 4 - infrastructure/cli/commands/init.py | 4 - infrastructure/cli/commands/scenario.py | 3 - infrastructure/cli/commands/whatif.py | 3 - tests/test_cli_contract.py | 94 ++++++++++++++++++++++ 10 files changed, 94 insertions(+), 27 deletions(-) create mode 100644 tests/test_cli_contract.py diff --git a/infrastructure/cli/commands/analyze.py b/infrastructure/cli/commands/analyze.py index 3de2667..f4f6966 100644 --- a/infrastructure/cli/commands/analyze.py +++ b/infrastructure/cli/commands/analyze.py @@ -4,12 +4,9 @@ import typer from infrastructure.cli.i18n import t from infrastructure.cli.services import build_services, console, load_model, resolve_currency -app = typer.Typer() - CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) -@app.command() def analyze( months: int = typer.Option(12, "--months", "-m", help=t("cmd.analyze.opt.months")), currency: str | None = CURRENCY_OPTION, diff --git a/infrastructure/cli/commands/compare.py b/infrastructure/cli/commands/compare.py index 33bcbf3..70edf45 100644 --- a/infrastructure/cli/commands/compare.py +++ b/infrastructure/cli/commands/compare.py @@ -12,12 +12,9 @@ from infrastructure.cli.services import ( resolve_currency, ) -app = typer.Typer() - CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) -@app.command() def compare( months: int = typer.Option(12, "--months", "-m", help=t("cmd.compare.opt.months")), currency: str | None = CURRENCY_OPTION, diff --git a/infrastructure/cli/commands/export_xlsx.py b/infrastructure/cli/commands/export_xlsx.py index c2e9901..b2ff792 100644 --- a/infrastructure/cli/commands/export_xlsx.py +++ b/infrastructure/cli/commands/export_xlsx.py @@ -5,11 +5,9 @@ from infrastructure.cli.i18n import t from infrastructure.cli.services import console, load_model from infrastructure.repositories import ExcelRepository, ExcelRepositoryError -app = typer.Typer() _repo = ExcelRepository() -@app.command(name="export-xlsx") def export_xlsx( path: str = typer.Argument("exports/forecast.xlsx", help=t("cmd.export.arg.path")), ) -> None: diff --git a/infrastructure/cli/commands/forecast.py b/infrastructure/cli/commands/forecast.py index ff02432..84bfeae 100644 --- a/infrastructure/cli/commands/forecast.py +++ b/infrastructure/cli/commands/forecast.py @@ -12,12 +12,9 @@ from infrastructure.cli.services import ( resolve_currency, ) -app = typer.Typer() - CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) -@app.command() def forecast( months: int = typer.Option(12, "--months", "-m", help=t("cmd.forecast.opt.months")), currency: str | None = CURRENCY_OPTION, diff --git a/infrastructure/cli/commands/import_xlsx.py b/infrastructure/cli/commands/import_xlsx.py index 5415ec8..707eab8 100644 --- a/infrastructure/cli/commands/import_xlsx.py +++ b/infrastructure/cli/commands/import_xlsx.py @@ -5,11 +5,9 @@ from infrastructure.cli.i18n import t from infrastructure.cli.services import console, save_model from infrastructure.repositories import ExcelRepository, ExcelRepositoryError -app = typer.Typer() _repo = ExcelRepository() -@app.command(name="import-xlsx") def import_xlsx( path: str = typer.Argument(..., help=t("cmd.import.arg.path")), ) -> None: diff --git a/infrastructure/cli/commands/info.py b/infrastructure/cli/commands/info.py index 3722524..8c77730 100644 --- a/infrastructure/cli/commands/info.py +++ b/infrastructure/cli/commands/info.py @@ -1,15 +1,11 @@ """cf info — сводка всей финансовой модели.""" -import typer from rich.table import Table from domain import CurrencyConverter from infrastructure.cli.i18n import t from infrastructure.cli.services import console, load_model -app = typer.Typer() - -@app.command() def info() -> None: """Сводка всей финансовой модели""" model = load_model() diff --git a/infrastructure/cli/commands/init.py b/infrastructure/cli/commands/init.py index d700ff4..e7bc620 100644 --- a/infrastructure/cli/commands/init.py +++ b/infrastructure/cli/commands/init.py @@ -1,15 +1,11 @@ """cf init — создать пустую модель.""" -import typer from domain import FinancialModel from infrastructure.cli.i18n import t from infrastructure.cli.paths import MODEL_PATH from infrastructure.cli.services import console, save_model -app = typer.Typer() - -@app.command() def init() -> None: """Создать пустую финансовую модель""" model = FinancialModel() diff --git a/infrastructure/cli/commands/scenario.py b/infrastructure/cli/commands/scenario.py index 5626aa5..de9dc6d 100644 --- a/infrastructure/cli/commands/scenario.py +++ b/infrastructure/cli/commands/scenario.py @@ -12,12 +12,9 @@ from infrastructure.cli.services import ( resolve_currency, ) -app = typer.Typer() - CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) -@app.command() def scenario( name: str = typer.Argument("baseline", help=t("cmd.scenario.arg.name")), months: int = typer.Option(12, "--months", "-m", help=t("cmd.scenario.opt.months")), diff --git a/infrastructure/cli/commands/whatif.py b/infrastructure/cli/commands/whatif.py index 9011fd4..5ee9f6d 100644 --- a/infrastructure/cli/commands/whatif.py +++ b/infrastructure/cli/commands/whatif.py @@ -11,12 +11,9 @@ from infrastructure.cli.services import ( resolve_currency, ) -app = typer.Typer() - CURRENCY_OPTION = typer.Option(None, "--currency", "-c", help=t("cmd.forecast.opt.currency")) -@app.command() def whatif( income: float = typer.Option(1.0, "--income", "-i", help=t("cmd.whatif.opt.income")), expense: float = typer.Option(1.0, "--expense", "-e", help=t("cmd.whatif.opt.expense")), diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py new file mode 100644 index 0000000..899b862 --- /dev/null +++ b/tests/test_cli_contract.py @@ -0,0 +1,94 @@ +"""Инвариант публичной поверхности CLI. + +Фиксирует набор команд, подкоманд и дефолтных путей, которые видит +пользователь. Обязан проходить ДО и ПОСЛЕ любых рефакторингов структуры +CLI (D3 — удаление мёртвых typer.Typer(), D25 — разбиение config_cmd.py +на пакет): если набор изменился, поведение CLI изменилось без +согласования — тест обязан упасть. +""" +import typer +from typer.main import get_command + +from infrastructure.cli.app import app +from infrastructure.cli.commands import config_cmd + +EXPECTED_COMMANDS = { + "init", + "forecast", + "scenario", + "whatif", + "compare", + "import-xlsx", + "export-xlsx", + "analyze", + "info", +} + +EXPECTED_CONFIG_COMMANDS = { + "base-currency", + "rate-set", + "rate-list", + "rate-remove", + "account-add", + "account-list", + "account-remove", + "transaction-add", + "transaction-list", + "transaction-remove", + "recurring-add", + "recurring-list", + "recurring-remove", + "asset-add", + "asset-list", + "asset-remove", + "liability-add", + "liability-list", + "liability-remove", +} + +EXPECTED_EXPORT_DEFAULT = "exports/forecast.xlsx" + + +def _click_app(typer_app: typer.Typer): + """Развернуть Typer-приложение в click-команду (то, что видит пользователь).""" + return get_command(typer_app) + + +def _command_names(typer_app: typer.Typer) -> set[str]: + return set(_click_app(typer_app).commands.keys()) + + +class TestCliSurface: + def test_top_level_commands(self): + assert _command_names(app) == EXPECTED_COMMANDS | {"config"} + + def test_config_subcommands(self): + assert _command_names(config_cmd.app) == EXPECTED_CONFIG_COMMANDS + + def test_config_subapp_reachable_from_root(self): + root = _click_app(app) + assert "config" in root.commands + assert set(root.commands["config"].commands.keys()) == EXPECTED_CONFIG_COMMANDS + + def test_every_command_has_a_callback(self): + """Leaf-команда без callback — «висячая» регистрация; ловим потерю wiring'а.""" + for name, command in _click_app(app).commands.items(): + if hasattr(command, "commands"): + continue # sub-typer (config) — у группы callback'а нет by design + assert command.callback is not None, f"команда {name} без callback" + + for name, command in _click_app(config_cmd.app).commands.items(): + assert command.callback is not None, f"команда config {name} без callback" + + +class TestDefaultPaths: + def test_export_xlsx_default_path_is_unchanged(self): + """Дефолт `cf export-xlsx` — строка, которую видит пользователь в --help.""" + command = _click_app(app).commands["export-xlsx"] + arg = next(p for p in command.params if p.name == "path") + assert arg.default == EXPECTED_EXPORT_DEFAULT + + def test_init_and_import_do_not_take_a_path(self): + root = _click_app(app) + assert not [p for p in root.commands["init"].params if p.name == "path"] + assert [p for p in root.commands["import-xlsx"].params if p.name == "path"]