diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 58be5ca..e706e0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 3017370..0e037ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index d9d1734..8a790c9 100644 --- a/README.md +++ b/README.md @@ -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`. diff --git a/README.ru.md b/README.ru.md index e388308..70e2049 100644 --- a/README.ru.md +++ b/README.ru.md @@ -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` проверяются как обычный код. diff --git a/docs/RULE-AUDIT.md b/docs/RULE-AUDIT.md new file mode 100644 index 0000000..e7b912e --- /dev/null +++ b/docs/RULE-AUDIT.md @@ -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. diff --git a/instructions/SKILL.md b/instructions/SKILL.md index 8171e62..446c3c1 100644 --- a/instructions/SKILL.md +++ b/instructions/SKILL.md @@ -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. diff --git a/pyproject.toml b/pyproject.toml index 7e5cb76..aa618fa 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/src/pytest_fsd/__init__.py b/src/pytest_fsd/__init__.py index e757d5d..1d2add4 100644 --- a/src/pytest_fsd/__init__.py +++ b/src/pytest_fsd/__init__.py @@ -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: diff --git a/src/pytest_fsd/_lib/ast_utils.py b/src/pytest_fsd/_lib/ast_utils.py index 9146dba..bed55be 100644 --- a/src/pytest_fsd/_lib/ast_utils.py +++ b/src/pytest_fsd/_lib/ast_utils.py @@ -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 @@ -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) diff --git a/src/pytest_fsd/_lib/fs_utils.py b/src/pytest_fsd/_lib/fs_utils.py index 0936a75..22de2d3 100644 --- a/src/pytest_fsd/_lib/fs_utils.py +++ b/src/pytest_fsd/_lib/fs_utils.py @@ -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 @@ -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) ] diff --git a/src/pytest_fsd/_lib/imports.py b/src/pytest_fsd/_lib/imports.py index 5ca1bdc..6aabc9d 100644 --- a/src/pytest_fsd/_lib/imports.py +++ b/src/pytest_fsd/_lib/imports.py @@ -7,6 +7,7 @@ from .ast_utils import get_node_location, parse_python_file from .dynamic_imports import analyze_imports +from .fs_utils import is_ignored_directory from ..config import FsdConfig @@ -74,7 +75,7 @@ def iter_imports( """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__") + dirs[:] = sorted(d for d in dirs if not is_ignored_directory(d)) for filename in sorted(files): if not filename.endswith(".py"): continue diff --git a/src/pytest_fsd/_lib/source_validation.py b/src/pytest_fsd/_lib/source_validation.py index da89458..b614bcf 100644 --- a/src/pytest_fsd/_lib/source_validation.py +++ b/src/pytest_fsd/_lib/source_validation.py @@ -7,6 +7,7 @@ from .violations import Violation from .dynamic_imports import analyze_imports +from .fs_utils import is_ignored_directory from ..config import FsdConfig @@ -21,21 +22,28 @@ def unreadable(error: OSError) -> None: violations.append(Violation(rule="python-source", file_path=str(error.filename), message=f"Cannot inspect source directory: {error}")) + try: + with os.scandir(base_dir) as entries: + layer_names = {entry.name for entry in entries} + except OSError as error: + unreadable(error) + return violations + 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): + if layer not in layer_names: continue for root, dirs, files in os.walk(layer_dir, onerror=unreadable): + dirs[:] = sorted(d for d in dirs if not is_ignored_directory(d)) 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 @@ -45,7 +53,7 @@ def unreadable(error: OSError) -> None: source = handle.read() tree = ast.parse(source, filename=file_path) violations.extend(analyze_imports(source, tree, file_path, base_dir).violations) - except (OSError, UnicodeError, SyntaxError, ValueError, LookupError) as error: + except (OSError, UnicodeError, SyntaxError, ValueError, LookupError, RecursionError) as error: violations.append(Violation( rule="python-source", file_path=file_path, line_number=getattr(error, "lineno", None), diff --git a/src/pytest_fsd/config.py b/src/pytest_fsd/config.py index 300ccc0..147e499 100644 --- a/src/pytest_fsd/config.py +++ b/src/pytest_fsd/config.py @@ -48,7 +48,10 @@ def load_config(root_dir: str) -> FsdConfig: with open(pyproject_path, "rb") as f: data = tomllib.load(f) - tool_config = data.get("tool", {}).get("pytest_fsd", {}) + tool_table = data.get("tool", {}) + if not isinstance(tool_table, dict): + raise ValueError("[tool] must be a table for pytest_fsd configuration") + tool_config = tool_table.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"} @@ -69,6 +72,8 @@ def load_config(root_dir: str) -> FsdConfig: 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") + if "__pycache__" in layers: + raise ValueError("pytest_fsd.layers cannot include reserved metadata directory '__pycache__'") 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))}") diff --git a/src/pytest_fsd/rules/ambiguous_slice_names/README.md b/src/pytest_fsd/rules/ambiguous_slice_names/README.md index ebd7977..b52e679 100644 --- a/src/pytest_fsd/rules/ambiguous_slice_names/README.md +++ b/src/pytest_fsd/rules/ambiguous_slice_names/README.md @@ -1,6 +1,6 @@ # `ambiguous-slice-names` -Forbid slice names that match segment names in the `shared` layer. For example, if `shared/i18n` exists, having `features/i18n` is confusing. +Forbid slice names that match segment names or their immediate child directories in the `shared` layer. For example, if `shared/i18n` exists, having `features/i18n` is confusing. ## Examples diff --git a/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py b/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py index a142b22..8295dfd 100644 --- a/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py +++ b/src/pytest_fsd/rules/ambiguous_slice_names/__init__.py @@ -8,7 +8,11 @@ import os from typing import Dict, List -from ..._lib.fs_utils import get_layer_by_canonical_name, get_sliced_layers +from ..._lib.fs_utils import ( + get_layer_by_canonical_name, + get_sliced_layers, + is_ignored_directory, +) from ..._lib.violations import Violation from ...config import FsdConfig @@ -32,7 +36,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: 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("_"): + if not os.path.isdir(segment_path) or is_ignored_directory(segment): continue shared_slices[segment] = f"{shared_layer}/{segment}" @@ -40,7 +44,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: for shared_slice in os.listdir(segment_path): if os.path.isdir( os.path.join(segment_path, shared_slice) - ) and not shared_slice.startswith("_"): + ) and not is_ignored_directory(shared_slice): shared_slices.setdefault( shared_slice, f"{shared_layer}/{segment}/{shared_slice}" ) @@ -58,7 +62,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: for slice_name in os.listdir(layer_path): slice_path = os.path.join(layer_path, slice_name) - if not os.path.isdir(slice_path) or slice_name.startswith("_"): + if not os.path.isdir(slice_path) or is_ignored_directory(slice_name): continue if slice_name in shared_slices: diff --git a/src/pytest_fsd/rules/excessive_slicing/__init__.py b/src/pytest_fsd/rules/excessive_slicing/__init__.py index b6a7e77..9b55afd 100644 --- a/src/pytest_fsd/rules/excessive_slicing/__init__.py +++ b/src/pytest_fsd/rules/excessive_slicing/__init__.py @@ -8,7 +8,7 @@ import os from typing import List -from ..._lib.fs_utils import get_sliced_layers +from ..._lib.fs_utils import is_ignored_directory, get_sliced_layers from ..._lib.violations import Violation from ...config import FsdConfig @@ -30,7 +30,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: slices = [ d for d in os.listdir(layer_path) - if os.path.isdir(os.path.join(layer_path, d)) and not d.startswith("_") + if os.path.isdir(os.path.join(layer_path, d)) and not is_ignored_directory(d) ] if len(slices) > DEFAULT_THRESHOLD: diff --git a/src/pytest_fsd/rules/forbidden_imports/README.md b/src/pytest_fsd/rules/forbidden_imports/README.md index ca0ff92..4d43a1c 100644 --- a/src/pytest_fsd/rules/forbidden_imports/README.md +++ b/src/pytest_fsd/rules/forbidden_imports/README.md @@ -10,10 +10,10 @@ This rule maps to Steiger's `no-higher-level-imports`. 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"]`: +For example, with default layers `["app", "pages", "widgets", "features", "entities", "shared"]`: - `features` can import from `entities` and `shared` -- `features` **cannot** import from `widgets`, `windows`, or `app` +- `features` **cannot** import from `widgets`, `pages`, or `app` ## Examples @@ -35,3 +35,5 @@ from src.pages.home import HomePage # VIOLATION: pages is above features ## Rationale This is one of the main rules of Feature-Sliced Design. It ensures low coupling and predictability during refactoring. + +Layer order follows the configured list, including custom or numerically prefixed names. Resolvable programmatic imports and literal executed code use the same check. External packages and imports in unconfigured layers are outside this rule. diff --git a/src/pytest_fsd/rules/import_locality/README.md b/src/pytest_fsd/rules/import_locality/README.md index d8e14e4..23b5a04 100644 --- a/src/pytest_fsd/rules/import_locality/README.md +++ b/src/pytest_fsd/rules/import_locality/README.md @@ -1,6 +1,6 @@ # `import-locality` -> 🔶 **Covered by Ruff.** This rule is NOT part of `pytest-fsd` core checks, but is fully enforceable via Ruff's `TID` (flake8-tidy-imports) plugin. +> 🔶 **Not implemented in pytest-fsd.** Ruff's `TID` rules can restrict imports, but they do not implement slice-aware FSD locality. Require that imports **within the same slice** be relative, and imports **from another slice** be absolute. diff --git a/src/pytest_fsd/rules/inconsistent_naming/README.md b/src/pytest_fsd/rules/inconsistent_naming/README.md index b54919d..fe40434 100644 --- a/src/pytest_fsd/rules/inconsistent_naming/README.md +++ b/src/pytest_fsd/rules/inconsistent_naming/README.md @@ -1,6 +1,6 @@ # `inconsistent-naming` -> 🔶 **Covered by Ruff.** This rule is NOT part of `pytest-fsd` core checks, but is fully enforceable via Ruff's `N` (pep8-naming) plugin. +> 🔶 **Not implemented in pytest-fsd.** Ruff's `N` rules check related Python naming conventions; they do not implement Steiger's pluralization rule. Ensure that all modules and directories follow consistent naming conventions (`snake_case` for Python). diff --git a/src/pytest_fsd/rules/no_cross_imports/README.md b/src/pytest_fsd/rules/no_cross_imports/README.md index 5c307ce..6c45569 100644 --- a/src/pytest_fsd/rules/no_cross_imports/README.md +++ b/src/pytest_fsd/rules/no_cross_imports/README.md @@ -28,3 +28,5 @@ from src.features.profile import Profile # VIOLATION: same layer (features) ## Rationale Cross-imports between slices create tight coupling, which makes it difficult to refactor or move slices independently. If two slices need to share code, that code should be extracted to a lower layer (e.g., `entities` or `shared`). + +The configured layer names may include ordering prefixes. Imports inside the same slice are allowed, including imports from its own `__init__.py`; importing a sibling slice package is forbidden even when it exposes a public API. Resolvable programmatic imports and literal executed code use the same check. Shared dependencies must still respect their public APIs under `no-public-api-sidestep`. diff --git a/src/pytest_fsd/rules/no_cross_imports/__init__.py b/src/pytest_fsd/rules/no_cross_imports/__init__.py index 8ed6c9d..5ee73f2 100644 --- a/src/pytest_fsd/rules/no_cross_imports/__init__.py +++ b/src/pytest_fsd/rules/no_cross_imports/__init__.py @@ -14,10 +14,15 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: """Reject imports of sibling slices, including their public packages.""" violations = [] sliced_layers = get_sliced_layers(config) + reported = set() 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]): + boundary = (path, location["line_number"], location["column_number"], target[:2]) + if boundary in reported: + continue + reported.add(boundary) 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]}'.", diff --git a/src/pytest_fsd/rules/no_file_segments/README.md b/src/pytest_fsd/rules/no_file_segments/README.md index 3728d69..a6234f6 100644 --- a/src/pytest_fsd/rules/no_file_segments/README.md +++ b/src/pytest_fsd/rules/no_file_segments/README.md @@ -4,6 +4,8 @@ Discourage using file-based segments (e.g., `model.py` directly in a slice) and suggest folder-based segments (e.g., `model/`) instead. +Every direct Python file except `__init__.py` is treated as a file segment, regardless of its name. The same check applies directly inside the sliceless `app` and `shared` layers. Files inside a folder segment are implementation modules and are allowed. A directory whose name ends in `.py` is not a file segment. + ## Configuration ```toml @@ -37,3 +39,7 @@ extra_rules = ["no-file-segments"] File segments are limited in growth potential — everything has to be in one file. Folder segments allow adding adjacent files in the future (e.g., `model/types.py`, `model/validators.py`). Folders are better for long-term project growth. > **Note:** This rule is optional because in Python small slices with a single `model.py` are common and acceptable. + +## Scope + +Configured layer names and source roots are supported, including numeric ordering prefixes. Ordinary underscore-prefixed package directories are checked. Dot-hidden directories and `__pycache__` are metadata and are skipped. Checks apply at the documented slice or segment boundary, not recursively to implementation packages. diff --git a/src/pytest_fsd/rules/no_file_segments/__init__.py b/src/pytest_fsd/rules/no_file_segments/__init__.py index 64d0fad..6067482 100644 --- a/src/pytest_fsd/rules/no_file_segments/__init__.py +++ b/src/pytest_fsd/rules/no_file_segments/__init__.py @@ -8,7 +8,10 @@ import os from typing import List -from ..._lib.fs_utils import get_sliced_layers +from ..._lib.fs_utils import ( + get_sliced_layers, + is_ignored_directory, +) from ..._lib.violations import Violation from ...config import FsdConfig @@ -28,11 +31,15 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: for slice_name in os.listdir(layer_path): slice_path = os.path.join(layer_path, slice_name) - if not os.path.isdir(slice_path) or slice_name.startswith("_"): + if not os.path.isdir(slice_path) or is_ignored_directory(slice_name): continue for file in os.listdir(slice_path): - if not file.endswith(".py") or file == "__init__.py": + if ( + not file.endswith(".py") + or file == "__init__.py" + or not os.path.isfile(os.path.join(slice_path, file)) + ): continue file_body = file[:-3] violations.append( @@ -54,7 +61,11 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: continue for file in os.listdir(layer_path): - if not file.endswith(".py") or file == "__init__.py": + if ( + not file.endswith(".py") + or file == "__init__.py" + or not os.path.isfile(os.path.join(layer_path, file)) + ): continue file_body = file[:-3] violations.append( diff --git a/src/pytest_fsd/rules/no_layer_public_api/README.md b/src/pytest_fsd/rules/no_layer_public_api/README.md index 97daab0..6fb4ab4 100644 --- a/src/pytest_fsd/rules/no_layer_public_api/README.md +++ b/src/pytest_fsd/rules/no_layer_public_api/README.md @@ -28,3 +28,7 @@ These directories serve as grouping containers for slices — they are not packa ## Rationale Having `__init__.py` in a layer directory misleads developers into thinking it is a module with its own API. Layers in FSD are purely structural containers. + +## Scope + +The check applies to direct children of configured sliced layers, including custom layer names and numeric ordering prefixes. The `app` and `shared` layers are exempt. Nested slice implementation directories are outside this rule. diff --git a/src/pytest_fsd/rules/no_layer_public_api/__init__.py b/src/pytest_fsd/rules/no_layer_public_api/__init__.py index 4cab489..d6b5fbb 100644 --- a/src/pytest_fsd/rules/no_layer_public_api/__init__.py +++ b/src/pytest_fsd/rules/no_layer_public_api/__init__.py @@ -27,7 +27,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: continue init_file = os.path.join(layer_path, "__init__.py") - if os.path.exists(init_file): + if os.path.isfile(init_file): violations.append( Violation( rule=RULE_NAME, diff --git a/src/pytest_fsd/rules/no_processes/README.md b/src/pytest_fsd/rules/no_processes/README.md index a3a9a88..14e8c06 100644 --- a/src/pytest_fsd/rules/no_processes/README.md +++ b/src/pytest_fsd/rules/no_processes/README.md @@ -1,6 +1,6 @@ # `no-processes` -> 🔶 **Covered by configuration.** Simply do not include `"processes"` in the `layers` list in `pyproject.toml`. +> 🔶 **Not a separately registered rule.** Simply do not include `"processes"` in the `layers` list in `pyproject.toml`. The Processes layer was deprecated from FSD because there weren't enough use cases to justify its existence. @@ -21,4 +21,4 @@ If your project has a `processes` layer, consider moving the code into `app` or 📂 cart/ ``` -In `pytest-fsd`, an unlisted layer is simply ignored by all rules. If you keep `processes` out of the `layers` config, its existence won't affect the checks, but its contents also won't be validated. +An unlisted `processes` directory is reported by `typo-in-layer-name`, unless explicitly listed in `ignore_paths`. Its contents are outside the configured-layer checks. If you explicitly add `processes` to `layers`, it is treated as a custom sliced layer; there is no separate deprecation check. diff --git a/src/pytest_fsd/rules/no_public_api_sidestep/README.md b/src/pytest_fsd/rules/no_public_api_sidestep/README.md index e1277ed..1a0f700 100644 --- a/src/pytest_fsd/rules/no_public_api_sidestep/README.md +++ b/src/pytest_fsd/rules/no_public_api_sidestep/README.md @@ -1,12 +1,20 @@ # `no-public-api-sidestep` -Forbid deep imports into other slices. All cross-slice imports must go through the slice's `__init__.py` (its Public API). +Forbid imports of another slice's internal modules and names outside its explicit `__all__` public API. + +Shared uses the same public boundaries as `public-api`: ordinary segments such as `shared/config` expose their root `__init__.py`; each immediate package in `shared/lib` and `shared/ui` exposes its own `__init__.py`. Individual Python modules in `shared/lib` and `shared/ui` are public entrypoints and do not need a package wrapper. The optional root APIs of `shared/lib` and `shared/ui` are not required boundaries. ## How it works Uses AST analysis to scan all import statements. If a module imports from another slice with a path deeper than `src.layer.slice` (e.g., `src.features.auth.model.handler`), that's a sidestep violation. -Imports within the same slice are allowed to be deep (internal imports). +Imports within the same slice or Shared API package are allowed to be deep (internal imports). Imports between Shared libraries or segments must use the target's public API. + +For example, `from src.shared.lib.dates import today` is allowed when `dates/__init__.py` explicitly exports `today`. Importing `src.shared.lib.dates.internal` from another library or an upper layer is forbidden. `from src.shared.lib.format_date import format_date` remains allowed when `format_date.py` is an individual module. + +Package imports such as `import src.features.auth` and `from src.features import auth` are allowed; the package name itself does not need to appear in its `__all__`. Explicit names imported from a public package must appear in a statically resolvable `__all__`. A wildcard import also requires a known export list. Supported declarations include lists, tuples, annotations, concatenation, `+=`, `append`, and `extend`; unknown or escaped export lists produce a diagnostic. Missing public API files are handled by `public-api`. + +Relative imports, nested source roots, configured layer prefixes, conditional imports, resolvable programmatic imports and literal executed code are checked without executing project modules. Sources in unconfigured layers, hidden directories and `__pycache__` are excluded. Underscore-prefixed Python packages remain in scope. ## Examples 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 07cc6e5..d8a4aba 100644 --- a/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py +++ b/src/pytest_fsd/rules/no_public_api_sidestep/__init__.py @@ -1,12 +1,16 @@ -"""Require cross-slice imports to use the target slice's public API.""" +"""Require imports between slices and Shared APIs to use public boundaries.""" import ast import os -from typing import List +from typing import List, Optional, Tuple from ..._lib.ast_utils import get_exported_names, get_node_location, parse_python_file -from ..._lib.fs_utils import get_sliced_layers from ..._lib.dynamic_imports import analyze_imports +from ..._lib.fs_utils import ( + get_layer_by_canonical_name, + get_sliced_layers, + is_ignored_directory, +) from ..._lib.imports import imported_modules, resolve_module from ..._lib.violations import Violation from ...config import FsdConfig @@ -14,8 +18,26 @@ RULE_NAME = "no-public-api-sidestep" +def _public_boundary( + target: Tuple[str, ...], base_dir: str, sliced_layers: List[str], shared_layer: Optional[str] +) -> Optional[Tuple[str, ...]]: + if len(target) < 2: + return None + if target[0] in sliced_layers: + return target[:2] + if target[0] != shared_layer: + return None + if target[1] not in ("ui", "lib"): + return target[:2] + # Shared UI components and libraries expose individual package APIs; + # standalone modules in these segments are already public entrypoints. + if len(target) >= 3 and os.path.isdir(os.path.join(base_dir, *target[:3])): + return target[:3] + return None + + def check(config: FsdConfig, project_root: str) -> List[Violation]: - """Verify that all cross-slice imports go through the slice's Public API.""" + """Verify imports use the slice or Shared package public API.""" violations = [] base_dir = os.path.join(project_root, config.base_path) base_module = config.base_path.replace(os.sep, ".").strip(".") @@ -23,14 +45,18 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: return violations sliced_layers = get_sliced_layers(config) - for root, _, files in os.walk(base_dir): - for file in files: + shared_layer = get_layer_by_canonical_name(config, "shared") + for root, dirs, files in os.walk(base_dir): + dirs[:] = sorted(name for name in dirs if not is_ignored_directory(name) + and (root != base_dir or name in config.layers)) + for file in sorted(files): if not file.endswith(".py"): continue file_path = os.path.join(root, file) 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 + if parts[0] not in config.layers: + continue + current_boundary = _public_boundary(tuple(parts[:-1]), base_dir, sliced_layers, shared_layer) parsed = parse_python_file(file_path) if parsed is None: continue @@ -44,7 +70,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: targets.append((target, alias.name, [])) elif isinstance(node, ast.ImportFrom): target = resolve_module(node.module, node.level, file_path, base_dir, config.layers) - if target is not None and len(target) >= 2: + if target is not None and _public_boundary(target, base_dir, sliced_layers, shared_layer): 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): @@ -52,31 +78,30 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: targets.append((imported, ".".join(imported), [])) for target, module_path, imported_names in targets: - if len(target) < 2: - continue - target_layer, target_slice = target[:2] - if target_layer not in sliced_layers: - continue - if current_layer == target_layer and current_slice == target_slice: + boundary = _public_boundary(target, base_dir, sliced_layers, shared_layer) + if boundary is None or current_boundary == boundary: continue + api_name = "/".join(boundary) + api_module = ".".join(part for part in (base_module, ".".join(boundary)) if part) + api_kind = "Slice" if boundary[0] in sliced_layers else "Shared API" location = get_node_location(node, source) - if len(target) > 2: + if len(target) > len(boundary): 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.", + f"from public API '{api_name}'. " + f"Import from '{api_module}' instead.", )) elif imported_names: - target_init = os.path.join(base_dir, target_layer, target_slice, "__init__.py") + target_init = os.path.join(base_dir, *boundary, "__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. " + message=f"{api_kind} '{api_name}' does not define `__all__` " + "as a statically resolvable sequence of strings in its __init__.py. " "Public API exports must be explicit to prevent encapsulation bypass.", )) else: @@ -85,7 +110,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: 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'. " + f"'{api_name}/__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 03bff56..255cf38 100644 --- a/src/pytest_fsd/rules/no_reserved_folder_names/__init__.py +++ b/src/pytest_fsd/rules/no_reserved_folder_names/__init__.py @@ -8,7 +8,7 @@ import os from typing import List -from ..._lib.fs_utils import STANDARD_SEGMENTS, get_canonical_layer +from ..._lib.fs_utils import is_ignored_directory, STANDARD_SEGMENTS, get_canonical_layer from ..._lib.violations import Violation from ...config import FsdConfig @@ -34,7 +34,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: # В слайсовых слоях сегменты лежат внутри слайсов for slice_name in os.listdir(layer_path): slice_path = os.path.join(layer_path, slice_name) - if not os.path.isdir(slice_path) or slice_name.startswith("_"): + if not os.path.isdir(slice_path) or is_ignored_directory(slice_name): continue _check_segments_subfolders( slice_path, f"{layer}/{slice_name}", violations @@ -49,12 +49,12 @@ def _check_segments_subfolders( """Check subfolders of segments inside a given parent path recursively.""" for segment_name in os.listdir(parent_path): segment_path = os.path.join(parent_path, segment_name) - if not os.path.isdir(segment_path) or segment_name.startswith("_"): + if not os.path.isdir(segment_path) or is_ignored_directory(segment_name): continue for root_dir, dirs, _ in os.walk(segment_path): # Игнорируем скрытые папки - dirs[:] = [d for d in dirs if not d.startswith("_")] + dirs[:] = [d for d in dirs if not is_ignored_directory(d)] for subfolder in dirs: if subfolder in STANDARD_SEGMENTS: diff --git a/src/pytest_fsd/rules/no_segmentless_slices/README.md b/src/pytest_fsd/rules/no_segmentless_slices/README.md index 4a58bbd..f59e6d5 100644 --- a/src/pytest_fsd/rules/no_segmentless_slices/README.md +++ b/src/pytest_fsd/rules/no_segmentless_slices/README.md @@ -30,3 +30,7 @@ A segment can be either a **folder** (e.g., `features/auth/model/`) or a **file* ## Rationale A slice without standard segments is usually an architectural smell — it suggests that the code is not properly decomposed into purpose-driven groups. + +## Scope + +Configured layer names and source roots are supported, including numeric ordering prefixes. Ordinary underscore-prefixed package directories are checked. Dot-hidden directories and `__pycache__` are metadata and are skipped. Checks apply at the documented slice or segment boundary, not recursively to implementation packages. diff --git a/src/pytest_fsd/rules/no_segmentless_slices/__init__.py b/src/pytest_fsd/rules/no_segmentless_slices/__init__.py index 53562b8..f4a2e1c 100644 --- a/src/pytest_fsd/rules/no_segmentless_slices/__init__.py +++ b/src/pytest_fsd/rules/no_segmentless_slices/__init__.py @@ -8,7 +8,11 @@ import os from typing import List -from ..._lib.fs_utils import STANDARD_SEGMENTS, get_sliced_layers +from ..._lib.fs_utils import ( + STANDARD_SEGMENTS, + get_sliced_layers, + is_ignored_directory, +) from ..._lib.violations import Violation from ...config import FsdConfig @@ -31,7 +35,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: for slice_name in os.listdir(layer_path): slice_path = os.path.join(layer_path, slice_name) - if not os.path.isdir(slice_path) or slice_name.startswith("_"): + if not os.path.isdir(slice_path) or is_ignored_directory(slice_name): continue has_segments = False diff --git a/src/pytest_fsd/rules/no_segments_on_sliced_layers/README.md b/src/pytest_fsd/rules/no_segments_on_sliced_layers/README.md index 85ea6ff..7913e5d 100644 --- a/src/pytest_fsd/rules/no_segments_on_sliced_layers/README.md +++ b/src/pytest_fsd/rules/no_segments_on_sliced_layers/README.md @@ -27,3 +27,7 @@ These layers must contain only **slices** (domain-meaningful subfolders). ## Rationale The name `api` is conventionally a segment in FSD. When you see it as a direct child of a sliced layer, it's either a poorly named slice (confusing) or code that ended up unsliced (a violation of FSD structure). + +## Scope + +The check applies to direct children of configured sliced layers, including custom layer names and numeric ordering prefixes. The `app` and `shared` layers are exempt. Nested slice implementation directories are outside this rule. diff --git a/src/pytest_fsd/rules/no_segments_on_sliced_layers/__init__.py b/src/pytest_fsd/rules/no_segments_on_sliced_layers/__init__.py index 6c04ab2..0e1027a 100644 --- a/src/pytest_fsd/rules/no_segments_on_sliced_layers/__init__.py +++ b/src/pytest_fsd/rules/no_segments_on_sliced_layers/__init__.py @@ -8,7 +8,11 @@ import os from typing import List -from ..._lib.fs_utils import STANDARD_SEGMENTS, get_sliced_layers +from ..._lib.fs_utils import ( + STANDARD_SEGMENTS, + get_sliced_layers, + is_ignored_directory, +) from ..._lib.violations import Violation from ...config import FsdConfig @@ -28,7 +32,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: for child_name in os.listdir(layer_path): child_path = os.path.join(layer_path, child_name) - if not os.path.isdir(child_path) or child_name.startswith("_"): + if not os.path.isdir(child_path) or is_ignored_directory(child_name): continue # Если имя папки совпадает с именем стандартного сегмента — это нарушение diff --git a/src/pytest_fsd/rules/no_ui_in_app/README.md b/src/pytest_fsd/rules/no_ui_in_app/README.md index 5516f5a..fa0e894 100644 --- a/src/pytest_fsd/rules/no_ui_in_app/README.md +++ b/src/pytest_fsd/rules/no_ui_in_app/README.md @@ -14,4 +14,4 @@ src/pages/home/ui/ # allowed import tkinter # violation in pytest-fsd ``` -The import check looks at static `import` and `from ... import ...` syntax. It does not detect dynamic imports or every possible GUI framework. +The import check covers static imports, resolvable programmatic imports and literal executed code without executing project modules. It applies to the configured App layer, including ordering prefixes. Relative local imports such as `from .tkinter import settings` are allowed. Hidden directories and `__pycache__` are excluded; underscore-prefixed Python packages remain in scope. The framework list is explicit and does not cover every GUI toolkit. 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 397c2ed..b673bb8 100644 --- a/src/pytest_fsd/rules/no_ui_in_app/__init__.py +++ b/src/pytest_fsd/rules/no_ui_in_app/__init__.py @@ -6,8 +6,8 @@ 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.dynamic_imports import analyze_imports +from ..._lib.fs_utils import get_layer_by_canonical_name, is_ignored_directory from ..._lib.violations import Violation from ...config import FsdConfig @@ -47,8 +47,9 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: ) ) - for root, _, files in os.walk(app_path): - for file in files: + for root, dirs, files in os.walk(app_path): + dirs[:] = sorted(name for name in dirs if not is_ignored_directory(name)) + for file in sorted(files): if not file.endswith(".py"): continue diff --git a/src/pytest_fsd/rules/no_wildcard_exports/README.md b/src/pytest_fsd/rules/no_wildcard_exports/README.md index cc5bf29..8664cd4 100644 --- a/src/pytest_fsd/rules/no_wildcard_exports/README.md +++ b/src/pytest_fsd/rules/no_wildcard_exports/README.md @@ -29,3 +29,5 @@ __all__ = ["User"] The rule examines import syntax without executing modules. It reports each wildcard statement with one-based line and character column positions and an exclusive end position. Conditional imports, including `if TYPE_CHECKING:`, are checked too. Unreadable files and files with invalid Python syntax produce a diagnostic with the underlying error. Python's `from . import model as model` explicitly imports one module and is allowed. It does not copy all of that module's names into the package namespace, so it is not treated as JavaScript's `export * as model`. + +Resolvable programmatic imports with a wildcard fromlist and literal executed wildcard imports are checked at their original call locations. Hidden directories and `__pycache__` are excluded; underscore-prefixed Python packages remain in scope. diff --git a/src/pytest_fsd/rules/no_wildcard_exports/__init__.py b/src/pytest_fsd/rules/no_wildcard_exports/__init__.py index c118ad8..d38e9ae 100644 --- a/src/pytest_fsd/rules/no_wildcard_exports/__init__.py +++ b/src/pytest_fsd/rules/no_wildcard_exports/__init__.py @@ -7,6 +7,7 @@ from ..._lib.ast_utils import get_node_location from ..._lib.dynamic_imports import analyze_imports +from ..._lib.fs_utils import is_ignored_directory from ..._lib.violations import Violation from ...config import FsdConfig @@ -19,7 +20,8 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: base_dir = os.path.join(project_root, config.base_path) for layer in config.layers: - for root, _, files in os.walk(os.path.join(base_dir, layer)): + for root, dirs, files in os.walk(os.path.join(base_dir, layer)): + dirs[:] = sorted(name for name in dirs if not is_ignored_directory(name)) if "__init__.py" not in files: continue file_path = os.path.join(root, "__init__.py") diff --git a/src/pytest_fsd/rules/public_api/README.md b/src/pytest_fsd/rules/public_api/README.md index 3e95818..2dd7a7a 100644 --- a/src/pytest_fsd/rules/public_api/README.md +++ b/src/pytest_fsd/rules/public_api/README.md @@ -1,6 +1,8 @@ # `public-api` -Require every slice (and every segment in `shared`) to have an `__init__.py` file that serves as its public API definition. +Require every slice and every shared segment other than `ui` and `lib` to have an `__init__.py` file that serves as its public API definition. + +`shared/ui` and `shared/lib` may contain individual modules without a root public API. Each immediate subfolder in those two segments must have its own `__init__.py`. This check stops at that boundary; it does not require every nested implementation package to declare a public API. The `app` layer is exempt. In Python, `__init__.py` acts as the public API entry point for a package. Other modules should import from the slice via this file, not from internal modules. @@ -25,10 +27,14 @@ In Python, `__init__.py` acts as the public API entry point for a package. Other 📂 auth/ # ❌ missing __init__.py 📂 model/ 📂 shared/ - 📂 lib/ # ❌ missing __init__.py - 📄 hash.py + 📂 config/ # ❌ missing __init__.py + 📄 settings.py ``` ## Rationale The public API for slices is the only entrypoint into a slice, ensuring that the internal structure can change freely as long as the public API stays the same. A slice without one becomes a weak point for refactoring. + +## Scope + +Configured layer names and source roots are supported, including numeric ordering prefixes. Ordinary underscore-prefixed package directories are checked. Dot-hidden directories and `__pycache__` are metadata and are skipped. Checks apply at the documented slice or segment boundary, not recursively to implementation packages. diff --git a/src/pytest_fsd/rules/public_api/__init__.py b/src/pytest_fsd/rules/public_api/__init__.py index a6d4a55..57e5c77 100644 --- a/src/pytest_fsd/rules/public_api/__init__.py +++ b/src/pytest_fsd/rules/public_api/__init__.py @@ -8,7 +8,11 @@ import os from typing import List -from ..._lib.fs_utils import get_layer_by_canonical_name, get_sliced_layers +from ..._lib.fs_utils import ( + get_layer_by_canonical_name, + get_sliced_layers, + is_ignored_directory, +) from ..._lib.violations import Violation from ...config import FsdConfig @@ -29,7 +33,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: for slice_name in os.listdir(layer_path): slice_path = os.path.join(layer_path, slice_name) - if not os.path.isdir(slice_path) or slice_name.startswith("_"): + if not os.path.isdir(slice_path) or is_ignored_directory(slice_name): continue init_file = os.path.join(slice_path, "__init__.py") @@ -50,7 +54,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: if os.path.isdir(shared_path): for segment_name in os.listdir(shared_path): segment_path = os.path.join(shared_path, segment_name) - if not os.path.isdir(segment_path) or segment_name.startswith("_"): + if not os.path.isdir(segment_path) or is_ignored_directory(segment_name): continue if segment_name in ("ui", "lib"): @@ -58,7 +62,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: # Но если внутри есть подпапки, они должны иметь __init__.py for child in os.listdir(segment_path): child_path = os.path.join(segment_path, child) - if os.path.isdir(child_path) and not child.startswith("_"): + if os.path.isdir(child_path) and not is_ignored_directory(child): child_init = os.path.join(child_path, "__init__.py") if not os.path.isfile(child_init): violations.append( diff --git a/src/pytest_fsd/rules/repetitive_naming/__init__.py b/src/pytest_fsd/rules/repetitive_naming/__init__.py index b129af0..a8597ca 100644 --- a/src/pytest_fsd/rules/repetitive_naming/__init__.py +++ b/src/pytest_fsd/rules/repetitive_naming/__init__.py @@ -8,7 +8,7 @@ import os from typing import List -from ..._lib.fs_utils import get_sliced_layers +from ..._lib.fs_utils import is_ignored_directory, get_sliced_layers from ..._lib.violations import Violation from ...config import FsdConfig @@ -31,10 +31,11 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: for slice_name in os.listdir(layer_path): slice_path = os.path.join(layer_path, slice_name) - if not os.path.isdir(slice_path) or slice_name.startswith("_"): + if not os.path.isdir(slice_path) or is_ignored_directory(slice_name): continue - for root, _, files in os.walk(slice_path): + for root, dirs, files in os.walk(slice_path): + dirs[:] = [d for d in dirs if not is_ignored_directory(d)] for file in files: if not file.endswith(".py") or file == "__init__.py": continue diff --git a/src/pytest_fsd/rules/segments_by_purpose/__init__.py b/src/pytest_fsd/rules/segments_by_purpose/__init__.py index d93dc39..f72c597 100644 --- a/src/pytest_fsd/rules/segments_by_purpose/__init__.py +++ b/src/pytest_fsd/rules/segments_by_purpose/__init__.py @@ -8,7 +8,7 @@ import os from typing import List -from ..._lib.fs_utils import get_canonical_layer +from ..._lib.fs_utils import is_ignored_directory, get_canonical_layer from ..._lib.violations import Violation from ...config import FsdConfig @@ -94,7 +94,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: # Для остальных слоев сегменты лежат внутри слайсов for slice_name in os.listdir(layer_path): slice_path = os.path.join(layer_path, slice_name) - if not os.path.isdir(slice_path) or slice_name.startswith("_"): + if not os.path.isdir(slice_path) or is_ignored_directory(slice_name): continue _check_entries_in_dir(slice_path, slice_name, violations) @@ -111,7 +111,7 @@ def _check_entries_in_dir( return for entry in entries: - if entry.startswith("_"): + if is_ignored_directory(entry): continue entry_path = os.path.join(parent_path, entry) diff --git a/src/pytest_fsd/rules/typo_in_layer_name/__init__.py b/src/pytest_fsd/rules/typo_in_layer_name/__init__.py index 446b5a7..ead8376 100644 --- a/src/pytest_fsd/rules/typo_in_layer_name/__init__.py +++ b/src/pytest_fsd/rules/typo_in_layer_name/__init__.py @@ -8,6 +8,7 @@ import os from typing import List +from ..._lib.fs_utils import is_ignored_directory from ..._lib.violations import Violation from ...config import FsdConfig @@ -32,7 +33,7 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: entry_path = os.path.join(base_dir, entry) if not os.path.isdir(entry_path): continue - if entry.startswith("_") or entry.startswith("."): + if is_ignored_directory(entry): continue if entry in known_layers or entry in ignored: continue diff --git a/tests/conftest.py b/tests/conftest.py index 587667f..6859d11 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -70,15 +70,6 @@ def _create_project(tree_str: str, extra_rules: Optional[List[str]] = None) -> P parse_steiger_tree(src_dir, tree_str) - # Add tmp_path to sys.path so pytest_archon can import the modules - import sys - sys.path.insert(0, str(tmp_path)) - return tmp_path - yield _create_project - - # Cleanup sys.path after tests (approximate cleanup) - import sys - if str(tmp_path) in sys.path: - sys.path.remove(str(tmp_path)) + return _create_project diff --git a/tests/rule_contracts.py b/tests/rule_contracts.py new file mode 100644 index 0000000..39788ff --- /dev/null +++ b/tests/rule_contracts.py @@ -0,0 +1,150 @@ +"""Portable positive/negative witnesses for every shipped architecture check. + +Used by pytest and by `python -I tests/rule_contracts.py VERSION` against wheels. +""" + +from pathlib import Path +import tempfile +from importlib.metadata import version +import sys + +import pytest_fsd +from pytest_fsd.config import load_config +from pytest_fsd._lib.source_validation import check_sources + +CORE_NAMES = { + 'forbidden-imports', 'no-cross-imports', 'no-public-api-sidestep', + 'no-layer-public-api', 'no-ui-in-app', 'repetitive-naming', + 'no-segmentless-slices', 'segments-by-purpose', 'ambiguous-slice-names', + 'no-segments-on-sliced-layers', 'public-api', 'typo-in-layer-name', +} +EXTRA_NAMES = { + 'excessive-slicing', 'shared-lib-grouping', 'no-file-segments', + 'no-reserved-folder-names', 'no-wildcard-exports', +} +GUARD_NAMES = {'python-source', 'dynamic-imports'} +ALL_NAMES = sorted(CORE_NAMES | EXTRA_NAMES | GUARD_NAMES) + + +def registry(): + rules = {module.RULE_NAME: module for module in pytest_fsd.CORE_RULES} + rules.update(pytest_fsd.EXTRA_RULES) + return rules + + +def verify_registry(): + assert {module.RULE_NAME for module in pytest_fsd.CORE_RULES} == CORE_NAMES + assert set(pytest_fsd.EXTRA_RULES) == EXTRA_NAMES + assert len(pytest_fsd.CORE_RULES) == len(CORE_NAMES) + + +def baseline(): + files = { + 'features/accounts/__init__.py': "__all__ = ['value']\nvalue = 1\n", + 'features/accounts/model/record.py': 'value = 1\n', + 'features/billing/__init__.py': "__all__ = ['value']\nvalue = 1\n", + 'features/billing/api/routes.py': '', + 'entities/customer/__init__.py': "__all__ = ['value']\nvalue = 1\n", + 'entities/customer/model/record.py': 'value = 1\n', + 'shared/config/__init__.py': "__all__ = ['value']\nvalue = 1\n", + 'shared/lib/formatting/__init__.py': "__all__ = ['value']\nvalue = 1\n", + 'shared/lib/formatting/core.py': 'value = 1\n', + 'app/config/start.py': '', + } + return files + + +def bad_files(name): + files = baseline() + changes = { + 'forbidden-imports': {'shared/config/runtime.py': 'from src.features.accounts import value\n'}, + 'no-cross-imports': {'features/accounts/model/record.py': 'from src.features.billing import value\n'}, + 'no-public-api-sidestep': {'app/config/start.py': 'from src.entities.customer.model.record import value\n'}, + 'no-layer-public-api': {'features/__init__.py': ''}, + 'no-ui-in-app': {'app/ui/panel.py': ''}, + 'repetitive-naming': {'features/accounts/model/accounts_record.py': ''}, + 'no-segmentless-slices': {'features/accounts/model/record.py': None}, + 'segments-by-purpose': {'features/accounts/services/client.py': ''}, + 'ambiguous-slice-names': { + 'features/formatting/__init__.py': '__all__ = []\n', + 'features/formatting/model/record.py': '', + }, + 'no-segments-on-sliced-layers': {'features/model/__init__.py': '', 'features/model/lib/record.py': ''}, + 'public-api': {'features/accounts/__init__.py': None}, + 'typo-in-layer-name': {'fietures/record.py': ''}, + 'no-file-segments': {'features/accounts/api.py': ''}, + 'no-reserved-folder-names': {'features/accounts/model/api/record.py': ''}, + 'no-wildcard-exports': {'features/accounts/__init__.py': "from .model.record import *\n__all__ = ['value']\n"}, + 'python-source': {'features/accounts/model/record.py': 'from broken import (\n'}, + 'dynamic-imports': {'features/accounts/model/record.py': '__import__(runtime_target)\n'}, + } + if name == 'excessive-slicing': + for index in range(19): # two baseline slices + 19 = 21 > 20 + files['features/item' + str(index) + '/__init__.py'] = '__all__ = []\n' + files['features/item' + str(index) + '/model/record.py'] = '' + elif name == 'shared-lib-grouping': + for index in range(16): + files['shared/lib/tool' + str(index) + '.py'] = '' + else: + for path, source in changes[name].items(): + if source is None: + files.pop(path) + else: + files[path] = source + return files + + +def materialize(root, files, extra_rules): + for relative, source in files.items(): + path = root / 'src' / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source, encoding='utf-8') + extras = ', '.join('"' + name + '"' for name in extra_rules) + (root / 'pyproject.toml').write_text( + '[tool.pytest_fsd]\nbase_path = "src"\n' + 'layers = ["app", "features", "entities", "shared"]\n' + 'extra_rules = [' + extras + ']\n', encoding='utf-8', + ) + + +def facade_message(root): + try: + pytest_fsd.validate_fsd_architecture(str(root)) + except AssertionError as error: + return str(error) + return '' + + +def check_case(name, root): + """Assert direct checking, facade dispatch, clean control and opt-in behavior.""" + extras = [name] if name in EXTRA_NAMES else [] + good, bad = root / 'good', root / 'bad' + materialize(good, baseline(), extras) + materialize(bad, bad_files(name), extras) + checker = check_sources if name in GUARD_NAMES else registry()[name].check + for project, expected in ((good, False), (bad, True)): + found = any(v.rule == name for v in checker(load_config(str(project)), str(project))) + assert found == expected, 'Direct check did not execute ' + name + message = facade_message(project) + assert ('[' + name + ']' in message) == expected, 'Facade did not execute ' + name + assert not any('[' + other + ']' in message for other in ALL_NAMES if other != name), message + if not expected: + assert not message, message + if name in EXTRA_NAMES: + text = (bad / 'pyproject.toml').read_text(encoding='utf-8') + (bad / 'pyproject.toml').write_text(text.replace('extra_rules = ["' + name + '"]', 'extra_rules = []'), encoding='utf-8') + assert not facade_message(bad), 'Disabled extra rule still affects validation: ' + name + + +def main(): + assert version('pytest-fsd') == sys.argv[1] + verify_registry() + for name in ALL_NAMES: + with tempfile.TemporaryDirectory(prefix='pytest-fsd-contract-') as directory: + check_case(name, Path(directory)) + print('PASS rule contract:', name) + print('Verified all 17 rules and both input guards; positive, negative and extra-rule controls.') + + +if __name__ == '__main__': + main() diff --git a/tests/rules/test_ambiguous_slice_names.py b/tests/rules/test_ambiguous_slice_names.py index 6ad63c4..601ced8 100644 --- a/tests/rules/test_ambiguous_slice_names.py +++ b/tests/rules/test_ambiguous_slice_names.py @@ -1,6 +1,13 @@ # tests/rules/test_ambiguous_slice_names.py """Tests for the ambiguous-slice-names rule.""" -from pytest_fsd.config import load_config +import pytest +from pytest_fsd.rules import ( + ambiguous_slice_names, repetitive_naming, segments_by_purpose, + typo_in_layer_name, no_reserved_folder_names, excessive_slicing, + shared_lib_grouping, +) + +from pytest_fsd.config import FsdConfig, load_config from pytest_fsd.rules.ambiguous_slice_names import RULE_NAME, check @@ -58,3 +65,44 @@ def test_ambiguous_slice_names_matches_shared_segments(create_project): assert violations[0].rule == RULE_NAME assert violations[0].file_path == str(project_root / "src/features/i18n") assert "shared/i18n" in violations[0].message + + +def test_hidden_shared_components_and_slices_are_ignored(create_project): + project_root = create_project( + '📂 shared\n 📂 .cache\n 📂 auth\n 📂 ui\n 📂 .button\n' + '📂 features\n 📂 auth\n 📂 .button\n' + ) + assert check(load_config(str(project_root)), str(project_root)) == [] + + +def test_ambiguous_names_custom_layers_and_directory_only(tmp_path): + for name in ('6_shared/i18n', '4_custom/i18n', '0_app/i18n'): + (tmp_path / 'src' / name).mkdir(parents=True) + (tmp_path / 'src/6_shared/file.py').touch() + (tmp_path / 'src/4_custom/file.py').mkdir() + config = FsdConfig(layers=['0_app', '4_custom', '6_shared']) + violations = check(config, str(tmp_path)) + assert [v.file_path for v in violations] == [str(tmp_path / 'src/4_custom/i18n')] + + +def test_private_shared_names_are_checked(create_project): + project_root = create_project('📂 shared\n 📂 lib\n 📂 _auth\n📂 features\n 📂 _auth') + violations = check(load_config(str(project_root)), str(project_root)) + assert [v.file_path for v in violations] == [str(project_root / 'src/features/_auth')] + + +def test_ambiguous_names_without_shared_layer_are_valid(tmp_path): + (tmp_path / 'src/custom/auth').mkdir(parents=True) + assert check(FsdConfig(layers=['custom']), str(tmp_path)) == [] + + +@pytest.mark.parametrize('rule', [ + ambiguous_slice_names, repetitive_naming, segments_by_purpose, + typo_in_layer_name, no_reserved_folder_names, excessive_slicing, + shared_lib_grouping, +]) +def test_naming_rules_missing_or_non_directory_root_is_safe(tmp_path, rule): + config = FsdConfig() + assert rule.check(config, str(tmp_path)) == [] + (tmp_path / 'src').touch() + assert rule.check(config, str(tmp_path)) == [] diff --git a/tests/rules/test_excessive_slicing.py b/tests/rules/test_excessive_slicing.py index d552fbe..6c5e8ce 100644 --- a/tests/rules/test_excessive_slicing.py +++ b/tests/rules/test_excessive_slicing.py @@ -1,6 +1,8 @@ # tests/rules/test_excessive_slicing.py """Tests for the excessive-slicing rule (extra).""" -from pytest_fsd.config import load_config +import pytest + +from pytest_fsd.config import FsdConfig, load_config from pytest_fsd.rules.excessive_slicing import RULE_NAME, check @@ -43,3 +45,19 @@ def test_excessive_slicing_violation(create_project, tmp_path): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "21 slices" in violations[0].message + + +@pytest.mark.parametrize('count', [19, 20, 21]) +def test_excessive_slicing_boundaries_and_non_slices(tmp_path, count): + for layer in ('0_app', '4_custom', '6_shared'): + path = tmp_path / 'src' / layer + path.mkdir(parents=True) + for i in range(count): + (path / ('_slice_%s' % i)).mkdir() + for name in ('.cache', '.git', '__pycache__'): + (path / name).mkdir() + (path / 'file.py').touch() + violations = check(FsdConfig(layers=['0_app', '4_custom', '6_shared']), str(tmp_path)) + assert [v.file_path for v in violations] == ([str(tmp_path / 'src/4_custom')] if count == 21 else []) + if violations: + assert '21 slices' in violations[0].message diff --git a/tests/rules/test_no_cross_imports.py b/tests/rules/test_no_cross_imports.py index 8fa9eec..8b05b6b 100644 --- a/tests/rules/test_no_cross_imports.py +++ b/tests/rules/test_no_cross_imports.py @@ -89,7 +89,7 @@ def test_no_cross_imports_errors(create_project): def test_no_cross_imports_shared_allowed(create_project): - """Shared layer slices can depend on each other.""" + """Shared segments can depend on each other through public APIs.""" project_root = create_project( """ 📂 shared @@ -102,6 +102,9 @@ def test_no_cross_imports_shared_allowed(create_project): """ ) + (project_root / "src" / "shared" / "config" / "__init__.py").write_text( + "env = {}\n__all__ = ['env']\n", encoding="utf-8" + ) (project_root / "src" / "shared" / "ui" / "component.py").write_text( "from src.shared.config import env\n", encoding="utf-8" ) diff --git a/tests/rules/test_no_file_segments.py b/tests/rules/test_no_file_segments.py index db10d03..7dde1e4 100644 --- a/tests/rules/test_no_file_segments.py +++ b/tests/rules/test_no_file_segments.py @@ -1,5 +1,12 @@ -# tests/rules/test_no_file_segments.py """Tests for the no-file-segments rule (extra).""" + +from pathlib import Path + +import pytest + +from pytest_fsd.config import FsdConfig + + from pytest_fsd.config import load_config from pytest_fsd.rules.no_file_segments import RULE_NAME, check @@ -40,3 +47,58 @@ def test_no_file_segments_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "model" in violations[0].message + + +def test_no_file_segments_ignores_directories_with_python_suffix(create_project): + project_root = create_project( + "📂 features\n 📂 auth\n 📂 model.py\n" + "📂 shared\n 📂 api.py\n" + "📂 app\n 📂 config.py" + ) + assert check(load_config(str(project_root)), str(project_root)) == [] + + +@pytest.mark.parametrize("base_path", ["src", "package/source", "."]) +@pytest.mark.parametrize("layer_name", ["features", "3_features", "custom"]) +def test_no_file_segments_configured_roots_layers_and_depth(tmp_path, base_path, layer_name): + config = FsdConfig(base_path=base_path, layers=["0_app", layer_name, "6_shared"]) + source = tmp_path / base_path + layer = source / layer_name + layer.mkdir(parents=True) + + (layer / "auth/model").mkdir(parents=True) + (layer / "auth/model/handler.py").touch() + (layer / "auth/__init__.py").touch() + (layer / "auth/ui.py").touch() + for exempt in ("0_app", "6_shared"): + (source / exempt / "model").mkdir(parents=True) + (source / exempt / "model/handler.py").touch() + (source / exempt / "__init__.py").touch() + (source / exempt / "config.py").touch() + assert {Path(v.file_path).relative_to(source).as_posix() for v in check(config, str(tmp_path))} == { + layer_name + "/auth/ui.py", "0_app/config.py", "6_shared/config.py" + } + + +@pytest.mark.parametrize("name", ["_private", "__private", ".metadata", "__pycache__"]) +def test_no_file_segments_private_packages_and_metadata(tmp_path, name): + config = FsdConfig() + slice_path = tmp_path / "src/features" / name + slice_path.mkdir(parents=True) + (slice_path / "model.py").touch() + violations = check(config, str(tmp_path)) + if name in ("_private", "__private"): + assert [Path(v.file_path) for v in violations] == [slice_path / "model.py"] + else: + assert violations == [] + + +@pytest.mark.parametrize("entry", ["missing_root", "file_root", "file_layer"]) +def test_no_file_segments_absent_directories(tmp_path, entry): + config = FsdConfig() + if entry == "file_root": + (tmp_path / "src").touch() + elif entry == "file_layer": + (tmp_path / "src").mkdir() + (tmp_path / "src/features").touch() + assert check(config, str(tmp_path)) == [] diff --git a/tests/rules/test_no_layer_public_api.py b/tests/rules/test_no_layer_public_api.py index 0ae2b97..a326175 100644 --- a/tests/rules/test_no_layer_public_api.py +++ b/tests/rules/test_no_layer_public_api.py @@ -1,5 +1,12 @@ -# tests/rules/test_no_layer_public_api.py """Tests for the no-layer-public-api rule.""" + +from pathlib import Path + +import pytest + +from pytest_fsd.config import FsdConfig + + from pytest_fsd.config import load_config from pytest_fsd.rules.no_layer_public_api import RULE_NAME, check @@ -38,3 +45,36 @@ def test_no_layer_public_api_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "features" in violations[0].message + + +def test_no_layer_public_api_ignores_directory_named_init(create_project): + project_root = create_project("📂 features\n 📂 __init__.py") + assert check(load_config(str(project_root)), str(project_root)) == [] + + +@pytest.mark.parametrize("base_path", ["src", "package/source", "."]) +@pytest.mark.parametrize("layer_name", ["features", "3_features", "custom"]) +def test_no_layer_public_api_configured_roots_layers_and_depth(tmp_path, base_path, layer_name): + config = FsdConfig(base_path=base_path, layers=["0_app", layer_name, "6_shared"]) + source = tmp_path / base_path + layer = source / layer_name + layer.mkdir(parents=True) + + (layer / "__init__.py").touch() + (layer / "auth").mkdir() + (layer / "auth/__init__.py").touch() + for exempt in ("0_app", "6_shared"): + (source / exempt).mkdir() + (source / exempt / "__init__.py").touch() + assert [Path(v.file_path) for v in check(config, str(tmp_path))] == [layer / "__init__.py"] + + +@pytest.mark.parametrize("entry", ["missing_root", "file_root", "file_layer"]) +def test_no_layer_public_api_absent_directories(tmp_path, entry): + config = FsdConfig() + if entry == "file_root": + (tmp_path / "src").touch() + elif entry == "file_layer": + (tmp_path / "src").mkdir() + (tmp_path / "src/features").touch() + assert check(config, str(tmp_path)) == [] diff --git a/tests/rules/test_no_reserved_folder_names.py b/tests/rules/test_no_reserved_folder_names.py index 5810d38..5a21c42 100644 --- a/tests/rules/test_no_reserved_folder_names.py +++ b/tests/rules/test_no_reserved_folder_names.py @@ -1,6 +1,9 @@ # tests/rules/test_no_reserved_folder_names.py """Tests for the no-reserved-folder-names rule (extra).""" -from pytest_fsd.config import load_config +import pytest +from pytest_fsd._lib.fs_utils import STANDARD_SEGMENTS + +from pytest_fsd.config import FsdConfig, load_config from pytest_fsd.rules.no_reserved_folder_names import RULE_NAME, check @@ -55,3 +58,43 @@ def test_reserved_names_are_checked_inside_custom_segments(create_project): str(project_root / "src/features/auth/routing/api"), } assert all(v.rule == RULE_NAME for v in violations) + + +def test_reserved_names_ignore_hidden_and_cache_trees(create_project): + project_root = create_project( + '📂 features\n 📂 auth\n 📂 model\n 📂 .cache\n 📂 api\n' + ' 📂 __pycache__\n 📂 lib\n 📂 .cache\n 📂 ui\n' + ' 📂 .cache\n 📂 model\n 📂 api\n' + '📂 shared\n 📂 .cache\n 📂 ui\n' + ) + assert check(load_config(str(project_root)), str(project_root)) == [] + + +def test_reserved_names_custom_layers_and_file_traps(tmp_path): + expected = [] + for name in ('4_custom/auth/routing/api', '6_shared/i18n/deep/model', '0_app/model/api'): + path = tmp_path / 'src' / name + path.mkdir(parents=True) + if not name.startswith('0_app'): + expected.append(str(path)) + (tmp_path / 'src/4_custom/auth/routing/ui.py').touch() + assert {v.file_path for v in check(FsdConfig(layers=['0_app', '4_custom', '6_shared']), str(tmp_path))} == set(expected) + + +def test_private_packages_are_checked_for_reserved_subfolders(create_project): + project_root = create_project('📂 features\n 📂 _auth\n 📂 _routing\n 📂 _private\n 📂 api') + assert [v.file_path for v in check(load_config(str(project_root)), str(project_root))] == [ + str(project_root / 'src/features/_auth/_routing/_private/api') + ] + + +@pytest.mark.parametrize('name', STANDARD_SEGMENTS) +def test_every_reserved_name_is_directory_only(tmp_path, name): + parent = tmp_path / 'src/shared/lib' + parent.mkdir(parents=True) + path = parent / name + path.touch() + assert check(FsdConfig(), str(tmp_path)) == [] + path.unlink() + path.mkdir() + assert [v.file_path for v in check(FsdConfig(), str(tmp_path))] == [str(path)] diff --git a/tests/rules/test_no_segmentless_slices.py b/tests/rules/test_no_segmentless_slices.py index 9cf798f..c9c5430 100644 --- a/tests/rules/test_no_segmentless_slices.py +++ b/tests/rules/test_no_segmentless_slices.py @@ -1,5 +1,12 @@ -# tests/rules/test_no_segmentless_slices.py """Tests for the no-segmentless-slices rule.""" + +from pathlib import Path + +import pytest + +from pytest_fsd.config import FsdConfig + + from pytest_fsd.config import load_config from pytest_fsd.rules.no_segmentless_slices import RULE_NAME, check @@ -57,3 +64,57 @@ def test_no_segmentless_slices_checks_entry_types(create_project): str(project_root / "src/features/bare_file"), str(project_root / "src/features/suffixed_directory"), } + + +@pytest.mark.parametrize("base_path", ["src", "package/source", "."]) +@pytest.mark.parametrize("layer_name", ["features", "3_features", "custom"]) +def test_no_segmentless_slices_configured_roots_layers_and_depth(tmp_path, base_path, layer_name): + config = FsdConfig(base_path=base_path, layers=["0_app", layer_name, "6_shared"]) + source = tmp_path / base_path + layer = source / layer_name + layer.mkdir(parents=True) + + for name in ("empty", "nested_only", "valid_directory", "valid_file"): + (layer / name).mkdir() + (layer / "nested_only/deep/model").mkdir(parents=True) + (layer / "valid_directory/model").mkdir() + (layer / "valid_file/api.py").touch() + for exempt in ("0_app", "6_shared"): + (source / exempt / "empty").mkdir(parents=True) + assert {Path(v.file_path).name for v in check(config, str(tmp_path))} == {"empty", "nested_only"} + + +@pytest.mark.parametrize("name", ["_private", "__private", ".metadata", "__pycache__"]) +def test_no_segmentless_slices_private_packages_and_metadata(tmp_path, name): + config = FsdConfig() + slice_path = tmp_path / "src/features" / name + slice_path.mkdir(parents=True) + violations = check(config, str(tmp_path)) + if name in ("_private", "__private"): + assert [Path(v.file_path) for v in violations] == [slice_path] + else: + assert violations == [] + + +@pytest.mark.parametrize("segment", ["ui", "model", "api", "lib", "config"]) +@pytest.mark.parametrize("kind", ["file", "directory"]) +def test_no_segmentless_slices_all_standard_segment_forms(tmp_path, segment, kind): + config = FsdConfig() + slice_path = tmp_path / "src/features/auth" + slice_path.mkdir(parents=True) + if kind == "file": + (slice_path / (segment + ".py")).touch() + else: + (slice_path / segment).mkdir() + assert check(config, str(tmp_path)) == [] + + +@pytest.mark.parametrize("entry", ["missing_root", "file_root", "file_layer"]) +def test_no_segmentless_slices_absent_directories(tmp_path, entry): + config = FsdConfig() + if entry == "file_root": + (tmp_path / "src").touch() + elif entry == "file_layer": + (tmp_path / "src").mkdir() + (tmp_path / "src/features").touch() + assert check(config, str(tmp_path)) == [] diff --git a/tests/rules/test_no_segments_on_sliced_layers.py b/tests/rules/test_no_segments_on_sliced_layers.py index 2daec49..0cc10a3 100644 --- a/tests/rules/test_no_segments_on_sliced_layers.py +++ b/tests/rules/test_no_segments_on_sliced_layers.py @@ -1,5 +1,12 @@ -# tests/rules/test_no_segments_on_sliced_layers.py """Tests for the no-segments-on-sliced-layers rule.""" + +from pathlib import Path + +import pytest + +from pytest_fsd.config import FsdConfig + + from pytest_fsd.config import load_config from pytest_fsd.rules.no_segments_on_sliced_layers import RULE_NAME, check @@ -35,3 +42,31 @@ def test_no_segments_on_sliced_layers_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "ui" in violations[0].message + + +@pytest.mark.parametrize("base_path", ["src", "package/source", "."]) +@pytest.mark.parametrize("layer_name", ["features", "3_features", "custom"]) +def test_no_segments_on_sliced_layers_configured_roots_layers_and_depth(tmp_path, base_path, layer_name): + config = FsdConfig(base_path=base_path, layers=["0_app", layer_name, "6_shared"]) + source = tmp_path / base_path + layer = source / layer_name + layer.mkdir(parents=True) + + for name in ("ui", "model", "api", "lib", "config"): + (layer / name).mkdir() + (layer / "auth/ui").mkdir(parents=True) + (layer / "api.py").touch() + for exempt in ("0_app", "6_shared"): + (source / exempt / "ui").mkdir(parents=True) + assert {Path(v.file_path).name for v in check(config, str(tmp_path))} == {"ui", "model", "api", "lib", "config"} + + +@pytest.mark.parametrize("entry", ["missing_root", "file_root", "file_layer"]) +def test_no_segments_on_sliced_layers_absent_directories(tmp_path, entry): + config = FsdConfig() + if entry == "file_root": + (tmp_path / "src").touch() + elif entry == "file_layer": + (tmp_path / "src").mkdir() + (tmp_path / "src/features").touch() + assert check(config, str(tmp_path)) == [] diff --git a/tests/rules/test_public_api.py b/tests/rules/test_public_api.py index 3c2d135..058feed 100644 --- a/tests/rules/test_public_api.py +++ b/tests/rules/test_public_api.py @@ -1,3 +1,9 @@ +from pathlib import Path + +import pytest + +from pytest_fsd.config import FsdConfig + from pytest_fsd.config import load_config from pytest_fsd.rules.public_api import RULE_NAME, check @@ -102,3 +108,74 @@ def test_public_api_requires_a_file_not_a_directory(create_project): for path in ["features/auth", "shared/api", "shared/ui/button", "shared/lib/dates"] } assert all(v.rule == RULE_NAME for v in violations) + + +@pytest.mark.parametrize("base_path", ["src", "package/source", "."]) +@pytest.mark.parametrize("layer_name", ["features", "3_features", "custom"]) +def test_public_api_configured_roots_layers_and_depth(tmp_path, base_path, layer_name): + config = FsdConfig(base_path=base_path, layers=["0_app", layer_name, "6_shared"]) + source = tmp_path / base_path + layer = source / layer_name + layer.mkdir(parents=True) + + (layer / "missing").mkdir() + (layer / "valid/deep").mkdir(parents=True) + (layer / "valid/__init__.py").touch() + (source / "0_app/no_api").mkdir(parents=True) + (source / "6_shared/config").mkdir(parents=True) + (source / "6_shared/ui/button").mkdir(parents=True) + (source / "6_shared/lib/dates/deep").mkdir(parents=True) + (source / "6_shared/lib/dates/__init__.py").touch() + assert {Path(v.file_path).relative_to(source).as_posix() for v in check(config, str(tmp_path))} == { + layer_name + "/missing", "6_shared/config", "6_shared/ui/button" + } + + +@pytest.mark.parametrize("name", ["_private", "__private", ".metadata", "__pycache__"]) +def test_public_api_private_packages_and_metadata(tmp_path, name): + config = FsdConfig() + slice_path = tmp_path / "src/features" / name + slice_path.mkdir(parents=True) + violations = check(config, str(tmp_path)) + if name in ("_private", "__private"): + assert [Path(v.file_path) for v in violations] == [slice_path] + else: + assert violations == [] + + +@pytest.mark.parametrize("segment", ["api", "ui", "lib"]) +@pytest.mark.parametrize("name", ["_private", "__private", ".metadata", "__pycache__"]) +def test_public_api_shared_private_packages_and_metadata(tmp_path, segment, name): + config = FsdConfig() + package = tmp_path / "src/shared" / segment / name + package.mkdir(parents=True) + if segment == "api": + (package.parent / "__init__.py").touch() + violations = check(config, str(tmp_path)) + if segment in ("ui", "lib") and name in ("_private", "__private"): + assert [Path(v.file_path) for v in violations] == [package] + else: + assert violations == [] + + +@pytest.mark.parametrize("name", ["_private", "__private", ".metadata", "__pycache__"]) +def test_public_api_shared_segment_names(tmp_path, name): + config = FsdConfig() + segment = tmp_path / "src/shared" / name + segment.mkdir(parents=True) + violations = check(config, str(tmp_path)) + if name in ("_private", "__private"): + assert [Path(v.file_path) for v in violations] == [segment] + else: + assert violations == [] + + +@pytest.mark.parametrize("entry", ["missing_root", "file_root", "file_layer"]) +def test_public_api_absent_directories(tmp_path, entry): + config = FsdConfig() + if entry == "file_root": + (tmp_path / "src").touch() + elif entry == "file_layer": + (tmp_path / "src").mkdir() + (tmp_path / "src/features").touch() + assert check(config, str(tmp_path)) == [] diff --git a/tests/rules/test_repetitive_naming.py b/tests/rules/test_repetitive_naming.py index c241ab0..d3b59ca 100644 --- a/tests/rules/test_repetitive_naming.py +++ b/tests/rules/test_repetitive_naming.py @@ -1,6 +1,6 @@ # tests/rules/test_repetitive_naming.py """Tests for the repetitive-naming rule.""" -from pytest_fsd.config import load_config +from pytest_fsd.config import FsdConfig, load_config from pytest_fsd.rules.repetitive_naming import RULE_NAME, check @@ -47,3 +47,38 @@ def test_repetitive_naming_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "auth_handler.py" in violations[0].message + + +def test_repetitive_naming_prunes_hidden_and_cache_directories(create_project): + project_root = create_project( + '📂 features\n 📂 auth\n 📂 .cache\n 📄 auth_cached.py\n' + ' 📂 __pycache__\n 📄 auth_cached.py\n' + ' 📂 .auth\n 📄 .auth_model.py\n' + ) + assert check(load_config(str(project_root)), str(project_root)) == [] + + +def test_repetitive_naming_exact_prefix_and_layer_scope(tmp_path): + for layer in ('0_app', '4_custom', '6_shared'): + path = tmp_path / 'src' / layer / 'auth' / 'model' + path.mkdir(parents=True) + for name in ('auth.py', 'auth_handler.py', 'author.py', 'oauth.py', 'auth.txt', '__init__.py'): + (path / name).touch() + config = FsdConfig(layers=['0_app', '4_custom', '6_shared']) + violations = check(config, str(tmp_path)) + assert {v.file_path for v in violations} == { + str(tmp_path / 'src/4_custom/auth/model/auth.py'), + str(tmp_path / 'src/4_custom/auth/model/auth_handler.py'), + } + + +def test_private_slices_and_modules_are_still_checked(create_project): + project_root = create_project( + '📂 features\n 📂 _auth\n 📄 _auth_model.py\n' + ' 📂 auth\n 📂 _private\n 📄 auth_model.py\n' + ) + violations = check(load_config(str(project_root)), str(project_root)) + assert {v.file_path for v in violations} == { + str(project_root / 'src/features/_auth/_auth_model.py'), + str(project_root / 'src/features/auth/_private/auth_model.py'), + } diff --git a/tests/rules/test_segments_by_purpose.py b/tests/rules/test_segments_by_purpose.py index 9340d43..bd8cc8b 100644 --- a/tests/rules/test_segments_by_purpose.py +++ b/tests/rules/test_segments_by_purpose.py @@ -2,7 +2,10 @@ """Tests for the segments-by-purpose rule.""" from pathlib import Path -from pytest_fsd.config import load_config +import pytest +from pytest_fsd.rules.segments_by_purpose import BANNED_SEGMENT_NAMES + +from pytest_fsd.config import FsdConfig, load_config from pytest_fsd.rules.segments_by_purpose import RULE_NAME, check @@ -70,3 +73,29 @@ def test_segments_by_purpose_rejects_new_upstream_names(create_project): ) violations = check(load_config(str(project_root)), str(project_root)) assert {Path(v.file_path).name for v in violations} == {"validators", "fixtures.py"} + + +@pytest.mark.parametrize('name', sorted(BANNED_SEGMENT_NAMES)) +@pytest.mark.parametrize('as_file', [False, True]) +def test_all_banned_segment_names(tmp_path, name, as_file): + parent = tmp_path / 'src/custom/auth' + parent.mkdir(parents=True) + path = parent / (name + '.py' if as_file else name) + path.touch() if as_file else path.mkdir() + violations = check(FsdConfig(layers=['custom']), str(tmp_path)) + assert [v.file_path for v in violations] == [str(path)] + + +def test_segments_by_purpose_depth_and_layer_scope(tmp_path): + for name in ('0_app/helpers', '4_custom/auth/model/helpers', + '4_custom/.cache/helpers', '4_custom/__pycache__/helpers', + '6_shared/lib/helpers'): + (tmp_path / 'src' / name).mkdir(parents=True) + assert check(FsdConfig(layers=['0_app', '4_custom', '6_shared']), str(tmp_path)) == [] + + +def test_private_slice_segments_are_checked(create_project): + project_root = create_project('📂 features\n 📂 _auth\n 📂 utils') + assert [v.file_path for v in check(load_config(str(project_root)), str(project_root))] == [ + str(project_root / 'src/features/_auth/utils') + ] diff --git a/tests/rules/test_shared_lib_grouping.py b/tests/rules/test_shared_lib_grouping.py index 6552804..2090c44 100644 --- a/tests/rules/test_shared_lib_grouping.py +++ b/tests/rules/test_shared_lib_grouping.py @@ -1,6 +1,8 @@ # tests/rules/test_shared_lib_grouping.py """Tests for the shared-lib-grouping rule (extra).""" -from pytest_fsd.config import load_config +import pytest + +from pytest_fsd.config import FsdConfig, load_config from pytest_fsd.rules.shared_lib_grouping import RULE_NAME, check @@ -44,3 +46,31 @@ def test_shared_lib_grouping_violation(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "16 ungrouped files" in violations[0].message + + +@pytest.mark.parametrize('count', [14, 15, 16]) +def test_shared_lib_grouping_boundaries_and_file_types(tmp_path, count): + path = tmp_path / 'src/6_shared/lib' + path.mkdir(parents=True) + for i in range(count): + (path / ('module_%s.py' % i)).touch() + (path / '__init__.py').touch() + (path / 'module.py').mkdir() + (path / 'notes.txt').touch() + nested = path / 'nested' + nested.mkdir() + for i in range(20): + (nested / ('nested_%s.py' % i)).touch() + violations = check(FsdConfig(layers=['6_shared']), str(tmp_path)) + assert [v.file_path for v in violations] == ([str(path)] if count == 16 else []) + + +def test_shared_lib_private_modules_count_but_other_layers_do_not(tmp_path): + for layer in ('0_app', '4_custom', '6_shared'): + lib = tmp_path / 'src' / layer / 'lib' + lib.mkdir(parents=True) + for i in range(16): + (lib / ('_module_%s.py' % i)).touch() + violations = check(FsdConfig(layers=['0_app', '4_custom', '6_shared']), str(tmp_path)) + assert [v.file_path for v in violations] == [str(tmp_path / 'src/6_shared/lib')] + assert check(FsdConfig(layers=['0_app', '4_custom']), str(tmp_path)) == [] diff --git a/tests/rules/test_typo_in_layer_name.py b/tests/rules/test_typo_in_layer_name.py index b155493..1584256 100644 --- a/tests/rules/test_typo_in_layer_name.py +++ b/tests/rules/test_typo_in_layer_name.py @@ -1,6 +1,6 @@ # tests/rules/test_typo_in_layer_name.py """Tests for the typo-in-layer-name rule.""" -from pytest_fsd.config import load_config +from pytest_fsd.config import FsdConfig, load_config from pytest_fsd.rules.typo_in_layer_name import RULE_NAME, check @@ -40,3 +40,26 @@ def test_typo_in_layer_name_typo(create_project): assert len(violations) == 1 assert violations[0].rule == RULE_NAME assert "fietures" in violations[0].message + + +def test_typo_names_configured_ignored_hidden_and_files(tmp_path): + root = tmp_path / 'source' + root.mkdir() + for name in ('0_app', 'custom', '6_shared', 'scripts', '.hidden', '__pycache__', 'fietures'): + (root / name).mkdir() + (root / 'unknown.py').touch() + config = FsdConfig(base_path='source', layers=['0_app', 'custom', '6_shared'], ignore_paths=['scripts']) + assert [v.file_path for v in check(config, str(tmp_path))] == [str(root / 'fietures')] + + +def test_ignoring_top_level_name_does_not_ignore_other_names(tmp_path): + (tmp_path / 'src/migrations').mkdir(parents=True) + violations = check(FsdConfig(ignore_paths=['scripts']), str(tmp_path)) + assert [v.file_path for v in violations] == [str(tmp_path / 'src/migrations')] + + +def test_private_top_level_directory_needs_configuration(tmp_path): + path = tmp_path / 'src/_custom' + path.mkdir(parents=True) + assert [v.file_path for v in check(FsdConfig(), str(tmp_path))] == [str(path)] + assert check(FsdConfig(ignore_paths=['_custom']), str(tmp_path)) == [] diff --git a/tests/test_audit_guards.py b/tests/test_audit_guards.py new file mode 100644 index 0000000..7ee42c5 --- /dev/null +++ b/tests/test_audit_guards.py @@ -0,0 +1,104 @@ +"""Guard regressions found during the complete rule audit.""" + +import ast +from pathlib import Path + +import pytest + +from pytest_fsd import validate_fsd_architecture +from pytest_fsd._lib.ast_utils import get_exported_names +from pytest_fsd.config import load_config + + +@pytest.mark.parametrize('code', [ + "alias = __all__\nalias.append('hidden')\n", + "configure(__all__)\n", + "def mutate():\n __all__[0] = 'hidden'\nmutate()\n", + "def mutate():\n alias = __all__\n alias.clear()\nmutate()\n", + "exec(\"__all__.clear()\")\n", +]) +def test_mutable_exports_cannot_prove_api_names(tmp_path, code): + file = tmp_path / '__init__.py' + file.write_text("__all__ = ['safe']\n" + code, encoding='utf-8') + assert get_exported_names(str(file)) is None + + +def test_later_fresh_exports_restore_static_knowledge(tmp_path): + file = tmp_path / '__init__.py' + file.write_text("__all__ = ['safe']\nconfigure(__all__)\n__all__ = ['fresh']\n", encoding='utf-8') + assert get_exported_names(str(file)) == ['fresh'] + + +def test_root_tool_value_must_be_a_table(tmp_path): + (tmp_path / 'pyproject.toml').write_text('tool = 42\n', encoding='utf-8') + with pytest.raises(ValueError, match='pytest_fsd'): + load_config(str(tmp_path)) + + +def test_unreadable_source_root_reports_incomplete_scan(tmp_path, monkeypatch): + source = tmp_path / 'src' + source.mkdir() + import os + original = os.scandir + + def blocked(path): + if Path(path) == source: + raise PermissionError(13, 'denied', str(source)) + return original(path) + + monkeypatch.setattr(os, 'scandir', blocked) + with pytest.raises(AssertionError, match='python-source'): + validate_fsd_architecture(str(tmp_path)) + + +def test_parser_recursion_failure_cannot_turn_into_success(tmp_path, monkeypatch): + file = tmp_path / 'src/features/account/model/source.py' + file.parent.mkdir(parents=True) + file.write_text('value = 1\n', encoding='utf-8') + + def too_deep(*args, **kwargs): + raise RecursionError('source too deep') + + monkeypatch.setattr(ast, 'parse', too_deep) + with pytest.raises(AssertionError, match='python-source'): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize('path', ['.cache', '__pycache__']) +def test_metadata_does_not_count_as_uninspectable_python(tmp_path, path): + file = tmp_path / 'src/shared' / path / 'broken.py' + file.parent.mkdir(parents=True) + file.write_text('from broken import (\n', encoding='utf-8') + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize('name', ['inconsistent-naming', 'import-locality', 'insignificant-slice', 'no-processes']) +def test_documentary_rule_pages_are_not_silent_extra_rules(tmp_path, name): + (tmp_path / 'pyproject.toml').write_text('[tool.pytest_fsd]\nextra_rules = ["' + name + '"]\n', encoding='utf-8') + with pytest.raises(ValueError, match='Unknown pytest_fsd extra_rules'): + load_config(str(tmp_path)) + + +def test_configured_layer_cannot_be_reserved_metadata(tmp_path): + (tmp_path / 'pyproject.toml').write_text('[tool.pytest_fsd]\nlayers = ["__pycache__"]\n', encoding='utf-8') + with pytest.raises(ValueError, match='reserved metadata'): + load_config(str(tmp_path)) + + +def test_configured_layer_file_is_an_incomplete_scan(tmp_path): + source = tmp_path / 'src' + source.mkdir() + (source / 'features').write_text('value = 1\n', encoding='utf-8') + with pytest.raises(AssertionError, match='python-source'): + validate_fsd_architecture(str(tmp_path)) + + +@pytest.mark.parametrize('code', [ + "def expose():\n return __all__\nexpose().append('hidden')\n", + "__all__ = alias = ['safe']\nalias.append('hidden')\n", + "__all__, other = (['different'], None)\n", +]) +def test_indirect_export_rebindings_do_not_reuse_stale_names(tmp_path, code): + file = tmp_path / '__init__.py' + file.write_text("__all__ = ['safe']\n" + code, encoding='utf-8') + assert get_exported_names(str(file)) is None diff --git a/tests/test_import_rule_audit.py b/tests/test_import_rule_audit.py new file mode 100644 index 0000000..c9e119b --- /dev/null +++ b/tests/test_import_rule_audit.py @@ -0,0 +1,239 @@ +"""Boundary regressions for the complete import-rule audit.""" + +import pytest + +from pytest_fsd.config import FsdConfig +from pytest_fsd.rules import ( + forbidden_imports, + no_cross_imports, + no_public_api_sidestep, + no_ui_in_app, + no_wildcard_exports, +) + + +def project(tmp_path, files, base="backend/src", layers=None): + for name, source in files.items(): + path = tmp_path / base / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(source, encoding="utf-8") + return FsdConfig(base_path=base, layers=layers or ["app", "features", "entities", "shared"]) + + +@pytest.mark.parametrize("target,api", [ + ("shared/config/settings", "shared/config"), + ("shared/lib/dates/internal", "shared/lib/dates"), + ("shared/ui/button/internal", "shared/ui/button"), +]) +@pytest.mark.parametrize("form", ["absolute", "relative", "dynamic", "exec"]) +def test_shared_implementation_imports_require_public_boundary(tmp_path, target, api, form): + module = target.replace("/", ".") + statements = { + "absolute": "from backend.src." + module + " import hidden", + "relative": "from .." + module + " import hidden", + "dynamic": "import importlib\nimportlib.import_module('backend.src." + module + "')", + "exec": "exec(\"from backend.src." + module + " import hidden\")", + } + statement = statements[form] + config = project(tmp_path, { + "app/start.py": statement + "\n", + api + "/__init__.py": "__all__ = ['visible']\n", + target + ".py": "hidden = 1\n", + }) + violations = no_public_api_sidestep.check(config, str(tmp_path)) + assert len(violations) == 1 + assert violations[0].rule == "no-public-api-sidestep" + assert "Importing internal module" in violations[0].message + assert violations[0].line_number == (2 if form == "dynamic" else 1) + assert violations[0].column_number == 1 + + +@pytest.mark.parametrize("api", ["shared/config", "shared/lib/dates", "shared/ui/button", "entities/user"]) +@pytest.mark.parametrize("exports", ["__all__ = ['visible']", "__all__ = []", ""]) +def test_public_boundary_export_names(tmp_path, api, exports): + module = "backend.src." + api.replace("/", ".") + config = project(tmp_path, { + "app/start.py": "from " + module + " import visible\n", + api + "/__init__.py": exports + "\n", + }) + violations = no_public_api_sidestep.check(config, str(tmp_path)) + assert len(violations) == (0 if "['visible']" in exports else 1) + + +@pytest.mark.parametrize("api", ["shared/config", "shared/lib/dates", "shared/ui/button", "entities/user"]) +@pytest.mark.parametrize("form", ["import", "from-parent", "from-own"]) +def test_public_packages_and_own_boundary_remain_allowed(tmp_path, api, form): + module = "backend.src." + api.replace("/", ".") + parent, name = module.rsplit(".", 1) + statements = { + "import": "import " + module, + "from-parent": "from " + parent + " import " + name, + "from-own": "from .internal import hidden", + } + source_path = api + "/source.py" if form == "from-own" else "app/start.py" + config = project(tmp_path, { + source_path: statements[form] + "\n", + api + "/__init__.py": "__all__ = []\n", + api + "/internal.py": "hidden = 1\n", + }) + assert no_public_api_sidestep.check(config, str(tmp_path)) == [] + + +@pytest.mark.parametrize("module", ["shared.lib.dates", "shared.ui.button"]) +def test_shared_standalone_modules_are_public_apis(tmp_path, module): + config = project(tmp_path, { + "app/start.py": "from backend.src." + module + " import visible\n", + module.replace(".", "/") + ".py": "visible = 1\n", + }) + assert no_public_api_sidestep.check(config, str(tmp_path)) == [] + + +def test_prefixed_shared_boundaries_and_sibling_libraries(tmp_path): + config = project(tmp_path, { + "6_shared/lib/one/source.py": "__import__('backend.src.6_shared.lib.two.internal')\n", + "6_shared/lib/one/__init__.py": "__all__ = []\n", + "6_shared/lib/two/__init__.py": "__all__ = []\n", + "6_shared/lib/two/internal.py": "hidden = 1\n", + }, layers=["1_app", "4_features", "5_entities", "6_shared"]) + # Numeric-prefixed layers are importable through programmatic loaders. + assert len(no_public_api_sidestep.check(config, str(tmp_path))) == 1 + + +@pytest.mark.parametrize("path", ["other/source.py", "__init__.py", ".cache/source.py"]) +def test_unconfigured_sources_do_not_trigger_public_api_rule(tmp_path, path): + config = project(tmp_path, { + path: "from backend.src.entities.user.internal import hidden\n", + "entities/user/internal.py": "hidden = 1\n", + }) + assert no_public_api_sidestep.check(config, str(tmp_path)) == [] + + +@pytest.mark.parametrize("rule", [forbidden_imports, no_cross_imports]) +@pytest.mark.parametrize("prefix", ["backend.src.", "src.", ""]) +@pytest.mark.parametrize("dynamic", [False, True]) +def test_layer_and_slice_boundaries_with_nested_roots(tmp_path, rule, prefix, dynamic): + module = prefix + "features.other" + statement = "__import__('" + module + "')" if dynamic else "from " + module + " import visible" + path = "shared/lib/start.py" if rule is forbidden_imports else "features/own/__init__.py" + config = project(tmp_path, {path: statement + "\n", "features/other/__init__.py": "__all__ = ['visible']\n"}) + violations = rule.check(config, str(tmp_path)) + assert violations + assert all(v.line_number == 1 and v.column_number == 1 for v in violations) + + +@pytest.mark.parametrize("framework", sorted(no_ui_in_app.FORBIDDEN_UI_MODULES)) +@pytest.mark.parametrize("dynamic", [False, True]) +def test_gui_frameworks_in_prefixed_app(tmp_path, framework, dynamic): + statement = "__import__('" + framework + ".widgets')" if dynamic else "from " + framework + " import Widget" + config = project(tmp_path, {"1_app/start.py": statement + "\n"}, layers=["1_app", "6_shared"]) + violations = no_ui_in_app.check(config, str(tmp_path)) + assert len(violations) == 1 + assert framework in violations[0].message + assert violations[0].line_number == 1 + + +@pytest.mark.parametrize("rule,path,source", [ + (no_public_api_sidestep, "features/own/.cache/source.py", "from backend.src.entities.user.internal import hidden\n"), + (no_ui_in_app, "app/.cache/source.py", "import tkinter\n"), + (no_wildcard_exports, "entities/user/.cache/__init__.py", "from external import *\n"), +]) +def test_ignored_directories_are_not_scanned(tmp_path, rule, path, source): + config = project(tmp_path, {path: source, "entities/user/internal.py": "hidden = 1\n"}) + assert rule.check(config, str(tmp_path)) == [] + + +@pytest.mark.parametrize("source", ["from .internal import *\n", "exec('from .internal import *')\n", "__import__('external', fromlist=['*'])\n"]) +def test_wildcard_apis_static_and_dynamic_boundaries(tmp_path, source): + config = project(tmp_path, {"shared/lib/dates/__init__.py": source}) + violations = no_wildcard_exports.check(config, str(tmp_path)) + assert len(violations) == 1 + assert violations[0].line_number == 1 + assert violations[0].column_number == 1 + + +@pytest.mark.parametrize("exports", [ + "__all__ = ['visible']\nexports = __all__\nexports.append('hidden')\n", + "__all__ = ['visible']\nexports = __all__\nexports.clear()\n", + "__all__ = ['visible']\ndef mutate():\n __all__.clear()\nmutate()\n", + "__all__ = ['visible']\nconfigure(__all__)\n", +]) +def test_escaped_export_lists_do_not_prove_public_names(tmp_path, exports): + config = project(tmp_path, { + "app/start.py": "from backend.src.entities.user import visible\n", + "entities/user/__init__.py": exports, + }) + violations = no_public_api_sidestep.check(config, str(tmp_path)) + assert len(violations) == 1 + assert "does not define `__all__`" in violations[0].message + + +@pytest.mark.parametrize("rule,path,source", [ + (forbidden_imports, "shared/_private/source.py", "from backend.src.features.other import visible\n"), + (no_cross_imports, "features/_private/source.py", "from backend.src.features.other import visible\n"), + (no_public_api_sidestep, "app/_private/source.py", "from backend.src.entities.user.internal import hidden\n"), + (no_ui_in_app, "app/_private/source.py", "import tkinter\n"), + (no_wildcard_exports, "entities/_private/__init__.py", "from external import *\n"), +]) +def test_private_python_packages_remain_in_scope(tmp_path, rule, path, source): + config = project(tmp_path, { + path: source, + "entities/user/internal.py": "hidden = 1\n", + "features/other/__init__.py": "__all__ = ['visible']\n", + }) + assert rule.check(config, str(tmp_path)) + + +def test_public_api_recommendation_with_source_root_itself(tmp_path): + config = project(tmp_path, { + "app/start.py": "from entities.user.internal import hidden\n", + "entities/user/internal.py": "hidden = 1\n", + }, base=".") + violations = no_public_api_sidestep.check(config, str(tmp_path)) + assert len(violations) == 1 + assert "Import from 'entities.user' instead." in violations[0].message + + +def test_cross_import_reports_each_sibling_boundary_once(tmp_path): + config = project(tmp_path, { + "features/own/source.py": "from backend.src.features.other import model, api\n", + "features/other/__init__.py": "__all__ = ['model', 'api']\n", + "features/other/model.py": "", + "features/other/api.py": "", + }) + violations = no_cross_imports.check(config, str(tmp_path)) + assert len(violations) == 1 + assert "features/other" in violations[0].message + + +def test_cross_import_preserves_distinct_sibling_boundaries(tmp_path): + config = project(tmp_path, { + "features/own/source.py": "from backend.src.features import other, another\n", + "features/other/__init__.py": "", + "features/another/__init__.py": "", + }) + violations = no_cross_imports.check(config, str(tmp_path)) + assert len(violations) == 2 + assert any("features/other" in v.message for v in violations) + assert any("features/another" in v.message for v in violations) + + +@pytest.mark.parametrize("rule,path", [ + (forbidden_imports, "6_shared/lib/source.py"), + (no_cross_imports, "4_features/own/source.py"), +]) +def test_numeric_layer_names_in_dynamic_import_boundaries(tmp_path, rule, path): + config = project(tmp_path, { + path: "__import__('backend.src.4_features.other')\n", + "4_features/other/__init__.py": "", + }, layers=["1_app", "4_features", "5_entities", "6_shared"]) + violations = rule.check(config, str(tmp_path)) + assert len(violations) == 1 + assert violations[0].line_number == 1 + + +def test_layer_rank_uses_configured_order(tmp_path): + config = project(tmp_path, { + "shared/lib/source.py": "from backend.src.features.other import visible\n", + "features/other/__init__.py": "__all__ = ['visible']\n", + }, layers=["shared", "features"]) + assert forbidden_imports.check(config, str(tmp_path)) == [] diff --git a/tests/test_rule_contracts.py b/tests/test_rule_contracts.py new file mode 100644 index 0000000..5fe9be3 --- /dev/null +++ b/tests/test_rule_contracts.py @@ -0,0 +1,53 @@ +"""Every shipped rule must have an effective negative and positive witness.""" + +import pytest +import pytest_fsd + +from rule_contracts import ALL_NAMES, CORE_NAMES, EXTRA_NAMES, check_case, verify_registry + + +def test_every_registered_rule_has_an_explicit_contract(): + verify_registry() + + +@pytest.mark.parametrize('name', ALL_NAMES) +def test_rule_contract(name, tmp_path): + check_case(name, tmp_path) + + +@pytest.mark.parametrize('name', sorted(CORE_NAMES | EXTRA_NAMES)) +def test_contract_detects_noop_rule_mutation(name, tmp_path, monkeypatch): + modules = {module.RULE_NAME: module for module in pytest_fsd.CORE_RULES} + modules.update(pytest_fsd.EXTRA_RULES) + monkeypatch.setattr(modules[name], 'check', lambda *args: []) + with pytest.raises(AssertionError, match='Direct check did not execute ' + name): + check_case(name, tmp_path) + + +@pytest.mark.parametrize('name', sorted(CORE_NAMES)) +def test_contract_detects_missing_core_dispatch(name, tmp_path, monkeypatch): + # Leave the direct checker available while disconnecting it from the facade. + original = list(pytest_fsd.CORE_RULES) + module = next(module for module in original if module.RULE_NAME == name) + monkeypatch.setattr(pytest_fsd, 'CORE_RULES', [m for m in original if m is not module]) + import rule_contracts + monkeypatch.setattr(rule_contracts, 'registry', lambda: {m.RULE_NAME: m for m in original}) + with pytest.raises(AssertionError, match='Facade did not execute ' + name): + check_case(name, tmp_path) + + +@pytest.mark.parametrize('name', sorted(EXTRA_NAMES)) +def test_contract_detects_missing_extra_dispatch(name, tmp_path, monkeypatch): + import rule_contracts + modules = rule_contracts.registry() + monkeypatch.setattr(pytest_fsd, 'EXTRA_RULES', {key: value for key, value in pytest_fsd.EXTRA_RULES.items() if key != name}) + monkeypatch.setattr(rule_contracts, 'registry', lambda: modules) + with pytest.raises(AssertionError, match='Facade did not execute ' + name): + check_case(name, tmp_path) + + +@pytest.mark.parametrize('name', ['python-source', 'dynamic-imports']) +def test_contract_detects_missing_input_guard(name, tmp_path, monkeypatch): + monkeypatch.setattr(pytest_fsd, 'check_sources', lambda *args: []) + with pytest.raises(AssertionError, match='Facade did not execute ' + name): + check_case(name, tmp_path) diff --git a/uv.lock b/uv.lock index 8fabee2..85a3a33 100644 --- a/uv.lock +++ b/uv.lock @@ -177,7 +177,7 @@ wheels = [ [[package]] name = "pytest-fsd" -version = "0.6.0" +version = "0.7.0" source = { editable = "." } dependencies = [ { name = "tomli", marker = "python_full_version < '3.11'" },