Files
tea/tests/test_boundaries.py
T
AlbertoPMDM 0e942e04c1 verification/ out of the package; ISSSTELEÓN check; a Dask-level task failure is an error row
- verification/ (hk1k, issste, common) moved out of src/: not in the wheel;
  the image imports it with PYTHONPATH=/opt/tea-modulo.
- python -m verification issste: every biomarker, legacy and modern, on
  processed/eeg-edf-2025|2026; age from the EDF header inside the task; group
  numbers only (file names, paths, dates and rows stay in the job).
- Pipeline.map (Dask): a task that dies (KilledWorker) becomes an error row
  instead of stopping the batch.
- deploy/verify.sh [hk1k|issste]; issste uses 3 workers x 6 GiB per pod.
2026-11-19 01:28:54 -06:00

112 lines
4.2 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"},
"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 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}"