"""What this module covers: the cycle's `analyze_eeg` step (TEA's EEG analysis before the silver load) and how the cycle gets its analysis (`webapi.orchestration.eeg`). Fixtures: `tea_base`, a migrated TEA database (`base_de`) holding one patient (`pac_id` 1, born 2024-01-01) and one EEG `e-1` with an EDF and no analysis; `fake_analysis`, an analysis that writes sleep and 21 channels on `e-1`, as the real one would, and notes whether a silver load existed when it ran. """ from datetime import date import pytest from hamilton import driver from sqlmodel import Session, select from models.eeg_analysis import Summary from webapi.orchestration import cycle, run, steps_of from webapi.orchestration.context import Context from webapi.orchestration.eeg import CLUSTER_ENV, live_eeg_analysis def _rows(sesion): from core.tea.models import Eeg, Pacientes sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2024, 1, 1))) sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_id_registro_laboratorio="LAB-1", eeg_fecha_estudio=date(2025, 6, 1), eeg_estudio=b"edf")) @pytest.fixture def tea_base(tmp_path): """Patient 1 and EEG `e-1` (an EDF, nothing analysed) in a migrated TEA database.""" from conftest import base_de base = base_de("tea", tmp_path, datos=_rows) yield base base.motor.dispose() @pytest.fixture def fake_analysis(tea_base): """Writes `eeg_con_sueno` 1 and `eeg_canales` 21 on `e-1`; `calls` records the loads that existed at each call.""" from core.tea.indicadores.models import Carga from core.tea.models import Eeg calls = [] def analysis(): with Session(tea_base.motor) as sesion: calls.append(len(sesion.exec(select(Carga)).all())) eeg = sesion.get(Eeg, "e-1") eeg.eeg_con_sueno, eeg.eeg_canales = 1, 21 sesion.add(eeg) sesion.commit() return Summary(pending=1, valid=1, not_valid=0, failed=0) analysis.calls = calls return analysis @pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"]) def test_the_eeg_analysis_runs_before_the_silver_load(proyecto): """Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema. Fails if `load` stops waiting for the analysis (the cycle would load an EEG's old analysis and pick the new one up only on the next cycle), or the analysis starts waiting for steps it doesn't need. """ dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build() deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"} assert "analyze_eeg" in deps["load"] assert deps["analyze_eeg"] == {"migrate"} order = steps_of(proyecto) assert order.index("analyze_eeg") < order.index("load") def test_without_an_analysis_the_step_does_nothing(): """Pins down: a context without `eeg_analysis` (CaCu, CaMa, the tests' cycles) makes the step a no-op. Fails if the step starts running an analysis nobody configured. """ pasos = run(Context("cacu", 2025, 2025), only=["analyze_eeg"]) assert [(p.name, p.summary) for p in pasos] == [("analyze_eeg", {})] def test_what_the_analysis_writes_is_loaded_by_the_same_cycle(tea_base, fake_analysis): """Pins down: the cycle runs the analysis once, before any silver load, and `load` then carries what it wrote into the EEG's silver observations. Fails if the analysis runs after `load` or more than once, or its summary stops being the step's. """ from core.tea.indicadores.models import Observacion, Procedimiento pasos = tea_base.run("analyze_eeg", "catalogs", "load", eeg_analysis=fake_analysis) assert pasos["analyze_eeg"] == {"pending": 1, "valid": 1, "not_valid": 0, "failed": 0} assert fake_analysis.calls == [0] with Session(tea_base.motor) as sesion: toma = sesion.exec(select(Procedimiento).where(Procedimiento.estudio_id == "eeg", Procedimiento.clase == "toma")).one() valores = {o.resultado_id: o.valor_numerico for o in sesion.exec( select(Observacion).where(Observacion.procedimiento_id == toma.procedimiento_id))} assert valores["eeg.canales"] == 21 def test_only_tea_has_an_analysis_and_it_can_be_turned_off(monkeypatch): """Pins down: TEA's cycle gets the analysis, with the cluster `EEG_ANALYSIS_CLUSTER` names; the other domains get none, `off` leaves it out, and an unknown value is refused. Fails if another domain starts analysing EEGs, `off` stops leaving the analysis out, or a mistyped cluster is silently taken as the default. """ monkeypatch.delenv(CLUSTER_ENV, raising=False) assert live_eeg_analysis("tea").keywords == {"cluster": "auto"} assert live_eeg_analysis("cacu") is None monkeypatch.setenv(CLUSTER_ENV, "sync") assert live_eeg_analysis("tea").keywords == {"cluster": "sync"} monkeypatch.setenv(CLUSTER_ENV, "off") assert live_eeg_analysis("tea") is None monkeypatch.setenv(CLUSTER_ENV, "everywhere") with pytest.raises(ValueError, match=CLUSTER_ENV): live_eeg_analysis("tea")