The suite keeps only logic tests
Check API validation and response shaping through direct calls. Checks: ruff check, ruff format --check, lint-imports (two contracts kept), and pytest (115 passed, 7 warnings in 42.52s). removed WebApi/tests/test_bundles.py::test_export_and_import_through_the_api — slow integration (logic now covered by test_layout_and_manifest_hold_every_file_hash and test_roundtrip_registers_candidates_with_lineage) removed WebApi/tests/test_bundles.py::test_import_refuses_a_wrong_sha_and_a_non_zip — slow integration (logic now covered by test_import_rejects_invalid_uploads) removed WebApi/tests/test_bundles.py::test_importing_the_same_bundle_again_fails_the_run — slow integration (logic now covered by test_importing_twice_is_a_conflict_and_partial_imports_skip) removed WebApi/tests/test_bundles.py::test_export_guard_failure_is_422 — slow integration (logic now covered by test_reference_group_size and test_selection_champion_latest_all) removed WebApi/tests/test_bundles.py::test_an_untrusted_bundle_is_refused — slow integration (logic now covered by test_import_rejects_invalid_uploads and test_import_refuses_an_untrusted_digest) removed WebApi/tests/test_cacu.py — parity-only removed WebApi/tests/test_cacu.py::test_cacu_from_the_hospital_to_indicators_and_risks — parity-only removed WebApi/tests/test_cama.py — parity-only removed WebApi/tests/test_cama.py::test_cama_from_the_hospital_to_indicators — parity-only removed WebApi/tests/test_conectar.py — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_concept_map_onto_a_code_no_field_allows_is_refused) removed WebApi/tests/test_conectar.py::test_an_operator_connects_a_site_and_settles_its_review — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_concept_map_onto_a_code_no_field_allows_is_refused) removed WebApi/tests/test_fhir_door.py — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and tests/test_core_tea_fhir.py for FHIR mappings) removed WebApi/tests/test_fhir_door.py::test_what_one_platform_serves_another_places_through_the_fhir_door — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and tests/test_core_tea_fhir.py for FHIR mappings) removed WebApi/tests/test_fhir_door.py::test_a_new_label_is_a_concept_map_row_not_code — slow integration (logic now covered by test_hospital_codes_and_dates_become_platform_values) removed WebApi/tests/test_governance.py::test_version_lifecycle — slow integration (logic now covered by models/tests/test_bundle.py::test_version_lifecycle) removed WebApi/tests/test_governance.py::test_imported_lineage — slow integration (logic now covered by test_roundtrip_registers_candidates_with_lineage) removed WebApi/tests/test_governance.py::test_preview — slow integration (logic now covered by test_the_job_deletes_its_files_and_returns_the_result_as_output and test_shape_outputs) removed WebApi/tests/test_governance.py::test_training_inputs — slow integration (logic now covered by the direct-call test_training_inputs) removed WebApi/tests/test_runs.py::test_unknown_run_is_404 — implementation-detail removed WebApi/tests/test_runs.py::test_failed_run_reports_its_error — slow integration (logic now covered by test_shape_failure_message_is_the_ops_own_exception) removed WebApi/tests/test_runs.py::test_history_filters_by_job_and_domain — implementation-detail removed WebApi/tests/test_runs.py::test_run_requests_validate_the_execution_choice — slow integration (logic now covered by test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode) removed WebApi/tests/test_runs.py::test_execution_options_and_health — implementation-detail removed WebApi/tests/test_runs.py::test_tea_eegs_analyze_validates_scope — slow integration (logic now covered by test_scope_validation) removed WebApi/tests/test_runs.py::test_a_locked_run_storage_is_read_again — implementation-detail removed WebApi/tests/test_runs.py::test_cancel_waits_for_a_starting_run — implementation-detail removed WebApi/tests/test_runs.py::test_cancel_a_finished_run_is_409 — slow integration (logic now covered by test_cancel_a_finished_run_is_409 with a client double) removed WebApi/tests/test_runs_concurrency.py — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for the queued transition) removed WebApi/tests/test_runs_concurrency.py::test_writing_runs_never_overlap — implementation-detail removed WebApi/tests/test_runs_concurrency.py::test_cancelling_an_ingest_run_leaves_no_silver_or_gold — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for the API state transition) removed WebApi/tests/test_runs_concurrency.py::test_cancelling_a_queued_run_never_starts_it — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for the queued transition) removed WebApi/tests/test_runs_concurrency.py::test_a_dead_run_does_not_stay_running — implementation-detail removed WebApi/tests/test_synthea.py — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and test_hospital_codes_and_dates_become_platform_values) removed WebApi/tests/test_synthea.py::test_a_synthea_population_comes_in_through_the_fhir_door — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url and test_hospital_codes_and_dates_become_platform_values) removed WebApi/tests/test_synthea_cama.py — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url for FHIR ingestion mapping) removed WebApi/tests/test_synthea_cama.py::test_a_synthea_cama_population_comes_in_through_the_fhir_door — slow integration (logic now covered by test_fhir_in_joins_encounter_results_and_subject_by_full_url for FHIR ingestion mapping) removed WebApi/tests/test_tea.py — parity-only removed WebApi/tests/test_tea.py::test_tea_from_the_hospital_to_indicators — parity-only removed WebApi/tests/test_training_config.py::test_tea_training_config_schema — slow integration (logic now covered by the direct-call test_tea_training_config_schema) removed WebApi/tests/test_training_config.py::test_other_domains_have_no_reference — slow integration (logic now covered by the direct-call test_other_domains_have_no_reference) removed WebApi/tests/test_training_config.py::test_train_validates_the_reference — slow integration (logic now covered by the direct-call test_train_validates_the_reference and test_bad_references_fail_with_a_reason) removed WebApi/tests/test_webapp.py — slow integration (logic now covered by existing WebApp unit tests for figure, row and export builders; loaded-page browser coverage is deferred to P5.5) removed WebApi/tests/test_webapp.py::test_every_page_loads_from_the_api — slow integration (logic now covered by existing WebApp unit tests for figure, row and export builders; loaded-page browser coverage is deferred to P5.5)
This commit is contained in:
@@ -1,153 +0,0 @@
|
|||||||
"""What the FHIR gate checks with: every resource the API serves, the HL7 validator over
|
|
||||||
them, and the follow-up list read the way the WebApp reads it."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from core import fhir
|
|
||||||
|
|
||||||
VALIDATOR = os.environ.get("FHIR_VALIDATOR_JAR", "/opt/fhir/validator_cli.jar")
|
|
||||||
PAGES = 100 # a search with more pages than this is a paging bug
|
|
||||||
E = fhir.EXTENSION
|
|
||||||
|
|
||||||
|
|
||||||
def pages(api, path: str, params=None) -> list[dict]:
|
|
||||||
"""Every page of a search, following `next` to the end."""
|
|
||||||
found, url = [], path
|
|
||||||
for _ in range(PAGES):
|
|
||||||
response = api.get(url, params=params)
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
assert response.headers["content-type"].startswith("application/fhir+json")
|
|
||||||
found.append(bundle := response.json())
|
|
||||||
url = next((x["url"] for x in bundle["link"] if x["relation"] == "next"), None)
|
|
||||||
params = None # the next link carries the query
|
|
||||||
if url is None:
|
|
||||||
return found
|
|
||||||
raise AssertionError(f"{path}: more than {PAGES} pages")
|
|
||||||
|
|
||||||
|
|
||||||
def served(api, base: str, periods: list[str], patients: list[str]) -> list[dict]:
|
|
||||||
"""Every kind of resource the base serves, each search paged to the end: metadata,
|
|
||||||
the measures and their reports, the follow-up list with what it includes, a read of
|
|
||||||
each patient, and each clinical search for them."""
|
|
||||||
found = [api.get(f"{base}/metadata").json()]
|
|
||||||
found += pages(api, f"{base}/Measure")
|
|
||||||
for measure in [e["resource"]["id"] for b in found[1:] for e in b["entry"]]:
|
|
||||||
found += pages(api, f"{base}/MeasureReport",
|
|
||||||
{"measure": measure, "reporting-period": ",".join(periods)}) # fmt: skip
|
|
||||||
found += pages(api, f"{base}/Patient", [
|
|
||||||
("follow-up-window", 12), ("_count", 25), ("_revinclude", "DiagnosticReport:subject"),
|
|
||||||
("_revinclude", "RiskAssessment:subject"), ("_include:iterate", "DiagnosticReport:result"),
|
|
||||||
]) # fmt: skip
|
|
||||||
found += [api.get(f"{base}/Patient/{p}").json() for p in patients]
|
|
||||||
for kind in ("DiagnosticReport", "Observation", "Condition", "Procedure", "RiskAssessment"):
|
|
||||||
found += pages(api, f"{base}/{kind}", {"subject": ",".join(patients), "_count": 40})
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def validate(resources: list[dict], folder: Path) -> tuple[list[dict], list[dict]]:
|
|
||||||
"""The HL7 validator (offline: no terminology server) over the resources, with our
|
|
||||||
conformance resources loaded: its errors and its warnings."""
|
|
||||||
data, ig = folder / "served", folder / "ig"
|
|
||||||
data.mkdir()
|
|
||||||
ig.mkdir()
|
|
||||||
for i, resource in enumerate(resources):
|
|
||||||
(data / f"{i:05d}.json").write_text(json.dumps(resource))
|
|
||||||
for resource in fhir.conformance():
|
|
||||||
(ig / f"{resource.get_resource_type()}-{resource.id}.json").write_text(
|
|
||||||
resource.model_dump_json(exclude_none=True)) # fmt: skip
|
|
||||||
out = folder / "outcome.json"
|
|
||||||
subprocess.run(["java", "-jar", VALIDATOR, str(data), str(ig), "-version", fhir.FHIR_VERSION,
|
|
||||||
"-tx", "n/a", "-ig", str(ig), "-output", str(out)],
|
|
||||||
check=False, capture_output=True) # fmt: skip
|
|
||||||
outcome = json.loads(out.read_text())
|
|
||||||
outcomes = [e["resource"] for e in outcome.get("entry", [])] or [outcome]
|
|
||||||
issues = [i for o in outcomes for i in o.get("issue", [])]
|
|
||||||
errors = [i for i in issues if i["severity"] in ("error", "fatal")]
|
|
||||||
return errors, [i for i in issues if i["severity"] == "warning"]
|
|
||||||
|
|
||||||
|
|
||||||
SCORE_REQUIRED = "A measureScore is required when the Measure.scoring="
|
|
||||||
|
|
||||||
|
|
||||||
def unscored(issue: dict, resources: list[dict]) -> bool:
|
|
||||||
"""The validator's one allowed error: a summary report of a period with nothing to
|
|
||||||
score (no denominator, nothing measured) has no score, since the rate or median is
|
|
||||||
undefined. FHIR's validator asks for one anyway."""
|
|
||||||
text = issue.get("details", {}).get("text", "")
|
|
||||||
where = " ".join(issue.get("expression", []))
|
|
||||||
if not text.startswith(SCORE_REQUIRED) or "/*MeasureReport/" not in where:
|
|
||||||
return False
|
|
||||||
report_id = where.split("/*MeasureReport/")[1].split("*/")[0]
|
|
||||||
everything = [r for b in resources for r in [b, *(e["resource"] for e in b.get("entry", []))]]
|
|
||||||
reports = [r for r in everything if r.get("id") == report_id
|
|
||||||
and r.get("resourceType") == "MeasureReport"] # fmt: skip
|
|
||||||
counts = {p["code"]["coding"][0]["code"]: p["count"]
|
|
||||||
for r in reports for p in r["group"][0]["population"]} # fmt: skip
|
|
||||||
nothing = counts.get("denominator", counts.get("measure-observation")) == 0
|
|
||||||
scored = any("measureScore" in r["group"][0] for r in reports)
|
|
||||||
return bool(reports) and nothing and not scored
|
|
||||||
|
|
||||||
|
|
||||||
def _ext(resource: dict, name: str) -> dict | None:
|
|
||||||
return next((x for x in resource.get("extension", []) if x["url"] == E + name), None)
|
|
||||||
|
|
||||||
|
|
||||||
def _code(concept: dict) -> str:
|
|
||||||
return concept["coding"][0]["code"]
|
|
||||||
|
|
||||||
|
|
||||||
def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]:
|
|
||||||
"""The follow-up list as the WebApp shows it, in order: per patient, her status, her
|
|
||||||
latest cytology and HPV sampled in the window, her days to diagnosis, and her latest
|
|
||||||
reported biopsy."""
|
|
||||||
included = {(e["resource"]["resourceType"], e["resource"]["id"]): e["resource"]
|
|
||||||
for b in bundles for e in b.get("entry", [])} # fmt: skip
|
|
||||||
rows = []
|
|
||||||
for b in bundles:
|
|
||||||
for patient in (e["resource"] for e in b.get("entry", [])
|
|
||||||
if e["search"]["mode"] == "match"): # fmt: skip
|
|
||||||
reports = [r for (kind, _), r in included.items() if kind == "DiagnosticReport"
|
|
||||||
and r["subject"]["reference"] == f"Patient/{patient['id']}"] # fmt: skip
|
|
||||||
|
|
||||||
def results(report: dict) -> dict:
|
|
||||||
return {_code(o["code"]): o for o in (
|
|
||||||
included[("Observation", x["reference"].split("/")[1])]
|
|
||||||
for x in report.get("result", []))} # fmt: skip
|
|
||||||
|
|
||||||
cytologies = sorted(
|
|
||||||
(r for r in reports if _code(r["code"]) == "cervical_cytology"
|
|
||||||
and start <= r["effectiveDateTime"] <= cutoff),
|
|
||||||
key=lambda r: r["effectiveDateTime"]) # fmt: skip
|
|
||||||
hpv = [r for r in cytologies if "cervical_cytology.hpv" in results(r)]
|
|
||||||
biopsies = sorted((r for r in reports if _code(r["code"]) == "cervical_biopsy"
|
|
||||||
and _ext(r, "report-date")),
|
|
||||||
key=lambda r: _ext(r, "report-date")["valueDate"]) # fmt: skip
|
|
||||||
status = _ext(patient, "follow-up-status")["valueCoding"]["code"]
|
|
||||||
row = {"person": patient["id"], "status": status, "cytology": None, "hpv": None,
|
|
||||||
"days_to_diagnosis": None, "biopsy": None} # fmt: skip
|
|
||||||
if cytologies:
|
|
||||||
last, found = cytologies[-1], results(cytologies[-1])
|
|
||||||
row["cytology"] = {"date": last["effectiveDateTime"], **{
|
|
||||||
k: _code(found[c]["valueCodeableConcept"]) if c in found else None
|
|
||||||
for k, c in (("result", "cervical_cytology.result"),
|
|
||||||
("adequacy", "cervical_cytology.adequacy"))}} # fmt: skip
|
|
||||||
days = _ext(last, "days-to-diagnosis")
|
|
||||||
row["days_to_diagnosis"] = days and days["valueInteger"]
|
|
||||||
if hpv:
|
|
||||||
found = results(hpv[-1])
|
|
||||||
typed = ("cervical_cytology.hpv_16", "cervical_cytology.hpv_18")
|
|
||||||
types = [found[k]["valueBoolean"] for k in typed if k in found]
|
|
||||||
row["hpv"] = {"date": hpv[-1]["effectiveDateTime"],
|
|
||||||
"positive": found["cervical_cytology.hpv"]["valueBoolean"],
|
|
||||||
"types_16_18": any(types) if types else None} # fmt: skip
|
|
||||||
if biopsies:
|
|
||||||
last, found = biopsies[-1], results(biopsies[-1])
|
|
||||||
grade = found.get("cervical_biopsy.histology")
|
|
||||||
histology = grade and _code(grade["valueCodeableConcept"])
|
|
||||||
row["biopsy"] = {"date": _ext(last, "report-date")["valueDate"],
|
|
||||||
"histology": histology} # fmt: skip
|
|
||||||
rows.append(row)
|
|
||||||
return rows
|
|
||||||
+29
-121
@@ -1,129 +1,37 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import time
|
from io import BytesIO
|
||||||
from pathlib import Path
|
from zipfile import ZipFile
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from fastapi import HTTPException, UploadFile
|
||||||
|
|
||||||
from models.tea.jobs import Baseline
|
from core.domains import Domain
|
||||||
from persistance import bundle, config, registry
|
from persistance import config
|
||||||
|
from webapi.models import import_models
|
||||||
NAME = "tea.curve_x"
|
|
||||||
|
|
||||||
|
|
||||||
def _register(platform, monkeypatch, n_reference=10):
|
@pytest.mark.parametrize(
|
||||||
with monkeypatch.context() as local:
|
("kind", "status", "detail"),
|
||||||
local.setenv("MLFLOW_TRACKING_URI", platform.env["MLFLOW_TRACKING_URI"])
|
[
|
||||||
local.chdir(platform.env["ISSSTELEON_DATA"])
|
("wrong_sha", 422, "not the one given"),
|
||||||
version = registry.register(
|
("non_zip", 422, "not a bundle"),
|
||||||
NAME,
|
("untrusted", 403, "not trusted on this server"),
|
||||||
Baseline("x", {"value": {}}),
|
],
|
||||||
{},
|
|
||||||
{"n_reference": n_reference},
|
|
||||||
{"technical_validation": {}, "interpretability": {}},
|
|
||||||
)
|
)
|
||||||
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
|
def test_import_rejects_invalid_uploads(tmp_path, monkeypatch, kind, status, detail):
|
||||||
registry.promote(NAME, version)
|
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
||||||
|
if kind == "non_zip":
|
||||||
|
data = b"hello"
|
||||||
|
else:
|
||||||
|
buffer = BytesIO()
|
||||||
|
with ZipFile(buffer, "w") as archive:
|
||||||
|
archive.writestr("manifest.json", "{}")
|
||||||
|
data = buffer.getvalue()
|
||||||
|
digest = hashlib.sha256(data).hexdigest()
|
||||||
|
sent = "0" * 64 if kind == "wrong_sha" else digest
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as rejected:
|
||||||
@pytest.fixture
|
import_models(Domain.TEA, sent, UploadFile(BytesIO(data), filename="bundle.zip"))
|
||||||
def exported(api, platform, monkeypatch):
|
assert rejected.value.status_code == status
|
||||||
_register(platform, monkeypatch)
|
assert detail in rejected.value.detail
|
||||||
response = api.get("/models/tea/export")
|
assert not (tmp_path / "bundles" / f"{digest}.zip").exists()
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
return response
|
|
||||||
|
|
||||||
|
|
||||||
def _trust(platform, sha, monkeypatch):
|
|
||||||
with monkeypatch.context() as local:
|
|
||||||
local.setattr(config, "DATA_DIR", Path(platform.env["ISSSTELEON_DATA"]))
|
|
||||||
bundle.trusted_file().write_text(f"{sha}\n")
|
|
||||||
|
|
||||||
|
|
||||||
def _post(api, data, sha):
|
|
||||||
return api.post(
|
|
||||||
"/models/tea/import", params={"sha256": sha}, files={"file": ("bundle.zip", data)}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _run(api, response):
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
run_id = response.json()["run_id"]
|
|
||||||
deadline = time.monotonic() + 120
|
|
||||||
while True:
|
|
||||||
response = api.get(f"/runs/{run_id}")
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
run = response.json()
|
|
||||||
if run["state"] in {"succeeded", "failed", "cancelled"}:
|
|
||||||
return run
|
|
||||||
assert time.monotonic() < deadline, run
|
|
||||||
time.sleep(1)
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_and_import_through_the_api(exported, fresh_api, fresh_platform, monkeypatch):
|
|
||||||
sha = hashlib.sha256(exported.content).hexdigest()
|
|
||||||
assert exported.headers["content-type"] == "application/zip"
|
|
||||||
assert exported.headers["x-bundle-sha256"] == sha
|
|
||||||
assert exported.headers["x-bundle-versions"] == "tea.curve_x/1"
|
|
||||||
assert (
|
|
||||||
exported.headers["content-disposition"]
|
|
||||||
== f'attachment; filename="tea-models-{sha[:12]}.zip"'
|
|
||||||
)
|
|
||||||
_trust(fresh_platform, sha, monkeypatch)
|
|
||||||
run = _run(fresh_api, _post(fresh_api, exported.content, sha.upper()))
|
|
||||||
assert run["state"] == "succeeded", run
|
|
||||||
response = fresh_api.get("/models/tea/curve_x/versions")
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
(version,) = response.json()
|
|
||||||
assert version["version"] == 1
|
|
||||||
assert version["metrics"]["n_reference"] == 10
|
|
||||||
assert version["reports"] == sorted(registry.REPORTS)
|
|
||||||
assert version["aliases"] == []
|
|
||||||
|
|
||||||
|
|
||||||
def test_import_refuses_a_wrong_sha_and_a_non_zip(api, exported):
|
|
||||||
wrong = _post(api, exported.content, "0" * 64)
|
|
||||||
assert wrong.status_code == 422
|
|
||||||
assert wrong.json()["detail"] == (
|
|
||||||
f"the file's SHA-256 is {exported.headers['x-bundle-sha256']}, not the one given"
|
|
||||||
)
|
|
||||||
non_zip = _post(api, b"hello", hashlib.sha256(b"hello").hexdigest())
|
|
||||||
assert non_zip.status_code == 422
|
|
||||||
assert non_zip.json()["detail"] == "not a bundle"
|
|
||||||
|
|
||||||
|
|
||||||
def test_importing_the_same_bundle_again_fails_the_run(
|
|
||||||
exported,
|
|
||||||
fresh_api,
|
|
||||||
fresh_platform,
|
|
||||||
monkeypatch,
|
|
||||||
):
|
|
||||||
sha = exported.headers["x-bundle-sha256"]
|
|
||||||
_trust(fresh_platform, sha, monkeypatch)
|
|
||||||
first = _run(fresh_api, _post(fresh_api, exported.content, sha))
|
|
||||||
assert first["state"] == "succeeded", first
|
|
||||||
second = _run(fresh_api, _post(fresh_api, exported.content, sha))
|
|
||||||
assert second["state"] == "failed", second
|
|
||||||
assert "already registered" in second["error"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_export_guard_failure_is_422(api, platform, monkeypatch):
|
|
||||||
assert api.get("/models/cacu/export").status_code == 409
|
|
||||||
_register(platform, monkeypatch, n_reference=3)
|
|
||||||
response = api.get("/models/tea/export")
|
|
||||||
assert response.status_code == 422
|
|
||||||
assert "reference group of 3 children is under 5" in response.json()["detail"]
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_untrusted_bundle_is_refused(api, platform, exported):
|
|
||||||
sha = exported.headers["x-bundle-sha256"]
|
|
||||||
response = _post(api, exported.content, sha)
|
|
||||||
assert response.status_code == 403
|
|
||||||
directory = Path(platform.env["ISSSTELEON_DATA"]) / "bundles"
|
|
||||||
assert response.json()["detail"] == (
|
|
||||||
f"bundle {sha} is not trusted on this server: "
|
|
||||||
f"the operator adds its SHA-256 to {directory / 'trusted'}"
|
|
||||||
)
|
|
||||||
assert not (directory / f"{sha}.zip").exists()
|
|
||||||
history = api.get("/runs", params={"job": "import_bundle"})
|
|
||||||
assert history.status_code == 200, history.text
|
|
||||||
assert history.json() == []
|
|
||||||
|
|||||||
@@ -1,213 +0,0 @@
|
|||||||
"""Phase 2 gate, CaCu: the synthetic hospital, loaded through one drawn pipeline, gives what
|
|
||||||
the current platform gives on the same hospital (the reference fixtures): its cohorts, its
|
|
||||||
indicators, and, trained by the platform's own jobs, its models' predictions. Promotion
|
|
||||||
needs the three reports. Real API, Dagster and MLflow; nothing faked.
|
|
||||||
|
|
||||||
Phase 3 adds the FHIR gate: every resource the API serves passes the HL7 validator, and
|
|
||||||
the follow-up list is the current platform's.
|
|
||||||
|
|
||||||
Fixed on purpose, so compared differently:
|
|
||||||
- cin2_pim_post_colposcopy scores each patient at her post-colposcopy index; the current
|
|
||||||
one scores at her first event (its cohort's index), so only its members are compared.
|
|
||||||
- cin2_logistic's index date is the index sample's, not 1970-01-01.
|
|
||||||
- survival indexes at the first biopsy reported as carcinoma or carcinoma in situ; the current
|
|
||||||
index read only invasive carcinoma and indexed nobody (its reference was captured with that
|
|
||||||
one rule fixed).
|
|
||||||
- One rule, one value: a diagnosis note assesses a sample within SAMPLE_TO_DIAGNOSIS_DAYS
|
|
||||||
(120). The current follow-up status reads the same rule as 180 days, so one patient
|
|
||||||
(198) is post-colposcopy there and pre-colposcopy here.
|
|
||||||
- FHIR asks every summary report for a score: a composition scores its count. A period
|
|
||||||
with nothing measured keeps its counts and has no score, the validator's one allowed
|
|
||||||
error (see fhir_checks.unscored).
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sqlite3
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
|
||||||
import pytest
|
|
||||||
from fhir_checks import follow_up, pages, served, unscored, validate
|
|
||||||
from test_conectar import ok, wait_for
|
|
||||||
|
|
||||||
from conftest import put_concept_map
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
|
||||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cacu"
|
|
||||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
|
|
||||||
REFERENCE_CUTOFF = "2026-11-23" # the current platform's cohort cut-off (follow-up ends)
|
|
||||||
CAPTURED_ON = "2026-11-25" # the day the indicators were captured: durations counted to it
|
|
||||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
|
||||||
COHORTS = {
|
|
||||||
"cacu_cohort_total": "cohorte_total",
|
|
||||||
"cacu_cohort_surveillance": "cohorte_vigilancia",
|
|
||||||
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
|
|
||||||
}
|
|
||||||
CODES = { # platform code -> the current platform's
|
|
||||||
"NILM": "NORMAL", "LSIL": "LIEBG", "HSIL": "LIEAG", "carcinoma": "CARCINOMA",
|
|
||||||
"normal": "NORMAL", "no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA",
|
|
||||||
"post_treatment": "POST_TRATAMIENTO", "post_colposcopy": "POST_COLPOSCOPIA",
|
|
||||||
"pre_colposcopy": "PRE_COLPOSCOPIA", "case": "CASO", "satisfactory": "SATISFACTORIO",
|
|
||||||
"unsatisfactory": "INSATISFACTORIO",
|
|
||||||
} # fmt: skip
|
|
||||||
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
|
|
||||||
"result": "citologia_alto_grado"} # fmt: skip
|
|
||||||
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
|
|
||||||
|
|
||||||
|
|
||||||
def _patients(q) -> dict[str, int]:
|
|
||||||
"""Each person's patient id in the hospital (for comparing only)."""
|
|
||||||
with sqlite3.connect(HOSPITAL / "hospital_cacu.db") as con:
|
|
||||||
number = {n.replace("-", ""): p for p, n in con.execute(
|
|
||||||
"select pac_id, pac_id_hospital from paciente")} # fmt: skip
|
|
||||||
rows = q("select distinct person_id, record_number from bronze.staged__identity")
|
|
||||||
return {person: number[record] for person, record in rows}
|
|
||||||
|
|
||||||
|
|
||||||
def _report(entry: dict, measure: str) -> tuple:
|
|
||||||
group = entry["resource"]["group"][0]
|
|
||||||
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
|
||||||
score = group.get("measureScore", {})
|
|
||||||
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
|
|
||||||
strata = {}
|
|
||||||
for s in group.get("stratifier", []):
|
|
||||||
code = s["code"][0]
|
|
||||||
name = code["coding"][0]["code"] if "coding" in code else code["text"]
|
|
||||||
name = CATEGORY.get(measure, "banda") if name == "category" else STRATA.get(name, name)
|
|
||||||
strata[name] = {CODES.get(x["value"]["text"], x["value"]["text"]): {
|
|
||||||
p["code"]["coding"][0]["code"]: p["count"] for p in x["population"]}
|
|
||||||
for x in s.get("stratum", [])} # fmt: skip
|
|
||||||
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
|
|
||||||
|
|
||||||
|
|
||||||
def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path):
|
|
||||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
|
||||||
put_concept_map(api, "hospital_cacu")
|
|
||||||
ok(api.put("/ingest/pipelines/cacu", json=pipeline))
|
|
||||||
wait_for(api, ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"])
|
|
||||||
q = platform.query
|
|
||||||
patient = _patients(q)
|
|
||||||
|
|
||||||
# Cohorts: the same patients, indexed on the same day.
|
|
||||||
for ours, theirs in COHORTS.items():
|
|
||||||
sql = f"select person_id, index_date from gold.{ours} where excluded_by is null"
|
|
||||||
found = {(patient[p], str(d)) for p, d in q(sql)}
|
|
||||||
frame = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / theirs / "dbt" / "1.parquet")
|
|
||||||
frame["fecha_indice"] = frame["fecha_indice"].astype(str)
|
|
||||||
assert found == set(frame[["pac_id", "fecha_indice"]].drop_duplicates()
|
|
||||||
.itertuples(index=False, name=None)), ours # fmt: skip
|
|
||||||
current = json.loads((REFERENCE / "models.json").read_text())
|
|
||||||
post_colposcopy = current["cin2_pim_post_colposcopy"]["version"]["metrics"]
|
|
||||||
members = q("select count(*) from gold.cacu_cohort_post_colposcopy where excluded_by is null")
|
|
||||||
assert members[0][0] == post_colposcopy["n_train"] + post_colposcopy["n_test"]
|
|
||||||
|
|
||||||
# Indicators: every measure, every semester, as the current platform answers them
|
|
||||||
# (no risk batch yet, so the risk bands are empty as they were).
|
|
||||||
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
|
||||||
(measures,) = pages(api, "/cacu/fhir/Measure")
|
|
||||||
for measure in [e["resource"] for e in measures["entry"]]:
|
|
||||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
|
||||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
|
||||||
found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
|
|
||||||
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
|
|
||||||
name = measure["name"]
|
|
||||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
|
||||||
a, b = _report(ours, name), _report(theirs, name)
|
|
||||||
where = (name, ours["resource"]["period"]["start"])
|
|
||||||
assert a[0] == b[0] and a[3] == b[3], where
|
|
||||||
if cohort: # scores its count; the current platform gave none
|
|
||||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
|
||||||
continue
|
|
||||||
assert (a[1] is None) == (b[1] is None), where
|
|
||||||
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
|
|
||||||
assert a[2] == pytest.approx(b[2]), where
|
|
||||||
|
|
||||||
# Models: one training run gives a version of each, with its two generated reports;
|
|
||||||
# none is promoted without the clinical validation.
|
|
||||||
wait_for(api, ok(api.post("/models/cacu/train", json={"as_of": REFERENCE_CUTOFF}))["run_id"])
|
|
||||||
names = ok(api.get("/models/cacu"))
|
|
||||||
assert set(names) == set(current)
|
|
||||||
for name in names:
|
|
||||||
(version,) = ok(api.get(f"/models/cacu/{name}/versions"))
|
|
||||||
assert version["reports"] == ["interpretability", "technical_validation"]
|
|
||||||
for metric in ("n_train", "n_test"):
|
|
||||||
assert version["metrics"][metric] == current[name]["version"]["metrics"][metric]
|
|
||||||
assert api.post(f"/models/cacu/{name}/versions/1/promote").status_code == 409
|
|
||||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
|
||||||
ok(api.post(f"/models/cacu/{name}/versions/1/reports/clinical_validation", files=files))
|
|
||||||
assert ok(api.post(f"/models/cacu/{name}/versions/1/promote")) == {"champion": 1}
|
|
||||||
|
|
||||||
# Risks: the champions score their cohorts with the current models' predictions.
|
|
||||||
wait_for(api, ok(api.post("/models/cacu/score"))["run_id"])
|
|
||||||
for name in names:
|
|
||||||
risks = pd.DataFrame(q(
|
|
||||||
"select person_id, index_date, horizon_years, probability, ci_low, ci_high "
|
|
||||||
f"from gold.cacu_risk where model = 'cacu.{name}'"
|
|
||||||
), columns=["person_id", "index_date", "horizon_years", "probability", "ci_low",
|
|
||||||
"ci_high"]) # fmt: skip
|
|
||||||
risks["pac_id"] = risks["person_id"].map(patient)
|
|
||||||
expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
|
||||||
if name == "cin2_pim_post_colposcopy": # fixed: scored at her own index
|
|
||||||
cohort = q("select person_id, index_date from gold.cacu_cohort_post_colposcopy "
|
|
||||||
"where excluded_by is null") # fmt: skip
|
|
||||||
assert set(map(tuple, risks[["person_id", "index_date"]].astype(str).values)) == {
|
|
||||||
(p, str(d)) for p, d in cohort} # fmt: skip
|
|
||||||
continue
|
|
||||||
both = risks.merge(expected, left_on=["pac_id", "horizon_years"],
|
|
||||||
right_on=["pac_id", "horizonte_anios"], how="outer",
|
|
||||||
indicator=True) # fmt: skip
|
|
||||||
assert (both["_merge"] == "both").all(), name
|
|
||||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
|
||||||
("ci_high", "ic_alto")]: # fmt: skip
|
|
||||||
if theirs in both:
|
|
||||||
np.testing.assert_allclose(both[ours].astype(float), both[theirs], rtol=1e-6)
|
|
||||||
|
|
||||||
# The risk band now has the surveillance cohort's scored members.
|
|
||||||
params = {"measure": "cacu-riesgo-banda", "reporting-period": "2025-S1"}
|
|
||||||
(bands,) = pages(api, "/cacu/fhir/MeasureReport", params)
|
|
||||||
assert bands["entry"][0]["resource"]["group"][0]["population"][0]["count"] > 0
|
|
||||||
|
|
||||||
# The follow-up list: the current platform's, at its cut-off, with the same window.
|
|
||||||
page = json.loads((REFERENCE / "pages.json").read_text())
|
|
||||||
theirs = page["/cacu/seguimiento?page_size=200"]["body"]
|
|
||||||
window, cutoff = theirs["ventana"], theirs["corte"]
|
|
||||||
params = [("follow-up-window", window["meses"]), ("follow-up-cutoff", cutoff),
|
|
||||||
("_count", 20), ("_revinclude", "DiagnosticReport:subject"),
|
|
||||||
("_include:iterate", "DiagnosticReport:result")] # fmt: skip
|
|
||||||
ours = follow_up(pages(api, "/cacu/fhir/Patient", params), window["desde"], cutoff)
|
|
||||||
assert [r["cytology"]["date"] for r in ours] == [
|
|
||||||
i["ultima_citologia"]["fecha"] for i in theirs["items"]
|
|
||||||
] # same order (ties aside)
|
|
||||||
expected = {int(i["pac_id"]): i for i in theirs["items"]}
|
|
||||||
assert {patient[r["person"]] for r in ours} == set(expected)
|
|
||||||
for row in ours:
|
|
||||||
cytology, hpv, biopsy = row["cytology"], row["hpv"], row["biopsy"]
|
|
||||||
shown = {
|
|
||||||
"estatus": CODES[row["status"]],
|
|
||||||
"ultima_citologia": {"fecha": cytology["date"],
|
|
||||||
"bethesda": CODES.get(cytology["result"], cytology["result"]),
|
|
||||||
"calidad": CODES.get(cytology["adequacy"])},
|
|
||||||
"ultimo_vph": hpv and {"fecha": hpv["date"], "genotipo_16_18": hpv["types_16_18"],
|
|
||||||
"resultado": "POSITIVO" if hpv["positive"] else "NEGATIVO"},
|
|
||||||
"dias_toma_diagnostico": row["days_to_diagnosis"],
|
|
||||||
"ultima_biopsia": biopsy and {
|
|
||||||
"fecha": biopsy["date"],
|
|
||||||
"grado": CODES.get(biopsy["histology"], biopsy["histology"]),
|
|
||||||
},
|
|
||||||
} # fmt: skip
|
|
||||||
item = expected[patient[row["person"]]]
|
|
||||||
if patient[row["person"]] == 198: # fixed: one horizon (120 days), not 180
|
|
||||||
assert (shown["estatus"], item["estatus"]["codigo"]) == (
|
|
||||||
"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA") # fmt: skip
|
|
||||||
shown["estatus"] = "POST_COLPOSCOPIA"
|
|
||||||
assert shown == {**{k: item[k] for k in shown}, "estatus": item["estatus"]["codigo"]}
|
|
||||||
|
|
||||||
# Every resource the API serves, every search paged to the end, passes the HL7
|
|
||||||
# validator (offline: structure, cardinality, profiles; no terminology server).
|
|
||||||
people = [r["person"] for r in ours[:10]]
|
|
||||||
resources = served(api, "/cacu/fhir", PERIODS, people)
|
|
||||||
errors, warnings = validate(resources, tmp_path)
|
|
||||||
print(f"HL7 validator: {len(warnings)} warnings")
|
|
||||||
assert [e for e in errors if not unscored(e, resources)] == []
|
|
||||||
@@ -1,207 +0,0 @@
|
|||||||
"""Phase 4 gate, CaMa: the synthetic hospital, loaded through one drawn pipeline, gives what
|
|
||||||
the current platform gives on the same hospital (the reference fixtures, captured at the last
|
|
||||||
load): its indicators, its follow-up list and, trained by the platform's own jobs, its
|
|
||||||
models' predictions. Real API, Dagster and MLflow; nothing faked.
|
|
||||||
|
|
||||||
Fixed on purpose, so compared differently:
|
|
||||||
- Survival follows each patient up to the day it is trained (`as_of`), not to the day the
|
|
||||||
job happens to run: the reference was trained on 2026-11-24.
|
|
||||||
- BI-RADS 4A, 4B and 4C are kept as reported. The current platform folds them into 4 when it
|
|
||||||
loads them, so here they are summed into its B4, and only here.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sqlite3
|
|
||||||
from collections import defaultdict
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import pandas as pd
|
|
||||||
import pytest
|
|
||||||
from fhir_checks import pages, served, unscored, validate
|
|
||||||
from test_conectar import ok, wait_for
|
|
||||||
|
|
||||||
from conftest import put_concept_map
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
|
||||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cama"
|
|
||||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cama.json"
|
|
||||||
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
|
|
||||||
TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained
|
|
||||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
|
||||||
CODES = { # platform code -> the current platform's
|
|
||||||
**{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")},
|
|
||||||
"4A": "B4", "4B": "B4", "4C": "B4",
|
|
||||||
"benign": "BENIGNO", "in_situ": "CARCINOMA_IN_SITU", "invasive": "CARCINOMA_INVASOR",
|
|
||||||
"no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA",
|
|
||||||
} # fmt: skip
|
|
||||||
CATEGORY = {"CAMA_BIOPSIAS": "grado", "CAMA_HISTOPATOLOGIA_BIRADS": "biopsia_grado"}
|
|
||||||
STATUS = {"cancer": "Diagnóstico confirmado, sin tratamiento registrado",
|
|
||||||
"pending_biopsy": "Pendiente de biopsia", "biopsy_no_result": "Biopsia sin resultado",
|
|
||||||
"benign_biopsy": "Biopsia benigna"} # fmt: skip
|
|
||||||
PRIORITY = {"high": "Alta", "medium": "Media", "low": "Baja"}
|
|
||||||
E = "https://isssteleon.org/fhir/StructureDefinition/"
|
|
||||||
|
|
||||||
|
|
||||||
def _patients(q) -> dict[str, str]:
|
|
||||||
"""Each person's patient id in the hospital (for comparing only)."""
|
|
||||||
with sqlite3.connect(HOSPITAL / "hospital_cama.db") as con:
|
|
||||||
number = {n.replace("-", ""): str(p) for p, n in con.execute(
|
|
||||||
"select pac_id, pac_id_hospital from paciente")} # fmt: skip
|
|
||||||
rows = q("select distinct person_id, record_number from bronze.staged__identity")
|
|
||||||
return {person: number[record] for person, record in rows}
|
|
||||||
|
|
||||||
|
|
||||||
def _ext(resource: dict, name: str):
|
|
||||||
found = next((x for x in resource.get("extension", []) if x["url"] == E + name), None)
|
|
||||||
return found and next(v for k, v in found.items() if k.startswith("value"))
|
|
||||||
|
|
||||||
|
|
||||||
def _follow_up(bundles: list[dict], cutoff: str, patient: dict[str, str]) -> list[dict]:
|
|
||||||
"""The follow-up list as the WebApp shows it: per patient, her status and priority, her
|
|
||||||
latest mammogram reported by the cut-off, and the latest reported biopsy it led to."""
|
|
||||||
resources = [e["resource"] for b in bundles for e in b.get("entry", [])]
|
|
||||||
observations = {r["id"]: r for r in resources if r["resourceType"] == "Observation"}
|
|
||||||
|
|
||||||
def values(report: dict) -> dict:
|
|
||||||
found = {}
|
|
||||||
for x in report.get("result", []):
|
|
||||||
o = observations[x["reference"].split("/")[1]]
|
|
||||||
value = o.get("valueDateTime") or o.get("valueCodeableConcept", {})
|
|
||||||
found[o["code"]["coding"][0]["code"].split(".")[1]] = (
|
|
||||||
value if isinstance(value, str) else value["coding"][0]["code"]
|
|
||||||
)
|
|
||||||
return found # fmt: skip
|
|
||||||
|
|
||||||
rows = []
|
|
||||||
for p in (r for r in resources if r["resourceType"] == "Patient"):
|
|
||||||
mine = [r for r in resources if r["resourceType"] == "DiagnosticReport"
|
|
||||||
and r["subject"]["reference"] == f"Patient/{p['id']}"] # fmt: skip
|
|
||||||
mammograms = [(r["effectiveDateTime"], values(r)) for r in mine
|
|
||||||
if r["code"]["coding"][0]["code"] == "mammography"
|
|
||||||
and (_ext(r, "report-date") or "9") <= cutoff] # fmt: skip
|
|
||||||
exam, mammogram = max(mammograms, key=lambda m: m[0])
|
|
||||||
biopsies = sorted((_ext(r, "report-date"), values(r)) for r in mine
|
|
||||||
if r["code"]["coding"][0]["code"] == "breast_biopsy"
|
|
||||||
and _ext(r, "report-date")
|
|
||||||
and exam <= _ext(r, "report-date") <= cutoff) # fmt: skip
|
|
||||||
biopsies = [b for b in biopsies if b[1].get("mammogram_exam_date") == exam]
|
|
||||||
last = biopsies[-1] if biopsies else (None, {})
|
|
||||||
rows.append({
|
|
||||||
"pac_id": patient[p["id"]], "mastografia_fecha": exam,
|
|
||||||
"birads": "BIRADS_" + mammogram["birads"][:1],
|
|
||||||
"estatus": STATUS[_ext(p, "follow-up-status")["code"]],
|
|
||||||
"prioridad": PRIORITY[_ext(p, "follow-up-priority")["code"]],
|
|
||||||
"biopsia": CODES.get(last[1].get("histology")), "biopsia_fecha": last[0],
|
|
||||||
}) # fmt: skip
|
|
||||||
return rows
|
|
||||||
|
|
||||||
|
|
||||||
def _report(entry: dict, measure: str) -> tuple:
|
|
||||||
group = entry["resource"]["group"][0]
|
|
||||||
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
|
||||||
score = group.get("measureScore", {})
|
|
||||||
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
|
|
||||||
strata = {}
|
|
||||||
for s in group.get("stratifier", []):
|
|
||||||
code = s["code"][0]
|
|
||||||
name = code["coding"][0]["code"] if "coding" in code else code["text"]
|
|
||||||
name = CATEGORY.get(measure, "birads") if name == "category" else name
|
|
||||||
cells: dict = defaultdict(lambda: defaultdict(int))
|
|
||||||
for x in s.get("stratum", []):
|
|
||||||
for p in x["population"]:
|
|
||||||
cells[CODES.get(x["value"]["text"], x["value"]["text"])][
|
|
||||||
p["code"]["coding"][0]["code"]] += p["count"] # fmt: skip
|
|
||||||
strata[name] = {k: dict(v) for k, v in cells.items()}
|
|
||||||
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
|
|
||||||
|
|
||||||
|
|
||||||
def test_cama_from_the_hospital_to_indicators(api, platform, tmp_path):
|
|
||||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
|
||||||
put_concept_map(api, "hospital_cama")
|
|
||||||
ok(api.put("/ingest/pipelines/cama", json=pipeline))
|
|
||||||
wait_for(api, ok(api.post("/ingest/pipelines/cama/runs", json={}))["run_id"])
|
|
||||||
|
|
||||||
# Indicators: every measure, every semester, as the current platform answers them.
|
|
||||||
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
|
||||||
(measures,) = pages(api, "/cama/fhir/Measure")
|
|
||||||
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
|
|
||||||
for measure in [e["resource"] for e in measures["entry"]]:
|
|
||||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
|
||||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
|
||||||
found = [e for b in pages(api, "/cama/fhir/MeasureReport", params) for e in b["entry"]]
|
|
||||||
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
|
|
||||||
name = measure["name"]
|
|
||||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
|
||||||
a, b = _report(ours, name), _report(theirs, name)
|
|
||||||
where = (name, ours["resource"]["period"]["start"])
|
|
||||||
assert a[0] == b[0] and a[3] == b[3], (where, a, b)
|
|
||||||
if cohort: # scores its count; the current platform gave none
|
|
||||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
|
||||||
continue
|
|
||||||
assert (a[1] is None) == (b[1] is None), where
|
|
||||||
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
|
|
||||||
assert a[2] == pytest.approx(b[2]), where
|
|
||||||
|
|
||||||
# The follow-up list: who, in which order, where her biopsy stands and how soon.
|
|
||||||
theirs = json.loads((REFERENCE / "pages.json").read_text())["/cama/seguimiento"]["body"]
|
|
||||||
window = theirs["ventana"]
|
|
||||||
params = {"follow-up-window": window["meses"], "follow-up-cutoff": window["hasta"],
|
|
||||||
"_revinclude": "DiagnosticReport:subject",
|
|
||||||
"_include:iterate": "DiagnosticReport:result", "_count": 200} # fmt: skip
|
|
||||||
ours = _follow_up(pages(api, "/cama/fhir/Patient", params), window["hasta"],
|
|
||||||
_patients(platform.query)) # fmt: skip
|
|
||||||
keys = ("pac_id", "mastografia_fecha", "birads", "estatus", "prioridad", "biopsia",
|
|
||||||
"biopsia_fecha") # fmt: skip
|
|
||||||
order = lambda r: (r["mastografia_fecha"], -int(r["pac_id"])) # noqa: E731
|
|
||||||
expected = [{k: r[k] for k in keys} for r in theirs["items"]]
|
|
||||||
assert sorted(ours, key=order, reverse=True) == sorted(expected, key=order, reverse=True)
|
|
||||||
assert [r["mastografia_fecha"] for r in ours] == [r["mastografia_fecha"] for r in expected]
|
|
||||||
|
|
||||||
# Models: one training run gives a version of each, with its two generated reports;
|
|
||||||
# none is promoted without the clinical validation.
|
|
||||||
current = json.loads((REFERENCE / "models.json").read_text())
|
|
||||||
wait_for(api, ok(api.post("/models/cama/train", json={"as_of": TRAINED_ON}))["run_id"])
|
|
||||||
names = ok(api.get("/models/cama"))
|
|
||||||
assert set(names) == {n for n, m in current.items() if m["status"] == "ok"}
|
|
||||||
for name in names:
|
|
||||||
(version,) = ok(api.get(f"/models/cama/{name}/versions"))
|
|
||||||
assert version["reports"] == ["interpretability", "technical_validation"]
|
|
||||||
for metric in ("n_train", "n_test"):
|
|
||||||
assert version["metrics"][metric] == current[name]["version"]["metrics"][metric]
|
|
||||||
assert api.post(f"/models/cama/{name}/versions/1/promote").status_code == 409
|
|
||||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
|
||||||
ok(api.post(f"/models/cama/{name}/versions/1/reports/clinical_validation", files=files))
|
|
||||||
assert ok(api.post(f"/models/cama/{name}/versions/1/promote")) == {"champion": 1}
|
|
||||||
report = api.get(f"/models/cama/{name}/versions/1/reports/interpretability")
|
|
||||||
assert report.headers["content-type"] == "application/json"
|
|
||||||
assert [c["name"] for c in report.json()["curves"]][0].startswith("Kaplan-Meier")
|
|
||||||
pdf = api.get(f"/models/cama/{name}/versions/1/reports/clinical_validation")
|
|
||||||
assert pdf.headers["content-type"] == "application/pdf" and pdf.content.startswith(b"%PDF")
|
|
||||||
|
|
||||||
# Risks: the champions score their cohorts with the current models' predictions.
|
|
||||||
wait_for(api, ok(api.post("/models/cama/score"))["run_id"])
|
|
||||||
patient = _patients(platform.query)
|
|
||||||
for name in names:
|
|
||||||
risks = pd.DataFrame(platform.query(
|
|
||||||
"select person_id, index_date, horizon_years, probability "
|
|
||||||
f"from gold.cama_risk where model = 'cama.{name}'"
|
|
||||||
), columns=["person_id", "index_date", "horizon_years", "probability"]) # fmt: skip
|
|
||||||
risks["pac_id"] = risks["person_id"].map(patient).astype(int)
|
|
||||||
expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
|
||||||
both = risks.merge(expected, left_on=["pac_id", "horizon_years"],
|
|
||||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
|
||||||
assert len(both) == len(expected) == len(risks), name
|
|
||||||
assert (both["index_date"].astype(str) == both["fecha_indice"].astype(str)).all()
|
|
||||||
np.testing.assert_allclose(both["probability"].astype(float), both["probabilidad"],
|
|
||||||
rtol=1e-6) # fmt: skip
|
|
||||||
|
|
||||||
# Every resource the API serves, every search paged to the end, passes the HL7
|
|
||||||
# validator (offline: structure, cardinality, profiles; no terminology server).
|
|
||||||
people = [r["id"] for b in pages(api, "/cama/fhir/Patient", {"follow-up-window": 12})
|
|
||||||
for r in (e["resource"] for e in b["entry"])][:10] # fmt: skip
|
|
||||||
resources = served(api, "/cama/fhir", PERIODS, people)
|
|
||||||
errors, warnings = validate(resources, tmp_path)
|
|
||||||
print(f"HL7 validator: {len(warnings)} warnings")
|
|
||||||
assert [e for e in errors if not unscored(e, resources)] == []
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
"""An operator connects ISSSTELEON's test source through the API, the way the /conectar
|
|
||||||
screens do: look into its tables, save the drawn pipeline, run it, read what came out, and
|
|
||||||
settle what review shows. Real API and Dagster processes; nothing faked."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import time
|
|
||||||
|
|
||||||
from sqlalchemy import create_engine, make_url, text
|
|
||||||
|
|
||||||
SQL = "dlt.sources.sql_database:sql_database"
|
|
||||||
CYTOLOGY = {"entity": "cervical_cytology"}
|
|
||||||
STUDIES = ("cervical_cytology", "cervical_biopsy", "mammography", "breast_biopsy",
|
|
||||||
"breast_treatment", "clinical_note") # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def ok(response, status=200):
|
|
||||||
assert response.status_code == status, response.text
|
|
||||||
return response.json()
|
|
||||||
|
|
||||||
|
|
||||||
def wait_for(api, run_id: str, seconds: int = 900) -> None:
|
|
||||||
deadline = time.monotonic() + seconds
|
|
||||||
while (status := ok(api.get(f"/runs/{run_id}"))["status"]) not in ("SUCCESS", "FAILURE"):
|
|
||||||
assert time.monotonic() < deadline, f"run {run_id} still {status}"
|
|
||||||
time.sleep(2)
|
|
||||||
assert status == "SUCCESS"
|
|
||||||
|
|
||||||
|
|
||||||
def run(api, pipeline: str) -> None:
|
|
||||||
wait_for(api, ok(api.post(f"/ingest/pipelines/{pipeline}/runs", json={}))["run_id"])
|
|
||||||
|
|
||||||
|
|
||||||
def test_an_operator_connects_a_site_and_settles_its_review(api, platform, site, tmp_path):
|
|
||||||
truth = site.truth
|
|
||||||
database = {"credentials": site.url, "schema": "dbo"}
|
|
||||||
|
|
||||||
# What the site has, and what one of its tables holds (documents shown by size).
|
|
||||||
found = ok(api.post("/ingest/sources/resources", json={"source": SQL, "args": database}))
|
|
||||||
assert found == ["ResultadoSubrogado"]
|
|
||||||
missing = {"credentials": "mssql+pymssql://sa:x@nowhere.invalid:1433/Pruebas"}
|
|
||||||
unreachable = api.post("/ingest/sources/resources", json={"source": SQL, "args": missing})
|
|
||||||
assert unreachable.status_code == 422, unreachable.text
|
|
||||||
reports = {"id": "reports", "kind": "source", "source": SQL, "args": database}
|
|
||||||
sample = ok(
|
|
||||||
api.post(
|
|
||||||
"/ingest/sources/preview?limit=3", json=reports | {"resource": "ResultadoSubrogado"}
|
|
||||||
)
|
|
||||||
)
|
|
||||||
assert len(sample) == 3 and all(r["Archivo"].endswith(" bytes>") for r in sample)
|
|
||||||
|
|
||||||
# A file someone uploads (a report sent by mail) becomes a source like any other.
|
|
||||||
engine = create_engine(site.url)
|
|
||||||
with engine.connect() as con:
|
|
||||||
pdf = con.execute(text("select Archivo from dbo.ResultadoSubrogado where Id = 1")).scalar()
|
|
||||||
engine.dispose()
|
|
||||||
uploaded = ok(api.post("/ingest/uploads", files={"file": ("informe.pdf", pdf)}))
|
|
||||||
mailed = {
|
|
||||||
"id": "mailed",
|
|
||||||
"kind": "source",
|
|
||||||
"source": "dlt.sources.filesystem:filesystem",
|
|
||||||
"args": {"bucket_url": uploaded["bucket_url"]},
|
|
||||||
"then": "persistance.readers:read_bytes",
|
|
||||||
}
|
|
||||||
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=mailed))) == 1
|
|
||||||
|
|
||||||
# The site's codes in platform terms: a ConceptMap, saved before the drawing that names
|
|
||||||
# it. One that maps onto a code no field allows is refused, saying which.
|
|
||||||
drawn = json.loads(site.drawn)
|
|
||||||
missing = api.put("/ingest/pipelines/site", json=drawn)
|
|
||||||
assert missing.status_code == 422 and "erick_site" in missing.text
|
|
||||||
codes = json.loads(site.concept_map.read_text())
|
|
||||||
wrong = json.loads(json.dumps(codes).replace('"code": "HSIL"', '"code": "BIRADS-7"'))
|
|
||||||
refused = api.put("/ingest/concept-maps/erick_site", json=wrong)
|
|
||||||
assert refused.status_code == 422 and "BIRADS-7 is not an allowed code" in refused.text
|
|
||||||
assert ok(api.put("/ingest/concept-maps/erick_site", json=codes)) == {"version": 1}
|
|
||||||
|
|
||||||
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
|
||||||
broken = {
|
|
||||||
"nodes": [
|
|
||||||
*drawn["nodes"],
|
|
||||||
{"id": "loose", "kind": "read", "inputs": ["gone"], "column": "x"},
|
|
||||||
]
|
|
||||||
}
|
|
||||||
assert "no node" in api.put("/ingest/pipelines/site", json=broken).text
|
|
||||||
assert ok(api.put("/ingest/pipelines/site", json=drawn)) == {"version": 1}
|
|
||||||
assert ok(api.get("/ingest/pipelines/site"))["version"] == 1
|
|
||||||
|
|
||||||
# A password is never shown, and survives the UI sending the masked drawing back.
|
|
||||||
shown = ok(api.get("/ingest/pipelines/site"))["pipeline"]
|
|
||||||
password = make_url(site.url).password
|
|
||||||
assert password not in json.dumps(shown)
|
|
||||||
assert ok(api.put("/ingest/pipelines/site", json=shown)) == {"version": 2}
|
|
||||||
stored = platform.query(
|
|
||||||
"select doc from config.pipelines where pipeline_id = 'site' and version = 2"
|
|
||||||
)
|
|
||||||
assert site.url in stored[0][0]
|
|
||||||
|
|
||||||
# Run it, and look at what any node produced.
|
|
||||||
run(api, "site")
|
|
||||||
record_of = {}
|
|
||||||
assert ok(api.get("/ingest/pipelines/site/nodes/resultados/rows?limit=3"))
|
|
||||||
held_by = platform.query("select id, _record from bronze.n__site__resultados")
|
|
||||||
record_of |= {f"ResultadoSubrogado:{i}": r for i, r in held_by}
|
|
||||||
assert len(record_of) == len(truth)
|
|
||||||
forms = sum(1 for r in truth
|
|
||||||
if r["entity"] == "cervical_cytology" and "document" not in r) # fmt: skip
|
|
||||||
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == forms
|
|
||||||
|
|
||||||
# Review: reports that contradict each other, rows held because their person is torn
|
|
||||||
# (a pathology report that fits two women of one name), and persons that may be one.
|
|
||||||
# (a disputed cytology shows all its records: both HPV copies and the form they share)
|
|
||||||
disputed = {(r["person"], r["values"]["sample_date"]) for r in truth if r.get("conflict")}
|
|
||||||
conflicting = {record_of[r["where"]] for r in truth if r["entity"] == "cervical_cytology"
|
|
||||||
and (r["person"], r["values"]["sample_date"]) in disputed} # fmt: skip
|
|
||||||
shown = {c["_record"] for c in ok(api.get("/review/conflicts", params=CYTOLOGY))}
|
|
||||||
assert shown and shown <= conflicting
|
|
||||||
persons = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"}))
|
|
||||||
assert persons["to_settle"] and len(persons["torn"]) == 1
|
|
||||||
|
|
||||||
# The reviewer settles all of it, checking each case against the source documents.
|
|
||||||
patient = site.patients(platform.query)
|
|
||||||
whose, before = {}, {}
|
|
||||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
|
||||||
whose.setdefault(person, set()).add(patient[record])
|
|
||||||
before[record] = person
|
|
||||||
# A queued person or candidate is one of its records (decisions are kept by record).
|
|
||||||
whose |= {record: whose[person] for record, person in before.items()}
|
|
||||||
for r in truth:
|
|
||||||
if r.get("flipped"):
|
|
||||||
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
|
||||||
ok(api.post("/review/rejections", json=decision), status=201)
|
|
||||||
merges = 0
|
|
||||||
for entry in persons["to_settle"]:
|
|
||||||
for c in entry["candidates"]:
|
|
||||||
same = whose[entry["person"]] == whose[c["candidate"]]
|
|
||||||
merges += same
|
|
||||||
decision = {"person": entry["person"], "candidate": c["candidate"], "same": same}
|
|
||||||
ok(api.post("/review/persons", json=decision), status=201)
|
|
||||||
# The torn person: the pathology reports without a birth date get the one their woman's
|
|
||||||
# other documents show.
|
|
||||||
at = {record_of[r["where"]]: r for r in truth}
|
|
||||||
for record in persons["torn"][0]["records"]:
|
|
||||||
r = at[record["_record"]]
|
|
||||||
if "birth_date" not in r["identity"]:
|
|
||||||
fix = {"record": record["_record"], "field": "birth_date",
|
|
||||||
"value": site.meta["birth_dates"][r["person"]]} # fmt: skip
|
|
||||||
ok(api.post("/review/corrections", json=fix), status=201)
|
|
||||||
# A row a rule held because a value came out wrong (a scan misread: "lA" for a stage)
|
|
||||||
# gets the value the reviewer reads in the document; one with nothing to fix is
|
|
||||||
# rejected, but for the torn person's rows, which wait for the correction above.
|
|
||||||
misread = []
|
|
||||||
for study in STUDIES:
|
|
||||||
for h in ok(api.get("/review/held", params={"entity": study})):
|
|
||||||
torn = any("disagree on birth date" in why for why in h["_held"])
|
|
||||||
r = at[h["_record"]]
|
|
||||||
truly = r.get("clinical_note") if study == "clinical_note" else r["values"]
|
|
||||||
wrong = {f: v for f, v in truly.items()
|
|
||||||
if v is not None and str(h["_raw"].get(f)) != str(v)} # fmt: skip
|
|
||||||
for field, v in wrong.items():
|
|
||||||
fix = {"entity": study, "record": h["_record"], "field": field, "value": str(v)}
|
|
||||||
ok(api.post("/review/corrections", json=fix), status=201)
|
|
||||||
if not wrong and not torn:
|
|
||||||
decision = {"entity": study, "record": h["_record"], "reason": "misread"}
|
|
||||||
ok(api.post("/review/rejections", json=decision), status=201)
|
|
||||||
misread.append((h["_record"], study))
|
|
||||||
stage = {"entity": "breast_biopsy", "record": "x", "field": "stage", "value": "VII"}
|
|
||||||
assert api.post("/review/corrections", json=stage).status_code == 422
|
|
||||||
bad = {"record": "x", "field": "birth_date", "value": "not a date"}
|
|
||||||
assert api.post("/review/corrections", json=bad).status_code == 422
|
|
||||||
|
|
||||||
# The next run applies every decision: one person per patient, nothing left to review,
|
|
||||||
# and silver holds every cytology but the wrong copies and the misreads.
|
|
||||||
run(api, "site")
|
|
||||||
assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == []
|
|
||||||
for study in STUDIES:
|
|
||||||
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
|
||||||
left = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"}))
|
|
||||||
assert left == {"to_settle": [], "torn": []}
|
|
||||||
people = {r["person"] for r in truth}
|
|
||||||
groups = {}
|
|
||||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
|
||||||
groups.setdefault(person, set()).add(patient[record])
|
|
||||||
assert sorted(map(sorted, groups.values())) == sorted([p] for p in people)
|
|
||||||
|
|
||||||
# Person ids are stable: a person keeps an id her records had, and an id that went
|
|
||||||
# away (merged by the review) resolves to the person that replaced it.
|
|
||||||
after = dict(platform.query("select _record, person_id from bronze.n__site__persons"))
|
|
||||||
gone = set(before.values()) - set(after.values())
|
|
||||||
replaced = dict(platform.query("select person_id, replaced_by from silver.person_link"))
|
|
||||||
assert merges and len(gone) == merges and set(replaced) == gone
|
|
||||||
for old, new in replaced.items():
|
|
||||||
assert new in set(after.values())
|
|
||||||
assert any(before[r] == old and after[r] == new for r in before)
|
|
||||||
# No person got a new id, but for the woman parted from the torn person (two namesakes
|
|
||||||
# one pathology report had joined): her records all come from that person.
|
|
||||||
new = set(after.values()) - set(before.values())
|
|
||||||
torn_id = persons["torn"][0]["person"]
|
|
||||||
assert len(new) <= 1
|
|
||||||
assert all(before[r] == torn_id for r, p in after.items() if p in new)
|
|
||||||
rejected = {r for r, study in misread if study == "cervical_cytology"}
|
|
||||||
rejected |= {record_of[r["where"]] for r in truth if r.get("flipped")}
|
|
||||||
cytologies = {(r["person"], r["values"]["sample_date"]) for r in truth
|
|
||||||
if r["entity"] == "cervical_cytology"
|
|
||||||
and record_of[r["where"]] not in rejected} # fmt: skip
|
|
||||||
assert platform.count("silver.cervical_cytology") == len(cytologies)
|
|
||||||
@@ -1,152 +0,0 @@
|
|||||||
"""Phase 3.5 gate: one silver, two doors. What one platform serves as FHIR, another takes
|
|
||||||
through its FHIR door, as a standard hospital would send it, and places the same silver: the
|
|
||||||
same values of the same studies of the same patients, and so the same indicators. The
|
|
||||||
receiving side is configuration only: a pipeline whose fhir nodes read the sender's inbox."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import sqlite3
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from fhir_checks import pages
|
|
||||||
from test_conectar import ok, run, wait_for
|
|
||||||
|
|
||||||
from conftest import put_concept_map
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
|
||||||
PIPELINES = ROOT / "tests" / "fixtures" / "pipelines"
|
|
||||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
|
||||||
SILVER = """
|
|
||||||
select i.value, o.study, o.instance, o.field,
|
|
||||||
o.value_text, o.value_num, o.value_bool, o.value_date
|
|
||||||
from silver.observation as o
|
|
||||||
join silver.person_identifier as i on i.person_id = o.person_id
|
|
||||||
where i.system not like '%curp' and i.system not like '%nss'
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
def _served(api) -> list[dict]:
|
|
||||||
"""Everything the CaCu FHIR base serves about every patient."""
|
|
||||||
patients = [e["resource"] for b in pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
|
||||||
for e in b.get("entry", [])] # fmt: skip
|
|
||||||
found = list(patients)
|
|
||||||
ids = [p["id"] for p in patients]
|
|
||||||
for kind in ("DiagnosticReport", "Observation", "Encounter"):
|
|
||||||
for i in range(0, len(ids), 50):
|
|
||||||
subject = ",".join(f"Patient/{p}" for p in ids[i : i + 50])
|
|
||||||
for b in pages(api, f"/cacu/fhir/{kind}", {"subject": subject, "_count": 200}):
|
|
||||||
found += [e["resource"] for e in b.get("entry", [])]
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def _silver(platform) -> set[tuple]:
|
|
||||||
"""Every value silver holds, by patient record number, as Python values (each engine
|
|
||||||
returns booleans and dates its own way)."""
|
|
||||||
|
|
||||||
def plain(row) -> tuple:
|
|
||||||
number, study, instance, field, text, num, flag, day = row
|
|
||||||
num = None if num is None else float(num)
|
|
||||||
flag = None if flag is None else bool(flag)
|
|
||||||
return number, study, instance, field, text, num, flag, day and str(day)[:10]
|
|
||||||
|
|
||||||
return {plain(r) for r in platform.query(SILVER)}
|
|
||||||
|
|
||||||
|
|
||||||
def test_what_one_platform_serves_another_places_through_the_fhir_door(
|
|
||||||
api, platform, fresh_api, fresh_platform
|
|
||||||
):
|
|
||||||
# The sending side: the CaCu hospital, loaded through its drawn pipeline.
|
|
||||||
put_concept_map(api, "hospital_cacu")
|
|
||||||
drawn = (PIPELINES / "hospital_cacu.json").read_text().replace("{hospital}", str(HOSPITAL))
|
|
||||||
ok(api.put("/ingest/pipelines/cacu", json=json.loads(drawn)))
|
|
||||||
run(api, "cacu")
|
|
||||||
sent = _served(api)
|
|
||||||
bundle = {"resourceType": "Bundle", "type": "batch", "entry": [
|
|
||||||
{"resource": r, "request": {"method": "PUT", "url": f"{r['resourceType']}/{r['id']}"}}
|
|
||||||
for r in sent
|
|
||||||
]} # fmt: skip
|
|
||||||
|
|
||||||
# The receiving side: what it sends goes nowhere without a pipeline to place it.
|
|
||||||
door = "/cacu/fhir?sender=hospital"
|
|
||||||
assert fresh_api.post(door, json=bundle).status_code == 404
|
|
||||||
receiving = (PIPELINES / "fhir_door.json").read_text().replace("{sender}", "hospital")
|
|
||||||
ok(fresh_api.put("/ingest/pipelines/hospital", json=json.loads(receiving)))
|
|
||||||
assert (
|
|
||||||
fresh_api.post(door, json={"resourceType": "Bundle", "type": "searchset"}).status_code
|
|
||||||
== 422
|
|
||||||
)
|
|
||||||
answer = fresh_api.post(door, json=bundle)
|
|
||||||
assert answer.status_code == 202, answer.text
|
|
||||||
assert answer.headers["content-type"].startswith("application/fhir+json")
|
|
||||||
assert len(answer.json()["entry"]) == len(sent)
|
|
||||||
wait_for(fresh_api, answer.headers["location"].rsplit("/", 1)[1])
|
|
||||||
|
|
||||||
# One silver: every value of every study instance, by patient record number.
|
|
||||||
placed = _silver(platform)
|
|
||||||
assert len(placed) > 1000 and {r[1] for r in placed} >= {"cervical_cytology", "clinical_note"}
|
|
||||||
assert _silver(fresh_platform) == placed
|
|
||||||
assert fresh_platform.count("silver.person") == platform.count("silver.person")
|
|
||||||
|
|
||||||
# And so the same indicators, every measure, every semester.
|
|
||||||
(measures,) = pages(api, "/cacu/fhir/Measure")
|
|
||||||
for measure in [e["resource"]["id"] for e in measures["entry"]]:
|
|
||||||
params = {"measure": measure, "reporting-period": ",".join(PERIODS),
|
|
||||||
"event-cutoff": "2026-11-25"} # fmt: skip
|
|
||||||
ours, theirs = (
|
|
||||||
[e["resource"]["group"] for b in pages(a, "/cacu/fhir/MeasureReport", params)
|
|
||||||
for e in b["entry"]]
|
|
||||||
for a in (api, fresh_api)
|
|
||||||
) # fmt: skip
|
|
||||||
assert ours == theirs, measure
|
|
||||||
|
|
||||||
|
|
||||||
# The same laboratory, a year later: it renamed its result column and writes its results in
|
|
||||||
# words. Nothing in code changes: the drawing names the new column, the ConceptMap gets the
|
|
||||||
# new spellings.
|
|
||||||
RENAMED = {"NORMAL": "Negativo para lesión", "LIEBG": "Lesión de bajo grado",
|
|
||||||
"LIEAG": "Lesión de alto grado"} # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_new_label_is_a_concept_map_row_not_code(api, platform, fresh_api, fresh_platform,
|
|
||||||
tmp_path): # fmt: skip
|
|
||||||
put_concept_map(api, "hospital_cacu")
|
|
||||||
drawn = (PIPELINES / "hospital_cacu.json").read_text()
|
|
||||||
ok(
|
|
||||||
api.put(
|
|
||||||
"/ingest/pipelines/cacu", json=json.loads(drawn.replace("{hospital}", str(HOSPITAL)))
|
|
||||||
)
|
|
||||||
)
|
|
||||||
run(api, "cacu")
|
|
||||||
|
|
||||||
(tmp_path / "lab").mkdir()
|
|
||||||
for name in ("hospital_cacu.db",):
|
|
||||||
(tmp_path / "lab" / name).write_bytes((HOSPITAL / name).read_bytes())
|
|
||||||
with sqlite3.connect(tmp_path / "lab" / "hospital_cacu.db") as con:
|
|
||||||
con.execute(
|
|
||||||
"alter table citologiacervical rename column cit_celulas_escamosas to PAP_RESULT"
|
|
||||||
)
|
|
||||||
for old, new in RENAMED.items():
|
|
||||||
con.execute(
|
|
||||||
"update citologiacervical set PAP_RESULT = ? where PAP_RESULT = ?", (new, old)
|
|
||||||
)
|
|
||||||
codes = json.loads(
|
|
||||||
(ROOT / "tests" / "fixtures" / "concept_maps" / "hospital_cacu.json").read_text()
|
|
||||||
)
|
|
||||||
bethesda = next(g for g in codes["group"] if g["target"].endswith("/bethesda"))
|
|
||||||
bethesda["element"] += [{"code": new, "target": [{"code": {"NORMAL": "NILM", "LIEBG": "LSIL",
|
|
||||||
"LIEAG": "HSIL"}[old], "equivalence": "equivalent"}]}
|
|
||||||
for old, new in RENAMED.items()] # fmt: skip
|
|
||||||
ok(fresh_api.put("/ingest/concept-maps/hospital_cacu", json=codes))
|
|
||||||
# The source names the database's column; the map names it as bronze holds it (the
|
|
||||||
# canvas preview shows dlt's normalised names: PAP_RESULT is pap_result).
|
|
||||||
renamed = drawn.replace(
|
|
||||||
'"cit_celulas_escamosas", "cit_vph_resultado"', '"PAP_RESULT", "cit_vph_resultado"'
|
|
||||||
)
|
|
||||||
renamed = renamed.replace('"result": "cit_celulas_escamosas"', '"result": "pap_result"')
|
|
||||||
renamed = renamed.replace("{hospital}", str(tmp_path / "lab"))
|
|
||||||
ok(fresh_api.put("/ingest/pipelines/cacu", json=json.loads(renamed)))
|
|
||||||
run(fresh_api, "cacu")
|
|
||||||
|
|
||||||
placed = _silver(platform)
|
|
||||||
assert any(r[3] == "result" and r[4] == "NILM" for r in placed)
|
|
||||||
assert _silver(fresh_platform) == placed
|
|
||||||
+29
-101
@@ -1,109 +1,37 @@
|
|||||||
import hashlib
|
from io import BytesIO
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from test_bundles import NAME, _post, _register, _run, _trust
|
from fastapi import HTTPException, UploadFile
|
||||||
|
|
||||||
from models.tea.jobs import Baseline
|
from core.domains import Domain
|
||||||
from persistance import registry
|
from webapi.models import training_inputs, upload_training_inputs
|
||||||
|
|
||||||
VERSIONS = "/models/tea/curve_x/versions"
|
|
||||||
|
|
||||||
|
|
||||||
def test_version_lifecycle(api, platform, monkeypatch):
|
def test_training_inputs(tmp_path, monkeypatch):
|
||||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", platform.env["MLFLOW_TRACKING_URI"])
|
root = tmp_path / "reference"
|
||||||
monkeypatch.chdir(platform.env["ISSSTELEON_DATA"])
|
monkeypatch.setenv("TEA_REFERENCE_ROOT", str(root))
|
||||||
for version in (1, 2):
|
assert training_inputs(Domain.TEA, "curve_x")["sets"] == []
|
||||||
assert registry.register(NAME, Baseline("x", {"value": {}}), {}, {}, {}) == version
|
with pytest.raises(HTTPException) as undefined:
|
||||||
path = f"{VERSIONS}/1"
|
training_inputs(Domain.TEA, "ados2_association")
|
||||||
response = api.get(f"{path}/checks")
|
assert undefined.value.status_code == 404
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
assert response.json() == {
|
def upload(name, files):
|
||||||
"version": 1,
|
return upload_training_inputs(
|
||||||
"status": "candidate",
|
Domain.TEA,
|
||||||
"checks": [{"report": report, "present": False} for report in registry.REPORTS],
|
"curve_x",
|
||||||
"promotable": False,
|
name,
|
||||||
}
|
[UploadFile(BytesIO(content), filename=filename) for filename, content in files],
|
||||||
assert api.get(f"{VERSIONS}/99/checks").status_code == 404
|
|
||||||
for version in (1, 2):
|
|
||||||
for report in registry.REPORTS:
|
|
||||||
registry.add_report(NAME, version, report, "report.json", b"{}")
|
|
||||||
assert api.get(f"{path}/checks").json()["promotable"]
|
|
||||||
assert api.post(f"{path}/promote").json() == {"champion": 1}
|
|
||||||
assert api.get(f"{path}/checks").json()["status"] == "champion"
|
|
||||||
refused = api.post(f"{path}/retire")
|
|
||||||
assert refused.status_code == 409
|
|
||||||
assert (
|
|
||||||
refused.json()["detail"] == "the champion cannot be retired; promote another version first"
|
|
||||||
)
|
)
|
||||||
assert api.post(f"{VERSIONS}/2/promote").json() == {"champion": 2}
|
|
||||||
assert api.get(f"{path}/checks").json()["status"] == "candidate"
|
|
||||||
assert api.post(f"{path}/retire").json() == {"status": "retired"}
|
|
||||||
assert api.post(f"{path}/promote").status_code == 409
|
|
||||||
checks = api.get(f"{path}/checks").json()
|
|
||||||
assert checks["status"] == "retired" and not checks["promotable"]
|
|
||||||
assert [v["status"] for v in api.get(VERSIONS).json()] == ["retired", "champion"]
|
|
||||||
|
|
||||||
|
expected = {"name": "cohort", "edf_files": 1, "has_ages": True, "bytes": 7}
|
||||||
|
assert upload("cohort", [("one.EDF", b"edf"), ("edades.csv", b"ages")]) == expected
|
||||||
|
assert training_inputs(Domain.TEA, "curve_x")["sets"] == [expected]
|
||||||
|
|
||||||
def test_imported_lineage(api, platform, fresh_api, fresh_platform, monkeypatch):
|
for invalid in ("bad.txt", "../x"):
|
||||||
_register(platform, monkeypatch)
|
with pytest.raises(HTTPException) as rejected:
|
||||||
bundle_exported = api.get("/models/tea/export")
|
upload("cohort", [("two.edf", b"edf"), (invalid, b"bad")])
|
||||||
assert bundle_exported.status_code == 200, bundle_exported.text
|
assert rejected.value.status_code == 422
|
||||||
sha = hashlib.sha256(bundle_exported.content).hexdigest()
|
with pytest.raises(HTTPException) as rejected:
|
||||||
_trust(fresh_platform, sha, monkeypatch)
|
upload("bad set", [("one.edf", b"edf")])
|
||||||
run = _run(fresh_api, _post(fresh_api, bundle_exported.content, sha))
|
assert rejected.value.status_code == 422
|
||||||
assert run["state"] == "succeeded", run
|
assert {path.name for path in (root / "cohort").iterdir()} == {"one.EDF", "edades.csv"}
|
||||||
response = fresh_api.get(f"{VERSIONS}/1/lineage")
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
lineage = response.json()
|
|
||||||
assert lineage["version"] == 1 and lineage["created"] > 0 and lineage["run_id"]
|
|
||||||
assert lineage["params"] == {}
|
|
||||||
assert lineage["metrics"] == {"n_reference": 10}
|
|
||||||
assert all(not tag.startswith("mlflow.") for tag in lineage["tags"])
|
|
||||||
assert lineage["imported"] == {"sha256": sha, "source_name": NAME, "source_version": "1"}
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def platform(platform):
|
|
||||||
platform.env["TEA_REFERENCE_ROOT"] = str(Path(platform.env["ISSSTELEON_DATA"]) / "references")
|
|
||||||
return platform
|
|
||||||
|
|
||||||
|
|
||||||
def test_training_inputs(api, platform):
|
|
||||||
root = Path(platform.env["TEA_REFERENCE_ROOT"])
|
|
||||||
path = "/models/tea/curve_x/inputs"
|
|
||||||
assert api.get(path).json()["sets"] == []
|
|
||||||
assert api.get("/models/tea/ados2_association/inputs").status_code == 404
|
|
||||||
response = api.post(
|
|
||||||
f"{path}/cohort/files",
|
|
||||||
files=[("files", ("one.EDF", b"edf")), ("files", ("edades.csv", b"ages"))],
|
|
||||||
)
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
cohort = {"name": "cohort", "edf_files": 1, "has_ages": True, "bytes": 7}
|
|
||||||
assert response.json() == cohort
|
|
||||||
assert api.get(path).json()["sets"] == [cohort]
|
|
||||||
for filename in ("bad.txt", "../x"):
|
|
||||||
response = api.post(
|
|
||||||
f"{path}/cohort/files",
|
|
||||||
files=[("files", ("two.edf", b"edf")), ("files", (filename, b"bad"))],
|
|
||||||
)
|
|
||||||
assert response.status_code == 422, response.text
|
|
||||||
assert (
|
|
||||||
api.post(f"{path}/bad%20set/files", files={"files": ("one.edf", b"edf")}).status_code == 422
|
|
||||||
)
|
|
||||||
assert {p.name for p in (root / "cohort").iterdir()} == {"one.EDF", "edades.csv"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_preview(api, tmp_path, monkeypatch):
|
|
||||||
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2] / "models" / "tests"))
|
|
||||||
from edf_files import small_edf
|
|
||||||
|
|
||||||
signal = small_edf(tmp_path / "small.edf")
|
|
||||||
run = _run(api, api.post("/tea/preview", files={"edf": ("small.edf", signal)}))
|
|
||||||
assert run["state"] == "succeeded", run
|
|
||||||
response = api.get(f"/tea/preview/{run['id']}")
|
|
||||||
assert response.status_code == 200, response.text
|
|
||||||
preview = response.json()
|
|
||||||
assert preview["state"] == "succeeded"
|
|
||||||
outputs = api.get(f"/runs/{run['id']}", params={"outputs": "true"}).json()["outputs"]
|
|
||||||
assert preview["result"] == outputs["preview_study.result"]
|
|
||||||
|
|||||||
+49
-170
@@ -1,12 +1,9 @@
|
|||||||
import os
|
|
||||||
import time
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
import yaml
|
from dagster import DagsterRunStatus
|
||||||
|
from fastapi import HTTPException
|
||||||
|
|
||||||
import conftest
|
|
||||||
from persistance.cluster import Progress
|
from persistance.cluster import Progress
|
||||||
from webapi.runs import STATE, graphql, shape
|
from webapi.runs import _locked, cancel_run, shape
|
||||||
|
|
||||||
PAYLOAD = {
|
PAYLOAD = {
|
||||||
"runId": "run",
|
"runId": "run",
|
||||||
@@ -88,7 +85,12 @@ def test_shape_progress_tag():
|
|||||||
assert run.progress.done == 3
|
assert run.progress.done == 3
|
||||||
assert run.progress.phase == "analyzing"
|
assert run.progress.phase == "analyzing"
|
||||||
assert shape(with_tag("{bad json"), []).progress is None
|
assert shape(with_tag("{bad json"), []).progress is None
|
||||||
for status, state in STATE.items():
|
for status, state in (
|
||||||
|
("QUEUED", "queued"),
|
||||||
|
("STARTING", "running"),
|
||||||
|
("CANCELING", "cancelling"),
|
||||||
|
("CANCELED", "cancelled"),
|
||||||
|
):
|
||||||
run = shape(PAYLOAD | {"status": status}, [])
|
run = shape(PAYLOAD | {"status": status}, [])
|
||||||
assert (run.status, run.state) == (status, state)
|
assert (run.status, run.state) == (status, state)
|
||||||
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
|
assert shape(PAYLOAD | {"status": "UNKNOWN"}, []).state == "running"
|
||||||
@@ -112,171 +114,48 @@ def test_shape_outputs():
|
|||||||
assert shape(PAYLOAD, events, outputs=False).outputs is None
|
assert shape(PAYLOAD, events, outputs=False).outputs is None
|
||||||
|
|
||||||
|
|
||||||
def _ok(response):
|
@pytest.mark.parametrize("initial", [DagsterRunStatus.QUEUED, DagsterRunStatus.STARTED])
|
||||||
assert response.status_code == 200, response.text
|
def test_cancel_returns_the_terminal_or_cancelling_state(initial):
|
||||||
return response.json()
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def failed_run(api):
|
|
||||||
run_id = _ok(api.post("/models/cacu/analyze"))["run_id"]
|
|
||||||
deadline = time.monotonic() + 120
|
|
||||||
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] != "failed":
|
|
||||||
assert time.monotonic() < deadline, run
|
|
||||||
time.sleep(1)
|
|
||||||
return run
|
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_run_is_404(api):
|
|
||||||
assert api.get("/runs/does-not-exist").status_code == 404
|
|
||||||
assert api.post("/runs/does-not-exist/cancel").status_code == 404
|
|
||||||
|
|
||||||
|
|
||||||
def test_failed_run_reports_its_error(failed_run):
|
|
||||||
assert failed_run["status"] == "FAILURE"
|
|
||||||
assert "analyze" in failed_run["error"]
|
|
||||||
assert isinstance(failed_run["info"], list)
|
|
||||||
assert isinstance(failed_run["warnings"], list)
|
|
||||||
assert any(
|
|
||||||
step["key"] == "analyze_studies" and step["status"] == "FAILURE"
|
|
||||||
for step in failed_run["steps"]
|
|
||||||
)
|
|
||||||
assert failed_run["domain"] == "cacu"
|
|
||||||
assert failed_run["job"] == "analyze"
|
|
||||||
|
|
||||||
|
|
||||||
def test_history_filters_by_job_and_domain(api, failed_run):
|
|
||||||
run_id = failed_run["id"]
|
|
||||||
history = _ok(api.get("/runs", params={"job": "analyze", "domain": "cacu"}))
|
|
||||||
assert run_id in {run["id"] for run in history}
|
|
||||||
for params in ({"job": "train"}, {"domain": "tea"}):
|
|
||||||
assert run_id not in {run["id"] for run in _ok(api.get("/runs", params=params))}
|
|
||||||
|
|
||||||
another_id = _ok(api.post("/models/cacu/analyze"))["run_id"]
|
|
||||||
page = _ok(api.get("/runs", params={"limit": 1}))
|
|
||||||
assert [run["id"] for run in page] == [another_id]
|
|
||||||
page = _ok(api.get("/runs", params={"limit": 1, "before": another_id}))
|
|
||||||
assert [run["id"] for run in page] == [run_id]
|
|
||||||
|
|
||||||
|
|
||||||
def test_cancel_a_finished_run_is_409(api, failed_run):
|
|
||||||
response = api.post(f"/runs/{failed_run['id']}/cancel")
|
|
||||||
assert response.status_code == 409
|
|
||||||
assert response.json()["detail"] == "the run already ended: failed"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def api_with_dagster_address(platform, request, monkeypatch):
|
|
||||||
ports = []
|
|
||||||
free_port = conftest._free_port
|
|
||||||
|
|
||||||
def record_port():
|
|
||||||
port = free_port()
|
|
||||||
ports.append(port)
|
|
||||||
return port
|
|
||||||
|
|
||||||
monkeypatch.setattr(conftest, "_free_port", record_port)
|
|
||||||
api = request.getfixturevalue("api")
|
|
||||||
monkeypatch.setenv("DAGSTER_HOST", "127.0.0.1")
|
|
||||||
monkeypatch.setenv("DAGSTER_PORT", str(ports[0]))
|
|
||||||
return api
|
|
||||||
|
|
||||||
|
|
||||||
def test_run_requests_validate_the_execution_choice(api_with_dagster_address):
|
|
||||||
api = api_with_dagster_address
|
|
||||||
path = "/models/tea/analyze"
|
|
||||||
for execution in (
|
|
||||||
{"mode": "remote", "scheduler": "tcp://evil:8786"},
|
|
||||||
{"mode": "local", "scheduler": "tcp://x:8786"},
|
|
||||||
):
|
|
||||||
assert api.post(path, json={"execution": execution}).status_code == 422
|
|
||||||
|
|
||||||
run_id = _ok(api.post(path, json={"execution": {"mode": "sync"}}))["run_id"]
|
|
||||||
data = graphql(
|
|
||||||
"""
|
|
||||||
query RunConfig($id: ID!) {
|
|
||||||
runOrError(runId: $id) { ... on Run { runConfigYaml } }
|
|
||||||
}
|
|
||||||
""",
|
|
||||||
{"id": run_id},
|
|
||||||
)
|
|
||||||
config = yaml.safe_load(data["runOrError"]["runConfigYaml"])
|
|
||||||
assert config["ops"]["analyze_studies"]["config"]["execution"]["mode"] == "sync"
|
|
||||||
|
|
||||||
|
|
||||||
def test_execution_options_and_health(api):
|
|
||||||
options = _ok(api.get("/execution/options"))
|
|
||||||
assert options["default_mode"] == "sync"
|
|
||||||
configured = [s for s in os.environ.get("DASK_SCHEDULERS", "").split(",") if s]
|
|
||||||
assert options["schedulers"] == configured
|
|
||||||
health = _ok(api.get("/execution/health", params={"mode": "local"}))
|
|
||||||
assert health["reachable"] is True
|
|
||||||
assert health["workers"] >= 1
|
|
||||||
if configured:
|
|
||||||
remote = {"mode": "remote", "scheduler": configured[0]}
|
|
||||||
health = _ok(api.get("/execution/health", params=remote))
|
|
||||||
assert health["reachable"] is True
|
|
||||||
assert health["workers"] == int(os.environ.get("DASK_EXPECTED_WORKERS", "1"))
|
|
||||||
else:
|
|
||||||
assert api.get("/execution/health", params={"mode": "remote"}).status_code == 422
|
|
||||||
assert api.get("/execution/health?mode=sync&reference=..%2Fx").status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_tea_eegs_analyze_validates_scope(api):
|
|
||||||
response = api.post("/tea/eegs/analyze", json={"scope": {"mode": "first_n"}})
|
|
||||||
assert response.status_code == 422
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_locked_run_storage_is_read_again(monkeypatch):
|
|
||||||
from fastapi import HTTPException
|
|
||||||
|
|
||||||
from webapi import runs
|
|
||||||
|
|
||||||
error = {"__typename": "PythonError", "message": "OperationalError: database is locked"}
|
|
||||||
locked = {"data": {"runOrError": {"__typename": "Run"}, "logsForRun": error}}
|
|
||||||
fine = {
|
|
||||||
"data": {
|
|
||||||
"runOrError": {"__typename": "Run"},
|
|
||||||
"logsForRun": {"__typename": "EventConnection"},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
answers = [locked, locked, fine]
|
|
||||||
|
|
||||||
class Answer:
|
|
||||||
status_code = 200
|
|
||||||
|
|
||||||
def __init__(self, payload):
|
|
||||||
self.payload = payload
|
|
||||||
|
|
||||||
def json(self):
|
|
||||||
return self.payload
|
|
||||||
|
|
||||||
monkeypatch.setattr(runs.time, "sleep", lambda s: None)
|
|
||||||
monkeypatch.setattr(runs.requests, "post", lambda *a, **k: Answer(answers.pop(0)))
|
|
||||||
assert runs.graphql("q", {}) == fine["data"]
|
|
||||||
monkeypatch.setattr(runs.requests, "post", lambda *a, **k: Answer(locked))
|
|
||||||
with pytest.raises(HTTPException) as raised:
|
|
||||||
runs.graphql("q", {})
|
|
||||||
assert raised.value.status_code == 503
|
|
||||||
|
|
||||||
|
|
||||||
def test_cancel_waits_for_a_starting_run(monkeypatch):
|
|
||||||
from webapi import runs
|
|
||||||
|
|
||||||
statuses = iter(["STARTING", "STARTING", "STARTED", "CANCELING"])
|
|
||||||
terminated = []
|
|
||||||
|
|
||||||
class Client:
|
class Client:
|
||||||
def get_run_status(self, run_id):
|
status = initial
|
||||||
class S:
|
|
||||||
value = next(statuses)
|
|
||||||
|
|
||||||
return S()
|
def get_run_status(self, run_id):
|
||||||
|
return self.status
|
||||||
|
|
||||||
def terminate_run(self, run_id):
|
def terminate_run(self, run_id):
|
||||||
terminated.append(run_id)
|
self.status = {
|
||||||
|
DagsterRunStatus.QUEUED: DagsterRunStatus.CANCELED,
|
||||||
|
DagsterRunStatus.STARTED: DagsterRunStatus.CANCELING,
|
||||||
|
}[self.status]
|
||||||
|
|
||||||
monkeypatch.setattr(runs.time, "sleep", lambda s: None)
|
result = cancel_run("r1", client=Client())
|
||||||
answer = runs.cancel_run("r1", client=Client())
|
expected = (
|
||||||
assert terminated == ["r1"]
|
("CANCELED", "cancelled")
|
||||||
assert answer.status == "CANCELING"
|
if initial == DagsterRunStatus.QUEUED
|
||||||
|
else ("CANCELING", "cancelling")
|
||||||
|
)
|
||||||
|
assert (result.id, result.status, result.state) == ("r1", *expected)
|
||||||
|
|
||||||
|
|
||||||
|
def test_cancel_a_finished_run_is_409():
|
||||||
|
class Client:
|
||||||
|
def get_run_status(self, run_id):
|
||||||
|
return DagsterRunStatus.SUCCESS
|
||||||
|
|
||||||
|
with pytest.raises(HTTPException) as error:
|
||||||
|
cancel_run("r1", client=Client())
|
||||||
|
assert error.value.status_code == 409
|
||||||
|
assert error.value.detail == "the run already ended: succeeded"
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_storage_lock_is_distinguished_from_a_run_failure():
|
||||||
|
assert _locked({"errors": [{"message": "OperationalError: database is locked"}]})
|
||||||
|
assert _locked(
|
||||||
|
{"data": {"logsForRun": {"__typename": "PythonError", "message": "database is locked"}}}
|
||||||
|
)
|
||||||
|
assert not _locked(
|
||||||
|
{"data": {"logsForRun": {"__typename": "EventConnection", "message": "database is locked"}}}
|
||||||
|
)
|
||||||
|
assert not _locked(
|
||||||
|
{"data": {"logsForRun": {"__typename": "PythonError", "message": "unknown error"}}}
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
import json
|
|
||||||
import time
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from sqlalchemy.exc import DBAPIError
|
|
||||||
from test_conectar import ok, wait_for
|
|
||||||
|
|
||||||
from conftest import put_concept_map
|
|
||||||
|
|
||||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures"
|
|
||||||
TERMINAL = {"succeeded", "failed", "cancelled"}
|
|
||||||
|
|
||||||
|
|
||||||
def load(api, domain):
|
|
||||||
put_concept_map(api, f"hospital_{domain}")
|
|
||||||
drawn = (FIXTURES / "pipelines" / f"hospital_{domain}.json").read_text()
|
|
||||||
pipeline = json.loads(drawn.replace("{hospital}", str(FIXTURES / "hospital")))
|
|
||||||
ok(api.put(f"/ingest/pipelines/{domain}", json=pipeline))
|
|
||||||
|
|
||||||
|
|
||||||
def _submit(api):
|
|
||||||
return ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"]
|
|
||||||
|
|
||||||
|
|
||||||
def _get_run(api, run_id):
|
|
||||||
return ok(api.get(f"/runs/{run_id}"))
|
|
||||||
|
|
||||||
|
|
||||||
def _wait_cancelled(api, run_id):
|
|
||||||
deadline = time.monotonic() + 300
|
|
||||||
while (run := _get_run(api, run_id))["state"] not in TERMINAL:
|
|
||||||
assert time.monotonic() < deadline, run
|
|
||||||
time.sleep(1)
|
|
||||||
assert run["state"] == "cancelled", run
|
|
||||||
return run
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
|
|
||||||
def test_writing_runs_never_overlap(api, platform):
|
|
||||||
load(api, "cacu")
|
|
||||||
first, second = _submit(api), _submit(api)
|
|
||||||
queued = False
|
|
||||||
deadline = time.monotonic() + 300
|
|
||||||
while True:
|
|
||||||
first_run, second_run = _get_run(api, first), _get_run(api, second)
|
|
||||||
queued |= first_run["state"] == "running" and second_run["state"] == "queued"
|
|
||||||
for run in (first_run, second_run):
|
|
||||||
assert run["state"] not in {"failed", "cancelled"}, run
|
|
||||||
if first_run["state"] == second_run["state"] == "succeeded":
|
|
||||||
break
|
|
||||||
assert time.monotonic() < deadline, (first_run, second_run)
|
|
||||||
time.sleep(1)
|
|
||||||
earlier, later = sorted((first_run, second_run), key=lambda run: run["started"])
|
|
||||||
assert later["started"] >= earlier["ended"] - 1
|
|
||||||
if not queued:
|
|
||||||
pytest.skip("the first run ended before the second was submitted")
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
|
|
||||||
def test_cancelling_an_ingest_run_leaves_no_silver_or_gold(api, platform):
|
|
||||||
load(api, "cacu")
|
|
||||||
run_id = _submit(api)
|
|
||||||
deadline = time.monotonic() + 300
|
|
||||||
while True:
|
|
||||||
run = _get_run(api, run_id)
|
|
||||||
if run["state"] == "running" and run["info"]:
|
|
||||||
break
|
|
||||||
assert run["state"] not in TERMINAL, run
|
|
||||||
assert time.monotonic() < deadline, run
|
|
||||||
time.sleep(1)
|
|
||||||
|
|
||||||
response = api.post(f"/runs/{run_id}/cancel")
|
|
||||||
if response.status_code == 409:
|
|
||||||
pytest.skip("the run ended before the cancel")
|
|
||||||
ok(response)
|
|
||||||
cancelled = _wait_cancelled(api, run_id)
|
|
||||||
assert cancelled["status"] == "CANCELED"
|
|
||||||
assert cancelled["error"] is None
|
|
||||||
with pytest.raises(DBAPIError):
|
|
||||||
platform.count("silver.person")
|
|
||||||
with pytest.raises(DBAPIError):
|
|
||||||
platform.count("gold.cacu_risk")
|
|
||||||
|
|
||||||
wait_for(api, _submit(api), 300)
|
|
||||||
assert platform.count("silver.person") > 0
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
|
|
||||||
def test_cancelling_a_queued_run_never_starts_it(api, platform):
|
|
||||||
load(api, "cacu")
|
|
||||||
runs = [_submit(api), _submit(api)]
|
|
||||||
deadline = time.monotonic() + 120
|
|
||||||
while True:
|
|
||||||
states = {run_id: _get_run(api, run_id)["state"] for run_id in runs}
|
|
||||||
running = [r for r, state in states.items() if state == "running"]
|
|
||||||
queued = [r for r, state in states.items() if state == "queued"]
|
|
||||||
if len(running) == 1 and len(queued) == 1:
|
|
||||||
break
|
|
||||||
if any(state in TERMINAL for state in states.values()):
|
|
||||||
pytest.skip(f"a run ended before the other was seen queued: {states}")
|
|
||||||
assert time.monotonic() < deadline, states
|
|
||||||
time.sleep(0.5)
|
|
||||||
ok(api.post(f"/runs/{queued[0]}/cancel"))
|
|
||||||
assert _wait_cancelled(api, queued[0])["steps"] == []
|
|
||||||
wait_for(api, running[0], 300)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skip(reason="needs killing the run worker; checked by hand")
|
|
||||||
def test_a_dead_run_does_not_stay_running():
|
|
||||||
pass
|
|
||||||
@@ -1,63 +0,0 @@
|
|||||||
"""Phase 3.5 gate: Synthea through the FHIR door. A seeded synthetic population (Synthea,
|
|
||||||
with the platform's cervical-screening module) arrives as a standard hospital would send it,
|
|
||||||
and every report it holds reaches silver: nothing held, one person per patient."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from fhir_checks import pages
|
|
||||||
from test_conectar import ok, wait_for
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
|
||||||
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
|
||||||
DOOR = ROOT / "tests" / "fixtures" / "pipelines" / "fhir_door.json"
|
|
||||||
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
|
||||||
|
|
||||||
|
|
||||||
def _population(out: Path, people: int = 20) -> list[dict]:
|
|
||||||
"""Synthea's FHIR R4 transaction Bundles, one per patient (fixed seeds)."""
|
|
||||||
subprocess.run(
|
|
||||||
["java", "-jar", SYNTHEA, "-p", str(people), "-s", "7", "-cs", "7", "-g", "F",
|
|
||||||
"-a", "25-64", "-d", str(MODULES), "-m", "cervical_screening",
|
|
||||||
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
|
||||||
"--exporter.hospital.fhir.export", "false",
|
|
||||||
"--exporter.practitioner.fhir.export", "false"],
|
|
||||||
check=True, capture_output=True, cwd=out.parent,
|
|
||||||
) # fmt: skip
|
|
||||||
return [json.loads(p.read_text()) for p in sorted((out / "fhir").glob("*.json"))]
|
|
||||||
|
|
||||||
|
|
||||||
def _reports(bundles: list[dict], study: str) -> int:
|
|
||||||
return sum(
|
|
||||||
1 for b in bundles for e in b["entry"]
|
|
||||||
if e["resource"]["resourceType"] == "DiagnosticReport"
|
|
||||||
and any(c.get("system") == STUDY and c.get("code") == study
|
|
||||||
for c in e["resource"].get("code", {}).get("coding", []))
|
|
||||||
) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_synthea_population_comes_in_through_the_fhir_door(api, platform, tmp_path):
|
|
||||||
bundles = _population(tmp_path / "synthea")
|
|
||||||
patients = sum(1 for b in bundles for e in b["entry"]
|
|
||||||
if e["resource"]["resourceType"] == "Patient") # fmt: skip
|
|
||||||
# Synthea counts the living: the women who died come on top of the twenty.
|
|
||||||
assert patients >= 20 and _reports(bundles, "cervical_cytology") > 40
|
|
||||||
|
|
||||||
receiving = DOOR.read_text().replace("{sender}", "synthea")
|
|
||||||
ok(api.put("/ingest/pipelines/synthea", json=json.loads(receiving)))
|
|
||||||
batch = {"resourceType": "Bundle", "type": "batch",
|
|
||||||
"entry": [e for b in bundles for e in b["entry"]]} # fmt: skip
|
|
||||||
answer = api.post("/cacu/fhir?sender=synthea", json=batch)
|
|
||||||
assert answer.status_code == 202, answer.text[:500]
|
|
||||||
wait_for(api, answer.headers["location"].rsplit("/", 1)[1])
|
|
||||||
|
|
||||||
# Nothing held, every report placed, one person per patient.
|
|
||||||
for study in ("cervical_cytology", "cervical_biopsy"):
|
|
||||||
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
|
||||||
assert platform.count(f"silver.{study}") == _reports(bundles, study), study
|
|
||||||
assert platform.count("silver.person") == patients
|
|
||||||
(served,) = pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
|
||||||
assert served["total"] == patients
|
|
||||||
@@ -1,90 +0,0 @@
|
|||||||
"""Phase 4.5: a CaMa population from Synthea (tests/fixtures/synthea/modules/
|
|
||||||
breast_screening.json) comes in through the FHIR door, by the API: every mammogram, biopsy
|
|
||||||
and first-course treatment lands in silver, each biopsy's results (sent as several reports of
|
|
||||||
the same day) as one biopsy, and gold's CaMa timeline carries the stage and the treatments the
|
|
||||||
survival model reads."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
from collections import Counter
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
from test_conectar import ok, wait_for
|
|
||||||
|
|
||||||
from conftest import ROOT
|
|
||||||
|
|
||||||
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
|
||||||
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
|
||||||
DOOR = ROOT / "tests" / "fixtures" / "pipelines" / "fhir_door_cama.json"
|
|
||||||
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
|
||||||
FIELD = "https://isssteleon.org/fhir/CodeSystem/catalog-field"
|
|
||||||
WOMEN = 300
|
|
||||||
|
|
||||||
|
|
||||||
def population(out: Path, women: int = WOMEN, seed: int = 7) -> list[dict]:
|
|
||||||
"""Synthea's FHIR R4 Bundles for `women` women of 40 to 89 (fixed seeds), with only the
|
|
||||||
resources the door reads."""
|
|
||||||
subprocess.run(
|
|
||||||
["java", "-jar", SYNTHEA, "-p", str(women), "-s", str(seed), "-cs", str(seed),
|
|
||||||
"-g", "F", "-a", "40-89", "-d", str(MODULES), "-m", "breast_screening",
|
|
||||||
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
|
||||||
"--exporter.hospital.fhir.export", "false",
|
|
||||||
"--exporter.practitioner.fhir.export", "false", "--exporter.years_of_history", "8",
|
|
||||||
"--exporter.fhir.included_resources", "Patient,Encounter,DiagnosticReport,Observation"],
|
|
||||||
check=True, capture_output=True, cwd=out.parent,
|
|
||||||
) # fmt: skip
|
|
||||||
return [json.loads(p.read_text()) for p in sorted((out / "fhir").glob("*.json"))]
|
|
||||||
|
|
||||||
|
|
||||||
def _sent(bundles: list[dict]) -> Counter:
|
|
||||||
"""What the bundles hold: mammograms, biopsies (one per patient and day), treatments, and
|
|
||||||
the treatments of patients with a mammogram or a biopsy (CaMa's timeline is theirs: the
|
|
||||||
export window can cut a study off and keep the treatment after it)."""
|
|
||||||
found: Counter = Counter()
|
|
||||||
biopsies = set()
|
|
||||||
for b in bundles:
|
|
||||||
studied = False
|
|
||||||
treated = 0
|
|
||||||
for e in b["entry"]:
|
|
||||||
r = e["resource"]
|
|
||||||
codes = [c for c in (r.get("code") or {}).get("coding", []) if c["system"] == STUDY]
|
|
||||||
codes += [c for t in r.get("type", []) for c in t.get("coding", [])
|
|
||||||
if c["system"] == STUDY] # fmt: skip
|
|
||||||
for c in codes:
|
|
||||||
if c["code"] == "breast_biopsy":
|
|
||||||
biopsies.add((r["subject"]["reference"], r["effectiveDateTime"][:10]))
|
|
||||||
else:
|
|
||||||
found[c["code"]] += 1
|
|
||||||
studied |= c["code"] in ("mammography", "breast_biopsy")
|
|
||||||
treated += c["code"] == "breast_treatment"
|
|
||||||
if r["resourceType"] == "Patient" and r.get("deceasedDateTime"):
|
|
||||||
found["death"] += 1
|
|
||||||
found["timeline_treatment"] += treated if studied else 0
|
|
||||||
found["breast_biopsy"] = len(biopsies)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_synthea_cama_population_comes_in_through_the_fhir_door(api, platform, tmp_path):
|
|
||||||
bundles = population(tmp_path / "synthea")
|
|
||||||
sent = _sent(bundles)
|
|
||||||
assert sent["breast_biopsy"] > 50 and sent["breast_treatment"] > 20 and sent["death"] > 0
|
|
||||||
|
|
||||||
receiving = DOOR.read_text().replace("{sender}", "synthea")
|
|
||||||
ok(api.put("/ingest/pipelines/synthea", json=json.loads(receiving)))
|
|
||||||
batch = {"resourceType": "Bundle", "type": "batch",
|
|
||||||
"entry": [e for b in bundles for e in b["entry"]]} # fmt: skip
|
|
||||||
answer = api.post("/cama/fhir?sender=synthea", json=batch)
|
|
||||||
assert answer.status_code == 202, answer.text[:500]
|
|
||||||
wait_for(api, answer.headers["location"].rsplit("/", 1)[1], 1800)
|
|
||||||
|
|
||||||
for study in ("mammography", "breast_biopsy", "breast_treatment"):
|
|
||||||
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
|
||||||
assert platform.count(f"silver.{study}") == sent[study], study
|
|
||||||
q = platform.query
|
|
||||||
# Each invasive biopsy holds all of its results; gold's timeline has them and the course.
|
|
||||||
assert q("select count(*) from silver.breast_biopsy where histology = 'invasive' and "
|
|
||||||
"(stage is null or her2 is null or grade is null)")[0][0] == 0 # fmt: skip
|
|
||||||
kinds = dict(q("select type, count(*) from gold.cama_events where type in "
|
|
||||||
"('stage', 'her2', 'treatment', 'death') group by type")) # fmt: skip
|
|
||||||
assert kinds.get("stage", 0) > 0 and kinds.get("treatment", 0) == sent["timeline_treatment"]
|
|
||||||
@@ -1,769 +0,0 @@
|
|||||||
"""Phase 4 gate, TEA: the synthetic hospital (EEG signals and ADOS-2 reports as BLOBs), loaded
|
|
||||||
through one drawn pipeline, gives what the current platform gives on the same hospital (the
|
|
||||||
reference fixtures, captured at the last load): the ADOS-2 results read from the reports and
|
|
||||||
their scores, the EEG analysis, its indicators and its pages. Real API, Dagster and MLflow.
|
|
||||||
|
|
||||||
The hospital (205 MB) is kept outside git; its path is TEA_HOSPITAL (default
|
|
||||||
~/isssteleon-data), and its hash is the manifest's.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import gzip
|
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sqlite3
|
|
||||||
import time
|
|
||||||
from collections import defaultdict
|
|
||||||
from datetime import date
|
|
||||||
from decimal import Decimal
|
|
||||||
from pathlib import Path
|
|
||||||
from urllib.parse import parse_qsl
|
|
||||||
|
|
||||||
import dagster as dg
|
|
||||||
import pytest
|
|
||||||
from fhir_checks import pages
|
|
||||||
from test_conectar import ok, wait_for
|
|
||||||
|
|
||||||
from conftest import put_concept_map
|
|
||||||
from core import fhir
|
|
||||||
from core.tea import ados2
|
|
||||||
from core.tea import fhir as tea_fhir
|
|
||||||
from models.definitions import tea_preview
|
|
||||||
from persistance import config, previews
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
SLOW = float(os.environ.get("TEA_GATE_SLOW", "1"))
|
|
||||||
HOSPITAL = Path(os.environ.get("TEA_HOSPITAL", Path.home() / "isssteleon-data"))
|
|
||||||
# The age curves' reference cohort (public, outside git) and where its measures are kept.
|
|
||||||
os.environ.setdefault("TEA_REFERENCE_DIR", "/mnt/drive/eeg-helsinki")
|
|
||||||
os.environ.setdefault("TEA_REFERENCE_CACHE", str(HOSPITAL / "cache"))
|
|
||||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "tea"
|
|
||||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_tea.json"
|
|
||||||
MANIFEST = ROOT / "tests" / "fixtures" / "hospital" / "manifest.json"
|
|
||||||
# The current platform's item columns, by module, for each item's meaning.
|
|
||||||
ITEMS = {
|
|
||||||
"vocalization_directed": {"module_1": "sa_a2"},
|
|
||||||
"pointing": {"module_1": "sa_a7", "module_2": "sa_a6"},
|
|
||||||
"gestures": {"module_1": "sa_a8", "module_2": "sa_a7"},
|
|
||||||
"unusual_eye_contact": {"module_1": "sa_b1", "module_2": "sa_b1"},
|
|
||||||
"facial_expressions": {"module_1": "sa_b3", "module_2": "sa_b2"},
|
|
||||||
"gaze_integration": {"module_1": "sa_b4"},
|
|
||||||
"shared_enjoyment": {"module_1": "sa_b5", "module_2": "sa_b3"},
|
|
||||||
"showing": {"module_1": "sa_b9", "module_2": "sa_b5"},
|
|
||||||
"joint_attention_initiation": {"module_1": "sa_b10", "module_2": "sa_b6"},
|
|
||||||
"joint_attention_response": {"module_1": "sa_b11"},
|
|
||||||
"social_overtures_quality": {"module_1": "sa_b12", "module_2": "sa_b8"},
|
|
||||||
"reciprocal_communication": {"module_2": "sa_b11"},
|
|
||||||
"rapport_quality": {"module_2": "sa_b12"},
|
|
||||||
"intonation": {"module_1": "rrb_a3"},
|
|
||||||
"stereotyped_language": {"module_1": "rrb_a5", "module_2": "rrb_a4"},
|
|
||||||
"unusual_sensory_interest": {"module_1": "rrb_d1", "module_2": "rrb_d1"},
|
|
||||||
"hand_finger_mannerisms": {"module_1": "rrb_d2", "module_2": "rrb_d2"},
|
|
||||||
"repetitive_interests": {"module_1": "rrb_d4", "module_2": "rrb_d4"},
|
|
||||||
} # fmt: skip
|
|
||||||
MODULES = {"MODULO_1": "module_1", "MODULO_2": "module_2"}
|
|
||||||
CLASSIFICATION = {"NO_ESPECTRO": "non_spectrum", "ESPECTRO_AUTISTA": "autism_spectrum",
|
|
||||||
"AUTISMO": "autism"} # fmt: skip
|
|
||||||
METRICS = {"RITMO_POSTERIOR": "posterior_rhythm", "HUSOS_SUENO_N2": "spindles_n2",
|
|
||||||
"HUSOS_SUENO_N3": "spindles_n3", "PICOS_PAROXISTICOS": "paroxysmal_spikes",
|
|
||||||
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient"} # fmt: skip
|
|
||||||
LEVELS = {"completo": "complete", "no_analizable": "not_analyzable", "parcial": "partial",
|
|
||||||
"sin_referencia_auricular": "no_ear_reference"} # fmt: skip
|
|
||||||
BIOMARKERS = {
|
|
||||||
"PICOS_PAROXISTICOS": "spikes",
|
|
||||||
"HUSOS_SUENO_N2": "spindles",
|
|
||||||
"RITMO_POSTERIOR": "posterior_rhythm",
|
|
||||||
"GRADIENTE_ANTEROPOSTERIOR": "gradient",
|
|
||||||
}
|
|
||||||
ZONES = {
|
|
||||||
"frontal_izq": "frontal_left",
|
|
||||||
"frontal_der": "frontal_right",
|
|
||||||
"frontal_media": "frontal_midline",
|
|
||||||
"temporal_izq": "temporal_left",
|
|
||||||
"temporal_der": "temporal_right",
|
|
||||||
}
|
|
||||||
CAPTURED_ON = "2026-11-28"
|
|
||||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
|
||||||
CODES = { # the current platform's code -> the platform's
|
|
||||||
"CONFIRMADO": "confirmed", "EN_PROCESO": "in_process", "SIN_TEA": "not_confirmed",
|
|
||||||
"SOLO_MCHAT": "mchat_only", "PSICOLOGIA": "psychology", "NEUROPEDIATRIA": "neuropediatrics",
|
|
||||||
"EEG": "eeg", "BUENO": "good", "MALO": "bad", "SIN_ANALIZAR": "not_analyzed",
|
|
||||||
"16_23": "16-23", "24_29": "24-29", "30_36": "30-36", "sin_dato": "no_data",
|
|
||||||
"FEMENINO": "female", "MASCULINO": "male", "EN_POBLACION": "in_population",
|
|
||||||
} # fmt: skip
|
|
||||||
STRATA = {"estado": "category", "paso": "category", "calidad": "category",
|
|
||||||
"grupo_edad": "age_group", "edad_sexo": "age_sex", "sexo": "sex"} # fmt: skip
|
|
||||||
ONLY_OURS = {"M30_RESULTADO_EEG": {"alteration"}}
|
|
||||||
|
|
||||||
|
|
||||||
def _code(text: str) -> str:
|
|
||||||
return "|".join(CODES.get(part, part) for part in text.split("|"))
|
|
||||||
|
|
||||||
|
|
||||||
def _report(entry: dict, ours: bool) -> tuple:
|
|
||||||
"""Counts, score and its extensions, and strata of one report, in the platform's codes.
|
|
||||||
The current platform's proportions report no initial population."""
|
|
||||||
group = entry["resource"]["group"][0]
|
|
||||||
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
|
||||||
if ours and "denominator" in populations:
|
|
||||||
populations.pop("initial-population")
|
|
||||||
score = group.get("measureScore", {})
|
|
||||||
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
|
|
||||||
strata = {}
|
|
||||||
for s in group.get("stratifier", []):
|
|
||||||
code = s["code"][0]
|
|
||||||
name = code["coding"][0]["code"] if "coding" in code else STRATA[code["text"]]
|
|
||||||
cells: dict = defaultdict(dict)
|
|
||||||
for x in s.get("stratum", []):
|
|
||||||
for p in x["population"]:
|
|
||||||
kind = p["code"]["coding"][0]["code"]
|
|
||||||
if not (ours and kind == "initial-population" and "denominator" in populations):
|
|
||||||
cells[_code(x["value"]["text"])][kind] = p["count"]
|
|
||||||
strata[name] = dict(cells)
|
|
||||||
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
|
|
||||||
|
|
||||||
|
|
||||||
def indicators(api) -> None:
|
|
||||||
"""Every measure, every semester, as the current platform answers them."""
|
|
||||||
reference = {k.upper(): v for k, v in
|
|
||||||
json.loads((REFERENCE / "indicators.json").read_text()).items()} # fmt: skip
|
|
||||||
(measures,) = pages(api, "/tea/fhir/Measure")
|
|
||||||
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
|
|
||||||
for measure in [e["resource"] for e in measures["entry"]]:
|
|
||||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
|
||||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
|
||||||
found = [e for b in pages(api, "/tea/fhir/MeasureReport", params) for e in b["entry"]]
|
|
||||||
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
|
|
||||||
name = measure["name"]
|
|
||||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
|
||||||
a, b = _report(ours, True), _report(theirs, False)
|
|
||||||
a = (*a[:3], {k: v for k, v in a[3].items() if k not in ONLY_OURS.get(name, ())})
|
|
||||||
where = (name, ours["resource"]["period"]["start"])
|
|
||||||
assert a[0] == b[0] and a[3] == b[3], (where, a, b)
|
|
||||||
if cohort:
|
|
||||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
|
||||||
continue
|
|
||||||
assert (a[1] is None) == (b[1] is None), where
|
|
||||||
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
|
|
||||||
assert a[2] == pytest.approx(b[2]), where
|
|
||||||
|
|
||||||
|
|
||||||
pytestmark = pytest.mark.skipif(
|
|
||||||
not (HOSPITAL / "hospital_tea.db").exists(), reason="the TEA hospital is outside git"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _day(value) -> date:
|
|
||||||
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
|
|
||||||
|
|
||||||
|
|
||||||
def _wait_for_sensor_analysis(api):
|
|
||||||
deadline = time.monotonic() + 3600 * SLOW
|
|
||||||
while time.monotonic() < deadline:
|
|
||||||
runs = ok(api.get("/runs", params={"job": "tea_eeg", "domain": "tea"}))
|
|
||||||
for run in runs:
|
|
||||||
if run["state"] == "failed":
|
|
||||||
pytest.fail(ok(api.get(f"/runs/{run['id']}"))["error"])
|
|
||||||
if any(run["state"] == "succeeded" for run in runs):
|
|
||||||
return
|
|
||||||
time.sleep(2)
|
|
||||||
pytest.fail("The sensor's tea_eeg run did not succeed within 3600 seconds")
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def scored_hospital(api, platform):
|
|
||||||
db = HOSPITAL / "hospital_tea.db"
|
|
||||||
expected = json.loads(MANIFEST.read_text())["files"]["hospital_tea.db"]["sha256"]
|
|
||||||
assert hashlib.sha256(db.read_bytes()).hexdigest() == expected
|
|
||||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
|
||||||
put_concept_map(api, "hospital_tea")
|
|
||||||
ok(api.put("/ingest/pipelines/tea", json=pipeline))
|
|
||||||
wait_for(api, ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"], int(1800 * SLOW))
|
|
||||||
_wait_for_sensor_analysis(api)
|
|
||||||
q = platform.query
|
|
||||||
|
|
||||||
# Silver holds every study of the hospital; each file (EEG signal, ADOS-2 report) is
|
|
||||||
# kept once, by its hash.
|
|
||||||
with sqlite3.connect(db) as con:
|
|
||||||
source = {s: con.execute(f"select count(*) from {s}").fetchone()[0]
|
|
||||||
for s in ("mchat", "ados2", "eeg", "evaluacion_neuropediatrica")} # fmt: skip
|
|
||||||
signed = "select count(*) from eeg where eeg_estudio is not null"
|
|
||||||
signals = con.execute(signed).fetchone()[0]
|
|
||||||
counts = {s: q(f"select count(*) from silver.{s}")[0][0] for s in ("mchat", "ados2", "eeg")}
|
|
||||||
assert counts == {s: source[s] for s in counts}
|
|
||||||
assert q("select count(*) from silver.clinical_note where specialty = 'pediatric_neurology'"
|
|
||||||
)[0][0] == source["evaluacion_neuropediatrica"] # fmt: skip
|
|
||||||
assert q("select count(*) from silver.eeg where edf is not null")[0][0] == signals
|
|
||||||
kept = "select count(*) from bronze.files where key in (select edf from silver.eeg)"
|
|
||||||
assert q(kept)[0][0] == signals
|
|
||||||
|
|
||||||
reference = {(r["ado_fecha"], r["ado_pac_id"]): r for r in
|
|
||||||
json.loads((REFERENCE / "tables" / "ados2.json").read_text())
|
|
||||||
if r["ado_modulo"]} # fmt: skip
|
|
||||||
numbers = dict(q("select distinct person_id, record_number from bronze.staged__identity"))
|
|
||||||
names = ["person_id", "evaluation_date", "module", *ITEMS]
|
|
||||||
sql = f"select {', '.join(names)} from silver.ados2 where module is not null"
|
|
||||||
found = [dict(zip(names, r, strict=True)) for r in q(sql)]
|
|
||||||
assert len(found) == len(reference) == counts["ados2"]
|
|
||||||
for row in found:
|
|
||||||
theirs = reference[(str(row["evaluation_date"])[:10],
|
|
||||||
int(numbers[row["person_id"]].removeprefix("N")))] # fmt: skip
|
|
||||||
module = MODULES[theirs["ado_modulo"]]
|
|
||||||
assert row["module"] == module
|
|
||||||
for item, by_module in ITEMS.items():
|
|
||||||
value = theirs["ado_" + by_module[module]] if module in by_module else None
|
|
||||||
assert row[item] == (None if value is None else pytest.approx(value)), item
|
|
||||||
# and their scores: the calibrated severity and the classification.
|
|
||||||
birth = q(f"select birth_date from silver.person where person_id = '{row['person_id']}'")
|
|
||||||
css, label = ados2.score({**row, "evaluation_date": _day(row["evaluation_date"])},
|
|
||||||
_day(birth[0][0])) # fmt: skip
|
|
||||||
assert (css, label) == (theirs["ado_css"], CLASSIFICATION[theirs["ado_clasificacion"]])
|
|
||||||
|
|
||||||
# The EEG analysis: every signal's verdict, level and metrics are the current platform's.
|
|
||||||
with sqlite3.connect(db) as con:
|
|
||||||
signals = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
|
|
||||||
hashes = {i: hashlib.sha256(b).hexdigest() for i, b in signals}
|
|
||||||
tables = REFERENCE / "tables"
|
|
||||||
reference = {hashes[r["eeg_id"]]: r for r in json.loads((tables / "eeg.json").read_text())
|
|
||||||
if r["eeg_id"] in hashes} # fmt: skip
|
|
||||||
found = {e: (v, lvl) for e, v, lvl in q("select edf, valid, level from bronze.eeg_analysis")}
|
|
||||||
assert set(found) == set(reference)
|
|
||||||
for edf, theirs in reference.items():
|
|
||||||
assert found[edf] == (bool(theirs["eeg_valido"]), LEVELS[theirs["eeg_nivel"]]), edf
|
|
||||||
by_id = {r["eeg_id"]: hashes.get(r["eeg_id"]) for r in reference.values()}
|
|
||||||
metrics = {(by_id.get(r["met_eeg_id"]), METRICS[r["met_codigo"]]): r
|
|
||||||
for r in json.loads((tables / "eeg_metrica.json").read_text())} # fmt: skip
|
|
||||||
ours = {(e, c): v for e, c, v in q("select edf, code, value from bronze.eeg_metrics")}
|
|
||||||
for key, theirs in metrics.items():
|
|
||||||
value = theirs["met_valor"]
|
|
||||||
assert ours.get(key) == (None if value is None else pytest.approx(value, rel=1e-12)), key
|
|
||||||
|
|
||||||
# The age curves: one training run gives a version of each, from the reference cohort;
|
|
||||||
# promoted after their clinical validation, they score every analysed EEG as the
|
|
||||||
# current platform's curves do.
|
|
||||||
wait_for(api, ok(api.post("/models/tea/train", json={}))["run_id"], int(3600 * SLOW))
|
|
||||||
names = ok(api.get("/models/tea"))
|
|
||||||
assert len(names) == 7
|
|
||||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
|
||||||
for name in names:
|
|
||||||
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
|
|
||||||
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
|
|
||||||
pending = {"scope": {"mode": "pending"}}
|
|
||||||
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], int(1800 * SLOW))
|
|
||||||
scored = {(e, c): r for e, c, *r in q(
|
|
||||||
"select edf, code, z, outside, p5, median, p95 from gold.tea_eeg_metrics")} # fmt: skip
|
|
||||||
for key, theirs in metrics.items():
|
|
||||||
if key not in scored: # an EEG of a child outside the cohort: not in gold
|
|
||||||
continue
|
|
||||||
expected = [theirs[f"met_{k}"] for k in ("z", "fuera", "p5", "mediana", "p95")]
|
|
||||||
assert scored[key] == [None if v is None else pytest.approx(v, rel=1e-9)
|
|
||||||
for v in expected], key # fmt: skip
|
|
||||||
|
|
||||||
return platform
|
|
||||||
|
|
||||||
|
|
||||||
def _association_gate(api, platform):
|
|
||||||
name = "ados2_association"
|
|
||||||
training = ok(api.post("/models/tea/train", json={"models": [name]}))["run_id"]
|
|
||||||
wait_for(api, training, int(3600 * SLOW))
|
|
||||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
|
||||||
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
|
|
||||||
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
|
|
||||||
pending = {"scope": {"mode": "pending"}}
|
|
||||||
wait_for(api, ok(api.post("/tea/eegs/analyze", json=pending))["run_id"], int(1800 * SLOW))
|
|
||||||
|
|
||||||
tables = REFERENCE / "tables"
|
|
||||||
reference = json.loads((tables / "relacion_ados2.json").read_text())
|
|
||||||
pair_keys = {}
|
|
||||||
expected_pairs = {}
|
|
||||||
for row in reference:
|
|
||||||
zone = row["rel_zona"]
|
|
||||||
pair = "|".join(
|
|
||||||
(BIOMARKERS[row["rel_biomarcador"]], ZONES.get(zone, zone), row["rel_resultado"])
|
|
||||||
)
|
|
||||||
pair_keys[row["rel_id"]] = pair
|
|
||||||
expected_pairs[pair] = row
|
|
||||||
q = platform.query
|
|
||||||
pairs = {key: values for key, *values in q(
|
|
||||||
"select key, n, n_cohort, method, same_direction, odds_ratio, ci_low, ci_high, p, q "
|
|
||||||
"from gold.tea_associations"
|
|
||||||
)} # fmt: skip
|
|
||||||
assert pairs.keys() == expected_pairs.keys()
|
|
||||||
for key, row in expected_pairs.items():
|
|
||||||
n, n_cohort, method, same_direction, *stats = pairs[key]
|
|
||||||
assert (n, n_cohort, method, same_direction) == (
|
|
||||||
row["rel_n"],
|
|
||||||
row["rel_n_cohorte"],
|
|
||||||
row["rel_modelo"],
|
|
||||||
row["rel_mismo_sentido"],
|
|
||||||
), key
|
|
||||||
for value, field in zip(stats, ("or", "ic_inf", "ic_sup", "p", "q"), strict=True):
|
|
||||||
expected = row[f"rel_{field}"]
|
|
||||||
assert value == (None if expected is None else pytest.approx(expected, rel=1e-3)), (
|
|
||||||
key,
|
|
||||||
field,
|
|
||||||
)
|
|
||||||
|
|
||||||
with sqlite3.connect(HOSPITAL / "hospital_tea.db") as con:
|
|
||||||
signals = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
|
|
||||||
hashes = {i: hashlib.sha256(b).hexdigest() for i, b in signals}
|
|
||||||
eeg_ids = {
|
|
||||||
(edf, str(day)[:10]): f"{person}|{str(day)[:10]}"
|
|
||||||
for edf, person, day in q("select edf, person_id, study_date from silver.eeg")
|
|
||||||
}
|
|
||||||
reference_eegs = {
|
|
||||||
row["eeg_id"]: eeg_ids.get((hashes.get(row["eeg_id"]), row["eeg_fecha_estudio"]))
|
|
||||||
for row in json.loads((tables / "eeg.json").read_text())
|
|
||||||
}
|
|
||||||
reference = json.loads((tables / "relacion_ados2_paciente.json").read_text())
|
|
||||||
expected_scores = {
|
|
||||||
(reference_eegs[row["rap_eeg_id"]], pair_keys[row["rap_rel_id"]]): row for row in reference
|
|
||||||
}
|
|
||||||
score_rows = q(
|
|
||||||
"select eeg_id, pair, z, probability, reference_probability "
|
|
||||||
"from gold.tea_association_scores"
|
|
||||||
)
|
|
||||||
scores = {(eeg_id, pair): (z, prob, ref) for eeg_id, pair, z, prob, ref in score_rows}
|
|
||||||
assert scores.keys() == expected_scores.keys()
|
|
||||||
for key, row in expected_scores.items():
|
|
||||||
z, prob, ref = scores[key]
|
|
||||||
assert z == pytest.approx(row["rap_valor_z"], rel=1e-9), key
|
|
||||||
assert prob == pytest.approx(row["rap_probabilidad"], abs=1e-4), key
|
|
||||||
assert ref == pytest.approx(row["rap_probabilidad_referencia"], abs=1e-4), key
|
|
||||||
|
|
||||||
|
|
||||||
def _fhir_code(concept):
|
|
||||||
return concept["coding"][0]["code"]
|
|
||||||
|
|
||||||
|
|
||||||
def _fhir_extensions(resource):
|
|
||||||
return {
|
|
||||||
e["url"].rsplit("/", 1)[-1]: next(
|
|
||||||
(v for k, v in e.items() if k.startswith("value")), e.get("extension")
|
|
||||||
)
|
|
||||||
for e in resource.get("extension", [])
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _assert_reference_number(actual, expected, *, rel=1e-9):
|
|
||||||
if expected is None or isinstance(expected, int):
|
|
||||||
assert actual == expected
|
|
||||||
else:
|
|
||||||
precision = float(Decimal("0.5").scaleb(expected.as_tuple().exponent))
|
|
||||||
assert actual == pytest.approx(float(expected), rel=rel, abs=precision)
|
|
||||||
|
|
||||||
|
|
||||||
def _fhir_check_gate(actual, reference):
|
|
||||||
units = {"electrodos": "electrodes", "fracción": "fraction"}
|
|
||||||
for a, b in [
|
|
||||||
(actual.get("valueQuantity"), reference.get("valueQuantity")),
|
|
||||||
*(
|
|
||||||
(
|
|
||||||
actual.get("referenceRange", [{}])[0].get(bound),
|
|
||||||
reference.get("referenceRange", [{}])[0].get(bound),
|
|
||||||
)
|
|
||||||
for bound in ("low", "high")
|
|
||||||
),
|
|
||||||
]:
|
|
||||||
if b is None:
|
|
||||||
assert a is None
|
|
||||||
else:
|
|
||||||
assert a.get("unit") == units.get(b.get("unit"), b.get("unit"))
|
|
||||||
_assert_reference_number(a["value"], b["value"])
|
|
||||||
text = reference.get("valueString")
|
|
||||||
assert actual.get("valueString") == LEVELS.get(text, text)
|
|
||||||
assert _fhir_code(actual["interpretation"][0]) == _fhir_code(reference["interpretation"][0])
|
|
||||||
decisive = next(c["valueBoolean"] for c in reference["component"]
|
|
||||||
if c["code"]["text"] == "decisive") # fmt: skip
|
|
||||||
assert _fhir_extensions(actual)["eeg-check-decisive"] == decisive
|
|
||||||
|
|
||||||
|
|
||||||
def _fhir_risk_gate(actual, reference):
|
|
||||||
def pair(prediction):
|
|
||||||
extensions = _fhir_extensions(prediction)
|
|
||||||
biomarker = BIOMARKERS[extensions["biomarcador"]["code"]]
|
|
||||||
zone = extensions["zona"]["code"]
|
|
||||||
return "|".join((biomarker, ZONES.get(zone, zone), _fhir_code(prediction["outcome"])))
|
|
||||||
|
|
||||||
predictions = {_fhir_code(p["outcome"]): p for p in actual["prediction"]}
|
|
||||||
expected = {pair(p): p for p in reference["prediction"]}
|
|
||||||
assert predictions.keys() == expected.keys()
|
|
||||||
for code, prediction in predictions.items():
|
|
||||||
theirs = expected[code]
|
|
||||||
_assert_reference_number(prediction["probabilityDecimal"], theirs["probabilityDecimal"],
|
|
||||||
rel=1e-3) # fmt: skip
|
|
||||||
extensions, theirs = _fhir_extensions(prediction), _fhir_extensions(theirs)
|
|
||||||
for ours, name in (
|
|
||||||
("odds-ratio", "odds-ratio"),
|
|
||||||
("ci-low", "ic-inf"),
|
|
||||||
("ci-high", "ic-sup"),
|
|
||||||
("q", "q"),
|
|
||||||
("reference-probability", "probabilidad-referencia"),
|
|
||||||
):
|
|
||||||
_assert_reference_number(extensions.get(f"association-{ours}"), theirs.get(name),
|
|
||||||
rel=1e-3) # fmt: skip
|
|
||||||
assert extensions.get("association-same-direction") == theirs.get("mismo-sentido")
|
|
||||||
|
|
||||||
|
|
||||||
def _fhir_eeg_gate(api, platform, patients, reference):
|
|
||||||
tables = REFERENCE / "tables"
|
|
||||||
|
|
||||||
def table(name):
|
|
||||||
return json.loads((tables / f"{name}.json").read_text(), parse_float=Decimal)
|
|
||||||
|
|
||||||
records = {r["eeg_pac_id"]: r["eeg_id"] for r in table("eeg")}
|
|
||||||
metric_ids = {(r["met_eeg_id"], METRICS[r["met_codigo"]]): r["met_id"]
|
|
||||||
for r in table("eeg_metrica")} # fmt: skip
|
|
||||||
sites = defaultdict(dict)
|
|
||||||
for kind, name, prefix, site in (
|
|
||||||
("eeg-electrode-10-20", "electrodo", "mel", "electrodo"),
|
|
||||||
("tea-eeg-zone", "zona", "mez", "zona"),
|
|
||||||
):
|
|
||||||
for r in table(f"eeg_metrica_{name}"):
|
|
||||||
code = r[f"{prefix}_{site}"]
|
|
||||||
sites[r[f"{prefix}_met_id"]][kind, ZONES.get(code, code)] = r[f"{prefix}_valor"]
|
|
||||||
|
|
||||||
scores = {
|
|
||||||
(tea_fhir._eeg_report_id(person, day), metric): z
|
|
||||||
for person, day, metric, z in platform.query(
|
|
||||||
"select e.person_id, e.study_date, s.metric, s.z from bronze.eeg_scores as s "
|
|
||||||
"join silver.eeg as e on e.edf = s.edf where s.part = 'value' and s.model is not null"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
by_child = defaultdict(list)
|
|
||||||
for resource in reference:
|
|
||||||
if "subject" in resource:
|
|
||||||
by_child[resource["subject"]["reference"]].append(resource)
|
|
||||||
params = [("follow-up-cutoff", "2026-12-31"), ("_count", 20)]
|
|
||||||
params += [("_revinclude", f"{kind}:subject") for kind in
|
|
||||||
("DiagnosticReport", "Observation", "Condition", "RiskAssessment")] # fmt: skip
|
|
||||||
served = defaultdict(dict)
|
|
||||||
for bundle in pages(api, "/tea/fhir/Patient", params):
|
|
||||||
for entry in bundle.get("entry", []):
|
|
||||||
r = entry["resource"]
|
|
||||||
if entry["search"]["mode"] == "include":
|
|
||||||
served[r["subject"]["reference"]][f"{r['resourceType']}/{r['id']}"] = r
|
|
||||||
|
|
||||||
for child, (person, number) in patients.items():
|
|
||||||
actual = served[f"Patient/{person}"]
|
|
||||||
theirs = by_child[child]
|
|
||||||
for kind in ("Observation", "DiagnosticReport", "RiskAssessment", "Condition"):
|
|
||||||
direct = {
|
|
||||||
f"{kind}/{r['id']}": r
|
|
||||||
for bundle in pages(api, f"/tea/fhir/{kind}", {"subject": f"Patient/{person}"})
|
|
||||||
for entry in bundle.get("entry", [])
|
|
||||||
if (r := entry["resource"])
|
|
||||||
}
|
|
||||||
assert direct == {key: r for key, r in actual.items() if key.startswith(f"{kind}/")}
|
|
||||||
|
|
||||||
def resources(kind, code=None, actual=actual):
|
|
||||||
return [
|
|
||||||
r
|
|
||||||
for r in actual.values()
|
|
||||||
if r["resourceType"] == kind and (code is None or _fhir_code(r["code"]) == code)
|
|
||||||
]
|
|
||||||
|
|
||||||
(expected_ados,) = [r for r in theirs if r["id"].startswith("ados2-")]
|
|
||||||
(ados,) = resources("Observation", "ados2")
|
|
||||||
components = {_fhir_code(c["code"]): c for c in expected_ados["component"]}
|
|
||||||
assert ados.get("valueInteger") == components.get("ados2.css", {}).get("valueInteger")
|
|
||||||
classification = components["ados2.clasificacion"]["valueCodeableConcept"]
|
|
||||||
assert (
|
|
||||||
_fhir_code(ados["interpretation"][0])
|
|
||||||
== CLASSIFICATION[_fhir_code(classification).rsplit(".", 1)[-1]]
|
|
||||||
)
|
|
||||||
(expected_mchat,) = [r for r in theirs if r["id"].startswith("mchat-")]
|
|
||||||
(mchat,) = resources("Observation", "mchat.score")
|
|
||||||
assert mchat["valueQuantity"]["value"] == expected_mchat["valueInteger"]
|
|
||||||
(expected_condition,) = [r for r in theirs if r["resourceType"] == "Condition"]
|
|
||||||
assert any(
|
|
||||||
r["recordedDate"] == expected_condition["recordedDate"]
|
|
||||||
and {"system": fhir.ICD10, "code": "F84.0"} in r["code"].get("coding", [])
|
|
||||||
for r in resources("Condition")
|
|
||||||
)
|
|
||||||
|
|
||||||
(expected_report,) = [r for r in theirs if r["resourceType"] == "DiagnosticReport"]
|
|
||||||
(report,) = resources("DiagnosticReport", "eeg")
|
|
||||||
quality, validity = map(_fhir_code, expected_report["conclusionCode"])
|
|
||||||
assert list(map(_fhir_code, report["conclusionCode"])) == [
|
|
||||||
CODES[quality],
|
|
||||||
validity.replace("-", "_"),
|
|
||||||
]
|
|
||||||
extensions = _fhir_extensions(report)
|
|
||||||
expected_extensions = _fhir_extensions(expected_report)
|
|
||||||
for name, code in (("duration-min", "duracion-min"), ("age-months", "edad-meses"),
|
|
||||||
("channels", "canales")): # fmt: skip
|
|
||||||
_assert_reference_number(extensions.get(f"eeg-{name}"), expected_extensions.get(code))
|
|
||||||
result = [actual[r["reference"]] for r in report["result"]]
|
|
||||||
assert all(r["subject"] == report["subject"] for r in result)
|
|
||||||
checks = {
|
|
||||||
(_fhir_code(r["code"]), _fhir_code(r["component"][0]["code"]) if r.get("component")
|
|
||||||
else None): r for r in result
|
|
||||||
if r["code"]["coding"][0]["system"].endswith("/tea-eeg-check")
|
|
||||||
} # fmt: skip
|
|
||||||
expected_checks = {
|
|
||||||
(_fhir_code(r["code"]), next((c["valueString"] for c in r["component"]
|
|
||||||
if c["code"]["text"] == "electrode"), None)): r
|
|
||||||
for r in theirs if r["id"].startswith("calidad-")
|
|
||||||
} # fmt: skip
|
|
||||||
assert checks.keys() == expected_checks.keys()
|
|
||||||
for key, check in checks.items():
|
|
||||||
_fhir_check_gate(check, expected_checks[key])
|
|
||||||
|
|
||||||
metrics = {_fhir_code(r["code"]): r for r in result
|
|
||||||
if r["code"]["coding"][0]["system"].endswith("/tea-eeg-metric")} # fmt: skip
|
|
||||||
expected_metrics = {METRICS[_fhir_code(r["code"]).upper()]: r for r in theirs
|
|
||||||
if r.get("code", {}).get("coding", [{}])[0].get("code", "").upper()
|
|
||||||
in METRICS} # fmt: skip
|
|
||||||
assert metrics.keys() == expected_metrics.keys()
|
|
||||||
for code, metric in metrics.items():
|
|
||||||
expected = expected_metrics[code]
|
|
||||||
_assert_reference_number(metric.get("valueQuantity", {}).get("value"),
|
|
||||||
expected.get("valueQuantity", {}).get("value")) # fmt: skip
|
|
||||||
z = _fhir_extensions(metric).get("eeg-z")
|
|
||||||
stored = scores.get((report["id"], code))
|
|
||||||
assert z == (pytest.approx(stored, rel=1e-9) if stored is not None else None)
|
|
||||||
expected_z = next((c["valueQuantity"]["value"] for c in expected.get("component", [])
|
|
||||||
if _fhir_code(c["code"]) == "z"), None) # fmt: skip
|
|
||||||
_assert_reference_number(z, expected_z)
|
|
||||||
components = {
|
|
||||||
(c["code"]["coding"][0]["system"].rsplit("/", 1)[-1], _fhir_code(c["code"])): c.get(
|
|
||||||
"valueQuantity", {}
|
|
||||||
).get("value")
|
|
||||||
for c in metric.get("component", [])
|
|
||||||
}
|
|
||||||
expected_sites = sites[metric_ids[records[number], code]]
|
|
||||||
assert components.keys() == expected_sites.keys()
|
|
||||||
for site, value in components.items():
|
|
||||||
_assert_reference_number(value, expected_sites[site])
|
|
||||||
|
|
||||||
expected_risks = [r for r in theirs if r["resourceType"] == "RiskAssessment"]
|
|
||||||
for risk, expected in zip(resources("RiskAssessment"), expected_risks, strict=True):
|
|
||||||
assert [b["reference"] for b in risk["basis"]] == [
|
|
||||||
f"DiagnosticReport/{report['id']}",
|
|
||||||
f"Observation/{ados['id']}",
|
|
||||||
]
|
|
||||||
_fhir_risk_gate(risk, expected)
|
|
||||||
|
|
||||||
|
|
||||||
def _follow_up_gate(api, platform):
|
|
||||||
with gzip.open(REFERENCE / "follow_up.json.gz", "rt") as file:
|
|
||||||
reference = json.load(file, parse_float=Decimal)
|
|
||||||
persons = {
|
|
||||||
int(number.removeprefix("N")): person
|
|
||||||
for person, number in platform.query(
|
|
||||||
"select distinct person_id, record_number from bronze.staged__identity"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
params_map = {
|
|
||||||
"etapa": "tea-step", "status": "follow-up-status", "resultado-eeg": "tea-eeg-result",
|
|
||||||
"modelo": "tea-model", "grupo-edad": "tea-age-group", "sexo": "tea-sex",
|
|
||||||
"mchat": "tea-mchat", "css": "tea-css",
|
|
||||||
} # fmt: skip
|
|
||||||
values = {
|
|
||||||
**CODES, "NEUROPEDIATRIA": "neurology", "anormal": "abnormal",
|
|
||||||
"sin-eeg-valido": "no_valid_eeg",
|
|
||||||
"si": "yes",
|
|
||||||
} # fmt: skip
|
|
||||||
counts = {
|
|
||||||
"con_eeg_valido": "valid", "sin_eeg_valido": "not_valid",
|
|
||||||
"normales": "normal", "anormales": "abnormal",
|
|
||||||
} # fmt: skip
|
|
||||||
for query, expected in reference.items():
|
|
||||||
params = []
|
|
||||||
for name, value in parse_qsl(query):
|
|
||||||
if name == "date":
|
|
||||||
dates = {"ge": "follow-up-start", "le": "follow-up-cutoff"}
|
|
||||||
params.append((dates[value[:2]], value[2:]))
|
|
||||||
else:
|
|
||||||
params.append((params_map[name], values.get(value, value)))
|
|
||||||
resources = [entry["resource"] for entry in expected["episodes"]["body"].get("entry", [])]
|
|
||||||
records = {
|
|
||||||
f"Patient/{r['id']}": int(next(
|
|
||||||
identifier["value"].removeprefix("N-") for identifier in r["identifier"]
|
|
||||||
if identifier["system"].endswith("/expediente")
|
|
||||||
))
|
|
||||||
for r in resources if r["resourceType"] == "Patient"
|
|
||||||
} # fmt: skip
|
|
||||||
children = {
|
|
||||||
persons[records[r["patient"]["reference"]]]
|
|
||||||
for r in resources if r["resourceType"] == "EpisodeOfCare"
|
|
||||||
} # fmt: skip
|
|
||||||
bundles = pages(api, "/tea/fhir/Patient", params)
|
|
||||||
assert {entry["resource"]["id"] for bundle in bundles
|
|
||||||
for entry in bundle.get("entry", [])} == children, query # fmt: skip
|
|
||||||
|
|
||||||
parameters = {}
|
|
||||||
alterations = {}
|
|
||||||
for parameter in expected["summary"]["body"]["parameter"]:
|
|
||||||
name = parameter["name"]
|
|
||||||
if name == "por_alteracion":
|
|
||||||
parts = {p["name"]: p for p in parameter["part"]}
|
|
||||||
metric = METRICS[parts["alteracion"]["valueCode"].upper()]
|
|
||||||
alterations[metric] = parts["pacientes"]["valueInteger"]
|
|
||||||
else:
|
|
||||||
parameters[counts[name]] = parameter["valueInteger"]
|
|
||||||
found = ok(api.get("/tea/fhir/Patient/$eeg-summary", params=params))
|
|
||||||
assert found["resourceType"] == "Parameters", query
|
|
||||||
assert {p["name"]: p["valueInteger"] for p in found["parameter"]
|
|
||||||
if p["name"] != "by_alteration"} == parameters, query # fmt: skip
|
|
||||||
assert {
|
|
||||||
p["part"][0]["valueCode"]: p["part"][1]["valueInteger"]
|
|
||||||
for p in found["parameter"] if p["name"] == "by_alteration"
|
|
||||||
} == alterations, query # fmt: skip
|
|
||||||
if query == "date=le2026-12-31":
|
|
||||||
patients = {child: (persons[number], number) for child, number in records.items()}
|
|
||||||
_fhir_eeg_gate(api, platform, patients, resources)
|
|
||||||
|
|
||||||
|
|
||||||
def test_tea_from_the_hospital_to_indicators(api, scored_hospital, monkeypatch):
|
|
||||||
_association_gate(api, scored_hospital)
|
|
||||||
|
|
||||||
indicators(api)
|
|
||||||
_follow_up_gate(api, scored_hospital)
|
|
||||||
|
|
||||||
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
|
|
||||||
listed = ok(api.get("/tea/eegs"))
|
|
||||||
summary = json.loads((REFERENCE / "pages.json").read_text())["/governance/tea/eeg/summary"]
|
|
||||||
expected = summary["body"]
|
|
||||||
assert (len(listed), sum(e["analysed"] for e in listed), sum(bool(e["valid"]) for e in listed)
|
|
||||||
) == (expected["eegs"], expected["analysed"], expected["valid"]) # fmt: skip
|
|
||||||
actual_summary = ok(api.get("/tea/eegs/summary"))
|
|
||||||
assert actual_summary == expected
|
|
||||||
assert (actual_summary["fhir_eegs"], actual_summary["fhir_metrics"]) == (62, 215)
|
|
||||||
one = next(e for e in listed if e["valid"])
|
|
||||||
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
|
|
||||||
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
|
|
||||||
for m in shown["metrics"]) # fmt: skip
|
|
||||||
|
|
||||||
assert shown["checks"] and shown["regions"]
|
|
||||||
curve = ok(api.get("/models/tea/eeg-posterior-rhythm/versions/1/curve"))
|
|
||||||
assert [row["age_months"] for row in curve] == list(range(16, 37))
|
|
||||||
|
|
||||||
_preview_matches_the_analysis_and_leaves_bronze_unchanged(scored_hospital, monkeypatch)
|
|
||||||
_reanalysis_by_id_in_local_mode_matches_sync(api, scored_hospital)
|
|
||||||
_cancel_during_analysis_leaves_bronze_and_gold_untouched(api, scored_hospital)
|
|
||||||
|
|
||||||
|
|
||||||
def _cancel_during_analysis_leaves_bronze_and_gold_untouched(api, platform):
|
|
||||||
def snapshot():
|
|
||||||
return (
|
|
||||||
platform.query(
|
|
||||||
"select edf, valid, level, analysed_at from bronze.eeg_analysis order by edf"
|
|
||||||
),
|
|
||||||
platform.count("bronze.eeg_metrics"),
|
|
||||||
platform.count("gold.tea_eeg_metrics"),
|
|
||||||
)
|
|
||||||
|
|
||||||
before = snapshot()
|
|
||||||
ids = [study["id"] for study in ok(api.get("/tea/eegs")) if study["valid"]]
|
|
||||||
body = {"scope": {"mode": "ids", "ids": ids}}
|
|
||||||
run_id = ok(api.post("/tea/eegs/analyze", json=body))["run_id"]
|
|
||||||
url = f"/runs/{run_id}"
|
|
||||||
deadline = time.monotonic() + 300
|
|
||||||
while (run := ok(api.get(url)))["state"] != "running":
|
|
||||||
assert run["state"] not in {"succeeded", "failed", "cancelled"}, run
|
|
||||||
assert time.monotonic() < deadline, run
|
|
||||||
time.sleep(1)
|
|
||||||
|
|
||||||
ok(api.post(f"{url}/cancel"))
|
|
||||||
deadline = time.monotonic() + 900
|
|
||||||
while (run := ok(api.get(url)))["state"] != "cancelled":
|
|
||||||
assert run["state"] not in {"succeeded", "failed"}, run
|
|
||||||
assert time.monotonic() < deadline, run
|
|
||||||
time.sleep(1)
|
|
||||||
assert snapshot() == before
|
|
||||||
|
|
||||||
|
|
||||||
def _reanalysis_by_id_in_local_mode_matches_sync(api, platform):
|
|
||||||
study_id = next(study["id"] for study in ok(api.get("/tea/eegs")) if study["valid"])
|
|
||||||
person, day = study_id.split("|")
|
|
||||||
person = person.replace("'", "''")
|
|
||||||
((edf,),) = platform.query(
|
|
||||||
f"select edf from silver.eeg where person_id = '{person}' "
|
|
||||||
f"and cast(study_date as varchar(10)) = '{_day(day).isoformat()}'"
|
|
||||||
)
|
|
||||||
|
|
||||||
def snapshot():
|
|
||||||
(row,) = platform.query(
|
|
||||||
"select valid, level, age_months, clean_fraction "
|
|
||||||
f"from bronze.eeg_analysis where edf = '{edf}'"
|
|
||||||
)
|
|
||||||
values = dict(
|
|
||||||
platform.query(f"select code, value from bronze.eeg_metrics where edf = '{edf}'")
|
|
||||||
)
|
|
||||||
return tuple(row), values
|
|
||||||
|
|
||||||
before, values = snapshot()
|
|
||||||
local = {"scope": {"mode": "ids", "ids": [study_id]}, "execution": {"mode": "local"}}
|
|
||||||
wait_for(api, ok(api.post("/tea/eegs/analyze", json=local))["run_id"])
|
|
||||||
after, reanalysed = snapshot()
|
|
||||||
|
|
||||||
def close(expected):
|
|
||||||
return None if expected is None else pytest.approx(expected, rel=1e-12)
|
|
||||||
|
|
||||||
assert after[:2] == before[:2]
|
|
||||||
assert list(after[2:]) == [close(v) for v in before[2:]]
|
|
||||||
assert reanalysed == {code: close(v) for code, v in values.items()}
|
|
||||||
|
|
||||||
unknown = {"scope": {"mode": "ids", "ids": ["N9999|2000-01-01"]}}
|
|
||||||
run_id = ok(api.post("/tea/eegs/analyze", json=unknown))["run_id"]
|
|
||||||
deadline = time.monotonic() + 900
|
|
||||||
while (run := ok(api.get(f"/runs/{run_id}")))["state"] not in (
|
|
||||||
"succeeded",
|
|
||||||
"failed",
|
|
||||||
"cancelled",
|
|
||||||
):
|
|
||||||
assert time.monotonic() < deadline, f"run {run_id} still {run['state']}"
|
|
||||||
time.sleep(2)
|
|
||||||
assert run["state"] == "failed", run
|
|
||||||
assert "no EEG" in run["error"]
|
|
||||||
|
|
||||||
|
|
||||||
def _preview_matches_the_analysis_and_leaves_bronze_unchanged(platform, monkeypatch):
|
|
||||||
q = platform.query
|
|
||||||
tables = (
|
|
||||||
"bronze.eeg_analysis", "bronze.eeg_checks", "bronze.eeg_metrics",
|
|
||||||
"bronze.eeg_scores", "bronze.files", "silver.eeg",
|
|
||||||
) # fmt: skip
|
|
||||||
before = {table: platform.count(table) for table in tables}
|
|
||||||
edf, content, birth, valid, level = q("""
|
|
||||||
select a.edf, f.content, p.birth_date, a.valid, a.level
|
|
||||||
from bronze.eeg_analysis a
|
|
||||||
join bronze.files f on f.key = a.edf
|
|
||||||
join silver.eeg e on e.edf = a.edf
|
|
||||||
join silver.person p on p.person_id = e.person_id
|
|
||||||
where a.valid and p.birth_date is not null and exists (
|
|
||||||
select 1 from gold.tea_eeg_metrics m where m.edf = a.edf and m.z is not null
|
|
||||||
)
|
|
||||||
order by a.edf
|
|
||||||
limit 1
|
|
||||||
""")[0]
|
|
||||||
values = dict(q(f"select code, value from bronze.eeg_metrics where edf = '{edf}'"))
|
|
||||||
scores = dict(q(f"select code, z from gold.tea_eeg_metrics where edf = '{edf}'"))
|
|
||||||
|
|
||||||
for name in ("PLATFORM_DATABASE_URL", "MLFLOW_TRACKING_URI", "ISSSTELEON_DATA"):
|
|
||||||
monkeypatch.setenv(name, platform.env[name])
|
|
||||||
monkeypatch.setattr(config, "DATA_DIR", Path(platform.env["ISSSTELEON_DATA"]))
|
|
||||||
key = previews.put(bytes(content))
|
|
||||||
with dg.DagsterInstance.ephemeral() as instance:
|
|
||||||
run = tea_preview.execute_in_process(
|
|
||||||
run_config={"ops": {"preview_study": {"config": {
|
|
||||||
"edf": key, "birth_date": _day(birth).isoformat(),
|
|
||||||
}}}},
|
|
||||||
instance=instance,
|
|
||||||
) # fmt: skip
|
|
||||||
assert run.success
|
|
||||||
(event,) = run.filter_events(lambda event: event.event_type == dg.DagsterEventType.STEP_OUTPUT)
|
|
||||||
result = previews.PreviewResult.model_validate(event.step_output_data.metadata["result"].value)
|
|
||||||
|
|
||||||
assert (result.eeg.valid, result.eeg.level) == (valid, level)
|
|
||||||
assert {metric.code for metric in result.eeg.metrics} == values.keys() == scores.keys()
|
|
||||||
for metric in result.eeg.metrics:
|
|
||||||
value, z = values[metric.code], scores[metric.code]
|
|
||||||
assert metric.value == (None if value is None else pytest.approx(value, rel=1e-12))
|
|
||||||
assert (metric.score.z if metric.score else None) == (
|
|
||||||
None if z is None else pytest.approx(z, rel=1e-9)
|
|
||||||
)
|
|
||||||
assert {table: platform.count(table) for table in tables} == before
|
|
||||||
assert not list(previews.area().iterdir())
|
|
||||||
@@ -1,22 +1,18 @@
|
|||||||
import time
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from core.domains import Domain
|
||||||
|
from webapi.models import Training, train, training_config
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def empty_reference_root(platform, tmp_path):
|
def sync_execution(monkeypatch):
|
||||||
root = tmp_path / "reference"
|
monkeypatch.setenv("EXECUTION_MODE", "sync")
|
||||||
root.mkdir()
|
|
||||||
platform.env["TEA_REFERENCE_ROOT"] = str(root)
|
|
||||||
|
|
||||||
|
|
||||||
def _ok(response):
|
def test_tea_training_config_schema():
|
||||||
assert response.status_code == 200, response.text
|
config = training_config(Domain.TEA, "example").model_dump()
|
||||||
return response.json()
|
|
||||||
|
|
||||||
|
|
||||||
def test_tea_training_config_schema(api):
|
|
||||||
config = _ok(api.get("/models/tea/example/training-config"))
|
|
||||||
assert (config["domain"], config["name"]) == ("tea", "example")
|
assert (config["domain"], config["name"]) == ("tea", "example")
|
||||||
schema = config["json_schema"]
|
schema = config["json_schema"]
|
||||||
assert schema["title"] == "TrainingForm"
|
assert schema["title"] == "TrainingForm"
|
||||||
@@ -37,9 +33,9 @@ def test_tea_training_config_schema(api):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def test_other_domains_have_no_reference(api):
|
def test_other_domains_have_no_reference():
|
||||||
for domain in ("cacu", "cama"):
|
for domain in ("cacu", "cama"):
|
||||||
config = _ok(api.get(f"/models/{domain}/example/training-config"))
|
config = training_config(Domain(domain), "example").model_dump()
|
||||||
assert (config["domain"], config["name"]) == (domain, "example")
|
assert (config["domain"], config["name"]) == (domain, "example")
|
||||||
schema = config["json_schema"]
|
schema = config["json_schema"]
|
||||||
assert set(schema["properties"]) == {"as_of", "execution"}
|
assert set(schema["properties"]) == {"as_of", "execution"}
|
||||||
@@ -47,19 +43,12 @@ def test_other_domains_have_no_reference(api):
|
|||||||
assert config["defaults"] == {"execution": {"mode": "sync", "scheduler": None}}
|
assert config["defaults"] == {"execution": {"mode": "sync", "scheduler": None}}
|
||||||
|
|
||||||
|
|
||||||
def test_train_validates_the_reference(api):
|
def test_train_validates_the_reference():
|
||||||
response = api.post("/models/cacu/train", json={"reference": {"name": "nope"}})
|
with pytest.raises(HTTPException) as rejected:
|
||||||
assert response.status_code == 422
|
train(Domain.CACU, Training(reference={"name": "nope"}))
|
||||||
assert response.json()["detail"] == "cacu models take no reference cohort"
|
assert rejected.value.status_code == 422
|
||||||
|
assert rejected.value.detail == "cacu models take no reference cohort"
|
||||||
|
|
||||||
for reference in ({"name": "../x"}, {"name": "nope", "line_hz": 55}):
|
for reference in ({"name": "../x"}, {"name": "nope", "line_hz": 55}):
|
||||||
response = api.post("/models/tea/train", json={"reference": reference})
|
with pytest.raises(ValidationError):
|
||||||
assert response.status_code == 422
|
Training(reference=reference)
|
||||||
|
|
||||||
run_id = _ok(api.post("/models/tea/train", json={"reference": {"name": "nope"}}))["run_id"]
|
|
||||||
deadline = time.monotonic() + 120
|
|
||||||
while (run := _ok(api.get(f"/runs/{run_id}")))["state"] in ("queued", "running"):
|
|
||||||
assert time.monotonic() < deadline, run
|
|
||||||
time.sleep(1)
|
|
||||||
assert run["state"] == "failed"
|
|
||||||
assert "no reference cohort 'nope'" in run["error"]
|
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
"""Phase 3 and 4 gate, the WebApp: every page loads from the new API. The platform runs as
|
|
||||||
in production (API, Dagster), loaded with the synthetic CaCu and CaMa hospitals (CaMa's
|
|
||||||
models trained, none promoted) and ISSSTELEON's test source; Playwright drives the real
|
|
||||||
pages against it (WebApp/e2e)."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pytest
|
|
||||||
from test_conectar import ok, run, wait_for
|
|
||||||
|
|
||||||
from conftest import put_concept_map
|
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
|
||||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
|
||||||
PIPELINES = ROOT / "tests" / "fixtures" / "pipelines"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.webapp
|
|
||||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) # pages read one API either way
|
|
||||||
def test_every_page_loads_from_the_api(api, platform, site):
|
|
||||||
for domain in ("cacu", "cama"):
|
|
||||||
drawn = (PIPELINES / f"hospital_{domain}.json").read_text()
|
|
||||||
put_concept_map(api, f"hospital_{domain}")
|
|
||||||
ok(api.put(f"/ingest/pipelines/{domain}", json=json.loads(
|
|
||||||
drawn.replace("{hospital}", str(HOSPITAL))))) # fmt: skip
|
|
||||||
run(api, domain)
|
|
||||||
# A trained CaMa version, unpromoted: what the governance page shows and refuses.
|
|
||||||
wait_for(api, ok(api.post("/models/cama/train", json={"as_of": "2026-11-24"}))["run_id"])
|
|
||||||
put_concept_map(api, "erick_site")
|
|
||||||
ok(api.put("/ingest/pipelines/site", json=json.loads(site.drawn)))
|
|
||||||
run(api, "site")
|
|
||||||
subprocess.run(["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
|
||||||
env={**os.environ, "API_URL": str(api.base_url).rstrip("/")}) # fmt: skip
|
|
||||||
Reference in New Issue
Block a user