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:
AlbertoPMDM
2026-11-18 19:54:15 -06:00
parent fbfad83861
commit 449acf8b44
11 changed files with 4450 additions and 3 deletions
+16
View File
@@ -0,0 +1,16 @@
# local clone of alberto/eeg, not tracked here
/eeg/
# python / tools
.venv/
__pycache__/
.pytest_cache/
*.egg-info/
# never commit signals or patient data
*.edf
*.npz
*.parquet
datos/
salidas/
mlruns/
+26 -1
View File
@@ -7,8 +7,33 @@ authors = [
{ name = "AlbertoPMDM", email = "albertopmdm@gmail.com" }
]
requires-python = ">=3.12"
dependencies = []
dependencies = [
"antropy>=0.2.3",
"dask>=2026.8.0",
"distributed>=2026.8.0",
"edfio>=0.4.18",
"fhir-resources>=8.3.0",
"fooof==1.1.1",
"meegkit>=0.2.0",
"mlflow>=3.18.0",
"mne>=1.13.2",
"numpy>=2.5.5",
"pandas>=3.1.1",
"scikit-learn>=1.9.1",
"scipy>=1.18.1",
"yasa>=0.8.1",
]
[build-system]
requires = ["uv_build>=0.13.1,<0.14.0"]
build-backend = "uv_build"
[dependency-groups]
dev = [
"pytest>=9.2.0",
]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["tests"]
markers = ["cluster: needs a Dask scheduler (DASK_SCHEDULER or DASK_SCHEDULER_ADDRESS)"]
+9 -2
View File
@@ -1,2 +1,9 @@
def hello() -> str:
return "Hello from tea-modulo!"
"""
tea_modulo: modular EEG library (EDF in, validation, preprocessing,
processes and biomarkers out).
Every biomarker and every process is its own module. Modules talk only
through `tea_modulo.contracts`; see the architecture plan.
"""
__version__ = "0.1.0"
+35
View File
@@ -0,0 +1,35 @@
"""
The shared API of `tea_modulo`: the only code every module may import.
from tea_modulo.contracts import Recording, Preprocessed, Study, Labels
from tea_modulo.contracts import check_module, CONTRACT_VERSION
"""
from tea_modulo.contracts.data import (
CONTRACT_VERSION,
DEVIATION_COLUMNS,
WINDOW_COLUMNS,
Labels,
Preprocessed,
Recording,
Study,
ValidationSummary,
sha256_of,
)
from tea_modulo.contracts.protocols import (
KINDS,
Biomarker,
ContractError,
Module,
Preprocessor,
Process,
Validator,
check_module,
)
__all__ = [
"CONTRACT_VERSION", "DEVIATION_COLUMNS", "WINDOW_COLUMNS",
"Recording", "ValidationSummary", "Preprocessed", "Labels", "Study", "sha256_of",
"Module", "Validator", "Preprocessor", "Process", "Biomarker",
"KINDS", "ContractError", "check_module",
]
+165
View File
@@ -0,0 +1,165 @@
"""
Data that crosses module boundaries.
Every module in `tea_modulo` talks to the others only through these frozen
dataclasses and the protocols in `contracts.protocols`. A module may be
replaced completely by any code that consumes and produces these objects.
Signals travel as MNE objects (`mne.io.BaseRaw`), so every module shares
MNE's handling of units (volts inside MNE), channel types, gaps
(`BAD_ACQ_SKIP` annotations) and timing.
"""
from __future__ import annotations
import hashlib
from collections.abc import Mapping
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import pandas as pd
CONTRACT_VERSION = "1.0"
# Columns of the table that Biomarker.predict returns.
DEVIATION_COLUMNS = ("feature", "value", "age_months", "outside", "z", "baseline")
# Columns that Preprocessed.windows must have.
WINDOW_COLUMNS = ("start_s", "end_s", "clean", "gap")
def sha256_of(path: str | Path, chunk: int = 1 << 20) -> str:
"""SHA-256 of a file, read in chunks."""
h = hashlib.sha256()
with open(path, "rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
@dataclass(frozen=True)
class Recording:
"""
An EDF file in memory.
- `raw`: the EDF as read by `mne.io.read_raw_edf` (preloaded). Gaps are
`BAD_ACQ_SKIP` annotations, as `ktlx2edf` writes them.
- `age_months`: age at the recording, if known.
- `source_sha256`: hash of the EDF file, for traceability.
- `source_name`: file stem only (never a full path, which may hold names).
"""
raw: Any # mne.io.BaseRaw (Any: contracts import mne lazily)
age_months: float | None
source_sha256: str
source_name: str = ""
@classmethod
def from_edf(cls, path: str | Path, *, age_months: float | None = None) -> Recording:
"""Read an EDF with MNE. The only EDF reader shared through contracts."""
import mne
path = Path(path)
raw = mne.io.read_raw_edf(path, preload=True, verbose="error")
return cls(raw=raw, age_months=age_months, source_sha256=sha256_of(path),
source_name=path.stem)
@dataclass(frozen=True)
class ValidationSummary:
"""
What preprocessing needs from validation.
- `valid`: 1 = valid, 0 = not valid.
- `level`: `completo`, `sin_referencia_auricular` or `no_analizable`.
- `bad_channels`: channel -> reason, for every channel to exclude.
- `ears_usable`: both ear channels usable (linked-ears reference possible).
- `line_db`: mains line level of the study, in dB.
- `clean_fraction`: fraction of clean 4 s windows.
"""
valid: int
level: str
bad_channels: Mapping[str, str]
ears_usable: bool
line_db: float
clean_fraction: float
extra: Mapping[str, Any] = field(default_factory=dict)
@dataclass(frozen=True)
class Preprocessed:
"""
What preprocessing hands to every process and biomarker.
- `variants`: variant name (e.g. "hp05_prom") -> preprocessed `Raw`.
EEG channels are re-referenced; EOG / ECG channels are filtered only.
- `windows`: one row per analysis window, columns `WINDOW_COLUMNS`
(start_s, end_s in seconds from the start of the recording; clean and
gap as booleans). Window length and step come from the plan.
- `plan`: the plan that produced this, as a schema-tagged dict.
- `plan_hash`: the plan's content hash.
"""
variants: Mapping[str, Any] # str -> mne.io.BaseRaw
windows: pd.DataFrame
age_months: float | None
plan: Mapping[str, Any]
plan_hash: str
source_sha256: str = ""
def __post_init__(self):
faltan = [c for c in WINDOW_COLUMNS if c not in self.windows.columns]
if faltan:
raise ValueError(f"Preprocessed.windows lacks columns: {', '.join(faltan)}")
if not self.variants:
raise ValueError("Preprocessed has no variant")
def variant(self, name: str):
"""The `Raw` of one variant, with a clear error if it is missing."""
try:
return self.variants[name]
except KeyError:
raise KeyError(f"variant {name!r} not in this study; it has "
f"{', '.join(self.variants)}") from None
@dataclass(frozen=True)
class Labels:
"""
What a process returns.
- `per_window`: one value per row of `Preprocessed.windows` (same index).
- `events`: one row per event; at least `onset_s` and `duration_s`.
"""
process: str
per_window: pd.Series | None = None
events: pd.DataFrame | None = None
def __post_init__(self):
if self.per_window is None and self.events is None:
raise ValueError(f"Labels of {self.process!r} have neither per_window nor events")
if self.events is not None:
faltan = [c for c in ("onset_s", "duration_s") if c not in self.events.columns]
if faltan:
raise ValueError(f"events of {self.process!r} lack columns: {', '.join(faltan)}")
@dataclass(frozen=True)
class Study:
"""What a biomarker reads: the preprocessed study plus process outputs."""
prep: Preprocessed
labels: Mapping[str, Labels] = field(default_factory=dict)
def label(self, process: str) -> Labels:
try:
return self.labels[process]
except KeyError:
raise KeyError(f"this study has no labels from process {process!r}; "
f"it has {', '.join(self.labels) or 'none'}") from None
def with_labels(self, labels: Labels) -> Study:
return Study(self.prep, {**self.labels, labels.process: labels})
+124
View File
@@ -0,0 +1,124 @@
"""
What each kind of module must offer.
A module is replaceable: any object that satisfies its protocol (and declares
the same `CONTRACT_VERSION`) can take its place in the pipeline. `check_module`
verifies this when a module is loaded.
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any, Protocol, runtime_checkable
import pandas as pd
from tea_modulo.contracts.data import (
CONTRACT_VERSION,
Labels,
Preprocessed,
Study,
ValidationSummary,
)
@runtime_checkable
class Module(Protocol):
name: str
version: str
contract_version: str
@runtime_checkable
class Validator(Module, Protocol):
def validate(self, edf_path, *, line_hz: float = 60.0,
subject: str | None = None) -> tuple[dict, int]: ...
def summarize(self, edf_path, *, line_hz: float = 60.0) -> ValidationSummary: ...
@runtime_checkable
class Preprocessor(Module, Protocol):
def plan_for(self, summary: ValidationSummary, base: Mapping[str, Any]) -> dict: ...
def run(self, edf_path, plan: Mapping[str, Any], *,
age_months: float | None = None) -> Preprocessed: ...
@runtime_checkable
class Process(Module, Protocol):
requires: tuple[str, ...]
def train(self, studies: Sequence[Study]) -> Process: ...
def predict(self, study: Study) -> Labels: ...
def save(self, path) -> None: ...
@classmethod
def load(cls, path) -> Process: ...
@runtime_checkable
class Biomarker(Module, Protocol):
requires: tuple[str, ...]
features: tuple[str, ...]
def measure(self, study: Study) -> Mapping[str, float]: ...
def train(self, data: Sequence[Study] | pd.DataFrame,
ages_months=None) -> Biomarker: ...
def predict(self, data: Study | pd.DataFrame, age_months=None) -> pd.DataFrame: ...
def save(self, path) -> None: ...
@classmethod
def load(cls, path) -> Biomarker: ...
KINDS: dict[str, type] = {
"validator": Validator,
"preprocessor": Preprocessor,
"process": Process,
"biomarker": Biomarker,
}
class ContractError(TypeError):
"""A module does not satisfy its protocol or contract version."""
def check_module(module: object, kind: str) -> object:
"""
Check that `module` satisfies the protocol of `kind` and was built for
this `CONTRACT_VERSION`. Returns the module, so it can be used inline.
"""
try:
proto = KINDS[kind]
except KeyError:
raise ValueError(f"unknown module kind {kind!r}; one of {', '.join(KINDS)}") from None
nombre = getattr(module, "name", type(module).__name__)
if not isinstance(module, proto):
faltan = [a for a in _members(proto) if not hasattr(module, a)]
raise ContractError(f"module {nombre!r} is not a {kind}: missing {', '.join(faltan)}")
cv = getattr(module, "contract_version", None)
if str(cv).split(".")[0] != CONTRACT_VERSION.split(".")[0]:
raise ContractError(f"module {nombre!r} was built for contract {cv}; "
f"this library has {CONTRACT_VERSION}")
if kind in ("process", "biomarker"):
req = getattr(module, "requires")
if not isinstance(req, tuple) or not all(isinstance(r, str) for r in req):
raise ContractError(f"module {nombre!r}: requires must be a tuple of names")
return module
def _members(proto: type) -> list[str]:
names = []
for klass in proto.__mro__:
if klass in (Protocol, object):
continue
names += [n for n in getattr(klass, "__annotations__", {})]
names += [n for n, v in vars(klass).items()
if not n.startswith("_") and (callable(v) or isinstance(v, classmethod))]
return list(dict.fromkeys(names))
+118
View File
@@ -0,0 +1,118 @@
"""
Contract test suites: run them against any implementation of a module,
including a replacement written outside this package.
from tea_modulo.contracts.testing import check_process, check_biomarker
check_process(MyDetector(), study)
check_biomarker(MyBiomarker(), studies, ages_months)
Each function raises AssertionError with a clear message on the first
violation and returns the module's output for further checks.
"""
from __future__ import annotations
import copy
import tempfile
from collections.abc import Sequence
from pathlib import Path
import pandas as pd
from tea_modulo.contracts.data import (
DEVIATION_COLUMNS,
Labels,
Preprocessed,
Study,
ValidationSummary,
)
from tea_modulo.contracts.protocols import check_module
def check_process(module, study: Study):
"""A process returns Labels aligned with the study's windows and round-trips save/load."""
check_module(module, "process")
for req in module.requires:
assert req in study.labels, f"{module.name}: test study lacks required labels {req!r}"
trained = module.train([study])
assert trained is not None, f"{module.name}.train must return the module"
out = trained.predict(study)
assert isinstance(out, Labels), f"{module.name}.predict must return Labels, not {type(out)}"
assert out.process == module.name, f"{module.name}: Labels.process is {out.process!r}"
if out.per_window is not None:
assert out.per_window.index.equals(study.prep.windows.index), \
f"{module.name}: per_window index must equal Preprocessed.windows.index"
with tempfile.TemporaryDirectory() as d:
trained.save(Path(d))
again = type(trained).load(Path(d)).predict(study)
_same_labels(out, again, module.name)
return out
def check_biomarker(module, studies: Sequence[Study], ages_months: Sequence[float]):
"""A biomarker measures, trains from studies and from a table, and predicts DEVIATION_COLUMNS."""
check_module(module, "biomarker")
vals = module.measure(studies[0])
assert set(vals) == set(module.features), \
f"{module.name}.measure returned {sorted(vals)}, features are {sorted(module.features)}"
for k, v in vals.items():
assert isinstance(v, (int, float)) and not isinstance(v, bool), \
f"{module.name}: feature {k} must be a number, got {type(v)}"
fresh = copy.deepcopy(module)
trained = module.train(list(studies), list(ages_months))
out = trained.predict(studies[0], age_months=ages_months[0])
_check_deviation(out, module)
table = pd.DataFrame([fresh.measure(s) for s in studies])
table["age_months"] = list(ages_months)
trained2 = fresh.train(table)
out2 = trained2.predict(table.iloc[[0]])
_check_deviation(out2, module)
with tempfile.TemporaryDirectory() as d:
trained.save(Path(d))
again = type(trained).load(Path(d)).predict(studies[0], age_months=ages_months[0])
pd.testing.assert_frame_equal(out.reset_index(drop=True), again.reset_index(drop=True))
return out
def check_preprocessed(prep: Preprocessed):
"""The output of a Preprocessor."""
assert isinstance(prep, Preprocessed)
w = prep.windows
assert (w["end_s"] > w["start_s"]).all(), "windows must have end_s > start_s"
assert w["clean"].dtype == bool and w["gap"].dtype == bool, "clean and gap must be boolean"
assert isinstance(prep.plan, dict) and "schema" in prep.plan, "plan must be a schema-tagged dict"
assert prep.plan_hash, "plan_hash is empty"
return prep
def check_validation(fhir: dict, valid: int, summary: ValidationSummary | None = None):
"""The output of a Validator."""
assert valid in (0, 1), f"valid must be 0 or 1, not {valid!r}"
assert fhir.get("resourceType") == "Bundle", "validate must return a FHIR Bundle"
reports = [e["resource"] for e in fhir.get("entry", [])
if e["resource"].get("resourceType") == "DiagnosticReport"]
assert len(reports) == 1, "the Bundle must hold exactly one DiagnosticReport"
code = reports[0]["conclusionCode"][0]["coding"][0]["code"]
assert code == ("valid" if valid else "not-valid"), \
f"conclusionCode {code!r} disagrees with valid={valid}"
if summary is not None:
assert summary.valid == valid, "summary.valid disagrees with validate()"
def _check_deviation(df: pd.DataFrame, module):
assert isinstance(df, pd.DataFrame), f"{module.name}.predict must return a DataFrame"
assert tuple(df.columns[: len(DEVIATION_COLUMNS)]) == DEVIATION_COLUMNS, \
f"{module.name}.predict columns {list(df.columns)} must start with {DEVIATION_COLUMNS}"
assert set(df["feature"]) <= set(module.features), f"{module.name}: unknown feature in predict"
assert df["outside"].isin([-1, 0, 1]).all(), f"{module.name}: outside must be -1, 0 or 1"
def _same_labels(a: Labels, b: Labels, name: str):
if a.per_window is not None:
pd.testing.assert_series_equal(a.per_window, b.per_window, obj=f"{name} per_window")
if a.events is not None:
pd.testing.assert_frame_equal(a.events.reset_index(drop=True),
b.events.reset_index(drop=True), obj=f"{name} events")
+29
View File
@@ -0,0 +1,29 @@
from __future__ import annotations
import numpy as np
import pandas as pd
import pytest
def make_prep(seconds=60.0, fs=250.0, channels=("Fp1", "Fp2", "O1", "O2"), seed=0,
window_s=4.0, step_s=2.0):
"""A small Preprocessed made in memory (white noise, one variant)."""
import mne
from tea_modulo.contracts import Preprocessed
rng = np.random.default_rng(seed)
n = int(seconds * fs)
info = mne.create_info(list(channels), fs, ch_types="eeg")
raw = mne.io.RawArray(rng.normal(0, 20e-6, (len(channels), n)), info, verbose="error")
starts = np.arange(0, seconds - window_s + 1e-9, step_s)
windows = pd.DataFrame({"start_s": starts, "end_s": starts + window_s,
"clean": np.ones(len(starts), bool),
"gap": np.zeros(len(starts), bool)})
plan = {"schema": 1, "name": "test"}
return Preprocessed(variants={"hp05_prom": raw}, windows=windows, age_months=24.0,
plan=plan, plan_hash="test")
@pytest.fixture
def prep():
return make_prep()
+154
View File
@@ -0,0 +1,154 @@
"""
The contracts themselves, and the contract suites run against fake modules
(the shape a replacement module must have).
"""
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from tea_modulo.contracts import (
CONTRACT_VERSION,
DEVIATION_COLUMNS,
ContractError,
Labels,
Preprocessed,
Study,
check_module,
)
from tea_modulo.contracts.testing import check_biomarker, check_process
class ConstantState:
"""A fake process: every window is 'vigilia'."""
name = "sleep_state"
version = "0.0.1"
contract_version = CONTRACT_VERSION
requires = ()
def train(self, studies):
return self
def predict(self, study):
w = study.prep.windows
return Labels(self.name, per_window=pd.Series("vigilia", index=w.index))
def save(self, path):
Path(path, "params.json").write_text("{}")
@classmethod
def load(cls, path):
return cls()
class MeanAmplitude:
"""A fake biomarker: mean absolute amplitude in µV, baseline = median and MAD."""
name = "mean_amplitude"
version = "0.0.1"
contract_version = CONTRACT_VERSION
requires = ("sleep_state",)
features = ("mean_abs_uv",)
def __init__(self):
self.median = None
self.mad = None
def measure(self, study):
x = study.prep.variant("hp05_prom").get_data() * 1e6
return {"mean_abs_uv": float(np.mean(np.abs(x)))}
def train(self, data, ages_months=None):
if isinstance(data, pd.DataFrame):
v = data["mean_abs_uv"].to_numpy()
else:
v = np.array([self.measure(s)["mean_abs_uv"] for s in data])
self.median = float(np.median(v))
self.mad = float(np.median(np.abs(v - self.median))) or 1.0
return self
def predict(self, data, age_months=None):
if isinstance(data, pd.DataFrame):
rows = data.to_dict("records")
else:
rows = [{**self.measure(data), "age_months": age_months}]
out = []
for r in rows:
z = (r["mean_abs_uv"] - self.median) / self.mad
out.append({"feature": "mean_abs_uv", "value": r["mean_abs_uv"],
"age_months": r.get("age_months"), "outside": int(np.sign(z)) if abs(z) > 3 else 0,
"z": z, "baseline": "median_mad"})
return pd.DataFrame(out, columns=list(DEVIATION_COLUMNS))
def save(self, path):
Path(path, "baseline.json").write_text(json.dumps({"median": self.median, "mad": self.mad}))
@classmethod
def load(cls, path):
m = cls()
d = json.loads(Path(path, "baseline.json").read_text())
m.median, m.mad = d["median"], d["mad"]
return m
def _study(prep):
return Study(prep).with_labels(ConstantState().predict(Study(prep)))
def test_preprocessed_requires_window_columns(prep):
with pytest.raises(ValueError, match="lacks columns"):
Preprocessed(variants=prep.variants, windows=prep.windows.drop(columns="gap"),
age_months=None, plan={"schema": 1}, plan_hash="x")
def test_missing_variant_and_label_messages(prep):
with pytest.raises(KeyError, match="hp05_orejas"):
prep.variant("hp05_orejas")
with pytest.raises(KeyError, match="no labels from process 'spindle_detection'"):
Study(prep).label("spindle_detection")
def test_labels_need_content_and_event_columns():
with pytest.raises(ValueError, match="neither"):
Labels("x")
with pytest.raises(ValueError, match="duration_s"):
Labels("x", events=pd.DataFrame({"onset_s": [1.0]}))
def test_check_module_refuses_wrong_kind_and_version():
with pytest.raises(ContractError, match="missing"):
check_module(object(), "process")
old = ConstantState()
old.contract_version = "0.9"
with pytest.raises(ContractError, match="contract 0.9"):
check_module(old, "process")
def test_fake_process_passes_the_suite(prep):
check_process(ConstantState(), Study(prep))
def test_fake_biomarker_passes_the_suite():
from conftest import make_prep
studies = [_study(make_prep(seed=i)) for i in range(6)]
out = check_biomarker(MeanAmplitude(), studies, [20, 22, 24, 26, 28, 30])
assert out["feature"].iloc[0] == "mean_abs_uv"
def test_recording_from_edf(tmp_path):
"""Recording.from_edf reads an EDF with MNE and keeps only the file stem."""
import mne
from tea_modulo.contracts import Recording
info = mne.create_info(["Fp1", "O1"], 250.0, "eeg")
raw = mne.io.RawArray(np.random.default_rng(0).normal(0, 20e-6, (2, 2500)), info, verbose="error")
p = tmp_path / "study.edf"
mne.export.export_raw(p, raw, fmt="edf", verbose="error")
rec = Recording.from_edf(p, age_months=30)
assert rec.raw.ch_names == ["Fp1", "O1"]
assert rec.source_name == "study" and len(rec.source_sha256) == 64
+110
View File
@@ -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}"
Generated
+3664
View File
File diff suppressed because it is too large Load Diff