contracts: shared data classes, protocols and contract test suites
Step 1 of the tea_modulo plan: Recording (MNE Raw from EDF), ValidationSummary, Preprocessed, Labels, Study, the Validator/Preprocessor/Process/Biomarker protocols with check_module(), reusable contract suites in contracts.testing, and an AST test that enforces the module boundary rule.
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
The boundary rule: a module imports only `tea_modulo.contracts`, the standard
|
||||
library and its approved third-party libraries. It never imports another
|
||||
`tea_modulo` module, so any module can be replaced without touching the rest.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
SRC = Path(__file__).resolve().parents[1] / "src" / "tea_modulo"
|
||||
|
||||
# Approved third-party libraries (top-level import names).
|
||||
BASE = {"numpy", "scipy", "pandas", "mne", "sklearn", "antropy", "fooof", "yasa",
|
||||
"meegkit", "edfio"}
|
||||
LEGACY = {"numpy", "scipy", "pandas", "sklearn"}
|
||||
EXTRA = {
|
||||
"validation": {"fhir"},
|
||||
"serving": {"mlflow"},
|
||||
"pipeline": {"dask", "distributed", "s3fs", "fsspec"},
|
||||
"verify": {"dask", "distributed", "s3fs", "fsspec"},
|
||||
"export": set(),
|
||||
}
|
||||
# files allowed to touch MNE / FHIR inside legacy (the contract adapters)
|
||||
LEGACY_ADAPTERS = {"_adapter.py", "fhir.py", "api.py", "__init__.py"}
|
||||
|
||||
|
||||
def unit_of(path: Path) -> tuple[str, ...]:
|
||||
"""The replaceable unit a file belongs to, as a path tuple under tea_modulo."""
|
||||
rel = path.relative_to(SRC).parts
|
||||
if rel[0] == "legacy":
|
||||
rest = rel[1:]
|
||||
if len(rest) >= 2 and rest[0] in ("processes", "biomarkers") and len(rest) > 2:
|
||||
return ("legacy", rest[0], rest[1])
|
||||
if len(rest) >= 2:
|
||||
return ("legacy", rest[0])
|
||||
return ("legacy",)
|
||||
if rel[0] in ("processes", "biomarkers") and len(rel) > 2:
|
||||
return (rel[0], rel[1])
|
||||
if len(rel) == 1:
|
||||
return ()
|
||||
return (rel[0],)
|
||||
|
||||
|
||||
def imports_of(path: Path):
|
||||
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
|
||||
pkg = list(path.relative_to(SRC.parent).with_suffix("").parts)
|
||||
if path.name != "__init__.py":
|
||||
pkg = pkg[:-1]
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Import):
|
||||
for a in node.names:
|
||||
yield a.name, node.lineno
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
if node.level:
|
||||
base = pkg[: len(pkg) - (node.level - 1)]
|
||||
mod = ".".join(base + ([node.module] if node.module else []))
|
||||
yield mod, node.lineno
|
||||
else:
|
||||
yield node.module or "", node.lineno
|
||||
|
||||
|
||||
def allowed_third_party(unit: tuple[str, ...], fname: str) -> set[str]:
|
||||
if not unit:
|
||||
return set()
|
||||
if unit[0] == "legacy":
|
||||
extra = {"mne", "fhir", "edfio"} if fname in LEGACY_ADAPTERS else set()
|
||||
return LEGACY | extra
|
||||
if unit[0] == "export":
|
||||
return {"numpy", "edfio"}
|
||||
return BASE | EXTRA.get(unit[0], set())
|
||||
|
||||
|
||||
FILES = sorted(p for p in SRC.rglob("*.py"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", FILES, ids=[str(p.relative_to(SRC)) for p in FILES])
|
||||
def test_imports_respect_boundaries(path):
|
||||
unit = unit_of(path)
|
||||
own = "tea_modulo." + ".".join(unit) if unit else "tea_modulo"
|
||||
bad = []
|
||||
for mod, line in imports_of(path):
|
||||
top = mod.split(".")[0]
|
||||
if top == "tea_modulo":
|
||||
if unit and unit[0] == "export":
|
||||
ok = mod == own or mod.startswith(own + ".")
|
||||
elif not unit:
|
||||
ok = mod in ("tea_modulo", "tea_modulo.contracts") or mod.startswith("tea_modulo.contracts.")
|
||||
else:
|
||||
ok = (mod == "tea_modulo.contracts" or mod.startswith("tea_modulo.contracts.")
|
||||
or mod == own or mod.startswith(own + "."))
|
||||
if unit == ("contracts",):
|
||||
ok = mod.startswith("tea_modulo.contracts")
|
||||
elif top in sys.stdlib_module_names or top == "__future__":
|
||||
ok = True
|
||||
else:
|
||||
ok = top in allowed_third_party(unit, path.name)
|
||||
if not ok:
|
||||
bad.append(f"line {line}: {mod}")
|
||||
assert not bad, f"{path.relative_to(SRC)} ({'.'.join(unit) or 'root'}) breaks the boundary: " + "; ".join(bad)
|
||||
|
||||
|
||||
def test_legacy_never_imports_dask():
|
||||
for p in (SRC / "legacy").rglob("*.py") if (SRC / "legacy").exists() else []:
|
||||
for mod, line in imports_of(p):
|
||||
assert mod.split(".")[0] not in ("dask", "distributed"), f"{p}:{line} imports {mod}"
|
||||
Reference in New Issue
Block a user