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 @@ -46,6 +46,7 @@ jobs:
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"
uv run --isolated --no-project --python ${{ matrix.python-version }} --with "${wheels[0]}" python -I tests/rule_contracts.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
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changelog

## 0.7.0

- Audit every implemented rule: 12 core rules, five opt-in rules, and both source/dynamic-import guards. Add portable positive/negative witnesses, opt-in controls and 36 no-op/dispatch/guard mutation controls; run all 19 installed-package contracts in every Python CI job.
- Check legitimate underscore-prefixed packages consistently; exclude dot-hidden metadata directories and `__pycache__` from structural, import and naming scans. Fix slice-count, collision and recursive naming errors caused by inconsistent directory filtering.
- Fix file/directory confusion in `no-file-segments` and `no-layer-public-api`.
- Enforce Shared public APIs in `no-public-api-sidestep`: segment APIs and individual shared/ui and shared/lib package APIs. Preserve own-boundary imports and standalone UI/library module entrypoints.
- Treat escaped/mutated `__all__` values as unknown instead of trusting stale exports. Deduplicate identical sibling-slice diagnostics and correct source-root import recommendations.
- Report unreadable source-root scans and parser recursion errors explicitly; stop structural validation on an uninspectable tree. Validate a malformed top-level TOML tool value.
- Document every audited rule and its witnesses in `docs/RULE-AUDIT.md`. Correct reference-only rule pages so they do not imply that missing checks or Ruff alternatives are active FSD rules.

## 0.6.0

