"""Инварианты направлений зависимостей внутри `infrastructure/` (D27). Смысл: `infrastructure/ai/` был связан с `infrastructure/cli/` только через `infrastructure.cli.i18n`, из-за чего AI-слой нельзя было переиспользовать в REST API / Web UI без затаскивания CLI. После выноса i18n в `infrastructure/i18n/` горизонтальная связь «не-CLI → CLI» запрещена и проверяется разбором AST, а не глазами. """ import ast from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[1] INFRA_ROOT = REPO_ROOT / "infrastructure" CLI_ROOT = INFRA_ROOT / "cli" I18N_ROOT = INFRA_ROOT / "i18n" CLI_PREFIX = "infrastructure.cli" def _iter_modules(): for path in sorted(INFRA_ROOT.rglob("*.py")): tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) yield path, tree def _cli_imports(tree: ast.Module) -> list[str]: """Все импорты `infrastructure.cli.*` в модуле (from-import и import).""" found: list[str] = [] for node in ast.walk(tree): if isinstance(node, ast.ImportFrom) and node.module: if node.module == CLI_PREFIX or node.module.startswith(CLI_PREFIX + "."): found.append(node.module) elif isinstance(node, ast.Import): for alias in node.names: if alias.name == CLI_PREFIX or alias.name.startswith(CLI_PREFIX + "."): found.append(alias.name) return found class TestNoCliDependency: def test_modules_outside_cli_do_not_import_cli(self): offenders = {} for path, tree in _iter_modules(): if path == CLI_ROOT or CLI_ROOT in path.parents: continue imports = _cli_imports(tree) if imports: offenders[str(path.relative_to(REPO_ROOT))] = imports assert not offenders, f"модули вне infrastructure/cli импортируют CLI: {offenders}" def test_i18n_package_does_not_import_cli(self): assert I18N_ROOT.is_dir() offenders = {} for path in sorted(I18N_ROOT.rglob("*.py")): imports = _cli_imports(ast.parse(path.read_text(encoding="utf-8"), filename=str(path))) if imports: offenders[str(path.relative_to(REPO_ROOT))] = imports assert not offenders, f"infrastructure/i18n импортирует CLI: {offenders}" def test_ai_layer_does_not_import_cli(self): offenders = {} for path in sorted((INFRA_ROOT / "ai").rglob("*.py")): imports = _cli_imports(ast.parse(path.read_text(encoding="utf-8"), filename=str(path))) if imports: offenders[str(path.relative_to(REPO_ROOT))] = imports assert not offenders, f"infrastructure/ai импортирует CLI: {offenders}" COMMANDS_ROOT = CLI_ROOT / "commands" CONFIG_PKG = COMMANDS_ROOT / "config" def _typer_instantiations(path: Path) -> list[int]: """Номера строк, где модуль создаёт `typer.Typer(...)` (D3: мёртвые Typer'ы).""" tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) lines = [] for node in ast.walk(tree): if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "Typer": lines.append(node.lineno) return lines class TestTyperRegistration: """D25: один Typer-объект на пакет `config`, остальные модули только декорируют.""" def test_config_package_creates_exactly_one_typer(self): hits = {path: _typer_instantiations(path) for path in sorted(CONFIG_PKG.rglob("*.py"))} hits = {path: lines for path, lines in hits.items() if lines} assert set(hits) == {CONFIG_PKG / "_app.py"}, f"Typer создаётся не только в _app.py: {sorted(map(str, hits))}" assert len(hits[CONFIG_PKG / "_app.py"]) == 1 def test_other_command_modules_do_not_create_typer_apps(self): offenders = {} for path in sorted(COMMANDS_ROOT.rglob("*.py")): if CONFIG_PKG in path.parents: continue lines = _typer_instantiations(path) if lines: offenders[str(path.relative_to(REPO_ROOT))] = lines assert not offenders, f"модули команд создают собственные Typer: {offenders}"