diff --git a/tests/test_webapp.py b/tests/test_webapp.py new file mode 100644 index 0000000..395f987 --- /dev/null +++ b/tests/test_webapp.py @@ -0,0 +1,141 @@ +import json +import os +import shutil +import socket +import sqlite3 +import subprocess +import time +from contextlib import closing, contextmanager +from pathlib import Path + +import httpx +import pytest + +from synthetic import tea + +ROOT = Path(__file__).parents[2] +FIXTURES = ROOT / "tests" / "fixtures" + + +def _ok(response: httpx.Response): + assert response.status_code == 200, response.text + return response.json() + + +def _port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def _until_up(url: str, process: subprocess.Popen, seconds: int = 180) -> None: + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + assert process.poll() is None, f"{process.args[0]} exited with {process.returncode}" + try: + if httpx.get(url, timeout=2).status_code == 200: + return + except httpx.TransportError: + pass + time.sleep(1) + raise TimeoutError(url) + + +def _wait(api: httpx.Client, run_id: str, seconds: int = 1800) -> None: + deadline = time.monotonic() + seconds + while (run := _ok(api.get(f"/runs/{run_id}")))["state"] not in ("succeeded", "failed"): + assert time.monotonic() < deadline, f"run {run_id} still {run['state']}" + time.sleep(2) + assert run["state"] == "succeeded", run.get("error") + + +def _sensor_run(api: httpx.Client, seconds: int = 300) -> str: + deadline = time.monotonic() + seconds + while not (runs := _ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))): + assert time.monotonic() < deadline, "the sensor started no tea_eeg run" + time.sleep(2) + return runs[0]["id"] + + +@contextmanager +def _platform(data: Path): + from mlflow.store.tracking.sqlalchemy_store import SqlAlchemyStore + + (data / "dagster").mkdir(parents=True) + (data / "reference").mkdir() + shutil.copy(ROOT / "dagster.yaml", data / "dagster") + tracking = f"sqlite:///{data / 'mlflow.db'}" + SqlAlchemyStore(tracking, (data / "mlflow").as_uri()).engine.dispose() + dagster_port, api_port = _port(), _port() + env = { + **os.environ, + "ISSSTELEON_DATA": str(data), + "DLT_DATA_DIR": str(data / "dlt"), + "DAGSTER_HOME": str(data / "dagster"), + "DAGSTER_HOST": "127.0.0.1", + "DAGSTER_PORT": str(dagster_port), + "MLFLOW_TRACKING_URI": tracking, + "MLFLOW_DISABLE_AGENT_HINT": "1", + "EXECUTION_MODE": "sync", + "TEA_REFERENCE_ROOT": str(data / "reference"), + } + webserver = subprocess.Popen( + ["dagster-webserver", "-m", "models.definitions", "-h", "127.0.0.1", + "-p", str(dagster_port)], env=env, cwd=data, + ) # fmt: skip + server = subprocess.Popen( + ["fastapi", "run", str(ROOT / "WebApi" / "webapi" / "main.py"), "--host", "127.0.0.1", + "--port", str(api_port)], env=env, cwd=data, + ) # fmt: skip + daemon = None + try: + _until_up(f"http://127.0.0.1:{dagster_port}/server_info", webserver) + daemon = subprocess.Popen( + ["dagster-daemon", "run", "-m", "models.definitions"], env=env, cwd=data + ) + _until_up(f"http://127.0.0.1:{api_port}/health", server) + with httpx.Client(base_url=f"http://127.0.0.1:{api_port}", timeout=120) as client: + yield client + finally: + for process in (server, daemon, webserver): + if process is not None: + process.terminate() + process.wait(timeout=30) + + +def _study_files(db: Path, out: Path) -> dict[str, str]: + out.mkdir() + with closing(sqlite3.connect(db)) as con: + edf, report, birth = con.execute( + "SELECT eeg_estudio, ord_pdf_blob, pac_fecha_nacimiento FROM eeg " + "JOIN pacientes ON pac_id = eeg_pac_id " + "JOIN ados2 ON ado_pac_id = eeg_pac_id " + "JOIN ordenes_estudio ON ord_id = ado_ord_id ORDER BY eeg_id LIMIT 1" + ).fetchone() + (out / "study.edf").write_bytes(edf) + (out / "ados2.pdf").write_bytes(report) + return { + "TEA_EDF": str(out / "study.edf"), + "TEA_ADOS2": str(out / "ados2.pdf"), + "TEA_BIRTH": birth, + } + + +@pytest.mark.webapp +def test_the_tea_pages_load_from_the_synthetic_hospital(tmp_path): + hospital = tmp_path / "hospital" + hospital.mkdir() + tea.build(hospital / "hospital_tea.db") + files = _study_files(hospital / "hospital_tea.db", tmp_path / "files") + concept_map = json.loads((FIXTURES / "concept_maps" / "hospital_tea.json").read_text()) + drawn = (FIXTURES / "pipelines" / "hospital_tea.json").read_text() + pipeline = json.loads(drawn.replace("{hospital}", str(hospital))) + with _platform(tmp_path / "platform") as api: + _ok(api.put("/ingest/concept-maps/hospital_tea", json=concept_map)) + _ok(api.put("/ingest/pipelines/tea", json=pipeline)) + _wait(api, _ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"]) + _wait(api, _sensor_run(api)) + subprocess.run( + ["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True, + env={**os.environ, **files, "API_URL": str(api.base_url).rstrip("/")}, + ) # fmt: skip