diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 630c9c2..58be5ca 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -45,6 +45,7 @@ jobs: run: | wheels=("$RUNNER_TEMP"/dist/*.whl) expected_version=$(uv run --locked --python ${{ matrix.python-version }} python -c 'from importlib.metadata import version; print(version("pytest-fsd"))') + uv run --isolated --no-project --python ${{ matrix.python-version }} --with "${wheels[0]}" python -I tests/installed_smoke.py "$expected_version" PYTEST_FSD_EXPECTED_VERSION="$expected_version" uv run --isolated --no-project --python ${{ matrix.python-version }} --with "${wheels[0]}" python -I - <<'PY' import os import tempfile diff --git a/CHANGELOG.md b/CHANGELOG.md index 37496fc..0c9390b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 0.5.0 + +- Replace runtime import checks with static AST analysis. Forbidden layer and sibling-slice imports now fail both under pytest and in standalone Python, without importing project code or requiring pytest-archon. +- Detect public-package, relative, aliased, source-root, nested-source-root, local-function, and `TYPE_CHECKING` imports; include package initializers. App and Shared segments remain free to import each other within their own layer. +- Repair public API checking for plain module imports, parent-package imports, nested roots, relative imports, and static `__all__` declarations and updates. +- Reject invalid configuration, unknown extra rules, missing source roots, and uninspectable Python files instead of silently passing. Respect Python encoding declarations and UTF-8 BOMs. +- Fix structural checks for fake API files, invalid segment filesystem types, names colliding with Shared segments, and reserved names inside custom segments. Avoid false GUI-import violations for relative modules. +- Add standalone/pytest regression controls and installed-wheel verification. Dynamic imports and dynamically computed exports remain outside static resolution. + ## 0.4.0 - Adapt the applicable changes from Steiger 0.7.0 / FSD plugin 0.8.0, published September 25, 2026. diff --git a/README.md b/README.md index 5e36383..7d44001 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,14 @@ def test_architecture(): Run `pytest tests/test_architecture.py`. Violations appear as assertion failures with a rule name and path. If your source root is different, set `base_path` accordingly. The validator reads `[tool.pytest_fsd]` from the project root; `validate_fsd_architecture(project_root="...")` can target another project. +Standalone checks also raise `AssertionError` on violations and return a nonzero exit status: + +```bash +python -c "from pytest_fsd import validate_fsd_architecture; validate_fsd_architecture()" +``` + +Unknown configuration keys/rules and invalid settings raise `ValueError`. A missing source root, uninspectable Python file, or symlink inside configured layers fails validation. `ignore_paths` excludes non-FSD top-level directories from the layer-name check; it does not suppress imports in configured layers. + ## Rules The default checks cover layer import direction (`forbidden-imports`), slice independence (`no-cross-imports`), public APIs (`public-api`, `no-public-api-sidestep`, `no-layer-public-api`), structure (`no-segmentless-slices`, `no-segments-on-sliced-layers`, `typo-in-layer-name`, `ambiguous-slice-names`), naming (`segments-by-purpose`, `repetitive-naming`), and `no-ui-in-app`. @@ -75,8 +83,8 @@ See the [rule documentation](src/pytest_fsd/rules/) for examples and details. ## Scope and limitations -- `forbidden-imports` and `no-cross-imports` use [pytest-archon](https://pypi.org/project/pytest-archon/). Imports guarded by `if TYPE_CHECKING:` are invisible to these runtime checks. -- `no-public-api-sidestep` analyzes Python syntax and explicit `__all__` lists. Dynamically assembled exports may be reported incorrectly. +- Import rules statically inspect Python syntax, including relative imports, package initializers, function-local imports and `if TYPE_CHECKING:` branches. They do not execute project code. Dynamically computed imports (`importlib`, `__import__`, `exec`) and custom import hooks are not resolved. +- `no-public-api-sidestep` supports static `__all__` lists/tuples, concatenation, annotations, `+=`, `append` and `extend`. Unresolved dynamic exports are reported as unknown. - Steiger's `inconsistent-naming` and `import-locality` have no direct equivalent here. Consider Ruff's `N` and `TID` rules for Python naming and relative imports; their behavior is not identical to Steiger's rules. - Steiger's `insignificant-slice` needs an import graph and is not implemented. The deprecated `processes` layer is not created by this package; omit it from `layers`. - This package checks Python files and filesystem structure. It does not implement every Steiger rule or every JavaScript-specific convention. diff --git a/README.ru.md b/README.ru.md index f11c5b4..6accd71 100644 --- a/README.ru.md +++ b/README.ru.md @@ -44,6 +44,14 @@ def test_architecture(): Запустите `pytest tests/test_architecture.py`. Нарушения выводятся как ошибки теста с именем правила и путём. Если исходный код лежит в другом каталоге, измените `base_path`. Валидатор читает `[tool.pytest_fsd]` из корня проекта; параметр `validate_fsd_architecture(project_root="...")` позволяет проверить другой проект. +Самостоятельный запуск тоже вызывает `AssertionError` при нарушениях и завершается с ненулевым кодом: + +```bash +python -c "from pytest_fsd import validate_fsd_architecture; validate_fsd_architecture()" +``` + +Неизвестные настройки и дополнительные правила вызывают `ValueError`. Отсутствующий каталог исходников, симлинки внутри настроенных слоёв и Python-файлы, которые невозможно разобрать, приводят к ошибке проверки. `ignore_paths` исключает посторонние каталоги из проверки имён слоёв, но не отключает проверку импортов настроенных слоёв. + ## Правила По умолчанию проверяются направление импортов между слоями (`forbidden-imports`), независимость слайсов (`no-cross-imports`), публичные API (`public-api`, `no-public-api-sidestep`, `no-layer-public-api`), структура (`no-segmentless-slices`, `no-segments-on-sliced-layers`, `typo-in-layer-name`, `ambiguous-slice-names`), именование (`segments-by-purpose`, `repetitive-naming`) и `no-ui-in-app`. @@ -75,7 +83,7 @@ extra_rules = [ ## Ограничения -- `forbidden-imports` и `no-cross-imports` используют [pytest-archon](https://pypi.org/project/pytest-archon/). Импорты под `if TYPE_CHECKING:` не видны этим проверкам во время выполнения. +- Правила импортов статически разбирают Python, включая относительные импорты, `__init__.py`, импорты внутри функций и ветки `if TYPE_CHECKING:`. Код проекта не исполняется. Динамические импорты (`importlib`, `__import__`, `exec`) и нестандартные загрузчики не разрешаются. - `no-public-api-sidestep` анализирует синтаксис Python и явные списки `__all__`. Динамически собранные экспорты могут давать ложные срабатывания. - Прямых аналогов Steiger `inconsistent-naming` и `import-locality` здесь нет. Для именования Python и относительных импортов можно использовать правила Ruff `N` и `TID`; их поведение не совпадает полностью с правилами Steiger. - `insignificant-slice` требует анализа графа импортов и не реализовано. Устаревший слой `processes` пакет не создаёт — не указывайте его в `layers`. diff --git a/instructions/SKILL.md b/instructions/SKILL.md index 7c5b651..8d74dfb 100644 --- a/instructions/SKILL.md +++ b/instructions/SKILL.md @@ -17,10 +17,7 @@ The `pytest-fsd` library enforces the Feature-Sliced Design (FSD) methodology. I ## Inner Workings -The library acts as a facade, calling two distinct verification backends: - -1. **Dynamic Engine (`pytest-archon`)**: Tests layer hierarchy and cross-slice isolation at runtime by examining module dependencies. -2. **Static Engine (AST Checker)**: Validates strict Public API compliance directly from text without executing code, which is safer and faster for syntax-level constraints. +The library acts as a facade over static AST and filesystem checks. Import rules inspect absolute and relative imports, public packages, initializers, local-function imports and `TYPE_CHECKING` branches without executing project code. They raise `AssertionError` under pytest and standalone Python. Dynamic imports and unresolved dynamic exports are outside static resolution; invalid source/configuration fails explicitly. Configuration is centralized in `pyproject.toml` under the section `[tool.pytest_fsd]`. @@ -28,7 +25,7 @@ Configuration is centralized in `pyproject.toml` under the section `[tool.pytest When you introduce code or refactor, `pytest-fsd` tests might fail. Here is how you should interpret and fix these errors: -### 1. `must not import layers above it` (Archon) +### 1. `must not import layers above it` (AST) **Trigger**: A lower layer (e.g., `entities`) is trying to import from a higher layer (e.g., `features`). **Resolution**: @@ -37,11 +34,11 @@ FSD dictates downward dependencies only. - Relocate the shared code to a lower layer (e.g., `shared`). - Use Dependency Inversion (DI) via interfaces or protocols to abstract the dependency. -### 2. `Slice 'X' is independent` (Archon) +### 2. `must not import sibling slice` (AST) **Trigger**: A slice (e.g., `features/user_auth`) is importing from another slice on the same layer (e.g., `features/user_cart`). **Resolution**: -Slices on the same layer must not communicate directly (except within `shared`). They must remain isolated. +Slices on the same layer must not communicate directly (App and Shared contain segments rather than slices). They must remain isolated. - Extract the common functionality into a lower layer (`entities` or `shared`). - Compose the slices together inside a higher-level layer (like `widgets` or `pages`/`windows`). diff --git a/pyproject.toml b/pyproject.toml index 0679d0b..f3932e7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "pytest-fsd" -version = "0.4.0" +version = "0.5.0" description = "Validate Feature-Sliced Design architecture in Python projects with pytest" keywords = ["feature-sliced-design", "fsd", "architecture", "pytest", "python", "steiger"] readme = "README.md" @@ -25,7 +25,6 @@ classifiers = [ "Topic :: Software Development :: Testing", ] dependencies = [ - "pytest-archon>=0.0.7", "tomli>=2.0.1; python_version < '3.11'", ] diff --git a/src/pytest_fsd/__init__.py b/src/pytest_fsd/__init__.py index 17abb94..e757d5d 100644 --- a/src/pytest_fsd/__init__.py +++ b/src/pytest_fsd/__init__.py @@ -9,6 +9,7 @@ from typing import List from ._lib.violations import Violation +from ._lib.source_validation import check_sources from .config import load_config from .rules import ( ambiguous_slice_names, @@ -67,7 +68,7 @@ def validate_fsd_architecture(project_root: str = ".") -> None: Raises AssertionError if any violations are found. """ config = load_config(project_root) - all_violations: List[Violation] = [] + all_violations: List[Violation] = check_sources(config, project_root) # Запускаем базовые правила for rule_module in CORE_RULES: diff --git a/src/pytest_fsd/_lib/ast_utils.py b/src/pytest_fsd/_lib/ast_utils.py index 46c2ea7..9146dba 100644 --- a/src/pytest_fsd/_lib/ast_utils.py +++ b/src/pytest_fsd/_lib/ast_utils.py @@ -2,16 +2,17 @@ """Shared AST parsing utilities used by multiple rules.""" import ast +import tokenize from typing import Dict, List, Tuple, Optional def parse_python_file(filepath: str) -> Optional[Tuple[str, ast.Module]]: """Read and parse Python source without importing or executing it.""" try: - with open(filepath, "r", encoding="utf-8") as f: + with tokenize.open(filepath) as f: source = f.read() return source, ast.parse(source, filename=filepath) - except (OSError, UnicodeError, SyntaxError, ValueError): + except (OSError, UnicodeError, SyntaxError, ValueError, LookupError): return None @@ -63,21 +64,69 @@ def get_imports_from_file( def get_exported_names(filepath: str) -> Optional[List[str]]: - """Return the list of names exported in __all__ if defined, or None if not defined.""" - try: - with open(filepath, "r", encoding="utf-8") as f: - tree = ast.parse(f.read(), filename=filepath) - except Exception: + """Return statically declared string exports, or None when unknown.""" + parsed = parse_python_file(filepath) + if parsed is None: + return None + _, tree = parsed + + def names(value: ast.AST) -> Optional[List[str]]: + if isinstance(value, (ast.List, ast.Tuple)): + result = [] + for element in value.elts: + if not isinstance(element, ast.Constant) or not isinstance(element.value, str): + return None + result.append(element.value) + return result + if isinstance(value, ast.BinOp) and isinstance(value.op, ast.Add): + left, right = names(value.left), names(value.right) + if left is not None and right is not None: + return left + right return None + exported = None for node in tree.body: + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + continue + for descendant in ast.walk(node): + if isinstance(descendant, ast.Subscript) and isinstance(descendant.ctx, (ast.Store, ast.Del)): + if isinstance(descendant.value, ast.Name) and descendant.value.id == "__all__": + exported = None if isinstance(node, ast.Assign): - for target in node.targets: - if isinstance(target, ast.Name) and target.id == "__all__": - if isinstance(node.value, (ast.List, ast.Tuple)): - return [ - elt.value - for elt in node.value.elts - if getattr(elt, "value", None) is not None - ] - return None + if any(isinstance(target, ast.Name) and target.id == "__all__" for target in node.targets): + exported = names(node.value) + elif isinstance(node, ast.AnnAssign): + if isinstance(node.target, ast.Name) and node.target.id == "__all__" and node.value is not None: + exported = names(node.value) + elif isinstance(node, ast.AugAssign): + if isinstance(node.target, ast.Name) and node.target.id == "__all__": + added = names(node.value) + if isinstance(node.op, ast.Add) and exported is not None and added is not None: + exported += added + else: + exported = None + elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Call): + call = node.value + if isinstance(call.func, ast.Attribute) and isinstance(call.func.value, ast.Name) and call.func.value.id == "__all__": + if exported is not None and len(call.args) == 1 and not call.keywords: + if call.func.attr == "append" and isinstance(call.args[0], ast.Constant) and isinstance(call.args[0].value, str): + exported.append(call.args[0].value) + continue + if call.func.attr == "extend": + added = names(call.args[0]) + if added is not None: + exported += added + continue + exported = None + else: + # Conditional declarations and mutations cannot define a known API. + for descendant in ast.walk(node): + if isinstance(descendant, ast.Name) and descendant.id == "__all__" and isinstance(descendant.ctx, (ast.Store, ast.Del)): + exported = None + break + if isinstance(descendant, ast.Call) and isinstance(descendant.func, ast.Attribute): + receiver = descendant.func.value + if isinstance(receiver, ast.Name) and receiver.id == "__all__": + exported = None + break + return exported diff --git a/src/pytest_fsd/_lib/imports.py b/src/pytest_fsd/_lib/imports.py new file mode 100644 index 0000000..af06b45 --- /dev/null +++ b/src/pytest_fsd/_lib/imports.py @@ -0,0 +1,90 @@ +"""Resolve local import statements without loading project modules.""" + +import ast +import os +from pathlib import Path +from typing import Iterator, List, Optional, Tuple + +from .ast_utils import get_node_location, parse_python_file +from ..config import FsdConfig + + +def resolve_module( + module: Optional[str], level: int, file_path: str, base_dir: str, layers: List[str] +) -> Optional[Tuple[str, ...]]: + """Resolve a module to components relative to the configured source root.""" + base = Path(base_dir).resolve() + parts = tuple(module.split(".")) if module else () + if level: + parent = Path(file_path).resolve().parent + for _ in range(level - 1): + parent = parent.parent + try: + relative = parent.joinpath(*parts).relative_to(base) + except ValueError: + return None + return relative.parts + + # Both `src.features.auth` and source-root imports `features.auth` are valid. + # Nested roots also accept their qualified path, e.g. `backend.src.features`. + for count in range(min(len(base.parts), len(parts)), 0, -1): + if parts[:count] == base.parts[-count:]: + candidate = parts[count:] + if candidate and candidate[0] in layers: + return candidate + if parts and parts[0] in layers and (base / parts[0]).is_dir(): + return parts + return None + + +def imported_modules( + node: ast.AST, file_path: str, base_dir: str, layers: List[str] +) -> List[Tuple[str, ...]]: + """Include package imports and existing child modules in from-imports.""" + result = [] + if isinstance(node, ast.Import): + for alias in node.names: + parts = resolve_module(alias.name, 0, file_path, base_dir, layers) + if parts is not None: + result.append(parts) + elif isinstance(node, ast.ImportFrom): + parts = resolve_module(node.module, node.level, file_path, base_dir, layers) + if parts is not None: + result.append(parts) + for alias in node.names: + child = Path(base_dir).joinpath(*parts, alias.name) + if alias.name != "*" and (child.is_dir() or child.with_suffix(".py").is_file()): + result.append(parts + (alias.name,)) + elif node.module and not node.level: + # `from src import features` (or a nested source root). + base = Path(base_dir).resolve() + module_parts = tuple(node.module.split(".")) + if module_parts == base.parts[-len(module_parts):]: + for alias in node.names: + if alias.name in layers and (base / alias.name).is_dir(): + result.append((alias.name,)) + return list(dict.fromkeys(result)) + + +def iter_imports( + config: FsdConfig, project_root: str +) -> Iterator[Tuple[str, Tuple[str, ...], Tuple[str, ...], dict]]: + """Yield local source/target components and diagnostic locations.""" + base_dir = os.path.join(project_root, config.base_path) + for root, dirs, files in os.walk(base_dir): + dirs[:] = sorted(d for d in dirs if d != "__pycache__") + for filename in sorted(files): + if not filename.endswith(".py"): + continue + file_path = os.path.join(root, filename) + source_parts = Path(file_path).relative_to(base_dir).parts + if source_parts[0] not in config.layers: + continue + parsed = parse_python_file(file_path) + if parsed is None: + continue # The facade reports unreadable/invalid Python sources. + source, tree = parsed + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + for target in imported_modules(node, file_path, base_dir, config.layers): + yield file_path, source_parts, target, get_node_location(node, source) diff --git a/src/pytest_fsd/_lib/source_validation.py b/src/pytest_fsd/_lib/source_validation.py new file mode 100644 index 0000000..712bbf3 --- /dev/null +++ b/src/pytest_fsd/_lib/source_validation.py @@ -0,0 +1,51 @@ +"""Report source files that cannot be inspected rather than silently passing.""" + +import ast +import os +import tokenize +from typing import List + +from .violations import Violation +from ..config import FsdConfig + + +def check_sources(config: FsdConfig, project_root: str) -> List[Violation]: + base_dir = os.path.join(project_root, config.base_path) + if not os.path.isdir(base_dir): + return [Violation(rule="python-source", file_path=base_dir, + message="Configured source directory does not exist.")] + violations = [] + + def unreadable(error: OSError) -> None: + violations.append(Violation(rule="python-source", file_path=str(error.filename), + message=f"Cannot inspect source directory: {error}")) + + for layer in config.layers: + layer_dir = os.path.join(base_dir, layer) + if os.path.islink(layer_dir) or (os.path.exists(layer_dir) and not os.path.isdir(layer_dir)): + violations.append(Violation(rule="python-source", file_path=layer_dir, + message="Configured layer must be a real directory, not a file or symlink.")) + continue + if not os.path.exists(layer_dir): + continue + for root, dirs, files in os.walk(layer_dir, onerror=unreadable): + for name in dirs + files: + path = os.path.join(root, name) + if os.path.islink(path): + violations.append(Violation(rule="python-source", file_path=path, + message="Symlinks inside configured layers cannot be inspected reliably.")) + dirs[:] = sorted(d for d in dirs if d != "__pycache__") + for filename in sorted(files): + if not filename.endswith(".py"): + continue + file_path = os.path.join(root, filename) + try: + with tokenize.open(file_path) as handle: + ast.parse(handle.read(), filename=file_path) + except (OSError, UnicodeError, SyntaxError, ValueError, LookupError) as error: + violations.append(Violation( + rule="python-source", file_path=file_path, + line_number=getattr(error, "lineno", None), + message=f"Cannot inspect Python source: {error}", + )) + return violations diff --git a/src/pytest_fsd/config.py b/src/pytest_fsd/config.py index 8e0097d..300ccc0 100644 --- a/src/pytest_fsd/config.py +++ b/src/pytest_fsd/config.py @@ -49,6 +49,29 @@ def load_config(root_dir: str) -> FsdConfig: data = tomllib.load(f) tool_config = data.get("tool", {}).get("pytest_fsd", {}) + if not isinstance(tool_config, dict): + raise ValueError("[tool.pytest_fsd] must be a table") + unknown = set(tool_config) - {"base_path", "layers", "ignore_paths", "extra_rules"} + if unknown: + raise ValueError(f"Unknown pytest_fsd settings: {', '.join(sorted(unknown))}") + if "base_path" in tool_config and ( + not isinstance(tool_config["base_path"], str) or not tool_config["base_path"].strip() + ): + raise ValueError("pytest_fsd.base_path must be a nonempty string") + for name in ("layers", "ignore_paths", "extra_rules"): + if name in tool_config: + value = tool_config[name] + if not isinstance(value, list) or not all(isinstance(item, str) and item for item in value): + raise ValueError(f"pytest_fsd.{name} must be a list of nonempty strings") + if "layers" in tool_config: + layers = tool_config["layers"] + if not layers or len(layers) != len(set(layers)): + raise ValueError("pytest_fsd.layers must be nonempty and contain no duplicates") + if any(layer in (".", "..") or any(char in layer for char in "/\\.") for layer in layers): + raise ValueError("pytest_fsd.layers must contain directory names, not paths") + unknown_rules = set(tool_config.get("extra_rules", [])) - AVAILABLE_EXTRA_RULES + if unknown_rules: + raise ValueError(f"Unknown pytest_fsd extra_rules: {', '.join(sorted(unknown_rules))}") config = FsdConfig() if "base_path" in tool_config: diff --git a/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py b/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py index ac3b2cd..a142b22 100644 --- a/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py +++ b/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py @@ -28,19 +28,22 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: if not os.path.isdir(shared_path): return violations - # Собираем имена компонентов (слайсов) внутри сегментов shared - # Например: shared/ui/button -> регистрируем 'button' (внутри сегмента 'ui') + # Include both shared segments and their nested components. shared_slices: Dict[str, str] = {} for segment in os.listdir(shared_path): segment_path = os.path.join(shared_path, segment) if not os.path.isdir(segment_path) or segment.startswith("_"): continue + shared_slices[segment] = f"{shared_layer}/{segment}" + for shared_slice in os.listdir(segment_path): if os.path.isdir( os.path.join(segment_path, shared_slice) ) and not shared_slice.startswith("_"): - shared_slices[shared_slice] = segment + shared_slices.setdefault( + shared_slice, f"{shared_layer}/{segment}/{shared_slice}" + ) if not shared_slices: return violations @@ -59,13 +62,13 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: continue if slice_name in shared_slices: - conflict_segment = shared_slices[slice_name] + conflict_path = shared_slices[slice_name] violations.append( Violation( rule=RULE_NAME, file_path=slice_path, message=f"Slice '{slice_name}' in layer '{layer}' has the same name as " - f"component 'shared/{conflict_segment}/{slice_name}'. This creates ambiguity about " + f"shared directory '{conflict_path}'. This creates ambiguity about " f"where new code should be placed.", ) ) diff --git a/src/pytest_fsd/rules/forbidden_imports/README.md b/src/pytest_fsd/rules/forbidden_imports/README.md index 3ab27a9..ca0ff92 100644 --- a/src/pytest_fsd/rules/forbidden_imports/README.md +++ b/src/pytest_fsd/rules/forbidden_imports/README.md @@ -8,7 +8,7 @@ This rule maps to Steiger's `no-higher-level-imports`. ## How it works -Uses `pytest-archon` to dynamically verify that modules in each layer do not import from any layer above them in the configured hierarchy. +Statically analyzes Python imports without executing project modules. Includes public packages, relative imports, package initializers and `TYPE_CHECKING` branches; works under pytest and standalone Python. For example, with default layers `["app", "windows", "widgets", "features", "entities", "shared"]`: diff --git a/src/pytest_fsd/rules/forbidden_imports/__init__.py b/src/pytest_fsd/rules/forbidden_imports/__init__.py index a1f38ad..e931160 100644 --- a/src/pytest_fsd/rules/forbidden_imports/__init__.py +++ b/src/pytest_fsd/rules/forbidden_imports/__init__.py @@ -1,15 +1,8 @@ -# src/pytest_fsd/rules/forbidden_imports/__init__.py -""" -[Rule: forbidden-imports / no-higher-level-imports] -Layers can only import from layers below them in the FSD hierarchy. -Uses pytest-archon for dynamic runtime checking. -""" +"""Layers may import only their own layer or layers below them.""" -import os from typing import List -from pytest_archon import archrule - +from ..._lib.imports import iter_imports from ..._lib.violations import Violation from ...config import FsdConfig @@ -17,45 +10,13 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: - """Verify that each layer only imports from layers below it.""" + """Check all static imports, including package initializers and type hints.""" violations = [] - base_path = config.base_path - layers = config.layers - - for i, current_layer in enumerate(layers): - layer_path = os.path.join(project_root, base_path, current_layer) - if not os.path.isdir(layer_path): - continue - - # Проверяем наличие .py файлов в слое - has_python_files = False - for _, _, files in os.walk(layer_path): - if any(f.endswith(".py") and f != "__init__.py" for f in files): - has_python_files = True - break - - if not has_python_files: - continue - - forbidden_layers = layers[:i] - if forbidden_layers: - forbidden_modules = [f"{base_path}.{layer}.*" for layer in forbidden_layers] - try: - ( - archrule( - f"[{current_layer.upper()}] must not import layers above it" - ) - .match(f"{base_path}.{current_layer}.*") - .should_not_import(*forbidden_modules) - .check(base_path) - ) - except BaseException as e: - violations.append( - Violation( - rule=RULE_NAME, - file_path=current_layer, - message=str(e).strip(), - ) - ) - + ranks = {layer: index for index, layer in enumerate(config.layers)} + for path, source, target, location in iter_imports(config, project_root): + if target and target[0] in ranks and ranks[target[0]] < ranks[source[0]]: + violations.append(Violation( + rule=RULE_NAME, file_path=path, **location, + message=f"Layer '{source[0]}' must not import layers above it: '{'.'.join(target)}'.", + )) return violations diff --git a/src/pytest_fsd/rules/no_cross_imports/README.md b/src/pytest_fsd/rules/no_cross_imports/README.md index 0849e34..5c307ce 100644 --- a/src/pytest_fsd/rules/no_cross_imports/README.md +++ b/src/pytest_fsd/rules/no_cross_imports/README.md @@ -4,9 +4,9 @@ Forbid imports between slices on the same layer. Slices within the same layer mu ## How it works -Uses `pytest-archon` to dynamically verify that each slice in a layer does not import from any other slice in the same layer. +Statically analyzes Python imports without executing project modules. Includes public packages, relative imports, package initializers and `TYPE_CHECKING` branches; works under pytest and standalone Python. -The `shared` layer is excluded from this check, as segments in `shared` may depend on each other. +The `app` and `shared` layers are excluded: they contain segments, which may depend on each other within the same layer. ## Examples diff --git a/src/pytest_fsd/rules/no_cross_imports/__init__.py b/src/pytest_fsd/rules/no_cross_imports/__init__.py index 9084415..8ed6c9d 100644 --- a/src/pytest_fsd/rules/no_cross_imports/__init__.py +++ b/src/pytest_fsd/rules/no_cross_imports/__init__.py @@ -1,16 +1,9 @@ -# src/pytest_fsd/rules/no_cross_imports/__init__.py -""" -[Rule: no-cross-imports] -Slices within the same layer must not import from each other. -Uses pytest-archon for dynamic runtime checking. -""" +"""Slices within a layer must be independent; App and Shared have no slices.""" -import os from typing import List -from pytest_archon import archrule - -from ..._lib.fs_utils import get_slices, get_canonical_layer +from ..._lib.fs_utils import get_sliced_layers +from ..._lib.imports import iter_imports from ..._lib.violations import Violation from ...config import FsdConfig @@ -18,40 +11,15 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: - """Verify that slices within the same layer do not import from each other.""" + """Reject imports of sibling slices, including their public packages.""" violations = [] - base_path = config.base_path - - for layer in config.layers: - # В shared слайсы могут зависеть друг от друга - if get_canonical_layer(layer) == "shared": - continue - - slices = get_slices(layer, os.path.join(project_root, base_path)) - if not slices: - continue - - for slice_name in slices: - other_slices = [ - f"{base_path}.{layer}.{s}.*" for s in slices if s != slice_name - ] - if other_slices: - try: - ( - archrule( - f"[{layer.upper()}] Slice '{slice_name}' is independent" - ) - .match(f"{base_path}.{layer}.{slice_name}.*") - .should_not_import(*other_slices) - .check(base_path) - ) - except AssertionError as e: - violations.append( - Violation( - rule=RULE_NAME, - file_path=f"{layer}/{slice_name}", - message=str(e).strip(), - ) - ) - + sliced_layers = get_sliced_layers(config) + for path, source, target, location in iter_imports(config, project_root): + if (len(source) >= 3 and len(target) >= 2 + and source[0] in sliced_layers and source[0] == target[0] + and source[1] != target[1]): + violations.append(Violation( + rule=RULE_NAME, file_path=path, **location, + message=f"Slice '{source[0]}/{source[1]}' must not import sibling slice '{target[0]}/{target[1]}'.", + )) return violations diff --git a/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py b/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py index 11d0334..842e440 100644 --- a/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py +++ b/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py @@ -1,9 +1,4 @@ -# src/pytest_fsd/rules/no_public_api_sidestep/__init__.py -""" -[Rule: no-public-api-sidestep] -Imports from other slices must go through the slice's __init__.py (Public API), -not through internal modules. -""" +"""Require cross-slice imports to use the target slice's public API.""" import ast import os @@ -11,6 +6,7 @@ from ..._lib.ast_utils import get_exported_names, get_node_location, parse_python_file from ..._lib.fs_utils import get_sliced_layers +from ..._lib.imports import imported_modules, resolve_module from ..._lib.violations import Violation from ...config import FsdConfig @@ -21,145 +17,74 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: """Verify that all cross-slice imports go through the slice's Public API.""" violations = [] base_dir = os.path.join(project_root, config.base_path) - base_module = config.base_path.replace(os.sep, ".") - + base_module = config.base_path.replace(os.sep, ".").strip(".") if not os.path.isdir(base_dir): return violations sliced_layers = get_sliced_layers(config) - for root, _, files in os.walk(base_dir): for file in files: if not file.endswith(".py"): continue - file_path = os.path.join(root, file) - - # Определяем слайс текущего файла - rel_path = os.path.relpath(file_path, base_dir) - parts = rel_path.split(os.sep) - - current_layer = parts[0] if len(parts) > 0 else None - current_slice = ( - parts[1] if len(parts) > 1 and current_layer in sliced_layers else None - ) - + parts = os.path.relpath(file_path, base_dir).split(os.sep) + current_layer = parts[0] + current_slice = parts[1] if len(parts) > 2 and current_layer in sliced_layers else None parsed = parse_python_file(file_path) if parsed is None: continue source, tree = parsed - imports = [] for node in ast.walk(tree): + targets = [] if isinstance(node, ast.Import): for alias in node.names: - imports.append((node, alias.name, 0, [alias.name])) + target = resolve_module(alias.name, 0, file_path, base_dir, config.layers) + if target is not None: + targets.append((target, alias.name, [])) elif isinstance(node, ast.ImportFrom): - imports.append((node, node.module, node.level, [a.name for a in node.names])) - - for node, module_path, level, imported_names in imports: - if level > 0: - # Разрешаем относительные импорты - file_dir_parts = parts[:-1] # Убираем имя файла + target = resolve_module(node.module, node.level, file_path, base_dir, config.layers) + if target is not None and len(target) >= 2: + targets.append((target, node.module or "." * node.level, [alias.name for alias in node.names])) + else: + for imported in imported_modules(node, file_path, base_dir, config.layers): + if len(imported) >= 2: + targets.append((imported, ".".join(imported), [])) - if level > len(file_dir_parts): - # Возврат за пределы src/ (или base_path), вне области FSD + for target, module_path, imported_names in targets: + if len(target) < 2: continue - - # Вычисляем путь назначения - resolved_parts = file_dir_parts[: len(file_dir_parts) - level + 1] - if module_path: - resolved_parts.extend(module_path.split(".")) - - import_parts = resolved_parts - layer_idx = 0 - else: - if not module_path: + target_layer, target_slice = target[:2] + if target_layer not in sliced_layers: continue - - import_parts = module_path.split(".") - - # Определяем, где в импорте начинается layer/slice - if module_path.startswith(f"{base_module}."): - # Стандартный вариант: "src.features.auth.model.handler" - layer_idx = 1 - elif import_parts[0] in sliced_layers: - # Альтернативный вариант: "features.auth.model.handler" - # Проверка физического существования (защита от коллизий с PyPI-библиотеками) - layer_path = os.path.join(base_dir, import_parts[0]) - if not os.path.isdir(layer_path): - continue - - if len(import_parts) > 1: - target_slice_path = os.path.join( - layer_path, import_parts[1] - ) - # Слайс может быть папкой или .py файлом - if not os.path.isdir( - target_slice_path - ) and not os.path.isfile(f"{target_slice_path}.py"): - continue - - layer_idx = 0 - else: + if current_layer == target_layer and current_slice == target_slice: continue - - remaining = import_parts[layer_idx:] - if len(remaining) < 2: - continue - - target_layer = remaining[0] - target_slice = remaining[1] - - if target_layer not in sliced_layers: - continue - - # Разрешаем импорт внутри одного слайса - if current_layer == target_layer and current_slice == target_slice: - continue - - # Длина > 2 (layer + slice + internal) → глубокий импорт - if len(remaining) > 2: - violations.append( - Violation( - rule=RULE_NAME, - file_path=file_path, - **get_node_location(node, source), + location = get_node_location(node, source) + if len(target) > 2: + violations.append(Violation( + rule=RULE_NAME, file_path=file_path, **location, message=f"Importing internal module '{module_path}' " f"from slice '{target_layer}/{target_slice}'. " f"Import from '{base_module}.{target_layer}.{target_slice}' instead.", - ) - ) - else: - # Длина == 2 (layer + slice) -> Обращение к __init__.py слайса - # Проверяем, что импортируемые имена действительно экспортируются в __all__ (Blind Spot 1) - if imported_names: - target_init_path = os.path.join( - base_dir, target_layer, target_slice, "__init__.py" - ) - if os.path.isfile(target_init_path): - exported_names = get_exported_names(target_init_path) - if exported_names is None: - violations.append( - Violation( - rule=RULE_NAME, - file_path=file_path, - **get_node_location(node, source), - message=f"Slice '{target_layer}/{target_slice}' does not define `__all__` in its __init__.py. " - f"Public API exports must be explicit to prevent encapsulation bypass.", - ) - ) - else: - for name in imported_names: - if name not in exported_names and name != "*": - violations.append( - Violation( - rule=RULE_NAME, - file_path=file_path, - **get_node_location(node, source), - message=f"Name '{name}' is not explicitly exported in " - f"'{target_layer}/{target_slice}/__init__.py'. " - f"Add it to `__all__` to make it part of the Public API.", - ) - ) - + )) + elif imported_names: + target_init = os.path.join(base_dir, target_layer, target_slice, "__init__.py") + if not os.path.isfile(target_init): + continue + exported_names = get_exported_names(target_init) + if exported_names is None: + violations.append(Violation( + rule=RULE_NAME, file_path=file_path, **location, + message=f"Slice '{target_layer}/{target_slice}' does not define `__all__` " + "as a static list of strings in its __init__.py. " + "Public API exports must be explicit to prevent encapsulation bypass.", + )) + else: + for name in imported_names: + if name != "*" and name not in exported_names: + violations.append(Violation( + rule=RULE_NAME, file_path=file_path, **location, + message=f"Name '{name}' is not explicitly exported in " + f"'{target_layer}/{target_slice}/__init__.py'. " + "Add it to `__all__` to make it part of the Public API.", + )) return violations diff --git a/src/pytest_fsd/rules/no_reserved_folder_names/__init__.py b/src/pytest_fsd/rules/no_reserved_folder_names/__init__.py index dd382be..03bff56 100644 --- a/src/pytest_fsd/rules/no_reserved_folder_names/__init__.py +++ b/src/pytest_fsd/rules/no_reserved_folder_names/__init__.py @@ -52,21 +52,19 @@ def _check_segments_subfolders( if not os.path.isdir(segment_path) or segment_name.startswith("_"): continue - # Если имя папки является стандартным сегментом, проверяем все ее подпапки - if segment_name in STANDARD_SEGMENTS: - for root_dir, dirs, _ in os.walk(segment_path): - # Игнорируем скрытые папки - dirs[:] = [d for d in dirs if not d.startswith("_")] + for root_dir, dirs, _ in os.walk(segment_path): + # Игнорируем скрытые папки + dirs[:] = [d for d in dirs if not d.startswith("_")] - for subfolder in dirs: - if subfolder in STANDARD_SEGMENTS: - subfolder_path = os.path.join(root_dir, subfolder) - violations.append( - Violation( - rule=RULE_NAME, - file_path=subfolder_path, - message=f"Subfolder '{subfolder}' inside segment " - f"'{context}/{segment_name}' uses a reserved segment name. " - f"This may cause confusion about the segment structure.", - ) + for subfolder in dirs: + if subfolder in STANDARD_SEGMENTS: + subfolder_path = os.path.join(root_dir, subfolder) + violations.append( + Violation( + rule=RULE_NAME, + file_path=subfolder_path, + message=f"Subfolder '{subfolder}' inside segment " + f"'{context}/{segment_name}' uses a reserved segment name. " + f"This may cause confusion about the segment structure.", ) + ) diff --git a/src/pytest_fsd/rules/no_segmentless_slices/__init__.py b/src/pytest_fsd/rules/no_segmentless_slices/__init__.py index b214567..53562b8 100644 --- a/src/pytest_fsd/rules/no_segmentless_slices/__init__.py +++ b/src/pytest_fsd/rules/no_segmentless_slices/__init__.py @@ -41,10 +41,15 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: continue for entry in entries: - if entry in STANDARD_SEGMENTS: + entry_path = os.path.join(slice_path, entry) + if entry in STANDARD_SEGMENTS and os.path.isdir(entry_path): has_segments = True break - if entry.endswith(".py") and entry[:-3] in STANDARD_SEGMENTS: + if ( + entry.endswith(".py") + and entry[:-3] in STANDARD_SEGMENTS + and os.path.isfile(entry_path) + ): has_segments = True break diff --git a/src/pytest_fsd/rules/no_ui_in_app/__init__.py b/src/pytest_fsd/rules/no_ui_in_app/__init__.py index f2fa0c6..f464bed 100644 --- a/src/pytest_fsd/rules/no_ui_in_app/__init__.py +++ b/src/pytest_fsd/rules/no_ui_in_app/__init__.py @@ -73,7 +73,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: ) ) elif isinstance(node, ast.ImportFrom): - if node.module: + if node.module and node.level == 0: base_import = node.module.split(".")[0] if base_import in FORBIDDEN_UI_MODULES: violations.append( diff --git a/src/pytest_fsd/rules/no_wildcard_exports/__init__.py b/src/pytest_fsd/rules/no_wildcard_exports/__init__.py index 42a4b34..0fab2d7 100644 --- a/src/pytest_fsd/rules/no_wildcard_exports/__init__.py +++ b/src/pytest_fsd/rules/no_wildcard_exports/__init__.py @@ -2,6 +2,7 @@ import ast import os +import tokenize from typing import List from ..._lib.ast_utils import get_node_location @@ -22,10 +23,10 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: continue file_path = os.path.join(root, "__init__.py") try: - with open(file_path, "r", encoding="utf-8") as api: + with tokenize.open(file_path) as api: source = api.read() tree = ast.parse(source, filename=file_path) - except (OSError, UnicodeError, SyntaxError, ValueError) as error: + except (OSError, UnicodeError, SyntaxError, ValueError, LookupError) as error: violations.append( Violation( rule=RULE_NAME, diff --git a/src/pytest_fsd/rules/public_api/__init__.py b/src/pytest_fsd/rules/public_api/__init__.py index 7c40cc5..a6d4a55 100644 --- a/src/pytest_fsd/rules/public_api/__init__.py +++ b/src/pytest_fsd/rules/public_api/__init__.py @@ -33,7 +33,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: continue init_file = os.path.join(slice_path, "__init__.py") - if not os.path.exists(init_file): + if not os.path.isfile(init_file): violations.append( Violation( rule=RULE_NAME, @@ -60,7 +60,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: child_path = os.path.join(segment_path, child) if os.path.isdir(child_path) and not child.startswith("_"): child_init = os.path.join(child_path, "__init__.py") - if not os.path.exists(child_init): + if not os.path.isfile(child_init): violations.append( Violation( rule=RULE_NAME, @@ -71,7 +71,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: ) else: init_file = os.path.join(segment_path, "__init__.py") - if not os.path.exists(init_file): + if not os.path.isfile(init_file): violations.append( Violation( rule=RULE_NAME, diff --git a/tests/installed_smoke.py b/tests/installed_smoke.py new file mode 100644 index 0000000..21d81ed --- /dev/null +++ b/tests/installed_smoke.py @@ -0,0 +1,42 @@ +"""Acceptance controls for an installed wheel, run with `python -I`.""" + +import sys +import tempfile +from importlib.metadata import version +from pathlib import Path + +from pytest_fsd import validate_fsd_architecture + + +def main(): + assert version("pytest-fsd") == sys.argv[1] + cases = [ + ("features/auth/api/router.py", "from src.features.tables import value\n", "no-cross-imports"), + ("shared/lib/source.py", "from src.features.tables import value\n", "forbidden-imports"), + ("features/auth/api/router.py", "from src.shared.lib import value\n", None), + ] + for source_path, source, expected_rule in cases: + with tempfile.TemporaryDirectory(prefix="pytest-fsd-wheel-") as directory: + root = Path(directory) + files = { + "features/auth/__init__.py": "__all__ = []\n", + "features/tables/__init__.py": "from .model.value import value\n__all__ = ['value']\n", + "features/tables/model/value.py": "raise RuntimeError('project must not execute')\nvalue = 1\n", + "shared/lib/__init__.py": "value = 1\n", + source_path: source, + } + for relative, body in files.items(): + path = root / "src" / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(body, encoding="utf-8") + try: + validate_fsd_architecture(directory) + except AssertionError as error: + assert expected_rule and "[" + expected_rule + "]" in str(error), str(error) + else: + assert expected_rule is None, "Installed wheel missed " + str(expected_rule) + print("PASS installed control:", expected_rule or "permitted import") + + +if __name__ == "__main__": + main() diff --git a/tests/rules/test_ambiguous_slice_names.py b/tests/rules/test_ambiguous_slice_names.py index 7e920bc..6ad63c4 100644 --- a/tests/rules/test_ambiguous_slice_names.py +++ b/tests/rules/test_ambiguous_slice_names.py @@ -44,3 +44,17 @@ def test_ambiguous_slice_names_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "button" in violations[0].message + + +def test_ambiguous_slice_names_matches_shared_segments(create_project): + project_root = create_project( + "📂 shared\n 📂 i18n\n 📄 __init__.py\n" + "📂 features\n 📂 i18n\n 📂 model\n 📄 __init__.py" + ) + + violations = check(load_config(str(project_root)), str(project_root)) + + assert len(violations) == 1 + assert violations[0].rule == RULE_NAME + assert violations[0].file_path == str(project_root / "src/features/i18n") + assert "shared/i18n" in violations[0].message diff --git a/tests/rules/test_forbidden_imports.py b/tests/rules/test_forbidden_imports.py index 2ae4835..2938ae9 100644 --- a/tests/rules/test_forbidden_imports.py +++ b/tests/rules/test_forbidden_imports.py @@ -2,8 +2,7 @@ """ Tests for the forbidden-imports rule. -Правило использует pytest-archon, который вызывает pytest.fail() напрямую. -Поэтому тестируем через subprocess, чтобы изолировать pytest-раннер. +End-to-end pytest subprocess controls for the static import checks. """ import os import subprocess diff --git a/tests/rules/test_no_cross_imports.py b/tests/rules/test_no_cross_imports.py index ab531d2..8fa9eec 100644 --- a/tests/rules/test_no_cross_imports.py +++ b/tests/rules/test_no_cross_imports.py @@ -2,8 +2,7 @@ """ Tests for the no-cross-imports rule. -Правило использует pytest-archon, который вызывает pytest.fail() напрямую. -Поэтому тестируем через subprocess, чтобы изолировать pytest-раннер. +End-to-end pytest subprocess controls for the static import checks. """ import os import subprocess diff --git a/tests/rules/test_no_public_api_sidestep.py b/tests/rules/test_no_public_api_sidestep.py index 78d0f3c..011952f 100644 --- a/tests/rules/test_no_public_api_sidestep.py +++ b/tests/rules/test_no_public_api_sidestep.py @@ -1,5 +1,7 @@ # tests/rules/test_no_public_api_sidestep.py """Tests for the no-public-api-sidestep rule.""" +import pytest + from pytest_fsd.config import load_config from pytest_fsd.rules.no_public_api_sidestep import RULE_NAME, check @@ -127,3 +129,121 @@ def test_no_public_api_sidestep_multiline_location(create_project): assert len(violations) == 1 assert (violations[0].line_number, violations[0].column_number) == (1, 1) assert (violations[0].end_line_number, violations[0].end_column_number) == (3, 2) + + +@pytest.mark.parametrize("statement", [ + "import src.features.auth", + "import src.features.auth as auth", + "from src.features import auth", + "from .. import auth", + "from features import auth", +]) +def test_slice_module_import_does_not_check_module_name_in_all(create_project, statement): + project_root = create_project( + "📂 features\n 📂 auth\n 📄 __init__.py\n 📄 model.py\n" + " 📂 profile\n 📄 __init__.py\n 📄 ui.py" + ) + (project_root / "src/features/auth/__init__.py").write_text("__all__ = ['do_auth']\n", encoding="utf-8") + (project_root / "src/features/profile/ui.py").write_text(statement + "\n", encoding="utf-8") + + assert check(load_config(str(project_root)), str(project_root)) == [] + + +@pytest.mark.parametrize("statement", [ + "import src.features.auth.model as model", + "from ..auth.model import do_auth", + "from features.auth.model import do_auth", +]) +def test_internal_import_spellings_are_rejected(create_project, statement): + project_root = create_project( + "📂 features\n 📂 auth\n 📄 __init__.py\n 📄 model.py\n" + " 📂 profile\n 📄 __init__.py\n 📄 ui.py" + ) + (project_root / "src/features/profile/ui.py").write_text(statement + "\n", encoding="utf-8") + + violations = check(load_config(str(project_root)), str(project_root)) + + assert len(violations) == 1 + assert "Importing internal module" in violations[0].message + + +@pytest.mark.parametrize("exports", [ + "__all__: list = ['do_auth']", + "__all__ = ('do_auth',)", + "__all__ = []\n__all__ += ['do_auth']", + "__all__ = [] + ['do_auth']", + "__all__ = []\n__all__.append('do_auth')", + "__all__ = []\n__all__.extend(['do_auth'])", + "__all__ = []\n__all__ = ['do_auth']", +]) +def test_static_export_declarations_are_recognized(create_project, exports): + project_root = create_project( + "📂 features\n 📂 auth\n 📄 __init__.py\n" + " 📂 profile\n 📄 ui.py" + ) + (project_root / "src/features/auth/__init__.py").write_text(exports + "\n", encoding="utf-8") + (project_root / "src/features/profile/ui.py").write_text("from src.features.auth import do_auth\n", encoding="utf-8") + + assert check(load_config(str(project_root)), str(project_root)) == [] + + +@pytest.mark.parametrize("exports", [ + "__all__ = ['do_auth']\n__all__ = []", + "__all__ = ['do_auth', 1]", + "__all__ = ['do_auth']\n__all__ = dynamic_names", + "__all__ = ['do_auth']\n__all__.clear()", + "__all__ = ['do_auth']\nif condition:\n __all__ = []", + "__all__ = ['do_auth']\n__all__[0] = 'other'", + "__all__ = ['do_auth']\nif condition:\n __all__.clear()", +]) +def test_invalid_or_replaced_exports_do_not_authorize_names(create_project, exports): + project_root = create_project( + "📂 features\n 📂 auth\n 📄 __init__.py\n" + " 📂 profile\n 📄 ui.py" + ) + (project_root / "src/features/auth/__init__.py").write_text(exports + "\n", encoding="utf-8") + (project_root / "src/features/profile/ui.py").write_text("from src.features.auth import do_auth\n", encoding="utf-8") + + assert len(check(load_config(str(project_root)), str(project_root))) == 1 + + +@pytest.mark.parametrize("exports, expected", [("__all__ = ['do_auth']", 0), ("", 1)]) +def test_wildcard_import_requires_explicit_exports(create_project, exports, expected): + project_root = create_project( + "📂 features\n 📂 auth\n 📄 __init__.py\n" + " 📂 profile\n 📄 ui.py" + ) + (project_root / "src/features/auth/__init__.py").write_text(exports + "\n", encoding="utf-8") + (project_root / "src/features/profile/ui.py").write_text("from src.features.auth import *\n", encoding="utf-8") + + assert len(check(load_config(str(project_root)), str(project_root))) == expected + + +def test_nested_base_path_and_relative_cross_slice_import(tmp_path): + from pytest_fsd.config import FsdConfig + + base = tmp_path / "package/src" + (base / "features/auth").mkdir(parents=True) + (base / "features/profile").mkdir(parents=True) + (base / "features/auth/__init__.py").write_text("__all__ = ['do_auth']\n", encoding="utf-8") + (base / "features/auth/model.py").touch() + (base / "features/profile/ui.py").write_text( + "from package.src.features.auth.model import do_auth\n" + "from ....src.features.auth.model import do_auth\n", encoding="utf-8" + ) + + violations = check(FsdConfig(base_path="package/src"), str(tmp_path)) + + assert len(violations) == 2 + assert [violation.line_number for violation in violations] == [1, 2] + + +def test_exported_module_is_a_valid_public_api_name(create_project): + project_root = create_project( + "📂 features\n 📂 auth\n 📄 __init__.py\n 📄 model.py\n" + " 📂 profile\n 📄 ui.py" + ) + (project_root / "src/features/auth/__init__.py").write_text("__all__ = ['model']\n", encoding="utf-8") + (project_root / "src/features/profile/ui.py").write_text("from src.features.auth import model\n", encoding="utf-8") + + assert check(load_config(str(project_root)), str(project_root)) == [] diff --git a/tests/rules/test_no_reserved_folder_names.py b/tests/rules/test_no_reserved_folder_names.py index a8f9051..5810d38 100644 --- a/tests/rules/test_no_reserved_folder_names.py +++ b/tests/rules/test_no_reserved_folder_names.py @@ -40,3 +40,18 @@ def test_no_reserved_folder_names_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "api" in violations[0].message + + +def test_reserved_names_are_checked_inside_custom_segments(create_project): + project_root = create_project( + "📂 shared\n 📂 i18n\n 📂 translations\n 📂 model\n" + "📂 features\n 📂 auth\n 📂 routing\n 📂 api" + ) + + violations = check(load_config(str(project_root)), str(project_root)) + + assert {v.file_path for v in violations} == { + str(project_root / "src/shared/i18n/translations/model"), + str(project_root / "src/features/auth/routing/api"), + } + assert all(v.rule == RULE_NAME for v in violations) diff --git a/tests/rules/test_no_segmentless_slices.py b/tests/rules/test_no_segmentless_slices.py index b70dadd..9cf798f 100644 --- a/tests/rules/test_no_segmentless_slices.py +++ b/tests/rules/test_no_segmentless_slices.py @@ -41,3 +41,19 @@ def test_no_segmentless_slices_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "auth" in violations[0].message + + +def test_no_segmentless_slices_checks_entry_types(create_project): + project_root = create_project( + "📂 features\n 📂 bare_file\n 📄 model\n" + " 📂 suffixed_directory\n 📂 model.py\n" + " 📂 file_segment\n 📄 model.py\n" + " 📂 directory_segment\n 📂 model" + ) + + violations = check(load_config(str(project_root)), str(project_root)) + + assert {v.file_path for v in violations} == { + str(project_root / "src/features/bare_file"), + str(project_root / "src/features/suffixed_directory"), + } diff --git a/tests/rules/test_no_ui_in_app.py b/tests/rules/test_no_ui_in_app.py index f0d969d..37b7395 100644 --- a/tests/rules/test_no_ui_in_app.py +++ b/tests/rules/test_no_ui_in_app.py @@ -78,3 +78,13 @@ def test_no_ui_in_app_rejects_ui_segment(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "app/ui" in violations[0].message + + +def test_relative_module_named_like_gui_framework_is_allowed(create_project): + project_root = create_project("📂 app\n 📄 main.py") + (project_root / "src/app/main.py").write_text( + "from .tkinter import settings\nfrom ..PyQt6 import settings\n", + encoding="utf-8", + ) + + assert check(load_config(str(project_root)), str(project_root)) == [] diff --git a/tests/rules/test_no_wildcard_exports.py b/tests/rules/test_no_wildcard_exports.py index 84da17b..a9b42dd 100644 --- a/tests/rules/test_no_wildcard_exports.py +++ b/tests/rules/test_no_wildcard_exports.py @@ -146,7 +146,7 @@ def test_unreadable_public_api_is_reported(create_project, monkeypatch): def refuse_read(*args, **kwargs): raise PermissionError("read denied") - monkeypatch.setattr("builtins.open", refuse_read) + monkeypatch.setattr("tokenize.open", refuse_read) violations = check(FsdConfig(), str(project_root)) assert len(violations) == 1 diff --git a/tests/rules/test_public_api.py b/tests/rules/test_public_api.py index 1cfe6e5..3c2d135 100644 --- a/tests/rules/test_public_api.py +++ b/tests/rules/test_public_api.py @@ -85,3 +85,20 @@ def test_public_api_shared_ui_lib_exceptions(create_project): # Expecting 1 violation: shared/ui/complex_widget is missing __init__.py assert len(violations) == 1 assert "Subfolder 'complex_widget' in 'shared/ui' is missing __init__.py" in violations[0].message + + +def test_public_api_requires_a_file_not_a_directory(create_project): + project_root = create_project( + "📂 features\n 📂 auth\n 📂 __init__.py\n" + "📂 shared\n 📂 api\n 📂 __init__.py\n" + " 📂 ui\n 📂 button\n 📂 __init__.py\n" + " 📂 lib\n 📂 dates\n 📂 __init__.py" + ) + + violations = check(load_config(str(project_root)), str(project_root)) + + assert {v.file_path for v in violations} == { + str(project_root / "src" / path) + for path in ["features/auth", "shared/api", "shared/ui/button", "shared/lib/dates"] + } + assert all(v.rule == RULE_NAME for v in violations) diff --git a/tests/test_import_validation.py b/tests/test_import_validation.py new file mode 100644 index 0000000..56f6952 --- /dev/null +++ b/tests/test_import_validation.py @@ -0,0 +1,131 @@ +"""Architecture boundaries must work without pytest-archon's runtime state.""" + +import os +from pathlib import Path +import subprocess +import sys + +import pytest + +from pytest_fsd import validate_fsd_architecture +from pytest_fsd.config import FsdConfig +from pytest_fsd.rules import forbidden_imports, no_cross_imports + + +def write_project(root, source, source_path="features/auth/api/router.py", base="src"): + files = { + "features/auth/__init__.py": "__all__ = []\n", + "features/tables/__init__.py": "from .model.value import value\n__all__ = ['value']\n", + "features/tables/model/value.py": "value = 1\n", + "shared/lib/__init__.py": "value = 1\n", + source_path: source, + } + for name, body in files.items(): + path = root / base / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(body, encoding="utf-8") + (root / "pyproject.toml").write_text( + '[tool.pytest_fsd]\nbase_path = "' + base + '"\n' + 'layers = ["app", "features", "entities", "shared"]\n', encoding="utf-8" + ) + return FsdConfig(base_path=base, layers=["app", "features", "entities", "shared"]) + + +@pytest.mark.parametrize("source", [ + "from src.features.tables import value\n", + "import src.features.tables as tables\n", + "from src.features import tables\n", + "from features.tables import value\n", + "from features import tables\n", + "from ...tables import value\n", + "from ... import tables\n", + "from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from src.features.tables import value\n", + "def operation():\n from src.features.tables import value\n", + "try:\n from src.features.tables import value\nexcept ImportError:\n pass\n", +]) +@pytest.mark.parametrize("path", ["features/auth/api/router.py", "features/auth/api/__init__.py"]) +def test_cross_slice_import_forms(tmp_path, source, path): + config = write_project(tmp_path, source, path) + violations = no_cross_imports.check(config, str(tmp_path)) + assert violations and all(v.rule == "no-cross-imports" for v in violations) + assert all(v.line_number and v.column_number for v in violations) + + +@pytest.mark.parametrize("source,path", [ + ("from src.features.tables import value\n", "shared/lib/source.py"), + ("from src.features.tables import value\n", "shared/__init__.py"), + ("import src.features\n", "shared/__init__.py"), + ("from src import features\n", "shared/__init__.py"), + ("from features import tables\n", "shared/__init__.py"), + ("from ...features.tables import value\n", "shared/lib/source.py"), + ("from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from src.features.tables import value\n", "shared/lib/source.py"), +]) +def test_upward_import_forms(tmp_path, source, path): + config = write_project(tmp_path, source, path) + violations = forbidden_imports.check(config, str(tmp_path)) + assert violations and all(v.rule == "forbidden-imports" for v in violations) + + +@pytest.mark.parametrize("base,prefix", [("backend/src", "backend.src"), ("backend/src", "src"), ("backend/src", "")]) +def test_nested_source_root_and_foreign_cwd(tmp_path, monkeypatch, base, prefix): + target = (prefix + "." if prefix else "") + "features.tables" + config = write_project(tmp_path, "from " + target + " import value\n", base=base) + monkeypatch.chdir(tmp_path.parent) + assert no_cross_imports.check(config, str(tmp_path)) + + +@pytest.mark.parametrize("source,path", [ + ("from src.shared.lib import value\n", "features/auth/api/router.py"), + ("from ..model import value\n", "features/auth/api/router.py"), + ("from src.app.config import value\n", "app/api/router.py"), + ("from src.shared.config import value\n", "shared/lib/source.py"), + ("import requests\n", "features/auth/api/router.py"), + ("import other.features.tables\n", "features/auth/api/router.py"), +]) +def test_permitted_import_controls(tmp_path, source, path): + config = write_project(tmp_path, source, path) + assert no_cross_imports.check(config, str(tmp_path)) == [] + assert forbidden_imports.check(config, str(tmp_path)) == [] + + +def test_validator_does_not_execute_sources_or_cache_projects(tmp_path): + config = write_project(tmp_path, "raise RuntimeError('must not run')\nfrom src.features.tables import value\n") + for _ in range(2): + with pytest.raises(AssertionError, match="no-cross-imports"): + validate_fsd_architecture(str(tmp_path)) + (tmp_path / "src/features/auth/api/router.py").write_text("", encoding="utf-8") + assert no_cross_imports.check(config, str(tmp_path)) == [] + + +@pytest.mark.parametrize("source,path,rule", [ + ("from src.features.tables import value\n", "features/auth/api/router.py", "no-cross-imports"), + ("from src.features.tables import value\n", "shared/lib/source.py", "forbidden-imports"), + ("from src.shared.lib import value\n", "features/auth/api/router.py", None), +]) +@pytest.mark.parametrize("runner", ["python", "pytest"]) +def test_public_facade_exit_status(tmp_path, source, path, rule, runner): + write_project(tmp_path, source, path) + env = dict(os.environ, PYTHONPATH=str(Path(__file__).resolve().parents[1] / "src"), + PYTEST_DISABLE_PLUGIN_AUTOLOAD="1", PYTEST_ADDOPTS="") + code = "from pytest_fsd import validate_fsd_architecture; validate_fsd_architecture(" + repr(str(tmp_path)) + ")" + if runner == "python": + command = [sys.executable, "-c", code] + else: + test_file = tmp_path / "test_architecture.py" + test_file.write_text("def test_architecture():\n " + code + "\n", encoding="utf-8") + command = [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", str(test_file)] + result = subprocess.run(command, cwd=tmp_path.parent, env=env, capture_output=True, text=True, timeout=30) + if rule: + assert result.returncode == 1, result.stdout + result.stderr + assert "[" + rule + "]" in result.stdout + result.stderr + if runner == "pytest": + assert "1 failed" in result.stdout + else: + assert result.returncode == 0, result.stdout + result.stderr + if runner == "pytest": + assert "1 passed" in result.stdout + + +def test_relative_import_can_leave_and_reenter_source_root(tmp_path): + config = write_project(tmp_path, "from .....src.features.tables import value\n", base="backend/src") + assert no_cross_imports.check(config, str(tmp_path)) diff --git a/tests/test_validation_inputs.py b/tests/test_validation_inputs.py new file mode 100644 index 0000000..35976cf --- /dev/null +++ b/tests/test_validation_inputs.py @@ -0,0 +1,73 @@ +"""Invalid input must not turn architecture checks into a silent success.""" + +import pytest + +from pytest_fsd import validate_fsd_architecture +from pytest_fsd.config import load_config +from pytest_fsd.rules import forbidden_imports + + +@pytest.mark.parametrize("setting", [ + 'extra_rules = ["no-wildcard-export"]', + 'layers = "features"', + 'layers = []', + 'layers = ["features", "features"]', + 'layers = ["../features"]', + 'extra_rules = "no-file-segments"', + 'ignore_paths = [42]', + 'base_path = ""', + 'base_path = 12', + 'extra_rule = ["no-file-segments"]', +]) +def test_invalid_configuration_fails(tmp_path, setting): + (tmp_path / "pyproject.toml").write_text('[tool.pytest_fsd]\n' + setting, encoding="utf-8") + with pytest.raises(ValueError, match="pytest_fsd"): + validate_fsd_architecture(str(tmp_path)) + + +def test_missing_source_directory_fails(tmp_path): + with pytest.raises(AssertionError, match="Configured source directory does not exist"): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize("content", [b"from src.features import (\n", b"\xff\n", b"# coding: unknown-encoding\n"]) +def test_invalid_source_fails(tmp_path, content): + file = tmp_path / "src/shared/lib/source.py" + file.parent.mkdir(parents=True) + file.write_bytes(content) + with pytest.raises(AssertionError, match="python-source"): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize("encoding", ["latin-1", "utf-8-sig"]) +def test_python_encoding_declaration_preserves_import_checks(tmp_path, encoding): + file = tmp_path / "src/shared/lib/source.py" + file.parent.mkdir(parents=True) + source = "# coding: " + ("latin-1" if encoding == "latin-1" else "utf-8") + "\n# café\nfrom src.features import tables\n" + file.write_bytes(source.encode(encoding)) + (tmp_path / "src/features/tables/model").mkdir(parents=True) + (tmp_path / "src/features/tables/__init__.py").write_text("__all__ = []\n", encoding="utf-8") + violations = forbidden_imports.check(load_config(str(tmp_path)), str(tmp_path)) + assert violations and all(v.rule == "forbidden-imports" for v in violations) + with pytest.raises(AssertionError, match="forbidden-imports"): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize("kind", ["layer", "directory", "file"]) +def test_symlinks_cannot_hide_import_violations(tmp_path, kind): + real = tmp_path / "real" + real.mkdir() + source = real / "source.py" + source.write_text("from src.features import tables\n", encoding="utf-8") + base = tmp_path / "src/shared" + if kind == "layer": + base.parent.mkdir() + base.symlink_to(real, target_is_directory=True) + elif kind == "directory": + base.mkdir(parents=True) + (base / "lib").symlink_to(real, target_is_directory=True) + else: + (base / "lib").mkdir(parents=True) + (base / "lib/source.py").symlink_to(source) + with pytest.raises(AssertionError, match="python-source"): + validate_fsd_architecture(str(tmp_path)) diff --git a/uv.lock b/uv.lock index c7491ec..3468e0f 100644 --- a/uv.lock +++ b/uv.lock @@ -175,26 +175,11 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] -[[package]] -name = "pytest-archon" -version = "0.0.7" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "pytest", version = "8.3.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" }, - { name = "pytest", version = "8.4.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.9.*'" }, - { name = "pytest", version = "9.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/42/da/8132aa99cee223c7c5b330ffb4bd8094343239774f917e71a21f74d52009/pytest_archon-0.0.7.tar.gz", hash = "sha256:6a1e814c84adbea4afc188369733ec898f2525cc401f3ca965498f8b3ee454d5", size = 48359, upload-time = "2025-09-19T20:56:24.784Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/98/81/a46c239c77d4ec4e3450d463517ff63f10c22962c037ca2b4125394cf400/pytest_archon-0.0.7-py3-none-any.whl", hash = "sha256:5aaad17cff853d058ca686dd1da425ce884daf33ae9668011323173631dc4e94", size = 44868, upload-time = "2025-09-19T20:56:23.16Z" }, -] - [[package]] name = "pytest-fsd" -version = "0.4.0" +version = "0.5.0" source = { editable = "." } dependencies = [ - { name = "pytest-archon" }, { name = "tomli", marker = "python_full_version < '3.11'" }, ] @@ -206,10 +191,7 @@ dev = [ ] [package.metadata] -requires-dist = [ - { name = "pytest-archon", specifier = ">=0.0.7" }, - { name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.1" }, -] +requires-dist = [{ name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0.1" }] [package.metadata.requires-dev] dev = [