ArchUnitPython - Architecture Testing
Enforce architecture rules in Python projects. Check for dependency directions, detect circular dependencies, enforce coding standards and much more. Integrates with pytest and any other testing framework. Very simple setup and pipeline integration. Zero runtime dependencies.
The #1 ArchUnit-style architecture testing library for Python, measured by GitHub stars.
Inspired by the amazing ArchUnit library but we are not affiliated with ArchUnit.
Setup • Use Cases • Features • Why ArchUnitPython? • Sponsor • Contributing • Documentation
⚡ 5 min Quickstart
Installation
pip install archunitpython
Choose the import root: Pass the directory containing your top-level Python
packages to project_files(...) and metrics(...). If import taskboard refers
to src/taskboard/, use "src"; if taskboard/ is at the repository root, use
".". This tells ArchUnitPython where to scan and how to resolve your imports.
Omitting the argument uses the current working directory; it does not
automatically discover a src/ layout. Details and examples.
Add tests
Simply add tests to your existing test suites. The following is an example using pytest. First we ensure that we have no circular dependencies.
from archunitpython import project_files, metrics, assert_passes
def test_no_circular_dependencies():
rule = project_files("src/").should().have_no_cycles()
assert_passes(rule)
Next we ensure that our layered architecture is respected.
def test_presentation_should_not_depend_on_database():
rule = (
project_files("src/")
.in_folder("**/presentation/**")
.should_not()
.depend_on_files()
.in_folder("**/database/**")
)
assert_passes(rule)
def test_business_should_not_depend_on_database():
rule = (
project_files("src/")
.in_folder("**/business/**")
.should_not()
.depend_on_files()
.in_folder("**/database/**")
)
assert_passes(rule)
# More layers ...
Lastly we ensure that some code metric rules are met.
def test_no_large_files():
rule = metrics("src/").count().lines_of_code().should_be_below(1000)
assert_passes(rule)
def test_high_cohesion():
# LCOM metric (lack of cohesion of methods), low = high cohesion
rule = metrics("src/").lcom().lcom96b().should_be_below(0.3)
assert_passes(rule)
CI Integration
These tests run automatically in your testing setup, for example in your CI pipeline, so that's basically it. This setup ensures that the architectural rules you have defined are always adhered to!
# GitHub Actions
- name: Run Architecture Tests
run: pytest tests/test_architecture.py -v
You can also export dependency graph reports as CI artifacts:
from archunitpython import project_graph
def test_generate_dependency_graph_reports():
graph = project_graph("src/").titled("Application Architecture")
graph.collapse_to_folder_depth(2).export_as_html(
"reports/dependency-graph.html"
)
graph.export_as_mermaid("reports/dependency-graph.mmd")
assert graph.snapshot().summary.node_count >= 0
🚐 Setup
Installation:
pip install archunitpython
That's it. Works with pytest, unittest, or any Python testing framework.
Choosing the import root
The optional project_path argument to project_files(...), metrics(...),
project_layers(...), project_slices(...), and project_graph(...) selects the
directory to analyze. Choose the directory containing your top-level Python
packages so absolute imports can be resolved within that directory. Relative
paths are interpreted from the current working directory; omitting the argument
uses that working directory.
For example, suppose your repository contains:
my_repo/
src/
taskboard/
__init__.py
application/board_service.py
domain/task.py
tests/test_architecture.py
An import such as from taskboard.domain.task import Task names
taskboard/domain/task.py underneath src/. It does not include src in the
import name. Run your tests from my_repo/ and use:
from archunitpython import assert_passes, metrics, project_files
def test_no_cycles():
rule = project_files("src").should().have_no_cycles()
assert_passes(rule)
def test_no_large_files():
rule = metrics("src").count().lines_of_code().should_be_below(1000)
assert_passes(rule)
The directory name itself has no special meaning:
| Package location, relative to your working directory |
Import name |
Argument |
src/taskboard/ |
taskboard |
"src" |
taskboard/ |
taskboard |
"." |
backend/taskboard/ |
taskboard |
"backend" |
Selectors such as .in_path("**/domain/**") and .in_folder(...) narrow which
files a rule checks. They do not change the import root. For example,
project_files().in_path("src/**") can select files under src/ while still
resolving absolute imports from the repository root. Set project_files("src")
first, then add selectors if you need to narrow the rule.
With the wrong root, imports between your own modules can be classified as
external, causing cycle and internal-dependency rules to miss violations and
dependency-based metrics to report incorrect values. The root also determines
which files are included in metric measurements. ArchUnitPython does not infer a
src/ import root from pyproject.toml or your Python environment; pass it
explicitly for this layout.
🎬 Demo
https://github.com/user-attachments/assets/56f2ad65-a2e1-4965-b84d-445cf7bf4cd2
Testing Framework
pytest (Recommended)
Use assert_passes() for clean assertion messages:
from archunitpython import project_files, assert_passes
def test_my_architecture():
rule = project_files("src/").should().have_no_cycles()
assert_passes(rule)
Any Other Framework
Use .check() directly and assert on the violations list:
from archunitpython import project_files
rule = project_files("src/").should().have_no_cycles()
violations = rule.check()
assert len(violations) == 0
Configuration Options
Both assert_passes() and .check() accept configuration options:
from archunitpython import CheckOptions
options = CheckOptions(
allow_empty_tests=True, # Don't fail when no files match
clear_cache=True, # Clear the graph cache
ignore_type_checking_imports=True, # Ignore imports inside if TYPE_CHECKING
)
violations = rule.check(options)
Excluding Files With .archignore
Add a .archignore file to your project root to permanently exclude generated or
irrelevant files from architecture checks and file-based metrics:
# Generated code
generated/
# Migration scripts
migrations/*.py
# A single root-level file
/legacy_adapter.py
Patterns support comments, blank lines, glob syntax, root-relative paths, path
patterns, and directory patterns with a trailing /.
Loading Common Rules From Config
For straightforward shared rules, you can load a JSON config file and still run
the resulting rules in your normal test suite:
{
"project_path": "src",
"rules": [
{
"name": "controllers must not use services directly",
"type": "forbidden_dependency",
"source": "**/controllers/**",
"target": "**/services/**"
},
{
"name": "source files have no cycles",
"type": "no_cycles"
}
]
}
from archunitpython import assert_passes, rules_from_config
def test_configured_architecture_rules():
for rule in rules_from_config("archunitpython.json"):
assert_passes(rule)
Supported rule types are no_cycles, forbidden_dependency, and
forbidden_external_dependency. The fluent Python API remains the primary and
most flexible interface.
Explaining Rules With .because(...)
Attach a rationale to a rule so failing assertions explain why the rule exists:
rule = (
project_files("src/")
.in_folder("**/controllers/**")
.should_not()
.depend_on_files()
.in_folder("**/database/**")
.because("controllers should stay thin and delegate persistence")
)
assert_passes(rule)
When the rule fails, the rationale is included in the assertion message.
🐹 Use Cases
Here is an overview of common use cases.
Layered Architecture:
Enforce that higher layers don't depend on lower layers and vice versa.
Clean Architecture / Hexagonal:
Validate that domain logic doesn't depend on infrastructure.
Microservices / Modular:
Ensure services/modules don't have forbidden cross-dependencies.
🐲 Example Repository
Here is a repository with a fully functioning example that uses ArchUnitPython to ensure architectural rules:
🐣 Features
This is an overview of what you can do with ArchUnitPython.
Circular Dependencies
def test_services_cycle_free():
rule = project_files("src/").in_folder("**/services/**").should().have_no_cycles()
assert_passes(rule)
Layer Dependencies
def test_clean_architecture_layers():
rule = (
project_files("src/")
.in_folder("**/presentation/**")
.should_not()
.depend_on_files()
.in_folder("**/database/**")
)
assert_passes(rule)
def test_business_not_depend_on_presentation():
rule = (
project_files("src/")
.in_folder("**/business/**")
.should_not()
.depend_on_files()
.in_folder("**/presentation/**")
)
assert_passes(rule)
Named Layer Rules
from archunitpython import project_layers
def test_clean_architecture_layers():
rule = (
project_layers("src/")
.layer("presentation").defined_by_folder("**/presentation/**")
.layer("business").defined_by_folder("**/business/**")
.layer("database").defined_by_folder("**/database/**")
.where_layer("presentation")
.may_only_depend_on_layers("business")
.where_layer("business")
.may_only_depend_on_layers()
.where_layer("database")
.may_only_depend_on_layers()
)
assert_passes(rule)
External Dependencies
def test_domain_does_not_import_requests():
rule = (
project_files("src/")
.in_folder("**/domain/**")
.should_not()
.depend_on_external_modules()
.matching("requests")
)
assert_passes(rule)
TYPE_CHECKING-aware Analysis
from archunitpython import CheckOptions
def test_type_only_dependencies_do_not_count_as_runtime_coupling():
rule = (
project_files("src/")
.in_folder("**/api/**")
.should_not()
.depend_on_files()
.in_folder("**/infrastructure/**")
)
assert_passes(rule, CheckOptions(ignore_type_checking_imports=True))
Dynamic Imports and Ignore Directives
ArchUnitPython detects string-based dynamic imports such as importlib.import_module("my_app.adapters.sql") and __import__("my_app.adapters.sql"). For known migration shims, you can suppress one import edge locally:
from my_app.adapters.sql import Repository # archunit: ignore
Namespace Packages
ArchUnitPython resolves imports from namespace packages that do not contain
__init__.py files. For example, from my_app.domain import model is resolved
to my_app/domain/model.py when my_app/domain/ is a namespace package.
Conditional Imports
Imports inside try blocks that handle ImportError or
ModuleNotFoundError are marked as conditional dependencies. This helps graph
reports distinguish optional imports and fallback implementations from regular
runtime imports. Conditional dependencies remain part of architecture checks;
relative and dynamic imports also retain their original import kind in graph
reports. An edge may therefore have multiple kinds: CSV reports use
pipe-delimited values such as relative|conditional, while HTML reports list
both values separately.
Naming Conventions
def test_naming_patterns():
rule = (
project_files("src/")
.in_folder("**/services/**")
.should()
.have_name("*_service.py")
)
assert_passes(rule)
Code Metrics
Metric rules evaluate every matching file or class independently. Use filters such as
in_folder(), with_name(), and for_classes_matching() when different parts of the
project need different limits.
def test_no_large_files():
rule = metrics("src/").count().lines_of_code().should_be_below(1000)
assert_passes(rule)
def test_high_class_cohesion():
rule = metrics("src/").lcom().lcom96b().should_be_below(0.3)
assert_passes(rule)
def test_method_count():
rule = metrics("src/").count().method_count().should_be_below_or_equal(20)
assert_passes(rule)
def test_field_count_for_data_classes():
rule = (
metrics("src/")
.for_classes_matching("*Data*")
.count()
.field_count()
.should_be(3)
)
assert_passes(rule)
Comparison Semantics