"""Инварианты направлений зависимостей внутри `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}"