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
41 changes: 39 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,46 @@ jobs:
run: uv python install ${{ matrix.python-version }}

- name: Install dependencies
run: uv sync
run: uv sync --locked --python ${{ matrix.python-version }}

- name: Verify Python ${{ matrix.python-version }}
run: uv run --locked --python ${{ matrix.python-version }} python -c "import sys; print(sys.version); assert '.'.join(map(str, sys.version_info[:2])) == '${{ matrix.python-version }}'"

- name: Run tests
run: uv run pytest tests/ -v --tb=short
run: uv run --locked --python ${{ matrix.python-version }} pytest tests/ -v --tb=short
env:
PYTHONPATH: src

- name: Build wheel and source distribution
run: uv build --python ${{ matrix.python-version }} --out-dir "$RUNNER_TEMP/dist"

- name: Validate installed wheel
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"))')
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
from importlib.metadata import version
from pathlib import Path

from pytest_fsd import validate_fsd_architecture

assert version("pytest-fsd") == os.environ["PYTEST_FSD_EXPECTED_VERSION"]
with tempfile.TemporaryDirectory() as root:
project = Path(root)
api = project / "src" / "shared" / "lib" / "__init__.py"
api.parent.mkdir(parents=True)
api.write_text("from .unavailable_module import *\n", encoding="utf-8")
(project / "pyproject.toml").write_text(
'[tool.pytest_fsd]\nextra_rules = ["no-wildcard-exports"]\n',
encoding="utf-8",
)
try:
validate_fsd_architecture(root)
except AssertionError as error:
assert "[no-wildcard-exports]" in str(error)
assert "__init__.py:1:1 ->" in str(error)
else:
raise AssertionError("Installed wheel did not run no-wildcard-exports")
PY
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Changelog

## 0.4.0

- Adapt the applicable changes from Steiger 0.7.0 / FSD plugin 0.8.0, published September 25, 2026.
- Add the opt-in `no-wildcard-exports` rule for `from module import *` in Python public APIs (`__init__.py`). It is disabled by default, matching upstream.
- Include character columns in AST import diagnostics and retain start/end positions on violations. Existing violations without column information keep their previous format.
- Select and verify the actual Python interpreter in each CI matrix job.
- Update development pytest to 9.1.1 on Python 3.10+, keeping pytest 8 on Python 3.8/3.9; refresh the dependency lock and build backend.

Steiger's language server, file watching, Node.js requirements, and JavaScript dependency-resolution cache do not apply to this pytest-based Python package. This release does not add those features.

