Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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.
Expand Down
10 changes: 9 additions & 1 deletion README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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`.
Expand Down
11 changes: 4 additions & 7 deletions instructions/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,15 @@ 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]`.

## Troubleshooting Architectural Violations

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**:
Expand All @@ -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`).
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -25,7 +25,6 @@ classifiers = [
"Topic :: Software Development :: Testing",
]
dependencies = [
"pytest-archon>=0.0.7",
"tomli>=2.0.1; python_version < '3.11'",
]

Expand Down
3 changes: 2 additions & 1 deletion src/pytest_fsd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
81 changes: 65 additions & 16 deletions src/pytest_fsd/_lib/ast_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Loading
Loading