pytest-archon

raw JSON →
0.0.7 verified Fri May 01 auth: no python

pytest-archon is a pytest plugin for enforcing architectural boundaries in Python projects. It allows you to define rules that prevent certain imports between modules, ensuring layering and dependency direction. Current version: 0.0.7. Release cadence: infrequent, no set schedule.

pip install pytest-archon
error ModuleNotFoundError: No module named 'pytest_archon'
cause pytest-archon is not installed or not installed in the current virtual environment.
fix
Run 'pip install pytest-archon' to install the package.
error TypeError: archrule() missing 1 required positional argument: 'package'
cause The archrule function requires the package name as the first argument.
fix
Use archrule('myapp.services') with a string argument.
error AttributeError: 'ArchRule' object has no attribute 'should_not_import'
cause The import is wrong: you imported ArchRule directly, but the correct usage is calling the archrule function.
fix
Use 'from pytest_archon import archrule' and then call archrule() to get the rule builder.
gotcha The archrule pattern strings are matched as substring matches by default; use precise package names to avoid false positives.
fix Use exact package/module names, e.g., 'myapp.services' not 'services'.
gotcha The .check() method scans the entire project from the given root, which may be slow on large codebases.
fix Restrict the scope by passing a subdirectory path or a list of modules to check.
gotcha Rules are defined as test functions; they are executed with other pytest tests. Ensure your architecture tests are collected and run.
fix Ensure the test file is in a test directory (e.g., tests/) and follows pytest naming conventions.

Define an architecture rule that prevents the 'services' package from importing 'ui' or 'db' packages in the 'myapp' project.

import pytest
from pytest_archon import archrule

def test_import_rule():
    (
        archrule("myapp.services")
        .should_not_import("myapp.ui")
        .should_not_import("myapp.db")
        .check("myapp")
    )