Files
nifodea/tests/test_cli_contract.py
T
oqyude af01efc41a 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).
2026-10-25 05:17:27 +03:00

96 lines
3.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Инвариант публичной поверхности 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"]