Files
models/tests/test_tea_job.py
T
alberto 0b4f7593e5 TEA hospital test follows the sensor flow; re-analysis by id in local mode; first_n
Update tests/test_tea_job.py. Use the synthetic TEA builder with the existing pipeline and concept map, ingest via the platform fixture without a daemon, and run first_n synchronously in process.

Use SQLite and its temporary platform environment, count an absent analysis table as zero, and clear the cached engine around the in-process calls.
2026-11-29 01:25:29 -06:00

175 lines
6.5 KiB
Python

"""The tea_eeg job's graph, sensor, config classes and synthetic EEG scope."""
from pathlib import Path
import dagster as dg
import pytest
from pydantic import ValidationError
from sqlalchemy import inspect
from models import definitions
from models.definitions import (
ExecutionConfig,
ScopeConfig,
after_ingest,
defs,
tea_eeg,
tea_eeg_after_ingest,
)
from models.tea import jobs as tea_jobs
from persistance import cluster, destination, eeg
from synthetic import tea
def _config(scope: dict) -> dict:
return {"ops": {"tea_analyze_studies": {"config": {
"scope": scope, "execution": {"mode": "sync"}}}}} # fmt: skip
@pytest.fixture
def calls(monkeypatch):
log = []
def analyze(scope=None, *, rebuild_gold=True):
log.append(("analyze", scope, rebuild_gold))
return 2
monkeypatch.setattr(tea_jobs, "analyze", analyze)
monkeypatch.setattr(tea_jobs, "score_curves", lambda: log.append(("score",)) or {"c": 3})
monkeypatch.setattr(tea_jobs, "relate", lambda: log.append(("relate",)))
monkeypatch.setattr(definitions.silver, "build", lambda sel: log.append(("build", sel)))
return log
def test_tea_eeg_runs_the_four_steps_in_order(calls):
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(), run_config=_config({"mode": "first_n", "n": 2})
)
assert result.success
assert [c[0] for c in calls] == ["analyze", "score", "relate", "build"]
assert calls[0][1].n == 2 and calls[0][2] is False
assert calls[3][1] == tea_jobs.GOLD_SELECT
assert result.output_for_node("tea_analyze_studies") == {"analysed": 2}
assert result.output_for_node("tea_score_curves") == {"scored": {"c": 3}}
assert result.output_for_node("tea_relate_ados2") == {"ados2_association": None}
assert result.output_for_node("tea_build_gold") == {"built": tea_jobs.GOLD_SELECT}
def test_a_failing_analysis_stops_the_graph(calls, monkeypatch):
def boom(scope=None, *, rebuild_gold=True):
raise RuntimeError("no signal")
monkeypatch.setattr(tea_jobs, "analyze", boom)
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(),
run_config=_config({"mode": "pending"}),
raise_on_error=False,
)
assert not result.success
assert calls == []
def test_a_bad_scope_fails_before_any_work(calls):
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(),
run_config=_config({"mode": "first_n"}),
raise_on_error=False,
)
assert not result.success
assert calls == []
failure = next(e for e in result.all_events if e.is_step_failure)
assert "first_n needs n" in str(failure.event_specific_data.error)
def test_scope_validation():
assert eeg.Scope().mode == "pending"
assert eeg.Scope(mode="first_n", n=3).n == 3
good = "p1|2024-05-06"
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
bad = [
{"mode": "first_n"},
{"mode": "first_n", "n": 0},
{"mode": "first_n", "n": 2, "ids": [good]},
{"mode": "ids"},
{"mode": "ids", "ids": [good], "n": 1},
{"mode": "ids", "ids": ["nobar"]},
{"mode": "ids", "ids": ["p|2024-5-6"]},
{"mode": "ids", "ids": ["|2024-05-06"]},
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
{"mode": "pending", "n": 1},
{"mode": "pending", "ids": [good]},
{"mode": "other"},
{"extra": 1},
]
for kwargs in bad:
with pytest.raises(ValidationError):
eeg.Scope(**kwargs)
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
with pytest.raises(ValidationError, match="first_n needs n"):
ScopeConfig(mode="first_n").model()
def test_config_mirrors_match_the_shared_models():
for config, shared in ((ScopeConfig, eeg.Scope), (ExecutionConfig, cluster.Execution)):
assert list(config.model_fields) == list(shared.model_fields)
for name, field in shared.model_fields.items():
assert config.model_fields[name].default == field.default, name
# a wrong value still reaches the shared model's validation
with pytest.raises(ValidationError):
ExecutionConfig(mode="cloud").model()
with pytest.raises(ValidationError):
ScopeConfig(mode="all").model()
def test_after_ingest_requests_a_run_only_with_pending_eegs():
skip = after_ingest("r1", lambda: False)
assert isinstance(skip, dg.SkipReason)
request = after_ingest("r1", lambda: True)
assert isinstance(request, dg.RunRequest)
assert request.run_key == "after-ingest-r1"
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
assert scope == {"mode": "pending"}
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
def test_definitions_load_with_every_job_and_the_sensor():
dg.Definitions.validate_loadable(defs)
names = {j.name for j in defs.jobs}
assert names >= {"ingest", "train", "score", "analyze", "tea_eeg"}
assert tea_eeg_after_ingest.default_status == dg.DefaultSensorStatus.RUNNING
def test_relate_is_a_no_op_until_phase_2():
assert tea_jobs.relate() is None
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
def test_tea_eeg_first_n_analyses_exactly_n(platform, tmp_path, monkeypatch):
tea.build(tmp_path / "hospital_tea.db")
fixtures = Path(__file__).parents[2] / "tests" / "fixtures"
drawing = tmp_path / "pipeline.json"
drawing.write_text(
(fixtures / "pipelines" / "hospital_tea.json")
.read_text()
.replace("{hospital}", str(tmp_path))
)
platform.save("concept_maps", "hospital_tea", fixtures / "concept_maps" / "hospital_tea.json")
platform.save("pipelines", "tea", drawing)
platform.ingest("tea")
for name in ("PLATFORM_DATABASE_URL", "DLT_DATA_DIR", "EXECUTION_MODE"):
monkeypatch.setenv(name, platform.env[name])
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
destination.engine.cache_clear()
try:
table = "bronze.eeg_analysis"
with destination.engine().connect() as con:
has_analysis = inspect(con).has_table("eeg_analysis", schema="bronze")
before = platform.count(table) if has_analysis else 0
pending = len(eeg.pending())
tea_jobs.analyze(eeg.Scope(mode="first_n", n=3), rebuild_gold=False)
assert platform.count(table) == before + 3
assert len(eeg.pending()) == pending - 3
finally:
destination.engine.cache_clear()