"""What this module covers: `$resumen-tea`'s `RiskAssessment`, the ADOS-2 association model as idiomatic FHIR: one resource per patient with a prediction per association row of the latest model version that scored the study's EEG (the clearest cohort association, lowest q, first), the model's metadata on the resource, the outcome as the ADOS-2 item or domain with its label from the code systems, the observed outcome read from the patient's ADOS-2, and the resource omitted entirely when no model row scored the patient's study EEG. Every resource is checked against FHIR's models. Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`) over TEA's fixture database (`staging.tea`) plus model and patient rows for child 1's study EEG (`eeg-1b`); needs `DBT_MANIFEST`. """ import os from datetime import date import pytest from test_fhir_tea import get, resources from conftest import base_de UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") def _rows(sesion): """The kit's seven children, plus a fitted model: one item row (sa_b2) and one domain row (SA) of version 0.2.0, both scored for child 1's study EEG (eeg-1b, 20 May). Child 1's ADOS-2 (ado-1) scores sa_b2 2 and its SA domain total is 6; no other child gets model rows.""" from importlib import import_module import_module("staging.tea").insertar(sesion) from core.tea.models import RelacionAdos2, RelacionAdos2Paciente sesion.add_all([ RelacionAdos2(rel_id="rel-2a", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="item", rel_resultado="sa_b2", rel_evento=">=1", rel_or=3.5, rel_ic_inf=1.4, rel_ic_sup=8.7, rel_q=0.02), RelacionAdos2(rel_id="rel-2b", rel_version="0.2.0", rel_nivel="item", rel_validado=0, rel_n_cohorte=60, rel_biomarcador="RITMO_POSTERIOR", rel_zona="occipital", rel_tipo="dominio", rel_resultado="SA", rel_evento=">=4", rel_or=0.8, rel_ic_inf=0.4, rel_ic_sup=1.6, rel_q=0.3), ]) sesion.add_all([ RelacionAdos2Paciente(rap_id="rap-2a", rap_rel_id="rel-2a", rap_eeg_id="eeg-1b", rap_valor_z=-4.08, rap_probabilidad=0.81, rap_probabilidad_referencia=0.22), RelacionAdos2Paciente(rap_id="rap-2b", rap_rel_id="rel-2b", rap_eeg_id="eeg-1b", rap_valor_z=-4.08, rap_probabilidad=0.35, rap_probabilidad_referencia=0.4), ]) @pytest.fixture(scope="module") def client(tmp_path_factory): if not os.environ.get("DBT_MANIFEST"): pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") mp = pytest.MonkeyPatch() mp.setenv("DEV_REVISION", "pruebas") mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False) base = base_de("tea", tmp_path_factory.mktemp("tea_fhir_relacion"), datos=_rows) base.run(*UNTIL_MODELS, allow_undecided=True) from webapi import create_app app = create_app() app.config.update(TESTING=True) with app.test_client() as test_client: yield test_client base.motor.dispose() mp.undo() def _extension(resource: dict) -> dict: return {e["url"].rsplit("/", 1)[-1]: e for e in resource["extension"]} def test_the_summary_emits_the_model_as_one_risk_assessment(client): """Pins down: child 1's summary carries one `RiskAssessment` (tagged simulated) with the model's metadata on the resource (version, expert validation, level, cohort size), dated at the study's EEG (20 May), based on the EEG's DiagnosticReport and the ADOS-2 Observation, and with one prediction per association row, the clearest cohort association (lowest q) first. Fails if the resource loses a metadata extension, changes order, or stops referencing what it was scored from.""" episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished")) (child_1,) = episodes bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea") (riesgo,) = resources(bundle, "RiskAssessment") assert riesgo["id"] == f"relacion-ados2-{child_1['id']}" assert riesgo["occurrenceDateTime"] == "2025-05-20" assert riesgo["meta"]["tag"][0]["code"] == "simulado" extension = _extension(riesgo) assert extension["modelo-version"]["valueString"] == "0.2.0" assert extension["modelo-validado"]["valueBoolean"] is False assert extension["modelo-nivel"]["valueString"] == "item" assert extension["modelo-n-cohorte"]["valueInteger"] == 60 (report,) = resources(bundle, "DiagnosticReport") ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-")) assert riesgo["basis"] == [{"reference": f"DiagnosticReport/{report['id']}"}, {"reference": f"Observation/{ados2['id']}"}] assert len(riesgo["prediction"]) == 2 assert [p["outcome"]["coding"][0]["code"] for p in riesgo["prediction"]] == ["ados2.sa_b2", "SA"] def test_a_prediction_carries_the_probability_the_cohort_stats_and_the_observed_outcome(client): """Pins down: a prediction has the outcome as the ADOS-2 item or domain with its label from the code systems (not from the row), the model's probability for the patient, and as extensions the EEG metric and scalp zone (with labels), the patient's z, the cohort's odds ratio with its interval and q, the event as stored, the reference probability (z = 0) and the outcome observed in the patient's ADOS-2 (the item's score 2, the SA domain's algorithm total 6). Fails if a label starts coming from the stored row, or a value stops reaching the prediction.""" episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished")) (child_1,) = episodes bundle = get(client, f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea") (riesgo,) = resources(bundle, "RiskAssessment") item, dominio = riesgo["prediction"] assert item["outcome"]["coding"][0] == { "system": "https://isssteleon.org/fhir/CodeSystem/tea-catalogo", "code": "ados2.sa_b2", "display": "Sonrisa social en respuesta"} assert dominio["outcome"]["coding"][0] == { "system": "https://isssteleon.org/fhir/CodeSystem/ados2-dominio", "code": "SA", "display": "Afecto social"} assert (item["probabilityDecimal"], dominio["probabilityDecimal"]) == (0.81, 0.35) extension = _extension(item) assert extension["biomarcador"]["valueCoding"] == { "system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-metrica", "code": "RITMO_POSTERIOR", "display": "Ritmo posterior"} assert extension["zona"]["valueCoding"] == { "system": "https://isssteleon.org/fhir/CodeSystem/tea-eeg-zona", "code": "occipital", "display": "Occipital"} assert (extension["tipo"]["valueString"], extension["evento"]["valueString"]) == ("item", ">=1") assert extension["valor-z"]["valueDecimal"] == -4.08 assert (extension["odds-ratio"]["valueDecimal"], extension["ic-inf"]["valueDecimal"], extension["ic-sup"]["valueDecimal"], extension["q"]["valueDecimal"]) == (3.5, 1.4, 8.7, 0.02) assert extension["probabilidad-referencia"]["valueDecimal"] == 0.22 assert extension["observado"]["valueInteger"] == 2 assert _extension(dominio)["observado"]["valueInteger"] == 6 def test_the_summary_omits_the_model_without_rows(client): """Pins down: a child whose study EEG no model row scored gets no `RiskAssessment` at all (not an empty one): child 2, in neuropediatrics without an EEG. Fails if the emission stops keying on the view's rows.""" episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&etapa=NEUROPEDIATRIA")) (child_2,) = episodes bundle = get(client, f"/tea/fhir/Patient/{child_2['id']}/$resumen-tea") assert not resources(bundle, "RiskAssessment")