Upstream references: [FSD plugin changelog](https://github.com/feature-sliced/steiger/blob/master/packages/steiger-plugin-fsd/CHANGELOG.md), [Steiger changelog](https://github.com/feature-sliced/steiger/blob/master/packages/steiger/CHANGELOG.md).
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

Validate [Feature-Sliced Design (FSD)](https://feature-sliced.design/) architecture in a Python project using pytest. The rules are adapted from the [Steiger FSD plugin](https://github.com/feature-sliced/steiger), with Python-specific checks where appropriate. This is an independent Python package, not an official Steiger port.

The applicable upstream changes are tracked through Steiger 0.7.0 / FSD plugin 0.8.0. See the [changelog](CHANGELOG.md) for Python adaptations.

## Install

```bash
Expand Down Expand Up @@ -61,10 +63,13 @@ extra_rules = [
"shared-lib-grouping", # More than 15 loose Python files in shared/lib
"no-file-segments", # Segments must be directories
"no-reserved-folder-names", # No nested segment names such as model/model
"no-wildcard-exports", # No `from module import *` in __init__.py
]
```

`no-file-segments` is a Python package option; it is not registered as a rule in Steiger FSD plugin 0.7.0. `no-cross-imports` is enabled here for compatibility, whereas the upstream plugin does not enable it by default. These choices are intentionally different from Steiger.
`no-wildcard-exports` was added in Steiger FSD plugin 0.8.0 and is disabled by default in both packages. It checks `__init__.py` files on every configured layer, including nested packages. Explicit module imports such as `from . import model as model` remain valid in Python. AST import diagnostics include line and character column numbers.

`no-file-segments` is a Python package option; it is not registered as a rule in Steiger FSD plugin 0.8.0. `no-cross-imports` is enabled here for compatibility, whereas the upstream plugin does not enable it by default. These choices are intentionally different from Steiger.

See the [rule documentation](src/pytest_fsd/rules/) for examples and details.

Expand Down
7 changes: 6 additions & 1 deletion README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

Проверка архитектуры Python-проекта по [Feature-Sliced Design (FSD)](https://feature-sliced.design/) через pytest. Правила адаптированы из [FSD-плагина Steiger](https://github.com/feature-sliced/steiger); там, где необходимо, добавлены проверки для Python. Это самостоятельный пакет, а не официальный порт Steiger.

Учтены применимые изменения до Steiger 0.7.0 / FSD-плагина 0.8.0. Адаптации для Python описаны в [журнале изменений](CHANGELOG.md).

## Установка

```bash
Expand Down Expand Up @@ -61,10 +63,13 @@ extra_rules = [
"shared-lib-grouping", # Более 15 отдельных Python-файлов в shared/lib
"no-file-segments", # Сегменты должны быть каталогами
"no-reserved-folder-names", # Без вложенных имён сегментов вроде model/model
"no-wildcard-exports", # Без `from module import *` в __init__.py
]
```

`no-file-segments` — опция этого Python-пакета: в реестре правил FSD-плагина Steiger 0.7.0 она отсутствует. `no-cross-imports` здесь по умолчанию включено для совместимости, а в Steiger по умолчанию отключено. Это осознанные различия.
`no-wildcard-exports` появилось в FSD-плагине Steiger 0.8.0 и по умолчанию отключено в обоих пакетах. Проверяются файлы `__init__.py` на всех указанных слоях, включая вложенные пакеты. Явные импорты модулей вроде `from . import model as model` допустимы в Python. Диагностика AST-проверок импортов теперь включает номер строки и позицию символа.

`no-file-segments` — опция этого Python-пакета: в реестре правил FSD-плагина Steiger 0.8.0 она отсутствует. `no-cross-imports` здесь по умолчанию включено для совместимости, а в Steiger по умолчанию отключено. Это осознанные различия.

Примеры и подробности находятся в [документации правил](src/pytest_fsd/rules/).

Expand Down
14 changes: 11 additions & 3 deletions instructions/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,22 @@ Slices on the same layer must not communicate directly (except within `shared`).
A slice's internal folder structure is strictly private. Only the root `__init__.py` of the slice exposes the Public API.

1. Add `from .ui.button import Button` to the slice's `__init__.py`.
2. Update the consuming file to import via the Public API: `from src.features.auth import Button`.
2. Include `Button` in the slice's explicit `__all__` list.
3. Update the consuming file to import via the Public API: `from src.features.auth import Button`.

### 4. `Layer folder 'X' contains __init__.py` (AST)

**Trigger**: A layer folder (e.g., `src/features/__init__.py`) contains a Python file instead of just subdirectories.
**Resolution**:
In FSD, layer folders (`features`, `entities`, etc.) act strictly as grouping namespaces. They do not have their own Public API. Delete the `__init__.py` file from the layer folder root.

## Unimplemented Steiger Rules
### 5. `Wildcard re-export` (AST, opt-in)

Note that while this library is heavily inspired by `steiger`, it focuses on _hard dependency constraints_. Stylistic rules (like `inconsistent-naming`, `excessive-slicing`, or folder naming conventions) are left to established Python tools like standard `ruff` configurations.
**Trigger**: A public API (`__init__.py`) uses `from .model import *` while `no-wildcard-exports` is enabled in `extra_rules`.
**Resolution**: List the imported names explicitly, then expose them through `__all__`. Explicit imports of modules such as `from . import model as model` are allowed.

## Additional and Unimplemented Rules

The default checks include structure and naming constraints as well as import rules. `excessive-slicing`, `shared-lib-grouping`, `no-file-segments`, `no-reserved-folder-names`, and `no-wildcard-exports` are available through `extra_rules`.

Applicable upstream changes are tracked through Steiger 0.7.0 / FSD plugin 0.8.0. `inconsistent-naming`, `import-locality`, and `insignificant-slice` remain unimplemented. Ruff naming and import rules may cover related Python concerns, but they are not equivalent Steiger checks.
7 changes: 4 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "pytest-fsd"
version = "0.3.0"
version = "0.4.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 Down Expand Up @@ -36,12 +36,13 @@ Repository = "https://github.com/Horcag/pytest-fsd.git"

[dependency-groups]
dev = [
"pytest>=8.3.5,<9",
"pytest>=8.3.5,<9; python_version < '3.10'",
"pytest>=9.1.1,<10; python_version >= '3.10'",
]

[tool.pytest.ini_options]
pythonpath = ["src"]

[build-system]
requires = ["uv_build>=0.9.27,<0.10.0"]
requires = ["uv_build>=0.13.0,<0.14.0"]
build-backend = "uv_build"
2 changes: 2 additions & 0 deletions src/pytest_fsd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
excessive_slicing,
no_file_segments,
no_reserved_folder_names,
no_wildcard_exports,
shared_lib_grouping,
)

Expand All @@ -53,6 +54,7 @@
"shared-lib-grouping": shared_lib_grouping,
"no-file-segments": no_file_segments,
"no-reserved-folder-names": no_reserved_folder_names,
"no-wildcard-exports": no_wildcard_exports,
}


Expand Down
39 changes: 34 additions & 5 deletions src/pytest_fsd/_lib/ast_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,37 @@
"""Shared AST parsing utilities used by multiple rules."""

import ast
from typing import List, Tuple, Optional
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:
source = f.read()
return source, ast.parse(source, filename=filepath)
except (OSError, UnicodeError, SyntaxError, ValueError):
return None


def get_node_location(node: ast.AST, source: str) -> Dict[str, Optional[int]]:
"""Return one-based character positions with an exclusive end position."""
lines = source.split("\n")

def column(line: Optional[int], offset: Optional[int]) -> Optional[int]:
if line is None or offset is None:
return None
# AST columns count UTF-8 bytes; diagnostics count characters.
return len(lines[line - 1].encode("utf-8")[:offset].decode("utf-8")) + 1

line = getattr(node, "lineno", None)
end_line = getattr(node, "end_lineno", None)
return {
"line_number": line,
"column_number": column(line, getattr(node, "col_offset", None)),
"end_line_number": end_line,
"end_column_number": column(end_line, getattr(node, "end_col_offset", None)),
}


def get_imports_from_file(
Expand All @@ -16,11 +46,10 @@ def get_imports_from_file(
2 = parent directory (`from ..foo import bar` -> module='foo', level=2)
"""
imports = []
try:
with open(filepath, "r", encoding="utf-8") as f:
tree = ast.parse(f.read(), filename=filepath)
except Exception:
parsed = parse_python_file(filepath)
if parsed is None:
return []
_, tree = parsed

for node in ast.walk(tree):
if isinstance(node, ast.Import):
Expand Down
5 changes: 5 additions & 0 deletions src/pytest_fsd/_lib/violations.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ class Violation:
file_path: str
message: str
line_number: Optional[int] = None
column_number: Optional[int] = None
end_line_number: Optional[int] = None
end_column_number: Optional[int] = None

def format(self) -> str:
"""Format the violation as a human-readable string."""
location = self.file_path
if self.line_number is not None:
location += f":{self.line_number}"
if self.column_number is not None:
location += f":{self.column_number}"
return f" - [{self.rule}] {location} -> {self.message}"
1 change: 1 addition & 0 deletions src/pytest_fsd/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class FsdConfig:
"shared-lib-grouping",
"no-file-segments",
"no-reserved-folder-names",
"no-wildcard-exports",
}


Expand Down
25 changes: 18 additions & 7 deletions src/pytest_fsd/rules/no_public_api_sidestep/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
not through internal modules.
"""

import ast
import os
from typing import List

from ..._lib.ast_utils import get_exported_names, get_imports_from_file
from ..._lib.ast_utils import get_exported_names, get_node_location, parse_python_file
from ..._lib.fs_utils import get_sliced_layers
from ..._lib.violations import Violation
from ...config import FsdConfig
Expand Down Expand Up @@ -43,9 +44,19 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]:
parts[1] if len(parts) > 1 and current_layer in sliced_layers else None
)

imports = get_imports_from_file(file_path)

for lineno, module_path, level, imported_names in imports:
parsed = parse_python_file(file_path)
if parsed is None:
continue
source, tree = parsed
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.append((node, alias.name, 0, [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] # Убираем имя файла
Expand Down Expand Up @@ -112,7 +123,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]:
Violation(
rule=RULE_NAME,
file_path=file_path,
line_number=lineno,
**get_node_location(node, source),
message=f"Importing internal module '{module_path}' "
f"from slice '{target_layer}/{target_slice}'. "
f"Import from '{base_module}.{target_layer}.{target_slice}' instead.",
Expand All @@ -132,7 +143,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]:
Violation(
rule=RULE_NAME,
file_path=file_path,
line_number=lineno,
**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.",
)
Expand All @@ -144,7 +155,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]:
Violation(
rule=RULE_NAME,
file_path=file_path,
line_number=lineno,
**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.",
Expand Down
18 changes: 6 additions & 12 deletions src/pytest_fsd/rules/no_ui_in_app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import os
from typing import List

from ..._lib.ast_utils import get_node_location, parse_python_file
from ..._lib.fs_utils import get_layer_by_canonical_name
from ..._lib.violations import Violation
from ...config import FsdConfig
Expand Down Expand Up @@ -52,17 +53,10 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]:

file_path = os.path.join(root, file)

try:
with open(file_path, "r", encoding="utf-8") as f:
content = f.read()

# Blind Spot 7 Optimization: Skip AST parsing if no UI keywords are present
if not any(ui_lib in content for ui_lib in FORBIDDEN_UI_MODULES):
continue

tree = ast.parse(content, filename=file_path)
except Exception:
parsed = parse_python_file(file_path)
if parsed is None:
continue
source, tree = parsed

for node in ast.walk(tree):
if isinstance(node, ast.Import):
Expand All @@ -73,7 +67,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]:
Violation(
rule=RULE_NAME,
file_path=file_path,
line_number=node.lineno,
**get_node_location(node, source),
message=f"Layer 'app' should not import UI framework "
f"'{base_import}'. Extract UI to 'windows', 'pages' or 'widgets'.",
)
Expand All @@ -86,7 +80,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]:
Violation(
rule=RULE_NAME,
file_path=file_path,
line_number=node.lineno,
**get_node_location(node, source),
message=f"Layer 'app' should not import UI framework "
f"'{base_import}'. Extract UI to 'windows', 'pages' or 'widgets'.",
)
Expand Down
Loading
Loading