- Analyze `importlib.import_module`, `importlib.__import__`, and built-in `__import__` using the same layer, slice, public API, and app/UI rules as ordinary imports.
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,13 @@ extra_rules = [

`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.
See the [rule documentation](src/pytest_fsd/rules/) for examples and details. The [complete rule audit](docs/RULE-AUDIT.md) maps all 17 implemented rules and both input guards to positive/negative, activation, threshold and installed-package checks.

## Scope and limitations

- 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. Programmatic imports through `importlib.import_module`, `importlib.__import__`, and built-in `__import__` are analyzed too. Loader aliases, literal names, constant bindings, concatenation, f-strings, joins, relative packages and fromlists are supported. Literal `exec`/`eval` strings and literal `compile` inputs are inspected recursively, with bounded expansion. Unresolved recognized loader calls or executed code fail with `[dynamic-imports]`; they do not silently pass. Arbitrary user-defined import hooks and runtime code are not executed.
- Shared APIs are enforced too: other segments use their root `__init__.py`; `shared/ui` and `shared/lib` expose individual component/library package APIs or standalone Python modules. Imports within the same boundary remain valid.
- Dot-hidden metadata directories and `__pycache__` are excluded from scans. Underscore-prefixed packages such as `_private` are ordinary code and are checked.
- `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`.
Expand Down
4 changes: 4 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,7 @@ extra_rules = [
MIT. См. [LICENSE](LICENSE).

Вызов `importlib.import_module(f"src.{layer}.tables")` проверяется, если значение `layer` известно. Если имя приходит только во время исполнения, проверка выдаёт `[dynamic-imports]`: замените такой вызов явным выбором между известными импортами. Чекер проверяет архитектуру и не является интерпретатором произвольного Python-кода или средством изоляции исполнения.

Полная [матрица аудита правил](docs/RULE-AUDIT.md) связывает все 17 реализованных правил и две входные проверки с допустимыми и запрещёнными примерами, включением правил и проверкой установленного пакета.

Публичные API Shared тоже проверяются: для обычных сегментов это `__init__.py` сегмента, для `shared/ui` и `shared/lib` — API отдельных пакетов компонентов/библиотек либо самостоятельные Python-модули. Внутри одной границы импорты свободны. Каталоги служебных данных с точкой в начале имени и `__pycache__` исключаются из сканирования; пакеты `_private` и `__private` проверяются как обычный код.
96 changes: 96 additions & 0 deletions docs/RULE-AUDIT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Complete rule audit — 0.7.0

Audit date: 2026-10-26. Scope: every implemented rule, configuration dispatch,
source inspection and dynamic-import guards. This is the Python package's
contract, including its documented differences from Steiger.

## Evidence that checks actually run

`tests/rule_contracts.py` contains an explicit inventory of all 12 core rules,
five opt-in rules and two input guards. Each has a clean project and a project
that violates only that named check. Both the direct checker and the public
`validate_fsd_architecture` facade must produce the expected result. Every
opt-in rule is also tested disabled. Inventory drift fails a test.

`tests/test_rule_contracts.py` also substitutes a no-op for each of the 17 rule
implementations, disconnects each of the 12 core and five extra dispatches,
and disables each of the two input guards. All 36 mutations must be detected
by the witnesses. An unrelated failure cannot satisfy a witness: diagnostics
must identify the intended rule and no other audited check.

CI builds a wheel and source distribution on Python 3.8–3.14. It runs
`python -I tests/rule_contracts.py VERSION` against the installed wheel outside
the source import path. All 19 named contracts must execute; the same portable
matrix is used for post-publication acceptance.

## Validation snapshot

The release audit contains 669 pytest cases on Python 3.11 and newer, including
36 mutation controls. Three language-version-specific cases are skipped on
Python 3.8/3.9 and one on Python 3.10. The installed-package matrix executes all
19 named contracts on every supported interpreter; none of those contracts is
skipped. Static validation includes Python 3.8 grammar, Ruff's error/undefined-
name checks and whitespace validation.

## Rule inventory and adversarial cases

| Check | Scope and audit cases | Focused regressions |
|---|---|---|
| `forbidden-imports` | Layer ordering, package and module targets, absolute/relative/dynamic imports, prefixed layers, nested roots, permitted downward imports | `test_import_validation.py`, `test_dynamic_imports.py`, `test_import_rule_audit.py` |
| `no-cross-imports` | Public-package and internal sibling imports, every sliced layer, own-slice and App/Shared controls; one diagnostic per sibling/location | `rules/test_no_cross_imports.py`, import suites |
| `no-public-api-sidestep` | Slice and Shared segment/library/component boundaries, explicit exports, same-boundary controls, standalone library/UI modules, relative and dynamic paths, source-root recommendations | `rules/test_no_public_api_sidestep.py`, `test_import_rule_audit.py` |
| `no-layer-public-api` | Sliced-layer API files, App/Shared exemption, directory named `__init__.py`, custom/prefixed layers and source roots | `rules/test_no_layer_public_api.py` |
| `no-ui-in-app` | App/UI folder and GUI framework imports, relative lookalikes, aliases/dynamic imports, non-App controls | `rules/test_no_ui_in_app.py`, dynamic/import audit suites |
| `repetitive-naming` | Exact slice name and underscore-prefix filename matches, nonmatching names, recursive metadata pruning and private packages | `rules/test_repetitive_naming.py` |
| `no-segmentless-slices` | All five standard segments as folders or files; nested-only, missing and fake segment types; custom roots/layers and private packages | `rules/test_no_segmentless_slices.py` |
| `segments-by-purpose` | All 50 banned names as directories and Python files, permitted purpose names, depth and App/Shared scope | `rules/test_segments_by_purpose.py` |
| `ambiguous-slice-names` | Collisions with Shared segment and immediate child names, deeper/nonmatching controls, metadata and private packages | `rules/test_ambiguous_slice_names.py` |
| `no-segments-on-sliced-layers` | Every direct standard segment folder, valid nested segments, App/Shared exemption, custom/prefixed layers and roots | `rules/test_no_segments_on_sliced_layers.py` |
| `public-api` | Missing and fake API files; private slices and Shared packages; intentional Shared/UI/lib root exception and immediate child APIs | `rules/test_public_api.py` |
| `typo-in-layer-name` | Unknown and configured layers, explicit top-level ignores, metadata exclusion and legitimate underscore directories | `rules/test_typo_in_layer_name.py` |
| `excessive-slicing` (opt-in) | 19/20/21 real slices, files and metadata do not count, private slices count, App/Shared exemption | `rules/test_excessive_slicing.py` |
| `shared-lib-grouping` (opt-in) | 14/15/16 loose Python files; APIs, subdirectories and non-Python files do not count; private Python modules count | `rules/test_shared_lib_grouping.py` |
| `no-file-segments` (opt-in) | Direct Python files in slices and App/Shared; real directories ending `.py` are not file segments; private packages | `rules/test_no_file_segments.py` |
| `no-reserved-folder-names` (opt-in) | All reserved names nested inside standard/custom segments, recursion and metadata/private-package behavior, App exemption | `rules/test_no_reserved_folder_names.py` |
| `no-wildcard-exports` (opt-in) | Public API wildcard syntax, nested APIs, dynamic fromlists/exec, named-import and internal-file controls; encoding/error locations | `rules/test_no_wildcard_exports.py`, dynamic/import audit suites |
| `python-source` guard | Missing/unreadable roots, invalid syntax/encoding, parser recursion, symlinks, layer file traps and metadata exclusions | `test_validation_inputs.py`, `test_audit_guards.py` |
| `dynamic-imports` guard | Unknown targets/fromlists/packages/code, escaped loaders, scope/branch handling, recursive expansion limits and no source execution | `test_dynamic_imports.py`, `test_audit_guards.py` |

Test paths in this table are relative to `tests/`. All rules additionally have
portable positive/negative facade and installed-wheel witnesses.

## Defects corrected

- Broad underscore exclusions let real `_private`/`__private` packages escape
structural and naming checks. Other traversals counted hidden/cache folders
as slices, collisions or recursively inspected source. All directory scans
now share the same metadata policy.
- `no-file-segments` treated directories ending `.py` as files;
`no-layer-public-api` treated a directory named `__init__.py` as an API file.
- Public API sidestep detection excluded every Shared target and inspected
unconfigured source directories. Shared boundary checks now match the API
presence rule; off-scope and metadata sources are excluded consistently.
- Mutable export-list aliases, opaque calls and called local mutators could
leave stale `__all__` values trusted. Such exports are now unknown until a
fresh static declaration restores knowledge.
- From-import package/child expansion emitted identical sibling diagnostics.
Sibling violations are deduplicated without losing different siblings.
- Unreadable root enumeration, malformed `[tool]` values and parser recursion
did not have consistent explicit validation errors. Reserved `__pycache__` cannot be configured as a layer that normal scans would skip.

Focused regressions were observed failing before their fixes. Threshold rules
and other paths that already met their contract were retained and given
additional positive/negative coverage.

## Reference pages are not registered checks

`inconsistent-naming`, `import-locality`, `insignificant-slice`, and
`no-processes` are documentation-only pages, not executable rule modules.
Attempting to enable any of them as an extra rule raises `ValueError`; they
cannot silently appear enabled. Ruff naming/import restrictions do not provide
the same FSD pluralization or slice-locality semantics. An unlisted `processes`
directory is caught by the unknown-layer rule unless explicitly ignored.

The audit does not turn semantic recommendations (for example, deciding whether
code is business logic) into implemented checks. The library inspects configured
Python architecture; it does not execute arbitrary Python or user import hooks.
4 changes: 4 additions & 0 deletions instructions/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,7 @@ In FSD, layer folders (`features`, `entities`, etc.) act strictly as grouping na
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.

## Complete rule verification

See `docs/RULE-AUDIT.md` for all 17 executable rules and the two input guards. Tests must check both accepted and rejected projects and confirm the named facade diagnostic. `tests/rule_contracts.py` runs the same 19 contracts against an installed package; CI also detects 36 no-op or dispatch mutations. Dot-hidden directories and `__pycache__` are metadata; underscore-prefixed packages remain checked. Shared imports must use segment APIs or individual shared/ui and shared/lib package APIs; imports inside the same boundary and standalone library/UI modules remain valid.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "pytest-fsd"
version = "0.6.0"
version = "0.7.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
5 changes: 5 additions & 0 deletions src/pytest_fsd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ def validate_fsd_architecture(project_root: str = ".") -> None:
"""
config = load_config(project_root)
all_violations: List[Violation] = check_sources(config, project_root)
if any(violation.rule == "python-source" for violation in all_violations):
# Structural rules cannot inspect an unreadable or invalid tree reliably.
raise AssertionError("FSD Architecture Validation failed:\n" + "\n".join(
violation.format() for violation in all_violations
))

# Запускаем базовые правила
for rule_module in CORE_RULES:
Expand Down
25 changes: 23 additions & 2 deletions src/pytest_fsd/_lib/ast_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def parse_python_file(filepath: str) -> Optional[Tuple[str, ast.Module]]:
with tokenize.open(filepath) as f:
source = f.read()
return source, ast.parse(source, filename=filepath)
except (OSError, UnicodeError, SyntaxError, ValueError, LookupError):
except (OSError, UnicodeError, SyntaxError, ValueError, LookupError, RecursionError):
return None


Expand Down Expand Up @@ -85,16 +85,37 @@ def names(value: ast.AST) -> Optional[List[str]]:
return None

exported = None
# A called local function can expose or change the export list indirectly.
mutators = {
definition.name for definition in tree.body
if isinstance(definition, (ast.FunctionDef, ast.AsyncFunctionDef))
and any(isinstance(child, ast.Name) and child.id == "__all__"
for child in ast.walk(definition))
}
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.Assign, ast.AnnAssign, ast.NamedExpr)):
value = descendant.value
if value is not None and any(isinstance(n, ast.Name) and n.id == "__all__" for n in ast.walk(value)):
exported = None # A mutable export list escaped through an alias.
if isinstance(descendant, ast.Call):
if isinstance(descendant.func, ast.Name) and descendant.func.id in mutators | {"exec", "eval"}:
exported = None
if any(isinstance(n, ast.Name) and n.id == "__all__"
for argument in list(descendant.args) + [kw.value for kw in descendant.keywords]
for n in ast.walk(argument)):
exported = None # An opaque call can change the list in place.
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):
if any(isinstance(target, ast.Name) and target.id == "__all__" for target in node.targets):
exported = names(node.value)
exported = names(node.value) if len(node.targets) == 1 else None
elif any(isinstance(child, ast.Name) and child.id == "__all__"
for target in node.targets for child in ast.walk(target)):
exported = None
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)
Expand Down
7 changes: 6 additions & 1 deletion src/pytest_fsd/_lib/fs_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
STANDARD_SEGMENTS = ("ui", "model", "api", "lib", "config")


def is_ignored_directory(name: str) -> bool:
"""Ignore filesystem metadata, never legitimate underscore packages."""
return name.startswith(".") or name == "__pycache__"


def get_canonical_layer(layer_name: str) -> str:
"""Return the layer name without ordering prefixes (e.g., '6_shared' -> 'shared')."""
# Remove leading digits and underscores
Expand Down Expand Up @@ -42,5 +47,5 @@ def get_slices(layer: str, base_path: str) -> List[str]:
return [
d
for d in os.listdir(path)
if os.path.isdir(os.path.join(path, d)) and not d.startswith("_")
if os.path.isdir(os.path.join(path, d)) and not is_ignored_directory(d)
]
Loading
Loading