diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ca5e451..852fa5b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,7 +14,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: ["3.14"] + python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13", "3.14"] steps: - uses: actions/checkout@v4 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..6943438 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Nikita Lebedev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 9a0279a..f71dd27 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,14 @@ -[🇷🇺 Читать на русском](README.ru.md) +[Русская версия](README.ru.md) # pytest-fsd -**FSD Architecture Validation for Python Projects.** +[![PyPI](https://img.shields.io/pypi/v/pytest-fsd)](https://pypi.org/project/pytest-fsd/) +[![Python](https://img.shields.io/pypi/pyversions/pytest-fsd)](https://pypi.org/project/pytest-fsd/) +[![CI](https://github.com/Horcag/pytest-fsd/actions/workflows/ci.yml/badge.svg)](https://github.com/Horcag/pytest-fsd/actions/workflows/ci.yml) -`pytest-fsd` automatically checks your Python project's architecture for compliance with the [Feature-Sliced Design](https://feature-sliced.design/) methodology. +Validate [Feature-Sliced Design (FSD)](https://feature-sliced.design/) architecture in a Python project using pytest. The rules are adapted from the [Steiger FSD plugin](https://github.com/feature-sliced/steiger), with Python-specific checks where appropriate. This is an independent Python package, not an official Steiger port. -It uses a hybrid approach: dynamic checks via [pytest-archon](https://pypi.org/project/pytest-archon/) + static AST analysis + file structure verification. - -## Installation +## Install ```bash pip install pytest-fsd @@ -16,147 +16,68 @@ pip install pytest-fsd uv add --dev pytest-fsd ``` -## Usage +Python 3.8–3.14 is supported. + +## Use -### 1. Configure `pyproject.toml` +Add the layers used by your project, from highest to lowest, to `pyproject.toml`: ```toml [tool.pytest_fsd] base_path = "src" -layers = ["app", "windows", "widgets", "features", "entities", "shared"] +layers = ["app", "pages", "widgets", "features", "entities", "shared"] +# ignore_paths = ["my_non_fsd_package"] ``` -### 2. Create a test +Create an architecture test: ```python # tests/test_architecture.py from pytest_fsd import validate_fsd_architecture -def test_project_architecture(): + +def test_architecture(): validate_fsd_architecture() ``` -### 3. Run - -```bash -pytest tests/test_architecture.py -vv -``` +Run `pytest tests/test_architecture.py`. Violations appear as assertion failures with a rule name and path. If your source root is different, set `base_path` accordingly. The validator reads `[tool.pytest_fsd]` from the project root; `validate_fsd_architecture(project_root="...")` can target another project. -## Library Architecture +## Rules -Each rule is a folder inside `src/pytest_fsd/rules//` containing: +The default checks cover layer import direction (`forbidden-imports`), slice independence (`no-cross-imports`), public APIs (`public-api`, `no-public-api-sidestep`, `no-layer-public-api`), structure (`no-segmentless-slices`, `no-segments-on-sliced-layers`, `typo-in-layer-name`, `ambiguous-slice-names`), naming (`segments-by-purpose`, `repetitive-naming`), and `no-ui-in-app`. -- `__init__.py` — verification logic (the function `check(config, project_root) -> List[Violation]`) -- `README.md` — rule description, examples, and rationale +`segments-by-purpose` includes the generic names added in Steiger's FSD plugin 0.7.0, such as `schemas`, `handlers`, `fixtures`, `middlewares`, `validators`, `resolvers`, `mutations`, and `assets`. These names are checked when used as FSD segments. Python `fixtures.py` in a slice is also flagged because this package checks file segments as well as directories. -``` -src/pytest_fsd/ - __init__.py # Facade: validate_fsd_architecture() - config.py # Reads [tool.pytest_fsd] from pyproject.toml - _lib/ # Shared utilities - violations.py # Unified Violation dataclass - ast_utils.py # AST parsing for imports - fs_utils.py # File utilities, segment constants - rules/ - forbidden_imports/ # pytest-archon: layers only import from layers below - no_cross_imports/ # pytest-archon: slices within the same layer are independent - no_public_api_sidestep/ # AST: importing from another slice is only allowed via its __init__.py - no_layer_public_api/ # FS: layer folders must not contain __init__.py - no_ui_in_app/ # AST: forbids importing UI frameworks directly into app - repetitive_naming/ # FS: files do not duplicate the slice name - no_segmentless_slices/ # FS: a slice must contain at least one standard segment - segments_by_purpose/ # FS: forbids utils/helpers/components/hooks - ambiguous_slice_names/ # FS: slice names must not match segment names in shared - no_segments_on_sliced_layers/ # FS: sliced layers must not contain segments directly - public_api/ # FS: every slice must have an __init__.py -``` +`no-ui-in-app` rejects an `app/ui` directory, as in Steiger. It also retains the Python-specific check for direct imports of common desktop GUI frameworks from the app layer. ---- - -## Steiger Rules Coverage Matrix - -Full list of rules from the [Steiger FSD Plugin](https://github.com/feature-sliced/steiger) and their status in `pytest-fsd`: - -| # | Steiger Rule | pytest-fsd Status | Description | -| --- | ----------------------------------------------- | ---------------------- | ----------------------------------------------------------------------------------------- | -| 1 | `forbidden-imports` / `no-higher-level-imports` | ✅ **Complete** | Layers only import from layers below them | -| 2 | `no-cross-imports` | ✅ **Complete** | Slices within the same layer are independent of each other | -| 3 | `no-public-api-sidestep` | ✅ **Complete** | Importing from another slice is only allowed via `__init__.py` | -| 4 | `public-api` | ✅ **Complete** | Every slice and shared segment must have an `__init__.py` | -| 5 | `no-layer-public-api` | ✅ **Complete** | Layer folders (`features/`, `entities/`) must not contain `__init__.py` | -| 6 | `segments-by-purpose` | ✅ **Complete** | Forbids `utils`, `helpers`, `hooks`, `components`, `modals`, `types`, `constants`, etc. | -| 7 | `no-segmentless-slices` | ✅ **Complete** | A slice must contain at least one standard segment | -| 8 | `repetitive-naming` | ✅ **Complete** | Files do not duplicate the slice name (`user/user_model.py` → `user/model.py`) | -| 9 | `no-ui-in-app` | ✅ **Complete** | The `app` layer must not import UI frameworks | -| 10 | `ambiguous-slice-names` | ✅ **Complete** | Slice names must not match segment names in `shared/` | -| 11 | `no-segments-on-sliced-layers` | ✅ **Complete** | Sliced layers do not have direct segment folders | -| 12 | `inconsistent-naming` | 🔶 **Ruff** | Enforced by the `N` (pep8-naming) plugin in `Ruff` | -| 13 | `import-locality` | 🔶 **Ruff** | Enforced by the `TID` (flake8-tidy-imports) plugin in `Ruff` | -| 14 | `typo-in-layer-name` | ✅ **Complete** | Forbids unknown layer folders (e.g., `fietures` instead of `features`) in the root | -| 15 | `no-processes` | 🔶 **Configuration** | The `processes` layer is deprecated; simply do not include it in `layers` | -| 16 | `excessive-slicing` | ⚡ **Optional** | More than 20 slices in one layer (threshold: 20) | -| 17 | `insignificant-slice` | 🟡 **Manual check** | Requires import graph analysis to determine "insignificant" slices | -| 18 | `no-file-segments` | ⚡ **Optional** | A segment as a file (`model.py`) instead of a folder (`model/`) | -| 19 | `shared-lib-grouping` | ⚡ **Optional** | More than 15 ungrouped files in `shared/lib` | -| 20 | `no-reserved-folder-names` | ⚡ **Optional** | Subfolders in segments must not match segment names | - -### Legend - -| Status | Meaning | -| -------------------------- | --------------------------------------------------------------------------------------------------- | -| ✅ **Complete** | The rule is fully automated and runs every time `pytest` is executed | -| ⚡ **Optional** | The rule is automated but is enabled via `extra_rules` in `pyproject.toml` | -| 🔶 **Ruff / Configuration** | Covered by external tools (`Ruff`) or `pyproject.toml` configuration | -| 🟡 **Manual check** | Requires subjective evaluation or complex analysis better suited for manual code review | - ---- - -## Enabling Optional Rules - -Add to `pyproject.toml`: +Enable additional checks only when they suit your project: ```toml [tool.pytest_fsd] base_path = "src" -layers = ["app", "windows", "widgets", "features", "entities", "shared"] +layers = ["app", "pages", "widgets", "features", "entities", "shared"] extra_rules = [ - "excessive-slicing", # ≤ 20 slices per layer - "shared-lib-grouping", # ≤ 15 files in shared/lib - "no-file-segments", # Segments must be folders, not files - "no-reserved-folder-names" # Segment subfolders cannot be named ui/model/api/lib/config + "excessive-slicing", # More than 20 slices per layer + "shared-lib-grouping", # More than 15 loose Python files in shared/lib + "no-file-segments", # Segments must be directories + "no-reserved-folder-names", # No nested segment names such as model/model ] ``` -Each rule is described in detail in `src/pytest_fsd/rules//README.md`. - ---- - -## Configuring Ruff for Related Rules - -For full coverage of FSD rules that Steiger checks at the linting level (which `pytest-fsd` does not duplicate), add to `pyproject.toml`: - -```toml -[tool.ruff.lint] -select = ["N", "TID"] - -[tool.ruff.lint.flake8-tidy-imports] -ban-relative-imports = "parents" -``` +`no-file-segments` is a Python package option; it is not registered as a rule in Steiger FSD plugin 0.7.0. `no-cross-imports` is enabled here for compatibility, whereas the upstream plugin does not enable it by default. These choices are intentionally different from Steiger. -| Ruff Plugin | Steiger Rule | What it checks | -| --------------------------- | --------------------- | ----------------------------------------------- | -| `N` (pep8-naming) | `inconsistent-naming` | `snake_case` for modules, variables, functions | -| `TID` (flake8-tidy-imports) | `import-locality` | Forbids relative imports from parent packages | +See the [rule documentation](src/pytest_fsd/rules/) for examples and details. -Detailed descriptions and configuration examples: `src/pytest_fsd/rules/inconsistent_naming/README.md` and `src/pytest_fsd/rules/import_locality/README.md`. +## Scope and limitations -## Known Limitations +- `forbidden-imports` and `no-cross-imports` use [pytest-archon](https://pypi.org/project/pytest-archon/). Imports guarded by `if TYPE_CHECKING:` are invisible to these runtime checks. +- `no-public-api-sidestep` analyzes Python syntax and explicit `__all__` lists. Dynamically assembled exports may be reported incorrectly. +- Steiger's `inconsistent-naming` and `import-locality` have no direct equivalent here. Consider Ruff's `N` and `TID` rules for Python naming and relative imports; their behavior is not identical to Steiger's rules. +- Steiger's `insignificant-slice` needs an import graph and is not implemented. The deprecated `processes` layer is not created by this package; omit it from `layers`. +- This package checks Python files and filesystem structure. It does not implement every Steiger rule or every JavaScript-specific convention. -- **`TYPE_CHECKING` imports**: Rules using `pytest-archon` (e.g., `forbidden-imports` and `no-cross-imports`) work based on dynamic import graph analysis at runtime. Imports inside `if TYPE_CHECKING:` blocks are not executed when the module loads and are therefore **not visible to these rules**. -- **Relative imports**: The `ast_utils.py` module supports relative paths for checking `no-public-api-sidestep`, however, `Ruff` (the `TID` plugin) is still better at controlling relative imports outside of slices. -- **Dynamic `__all__`**: The `no-public-api-sidestep` rule uses static AST analysis to extract `__all__` from the `__init__.py` file. If the export list is formed dynamically (e.g., `__all__ = a + b`), the static analyzer will not be able to read it, and the tool may yield false positive violations. Exports in `__all__` must be defined as an explicit list or tuple. -- **Minimum Python Version**: The library supports Python **3.8+**. For Python `<3.11`, backward compatibility is provided via the `tomli` package, and on Python `3.11+` the built-in `tomllib` is used. +See the [upstream FSD plugin changelog](https://github.com/feature-sliced/steiger/blob/master/packages/steiger-plugin-fsd/CHANGELOG.md) for Steiger's release history. ## License -MIT \ No newline at end of file +MIT. See [LICENSE](LICENSE). diff --git a/README.ru.md b/README.ru.md index 5195256..bf18070 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,12 +1,12 @@ -[🇬🇧 Read in English](README.md) +[English](README.md) # pytest-fsd -**FSD Architecture Validation for Python Projects.** +[![PyPI](https://img.shields.io/pypi/v/pytest-fsd)](https://pypi.org/project/pytest-fsd/) +[![Python](https://img.shields.io/pypi/pyversions/pytest-fsd)](https://pypi.org/project/pytest-fsd/) +[![CI](https://github.com/Horcag/pytest-fsd/actions/workflows/ci.yml/badge.svg)](https://github.com/Horcag/pytest-fsd/actions/workflows/ci.yml) -`pytest-fsd` автоматически проверяет архитектуру вашего Python-проекта на соответствие методологии [Feature-Sliced Design](https://feature-sliced.design/). - -Использует гибридный подход: динамические проверки через [pytest-archon](https://pypi.org/project/pytest-archon/) + статический AST-анализ + проверка файловой структуры. +Проверка архитектуры Python-проекта по [Feature-Sliced Design (FSD)](https://feature-sliced.design/) через pytest. Правила адаптированы из [FSD-плагина Steiger](https://github.com/feature-sliced/steiger); там, где необходимо, добавлены проверки для Python. Это самостоятельный пакет, а не официальный порт Steiger. ## Установка @@ -16,147 +16,68 @@ pip install pytest-fsd uv add --dev pytest-fsd ``` +Поддерживается Python 3.8–3.14. + ## Использование -### 1. Настройка `pyproject.toml` +Укажите слои проекта в `pyproject.toml` от верхнего к нижнему: ```toml [tool.pytest_fsd] base_path = "src" -layers = ["app", "windows", "widgets", "features", "entities", "shared"] +layers = ["app", "pages", "widgets", "features", "entities", "shared"] +# ignore_paths = ["my_non_fsd_package"] ``` -### 2. Создание теста +Создайте архитектурный тест: ```python # tests/test_architecture.py from pytest_fsd import validate_fsd_architecture -def test_project_architecture(): + +def test_architecture(): validate_fsd_architecture() ``` -### 3. Запуск - -```bash -pytest tests/test_architecture.py -vv -``` +Запустите `pytest tests/test_architecture.py`. Нарушения выводятся как ошибки теста с именем правила и путём. Если исходный код лежит в другом каталоге, измените `base_path`. Валидатор читает `[tool.pytest_fsd]` из корня проекта; параметр `validate_fsd_architecture(project_root="...")` позволяет проверить другой проект. -## Архитектура библиотеки +## Правила -Каждое правило — это папка внутри `src/pytest_fsd/rules//` с: +По умолчанию проверяются направление импортов между слоями (`forbidden-imports`), независимость слайсов (`no-cross-imports`), публичные API (`public-api`, `no-public-api-sidestep`, `no-layer-public-api`), структура (`no-segmentless-slices`, `no-segments-on-sliced-layers`, `typo-in-layer-name`, `ambiguous-slice-names`), именование (`segments-by-purpose`, `repetitive-naming`) и `no-ui-in-app`. -- `__init__.py` — логика проверки (функция `check(config, project_root) -> List[Violation]`) -- `README.md` — описание правила, примеры, rationale +`segments-by-purpose` включает общие имена из FSD-плагина Steiger 0.7.0: `schemas`, `handlers`, `fixtures`, `middlewares`, `validators`, `resolvers`, `mutations`, `assets` и другие. Они проверяются в роли FSD-сегментов. Пакет также проверяет сегменты-файлы, поэтому `fixtures.py` внутри слайса будет отмечен. -``` -src/pytest_fsd/ - __init__.py # Фасад: validate_fsd_architecture() - config.py # Чтение [tool.pytest_fsd] из pyproject.toml - _lib/ # Общие утилиты - violations.py # Единый Violation dataclass - ast_utils.py # AST-парсинг импортов - fs_utils.py # Файловые утилиты, константы сегментов - rules/ - forbidden_imports/ # pytest-archon: слои импортируют только нижележащие - no_cross_imports/ # pytest-archon: слайсы в одном слое независимы - no_public_api_sidestep/ # AST: импорт только через __init__.py слайса - no_layer_public_api/ # FS: слоевые папки без __init__.py - no_ui_in_app/ # AST: запрет UI-фреймворков в app - repetitive_naming/ # FS: файлы не дублируют имя слайса - no_segmentless_slices/ # FS: слайс содержит хотя бы один сегмент - segments_by_purpose/ # FS: запрет utils/helpers/components/hooks - ambiguous_slice_names/ # FS: имена слайсов ≠ имена сегментов shared - no_segments_on_sliced_layers/ # FS: в слайсовых слоях не должно быть сегментов напрямую - public_api/ # FS: каждый слайс должен иметь __init__.py -``` +`no-ui-in-app` запрещает каталог `app/ui`, как и Steiger. Дополнительно сохранена Python-проверка прямых импортов распространённых GUI-библиотек из слоя `app`. ---- - -## Матрица покрытия правил Steiger - -Полный список правил из [Steiger FSD Plugin](https://github.com/feature-sliced/steiger) и их статус в `pytest-fsd`: - -| # | Steiger Rule | pytest-fsd Status | Описание | -| --- | ----------------------------------------------- | ---------------------- | -------------------------------------------------------------------------------------- | -| 1 | `forbidden-imports` / `no-higher-level-imports` | ✅ **Полностью** | Слои импортируют только нижележащие слои | -| 2 | `no-cross-imports` | ✅ **Полностью** | Слайсы в одном слое независимы друг от друга | -| 3 | `no-public-api-sidestep` | ✅ **Полностью** | Импорт из чужого слайса только через `__init__.py` | -| 4 | `public-api` | ✅ **Полностью** | Каждый слайс и сегмент shared обязан иметь `__init__.py` | -| 5 | `no-layer-public-api` | ✅ **Полностью** | Папки слоев (`features/`, `entities/`) не должны содержать `__init__.py` | -| 6 | `segments-by-purpose` | ✅ **Полностью** | Запрет `utils`, `helpers`, `hooks`, `components`, `modals`, `types`, `constants` и др. | -| 7 | `no-segmentless-slices` | ✅ **Полностью** | Слайс обязан содержать хотя бы один стандартный сегмент | -| 8 | `repetitive-naming` | ✅ **Полностью** | Файлы не дублируют имя слайса (`user/user_model.py` → `user/model.py`) | -| 9 | `no-ui-in-app` | ✅ **Полностью** | Слой `app` не должен импортировать UI-фреймворки | -| 10 | `ambiguous-slice-names` | ✅ **Полностью** | Имена слайсов не совпадают с сегментами `shared/` | -| 11 | `no-segments-on-sliced-layers` | ✅ **Полностью** | В слайсовых слоях нет прямых папок-сегментов | -| 12 | `inconsistent-naming` | 🔶 **Ruff** | Обеспечивается плагином `N` (pep8-naming) в `Ruff` | -| 13 | `import-locality` | 🔶 **Ruff** | Обеспечивается плагином `TID` (flake8-tidy-imports) в `Ruff` | -| 14 | `typo-in-layer-name` | ✅ **Полностью** | Запрет неизвестных папок (например, `fietures` вместо `features`) в корне | -| 15 | `no-processes` | 🔶 **Конфигурация** | Слой `processes` deprecated; просто не включайте его в `layers` | -| 16 | `excessive-slicing` | ⚡ **Опционально** | Более 20 слайсов в одном слое (порог: 20) | -| 17 | `insignificant-slice` | 🟡 **Ручная проверка** | Требует анализа графа импортов для определения "незначительных" слайсов | -| 18 | `no-file-segments` | ⚡ **Опционально** | Сегмент как файл (`model.py`) вместо папки (`model/`) | -| 19 | `shared-lib-grouping` | ⚡ **Опционально** | Более 15 файлов в `shared/lib` без группировки | -| 20 | `no-reserved-folder-names` | ⚡ **Опционально** | Подпапки в сегментах не должны совпадать с именами сегментов | - -### Легенда - -| Статус | Значение | -| -------------------------- | --------------------------------------------------------------------------------------------------- | -| ✅ **Полностью** | Правило полностью автоматизировано и выполняется при каждом запуске `pytest` | -| ⚡ **Опционально** | Правило автоматизировано, но включается через `extra_rules` в `pyproject.toml` | -| 🔶 **Ruff / Конфигурация** | Покрывается внешними инструментами (`Ruff`) или конфигурацией `pyproject.toml` | -| 🟡 **Ручная проверка** | Требует субъективной оценки или сложного анализа, который лучше производить вручную при code review | - ---- - -## Включение дополнительных правил - -Добавьте в `pyproject.toml`: +При необходимости включите дополнительные проверки: ```toml [tool.pytest_fsd] base_path = "src" -layers = ["app", "windows", "widgets", "features", "entities", "shared"] +layers = ["app", "pages", "widgets", "features", "entities", "shared"] extra_rules = [ - "excessive-slicing", # ≤ 20 слайсов на слой - "shared-lib-grouping", # ≤ 15 файлов в shared/lib - "no-file-segments", # Сегменты должны быть папками, не файлами - "no-reserved-folder-names" # Подпапки сегментов не могут называться ui/model/api/lib/config + "excessive-slicing", # Более 20 слайсов в слое + "shared-lib-grouping", # Более 15 отдельных Python-файлов в shared/lib + "no-file-segments", # Сегменты должны быть каталогами + "no-reserved-folder-names", # Без вложенных имён сегментов вроде model/model ] ``` -Каждое правило подробно описано в `src/pytest_fsd/rules//README.md`. - ---- - -## Настройка Ruff для смежных правил - -Для полного покрытия FSD-правил, которые Steiger проверяет на уровне линтинга (и которые `pytest-fsd` не дублирует), добавьте в `pyproject.toml`: - -```toml -[tool.ruff.lint] -select = ["N", "TID"] - -[tool.ruff.lint.flake8-tidy-imports] -ban-relative-imports = "parents" -``` +`no-file-segments` — опция этого Python-пакета: в реестре правил FSD-плагина Steiger 0.7.0 она отсутствует. `no-cross-imports` здесь по умолчанию включено для совместимости, а в Steiger по умолчанию отключено. Это осознанные различия. -| Ruff Plugin | Steiger Rule | Что проверяет | -| --------------------------- | --------------------- | ----------------------------------------------- | -| `N` (pep8-naming) | `inconsistent-naming` | `snake_case` для модулей, переменных, функций | -| `TID` (flake8-tidy-imports) | `import-locality` | Запрет relative imports из родительских пакетов | +Примеры и подробности находятся в [документации правил](src/pytest_fsd/rules/). -Подробные описания и примеры конфигурации: `src/pytest_fsd/rules/inconsistent_naming/README.md` и `src/pytest_fsd/rules/import_locality/README.md`. +## Ограничения -## Известные ограничения (Known Limitations) +- `forbidden-imports` и `no-cross-imports` используют [pytest-archon](https://pypi.org/project/pytest-archon/). Импорты под `if TYPE_CHECKING:` не видны этим проверкам во время выполнения. +- `no-public-api-sidestep` анализирует синтаксис Python и явные списки `__all__`. Динамически собранные экспорты могут давать ложные срабатывания. +- Прямых аналогов Steiger `inconsistent-naming` и `import-locality` здесь нет. Для именования Python и относительных импортов можно использовать правила Ruff `N` и `TID`; их поведение не совпадает полностью с правилами Steiger. +- `insignificant-slice` требует анализа графа импортов и не реализовано. Устаревший слой `processes` пакет не создаёт — не указывайте его в `layers`. +- Пакет проверяет Python-файлы и структуру каталогов. Он не реализует все правила Steiger и все соглашения JavaScript. -- **`TYPE_CHECKING` импорты**: Правила, использующие `pytest-archon` (например, `forbidden-imports` и `no-cross-imports`), работают на базе динамического анализа графа импортов в рантайме. Импорты, находящиеся внутри блоков `if TYPE_CHECKING:`, не выполняются при загрузке модуля и, следовательно, **не видны для этих правил**. -- **Относительные импорты**: В модуле `ast_utils.py` добавлена поддержка относительных путей для проверки `no-public-api-sidestep`, однако `Ruff` (плагин `TID`) всё равно лучше справляется с контролем относительных импортов за пределами слайсов. -- **Динамический `__all__`**: Правило `no-public-api-sidestep` использует статический AST-анализ для извлечения `__all__` из файла `__init__.py`. Если список экспортов формируется динамически (например, `__all__ = a + b`), статический анализатор не сможет его прочитать, и инструмент может выдать ложноположительные нарушения. Экспорты в `__all__` должны быть заданы как явный список или кортеж. -- **Минимальная версия Python**: Библиотека поддерживает Python **3.8+**. Для Python `<3.11` используется обратная совместимость через пакет `tomli`, а на Python `3.11+` — встроенный `tomllib`. +История выпусков Steiger — в [журнале изменений FSD-плагина](https://github.com/feature-sliced/steiger/blob/master/packages/steiger-plugin-fsd/CHANGELOG.md). ## Лицензия -MIT +MIT. См. [LICENSE](LICENSE). diff --git a/pyproject.toml b/pyproject.toml index d5ac12f..8a82834 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,23 +1,27 @@ [project] name = "pytest-fsd" -version = "0.2.1" -description = "Feature-Sliced Design (FSD) architecture validation plugin for pytest" +version = "0.3.0" +description = "Validate Feature-Sliced Design architecture in Python projects with pytest" +keywords = ["feature-sliced-design", "fsd", "architecture", "pytest", "python", "steiger"] readme = "README.md" authors = [ { name = "Lebedev Nikita", email = "rachet337@gmail.com" } ] requires-python = ">=3.8" -license = { text = "MIT" } +license = "MIT" +license-files = ["LICENSE"] classifiers = [ "Development Status :: 4 - Beta", "Framework :: Pytest", "Intended Audience :: Developers", - "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Software Development :: Quality Assurance", "Topic :: Software Development :: Testing", ] dependencies = [ diff --git a/src/pytest_fsd/_lib/fs_utils.py b/src/pytest_fsd/_lib/fs_utils.py index 1201b11..0936a75 100644 --- a/src/pytest_fsd/_lib/fs_utils.py +++ b/src/pytest_fsd/_lib/fs_utils.py @@ -3,7 +3,7 @@ import os import re -from typing import List +from typing import List, Optional from ..config import FsdConfig @@ -17,7 +17,7 @@ def get_canonical_layer(layer_name: str) -> str: return re.sub(r"^[0-9_]+", "", layer_name) -def get_layer_by_canonical_name(config: FsdConfig, name: str) -> str | None: +def get_layer_by_canonical_name(config: FsdConfig, name: str) -> Optional[str]: """Find the actual layer name in config that matches the canonical name.""" for layer in config.layers: if get_canonical_layer(layer) == name: 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 2ab4221..5516f5a 100644 --- a/src/pytest_fsd/rules/no_ui_in_app/README.md +++ b/src/pytest_fsd/rules/no_ui_in_app/README.md @@ -1,38 +1,17 @@ # `no-ui-in-app` -Forbid direct imports of UI frameworks in the `app` layer. +Reject an `app/ui` directory. This matches the [Steiger FSD rule](https://github.com/feature-sliced/steiger/tree/master/packages/steiger-plugin-fsd/src/no-ui-in-app): the app layer should configure and compose the application, while UI components belong in pages or widgets. -The `app` layer is meant for application initialization: providers, routing, store configuration. UI components should live in `pages`, `windows`, or `widgets` layers. +This Python package also rejects direct imports of these desktop GUI modules anywhere under `app`: `tkinter`, `PyQt5`, `PyQt6`, `PySide2`, `PySide6`, `ttkbootstrap`, and `customtkinter`. This extra check is specific to `pytest-fsd`. -> [!NOTE] -> This rule is currently focused on **Desktop GUI frameworks**. For web frameworks (like FastAPI, Django) where the UI layer might be structured differently or absent (API-only), this rule's default checks may not apply directly. - -## Checked UI frameworks - -`tkinter`, `PyQt5`, `PyQt6`, `PySide2`, `PySide6`, `ttkbootstrap`, `customtkinter` - -## Examples - -✅ Pass: - -```python -# src/app/main.py -from src.pages.main import MainPage # OK: app uses a page, doesn't build UI itself - -app = MainPage() -app.mainloop() +```text +src/app/ui/ # violation +src/pages/home/ui/ # allowed ``` -❌ Fail: - ```python # src/app/main.py -import tkinter as tk # ❌ UI framework in app layer - -root = tk.Tk() -root.mainloop() +import tkinter # violation in pytest-fsd ``` -## Rationale - -Mixing initialization logic with UI creation leads to monolithic app layers. UI components should be decomposed into slices in appropriate layers like `pages` or `widgets`. +The import check looks at static `import` and `from ... import ...` syntax. It does not detect dynamic imports or every possible GUI framework. 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 6c825e2..db3dc7c 100644 --- a/src/pytest_fsd/rules/no_ui_in_app/__init__.py +++ b/src/pytest_fsd/rules/no_ui_in_app/__init__.py @@ -1,9 +1,5 @@ # src/pytest_fsd/rules/no_ui_in_app/__init__.py -""" -[Rule: no-ui-in-app] -The app layer should not directly import UI frameworks. -UI components belong in pages/windows/widgets layers. -""" +"""Reject app/ui and direct GUI framework imports in the app layer.""" import ast import os @@ -39,6 +35,16 @@ def check(config: FsdConfig, project_root: str) -> List[Violation]: if not os.path.isdir(app_path): return violations + ui_path = os.path.join(app_path, "ui") + if os.path.isdir(ui_path): + violations.append( + Violation( + rule=RULE_NAME, + file_path=ui_path, + message="Segment 'app/ui' is not allowed. Put UI components in pages or widgets.", + ) + ) + for root, _, files in os.walk(app_path): for file in files: if not file.endswith(".py"): diff --git a/src/pytest_fsd/rules/segments_by_purpose/README.md b/src/pytest_fsd/rules/segments_by_purpose/README.md index 771dec3..811537c 100644 --- a/src/pytest_fsd/rules/segments_by_purpose/README.md +++ b/src/pytest_fsd/rules/segments_by_purpose/README.md @@ -1,38 +1,13 @@ # `segments-by-purpose` -Discourage the use of segment names that group code by its essence, and instead encourage grouping by purpose. +FSD segment names should describe their purpose (`ui`, `model`, `api`, `lib`, `config`) rather than the kind of item inside them. The check covers direct children of slices and direct children of `shared`; it also checks `.py` files acting as segments. -## Banned segment names - -`utils`, `util`, `helpers`, `helper`, `hooks`, `hook`, `modals`, `modal`, `components`, `component`, `types`, `type`, `interfaces`, `interface`, `containers`, `container`, `services`, `service`, `constants`, `consts`, `const` - -## Examples - -✅ Pass: - -``` -📂 shared/ - 📂 ui/ - 📂 lib/ -📂 entities/ - 📂 user/ - 📂 ui/ - 📂 model/ -``` - -❌ Fail: - -``` -📂 shared/ - 📂 utils/ # ❌ - 📂 helpers/ # ❌ - 📂 hooks/ # ❌ -📂 entities/ - 📂 user/ - 📂 components/ # ❌ - 📂 model/ +```text +src/features/auth/validators/ # violation +src/features/auth/fixtures.py # violation +src/features/auth/model/ # allowed ``` -## Rationale +The forbidden names include generic names from [Steiger FSD plugin 0.7.0](https://github.com/feature-sliced/steiger/blob/master/packages/steiger-plugin-fsd/src/segments-by-purpose/index.ts), such as `components`, `helpers`, `utils`, `types`, `services`, `stores`, `schemas`, `handlers`, `fixtures`, `middlewares`, `validators`, `resolvers`, `mutations`, and `assets`, including their singular forms. The existing Python port also checks `hook(s)` and `container(s)`. Framework-specific JavaScript terms are not all copied into this Python rule. -Segments group code by **technical purpose**. Folder names like `components` sound like they only contain UI components, but there are other things that affect UI (formatters, browser API hooks, etc.) that share the same purpose. `hooks` is an abstract concept — it doesn't tell anything about what the function does. `utils` and `helpers` risk becoming a dumping ground for unrelated code. +A `fixtures` directory outside the configured FSD layers is not checked. diff --git a/src/pytest_fsd/rules/segments_by_purpose/__init__.py b/src/pytest_fsd/rules/segments_by_purpose/__init__.py index c5d51e0..d93dc39 100644 --- a/src/pytest_fsd/rules/segments_by_purpose/__init__.py +++ b/src/pytest_fsd/rules/segments_by_purpose/__init__.py @@ -35,8 +35,37 @@ "services", "service", "constants", + "constant", "consts", "const", + "stores", + "store", + "functions", + "function", + "classes", + "class", + "enums", + "enum", + "decorators", + "decorator", + "schemas", + "schema", + "handlers", + "handler", + "fixtures", + "fixture", + "middlewares", + "middleware", + "validators", + "validator", + "validations", + "validation", + "resolvers", + "resolver", + "mutations", + "mutation", + "assets", + "asset", } diff --git a/tests/rules/test_no_ui_in_app.py b/tests/rules/test_no_ui_in_app.py index 1879bab..2b755c3 100644 --- a/tests/rules/test_no_ui_in_app.py +++ b/tests/rules/test_no_ui_in_app.py @@ -62,3 +62,17 @@ def test_no_ui_in_app_from_import(create_project): violations = check(config, str(project_root)) assert len(violations) == 1 assert "PyQt6" in violations[0].message + + +def test_no_ui_in_app_rejects_ui_segment(create_project): + project_root = create_project( + """ + 📂 app + 📂 ui + 📄 __init__.py + """ + ) + violations = check(load_config(str(project_root)), str(project_root)) + assert len(violations) == 1 + assert violations[0].rule == RULE_NAME + assert "app/ui" in violations[0].message diff --git a/tests/rules/test_segments_by_purpose.py b/tests/rules/test_segments_by_purpose.py index 59bf750..9340d43 100644 --- a/tests/rules/test_segments_by_purpose.py +++ b/tests/rules/test_segments_by_purpose.py @@ -1,5 +1,7 @@ # tests/rules/test_segments_by_purpose.py """Tests for the segments-by-purpose rule.""" +from pathlib import Path + from pytest_fsd.config import load_config from pytest_fsd.rules.segments_by_purpose import RULE_NAME, check @@ -55,3 +57,16 @@ def test_segments_by_purpose_banned_in_shared(create_project): violations = check(config, str(project_root)) assert len(violations) == 1 assert "helpers" in violations[0].message + + +def test_segments_by_purpose_rejects_new_upstream_names(create_project): + project_root = create_project( + """ + 📂 features + 📂 auth + 📂 validators + 📄 fixtures.py + """ + ) + violations = check(load_config(str(project_root)), str(project_root)) + assert {Path(v.file_path).name for v in violations} == {"validators", "fixtures.py"} diff --git a/uv.lock b/uv.lock index 28217cd..a0d0b8c 100644 --- a/uv.lock +++ b/uv.lock @@ -22,7 +22,7 @@ version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "typing-extensions", version = "4.13.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" }, - { name = "typing-extensions", version = "4.15.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.9' and python_full_version < '3.13'" }, + { name = "typing-extensions", version = "4.16.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.9' and python_full_version < '3.13'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -56,11 +56,27 @@ wheels = [ [[package]] name = "packaging" -version = "26.0" +version = "26.2" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/65/ee/299d360cdc32edc7d2cf530f3accf79c4fca01e96ffc950d8a52213bd8e4/packaging-26.0.tar.gz", hash = "sha256:00243ae351a257117b6a241061796684b084ed1c516a08c48a3f7e147a9d80b4", size = 143416, upload-time = "2026-01-21T20:50:39.064Z" } +resolution-markers = [ + "python_full_version < '3.9'", +] +sdist = { url = "https://files.pythonhosted.org/packages/d7/f1/e7a6dd94a8d4a5626c03e4e99c87f241ba9e350cd9e6d75123f992427270/packaging-26.2.tar.gz", hash = "sha256:ff452ff5a3e828ce110190feff1178bb1f2ea2281fa2075aadb987c2fb221661", size = 228134, upload-time = "2026-04-24T20:15:23.917Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.10'", + "python_full_version == '3.9.*'", +] +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/b7/b9/c538f279a4e237a006a2c98387d081e9eb060d203d8ed34467cc0f0b9b53/packaging-26.0-py3-none-any.whl", hash = "sha256:b36f1fef9334a5588b4166f8bcd26a14e521f2b55e6b9de3aaa80d3ff7a37529", size = 74366, upload-time = "2026-01-21T20:50:37.788Z" }, + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, ] [[package]] @@ -90,11 +106,11 @@ wheels = [ [[package]] name = "pygments" -version = "2.19.2" +version = "2.21.0" source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/b0/77/a5b8c569bf593b0140bde72ea885a803b82086995367bf2037de0159d924/pygments-2.19.2.tar.gz", hash = "sha256:636cb2477cec7f8952536970bc533bc43743542f70392ae026374600add5b887", size = 4968631, upload-time = "2025-06-21T13:39:12.283Z" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" }, + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, ] [[package]] @@ -108,7 +124,7 @@ dependencies = [ { name = "colorama", marker = "python_full_version < '3.9' and sys_platform == 'win32'" }, { name = "exceptiongroup", marker = "python_full_version < '3.9'" }, { name = "iniconfig", version = "2.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" }, - { name = "packaging", marker = "python_full_version < '3.9'" }, + { name = "packaging", version = "26.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" }, { name = "pluggy", version = "1.5.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.9'" }, { name = "tomli", marker = "python_full_version < '3.9'" }, ] @@ -130,7 +146,7 @@ dependencies = [ { name = "exceptiongroup", marker = "python_full_version >= '3.9' and python_full_version < '3.11'" }, { name = "iniconfig", version = "2.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.9.*'" }, { name = "iniconfig", version = "2.3.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.10'" }, - { name = "packaging", marker = "python_full_version >= '3.9'" }, + { name = "packaging", version = "26.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.9'" }, { name = "pluggy", version = "1.6.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.9'" }, { name = "pygments", marker = "python_full_version >= '3.9'" }, { name = "tomli", marker = "python_full_version >= '3.9' and python_full_version < '3.11'" }, @@ -155,7 +171,7 @@ wheels = [ [[package]] name = "pytest-fsd" -version = "0.2.0" +version = "0.3.0" source = { editable = "." } dependencies = [ { name = "pytest-archon" }, @@ -245,13 +261,13 @@ wheels = [ [[package]] name = "typing-extensions" -version = "4.15.0" +version = "4.16.0" source = { registry = "https://pypi.org/simple" } resolution-markers = [ "python_full_version >= '3.10'", "python_full_version == '3.9.*'", ] -sdist = { url = "https://files.pythonhosted.org/packages/72/94/1a15dd82efb362ac84269196e94cf00f187f7ed21c242792a923cdb1c61f/typing_extensions-4.15.0.tar.gz", hash = "sha256:0cea48d173cc12fa28ecabc3b837ea3cf6f38c6d1136f85cbaaf598984861466", size = 109391, upload-time = "2025-08-25T13:49:26.313Z" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/18/67/36e9267722cc04a6b9f15c7f3441c2363321a3ea07da7ae0c0707beb2a9c/typing_extensions-4.15.0-py3-none-any.whl", hash = "sha256:f0fa19c6845758ab08074a0cfa8b7aecb71c999ca73d62883bc25cc018c4e548", size = 44614, upload-time = "2025-08-25T13:49:24.86Z" }, + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ]