Files
tea/tests/test_boundaries.py
T
AlbertoPMDM 4deba99c92 aperiodic and mse, legacy and modern
- The cluster route's 2 s window table (ventanas.cortar + estado_director
  exclusions and labels) rebuilt from the contract, one private copy per
  module.
- legacy: biomarcadores espectro.py, aperiodico.py (FOOOF with Wilkinson's
  modifications) and complejidad.py copied unchanged; exponent per region
  and state (NaN under 20 windows or R2 < 0.9); MSE fine / coarse / total.
- modern: MNE multitaper + fooof with the same two Wilkinson modifications;
  antropy sample entropy with Costa's fixed tolerance.

Copies byte-identical to the submodule; modern within 2% (exponent) and 1%
(MSE) of legacy on the synthetic study; contract suites pass.
2026-11-18 21:52:22 -06:00

115 lines
4.4 KiB
Python

"""
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", "fooof"} # fooof: biomarcadores-tea dependency
EXTRA = {
"validation": {"fhir"},
"serving": {"mlflow"},
"pipeline": {"dask", "distributed", "s3fs", "fsspec", "psutil"},
"verify": {"dask", "distributed", "s3fs", "fsspec"},
"export": set(),
}
# lazy imports inside the director's figure / HDF5 helpers (never reached by legacy)
DIRECTOR_LAZY = {"matplotlib", "h5py"}
# 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 | DIRECTOR_LAZY
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 unit == ("verify",):
ok = True # an application: it wires everything, like tests do
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}"