Files
chemenu-ng/tests/test_import_contracts.py
torbenandClaude Opus 5.5 f2882511f4
CI / checks (pull_request) Successful in 45s
Forbid layer imports in the root package
The layers contract does not check chemenu/__init__.py itself, so an import
there would load a layer for every importer without any check failing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 21:49:48 +01:00

145 lines
5.2 KiB
Python

"""Tests for the layer import contract enforced by import-linter."""
import itertools
import os
import shutil
import subprocess
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
PACKAGES = ["domain", "ports", "application", "adapters", "evals"]
ALLOWED = [
("ports", "domain"),
("application", "ports"),
("application", "domain"),
("adapters", "ports"),
("adapters", "domain"),
("evals", "ports"),
("evals", "domain"),
]
FORBIDDEN = [pair for pair in itertools.permutations(PACKAGES, 2) if pair not in ALLOWED]
@pytest.fixture
def project(tmp_path: Path) -> Path:
"""Copy the source tree and pyproject.toml into an isolated directory."""
shutil.copytree(
ROOT / "src" / "chemenu",
tmp_path / "chemenu",
ignore=shutil.ignore_patterns("__pycache__"),
)
shutil.copy(ROOT / "pyproject.toml", tmp_path / "pyproject.toml")
return tmp_path
def run_lint(project: Path) -> subprocess.CompletedProcess[str]:
"""Run lint-imports in a subprocess so grimp sees the copy, not the installed package."""
exe = Path(sys.executable).parent / "lint-imports"
return subprocess.run( # noqa: S603
[str(exe), "--no-cache", "--no-logo"],
cwd=project,
capture_output=True,
text=True,
check=False,
# rich wraps its output at COLUMNS; keep each message on one line.
env={**os.environ, "COLUMNS": "200"},
)
def add_import(project: Path, importer: str, imported: str) -> None:
"""Add a probe module in `importer` that imports `chemenu.<imported>`."""
probe = project / "chemenu" / importer / "_probe.py"
probe.write_text(f"import chemenu.{imported}\n", encoding="utf-8")
def packages_without_init(package: Path) -> list[Path]:
"""Return directories with modules but no ``__init__.py``; grimp does not see them."""
directories = {
parent
for path in package.rglob("*.py")
for parent in path.parents
if parent.is_relative_to(package)
}
return sorted(path for path in directories if not (path / "__init__.py").is_file())
def test_current_tree_passes(project: Path) -> None:
result = run_lint(project)
assert result.returncode == 0, result.stdout + result.stderr
@pytest.mark.parametrize(("importer", "imported"), FORBIDDEN)
def test_forbidden_import_fails(project: Path, importer: str, imported: str) -> None:
add_import(project, importer, imported)
result = run_lint(project)
assert result.returncode == 1, result.stdout + result.stderr
assert f"chemenu.{importer} is not allowed to import chemenu.{imported}:" in result.stdout
@pytest.mark.parametrize(("importer", "imported"), ALLOWED)
def test_allowed_import_passes(project: Path, importer: str, imported: str) -> None:
add_import(project, importer, imported)
result = run_lint(project)
assert result.returncode == 0, result.stdout + result.stderr
def test_type_checking_import_fails(project: Path) -> None:
probe = project / "chemenu" / "domain" / "_probe.py"
probe.write_text(
"from typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n import chemenu.adapters\n",
encoding="utf-8",
)
result = run_lint(project)
assert result.returncode == 1, result.stdout + result.stderr
assert "chemenu.domain is not allowed to import chemenu.adapters:" in result.stdout
@pytest.mark.parametrize("imported", [*PACKAGES, "evals.model"])
def test_root_package_import_fails(project: Path, imported: str) -> None:
(project / "chemenu" / "__init__.py").write_text(
f"import chemenu.{imported}\n", encoding="utf-8"
)
result = run_lint(project)
assert result.returncode == 1, result.stdout + result.stderr
assert f"chemenu is not allowed to import chemenu.{imported}:" in result.stdout
def test_undeclared_package_fails(project: Path) -> None:
steps = project / "chemenu" / "steps"
steps.mkdir()
(steps / "__init__.py").write_text("", encoding="utf-8")
result = run_lint(project)
assert result.returncode == 1, result.stdout + result.stderr
assert "chemenu.steps" in result.stdout
def test_undeclared_module_fails(project: Path) -> None:
(project / "chemenu" / "main.py").write_text("", encoding="utf-8")
result = run_lint(project)
assert result.returncode == 1, result.stdout + result.stderr
assert "chemenu.main" in result.stdout
def test_current_tree_has_no_namespace_packages() -> None:
assert packages_without_init(ROOT / "src" / "chemenu") == []
@pytest.mark.parametrize("location", ["steps", "domain/sub"])
def test_namespace_package_is_found(project: Path, location: str) -> None:
directory = project / "chemenu" / location
directory.mkdir()
(directory / "probe.py").write_text("import chemenu.adapters\n", encoding="utf-8")
assert packages_without_init(project / "chemenu") == [directory]
@pytest.mark.parametrize("location", ["steps", "domain/sub"])
def test_namespace_package_with_inner_package_is_found(project: Path, location: str) -> None:
directory = project / "chemenu" / location
inner = directory / "inner"
inner.mkdir(parents=True)
(inner / "__init__.py").write_text("import chemenu.adapters\n", encoding="utf-8")
assert packages_without_init(project / "chemenu") == [directory]