"""What this module covers: TEA's FHIR R4 endpoint (`/tea/fhir/`): the capability statement, the measures as `Measure` and their answers as `MeasureReport` (one period and several), the follow-up list as `EpisodeOfCare` with its filters, paging and includes, the EEG summary and the patient summary; and that the alterations stay hidden until validated. Every resource is checked against FHIR's models (`fhir.resources`, R4B, which keeps R4's shape for these resources). Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes exist) over TEA's fixture database (`staging.tea`) loaded through the cycle up to `event_models`; needs `DBT_MANIFEST`. `validated`, the switch that shows the alterations (`TEA_ALTERACIONES_VALIDADAS`). """ import json import os import pytest from fhir.resources.R4B import get_fhir_model_class from conftest import base_de UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") @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")) 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() @pytest.fixture def validated(monkeypatch): monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") def valid(resource: dict) -> dict: """The resource, after checking it and every resource in it against FHIR's model of its type.""" get_fhir_model_class(resource["resourceType"]).model_validate(resource) for item in resource.get("entry", ()): get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"]) return resource def get(client, url: str, status: int = 200) -> dict: response = client.get(url) assert response.status_code == status, response.get_json() assert response.mimetype == "application/fhir+json" return valid(response.get_json()) def resources(bundle: dict, kind: str | None = None, mode: str | None = None) -> list[dict]: return [e["resource"] for e in bundle["entry"] if (kind is None or e["resource"]["resourceType"] == kind) and (mode is None or e.get("search", {}).get("mode") == mode)] def test_the_capability_statement_lists_the_measures_and_the_patient_routes(client): """Pins down: `metadata` is a valid CapabilityStatement naming Measure with `evaluate-measure` and, in DEV, EpisodeOfCare with its search parameters. Fails if a route drops out of it.""" body = get(client, "/tea/fhir/metadata") kinds = {r["type"]: r for r in body["rest"][0]["resource"]} assert {"Measure", "MeasureReport", "EpisodeOfCare", "Patient"} <= set(kinds) assert {p["name"] for p in kinds["EpisodeOfCare"]["searchParam"]} >= {"date", "etapa", "fecha-etapa", "alteracion"} def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monkeypatch): """Pins down: the Measure list has the nine measures without alterations; M30 shows only with the switch on. Fails if M30 leaks before the domain expert validates the references, or the switch stops showing it.""" ids = {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} assert len(ids) == 9 and "M30-resultado-eeg" not in ids assert get(client, "/tea/fhir/Measure/M30_resultado_eeg", 404)["resourceType"] == "OperationOutcome" monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))} def test_the_routes_outside_fhir_hide_m30_too(client, monkeypatch): """Pins down: `/tea/indicadores` neither lists nor answers M30 until the alterations are validated, and does both with the switch on. Fails if the measures answered outside `/tea/fhir/` stop waiting for the validation.""" assert "M30_resultado_eeg" not in {m["id"] for m in client.get("/tea/indicadores").get_json()} assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 404 monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") assert "M30_resultado_eeg" in {m["id"] for m in client.get("/tea/indicadores").get_json()} assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 200 def test_a_measure_carries_what_the_page_needs(client): """Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category labels. Fails if the page's catalog fields stop reaching the Measure.""" m28 = get(client, "/tea/fhir/Measure/M28_casos_por_estado") assert m28["url"] == "https://isssteleon.org/fhir/Measure/M28-casos-por-estado" assert m28["title"] == "Casos por estatus" and m28["scoring"]["coding"][0]["code"] == "cohort" assert {e["extension"][0]["valueCode"] for e in m28["extension"] if e["url"].endswith("/categoria")} == { "SOLO_MCHAT", "PSICOLOGIA", "NEUROPEDIATRIA", "EEG"} m24 = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico") assert m24["group"][0]["stratifier"][0]["code"]["coding"][0]["code"] == "grupo_edad" assert "denominator-exclusion" in {p["code"]["coding"][0]["code"] for p in m24["group"][0]["population"]} def test_evaluate_measure_answers_one_period_as_a_measure_report(client): """Pins down: `$evaluate-measure` with periodStart and periodEnd answers that period of `dim_periodo`: M28's first semester of 2025 counts six children by stage, as a cohort whose stages are a stratifier. Fails if the period lookup, the canonical or the C2 shape changes.""" report = get(client, "/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure" "?periodStart=2025-01-01&periodEnd=2025-06-30") assert report["measure"].startswith("https://isssteleon.org/fhir/Measure/M28-casos-por-estado|") (group,) = report["group"] assert group["population"][0]["count"] == 6 stages = {s["value"]["coding"][0]["code"]: s["population"][0]["count"] for s in group["stratifier"][0]["stratum"]} assert stages == {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2} def test_a_proportion_reports_its_exclusion_and_its_strata_with_codings(client): """Pins down: M24's report has the exclusion count (child 2's note without F84.0) and each age group as a coded stratum. Fails if `denominator-exclusion` or the stratum codings drop out.""" report = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico/$evaluate-measure?periodo=2025-04") counts = {p["code"]["coding"][0]["code"]: p["count"] for p in report["group"][0]["population"]} assert counts == {"denominator": 3, "numerator": 1, "denominator-exclusion": 1} values = {s["value"]["coding"][0]["code"] for s in report["group"][0]["stratifier"][0]["stratum"]} assert {"16_23", "30_36"} <= values def test_the_measure_report_search_answers_several_periods_with_paging(client): """Pins down: `MeasureReport?measure=…&tipo-periodo=mes&period=ge…&period=le…` gives one report per month, and `_count` pages them with a `next` link. Fails if the search stops selecting `dim_periodo` by type and dates.""" url = ("/tea/fhir/MeasureReport?measure=https://isssteleon.org/fhir/Measure/M26-dias-mchat-ados2" "&tipo-periodo=mes&period=ge2025-01-01&period=le2025-03-31") body = get(client, url) assert body["total"] == 3 and [r["period"]["start"] for r in resources(body)] == [ "2025-01-01", "2025-02-01", "2025-03-01"] paged = get(client, url + "&_count=2") assert len(paged["entry"]) == 2 and any(link["relation"] == "next" for link in paged["link"]) def test_the_follow_up_list_is_each_child_s_episode_at_the_cut_off(client): """Pins down: `EpisodeOfCare?date=le…` gives each child who entered by the cut-off, at its stage then: at 31 May, children 1, 2, 3, 6 and 7 (child 5 enters in June), child 1 finished on its good EEG. A window from 1 June leaves child 1 out. Fails if the episode's status, stage or window drift from the measures' rules.""" may = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-05-31")) assert len(may) == 5 assert sorted(e["status"] for e in may) == ["active"] * 4 + ["finished"] assert all(e["meta"]["tag"][0]["code"] == "simulado" for e in may) june = resources(get(client, "/tea/fhir/EpisodeOfCare?date=ge2025-06-01&date=le2025-06-30")) assert len(june) == 5 and "finished" in {e["status"] for e in june} @pytest.mark.parametrize(("query", "n"), [ ("etapa=PSICOLOGIA", 1), ("grupo-edad=24_29", 2), ("mchat=ge12", 3), ("css=ge4", 3), ("fecha-etapa=ge2025-06-01&fecha-etapa=le2025-06-30", 2), ("status=finished", 2), ("resultado-eeg=sin-eeg-valido", 3), ]) def test_the_follow_up_filters(client, query, n): """Pins down each search parameter at the year's end, over the six children who entered by then: child 3 at psychology; children 2 and 6 in 24 to 29 months (finished episodes still list); M-CHAT of 12 or more for children 1, 3 and 6; CSS of 4 or more for 1, 2 and 6; a stage dated in June for child 5 (its M-CHAT; its EEG doesn't count) and child 6 (EEG on 2 June); children 1 and 6 finished; children 2, 3 and 7 without a valid EEG. Fails if a filter stops reading its column.""" assert get(client, f"/tea/fhir/EpisodeOfCare?date=le2025-12-31&{query}")["total"] == n def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client): """Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT, ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality observations, one per check of its analysis (clean windows, usable scalp, triage level, line noise) as the analysis's own report writes them; no metric observation while the alterations are hidden. Fails if an included resource drops out, a check stops reaching the report or changes shape, or the alterations leak.""" body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*") included = resources(body, mode="include") kinds = {r["resourceType"] for r in included} assert {"Patient", "CarePlan", "Observation", "Condition", "DiagnosticReport", "Procedure"} <= kinds assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient") reports = [r for r in included if r["resourceType"] == "DiagnosticReport"] assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"} assert all(len(r["result"]) == 4 for r in reports) assert all(r["conclusionCode"][1]["coding"][0] == {"system": "urn:tea:validation", "code": "valid"} for r in reports) quality = [r for r in included if r["resourceType"] == "Observation" and r["id"].startswith("calidad-")] assert {r["code"]["coding"][0]["system"] for r in quality} == {"urn:tea:validation"} clean = next(r for r in quality if r["code"]["coding"][0]["code"] == "clean-windows") assert (clean["valueQuantity"]["value"], clean["referenceRange"][0]["low"]["value"]) == (95.0, 60.0) assert clean["interpretation"][0]["coding"][0]["code"] == "N" assert clean["component"] == [{"code": {"text": "decisive"}, "valueBoolean": True}] triage = next(r for r in quality if r["code"]["coding"][0]["code"] == "triage-level") assert triage["valueString"] == "completo" ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"] assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2) def test_a_bad_eeg_reports_its_failed_check_and_its_bad_channel(client): """Pins down, on a bad EEG's rows as dbt's views give them (too few clean windows, a dead channel at T3): the report says MALO and the analysis's not-valid with the triage level; the clean windows are abnormal and decisive; the dead channel is an abnormal observation with its electrode as a component; every resource conforms to FHIR. Fails if a failed check or a bad channel stops reaching FHIR, or loses its electrode or decisive flag.""" from webapi.fhir import tea eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-04-02", "calidad": "MALO", "valido": 0, "nivel": "parcial", "duracion_min": 25.0, "canales": 19} checks = [ {"procedimiento_id": 9, "criterio": "clean_windows", "electrodo": None, "valor": 40.0, "valor_texto": None, "bajo": 60.0, "alto": None, "anormal": 1, "decisivo": 1, "etiqueta": "Ventanas limpias", "unidad": "%"}, {"procedimiento_id": 9, "criterio": "dead_channel", "electrodo": "T3", "valor": None, "valor_texto": "dead channel", "bajo": None, "alto": None, "anormal": 1, "decisivo": 0, "etiqueta": "Canal muerto", "unidad": None}, ] resources = tea.eeg_resources(eeg, "P-X", [], [], False, checks) report = next(r for r in resources if r["resourceType"] == "DiagnosticReport") assert [c["coding"][0]["code"] for c in report["conclusionCode"]] == ["MALO", "not-valid"] assert report["conclusion"].endswith("(nivel de triaje: parcial).") clean, dead = (r for r in resources if r["resourceType"] == "Observation") assert (clean["interpretation"][0]["coding"][0]["code"], clean["component"][-1]["valueBoolean"]) == ("A", True) assert dead["id"] == "calidad-dead-channel-T3-9" and dead["valueString"] == "dead channel" assert dead["component"] == [{"code": {"text": "electrode"}, "valueString": "T3"}, {"code": {"text": "decisive"}, "valueBoolean": False}] for resource in resources: get_fhir_model_class(resource["resourceType"]).model_validate(resource) def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch): """Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's slow posterior rhythm). Fails if the filter leaks alterations before validation.""" assert get(client, "/tea/fhir/EpisodeOfCare?alteracion=ritmo_posterior", 403)["resourceType"] == "OperationOutcome" monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") assert get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&alteracion=ritmo_posterior")["total"] == 1 def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(client, monkeypatch): """Pins down `$resumen-eeg`: children 1, 5 and 6 with a valid EEG, 2, 3 and 7 without; with the alterations validated, child 1 abnormal (posterior rhythm), 5 and 6 normal. Fails if the summary counts bad EEGs as valid or shows the split before validation.""" def counts(body): return {p["name"]: p.get("valueInteger") for p in body["parameter"] if "valueInteger" in p} hidden = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31") assert counts(hidden) == {"con_eeg_valido": 3, "sin_eeg_valido": 3} monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") shown = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31") assert counts(shown) == {"con_eeg_valido": 3, "sin_eeg_valido": 3, "normales": 2, "anormales": 1} def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch): """Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated, the metrics against their age baseline (p5 as the low end of the reference, the median as a component) and each electrode's z-score; and its episode, with the age group. Fails if the summary takes another EEG, shows the alterations before validation, maps the electrodes' raw values or loses the age group.""" episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished")) (child_1,) = episodes path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea" bundle = get(client, path) assert bundle["type"] == "collection" (report,) = resources(bundle, "DiagnosticReport") assert report["effectiveDateTime"] == "2025-05-20" and report["conclusionCode"][0]["coding"][0]["code"] == "BUENO" ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-")) codes = {c["code"]["coding"][0]["code"] for c in ados2["component"]} assert {"ados2.modulo", "ados2.css", "SA", "RRB", "ados2.sa_b1"} <= codes assert not any("tea-eeg-metrica" in o["code"]["coding"][0]["system"] for o in resources(bundle, "Observation")) monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1") shown = get(client, path) metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")] rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-")) assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5 assert {c["code"]["coding"][0]["code"]: c["valueQuantity"]["value"] for c in rhythm["component"]} == { "z": -4.08, "mediana": 5.75} (episode,) = resources(shown, "EpisodeOfCare") assert episode["extension"][0]["valueCoding"]["code"] == "16_23" electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-")) assert [(c["code"]["coding"][0]["code"], c["valueQuantity"]["value"]) for c in electrodes["component"]] == [ ("O1", -2.8), ("O2", -2.4), ("Pz", -1.1)] def test_a_metric_the_baseline_couldnt_score_keeps_its_value(): """Pins down: a metric with a value but no z (no baseline in production, or an age it doesn't cover) keeps its value and has no interpretation nor reference; one without a value is `not-performed`. Fails if an unscored metric loses its value (the summary couldn't tell it from one never measured) or gets an interpretation it doesn't have.""" from webapi.fhir import tea eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-05-20"} row = {"procedimiento_id": 9, "ref_min": None, "ref_mediana": None, "ref_max": None, "grupo_edad_eeg": "16_23", "estado": "no_evaluable", "valor_z": None} unscored, unmeasured = tea.metric_observations(eeg, [{**row, "metrica": "ritmo_posterior", "valor": 6.8}, {**row, "metrica": "husos_sueno_n3", "valor": None}], [], "P-X", False)[::-1] assert unscored["valueQuantity"]["value"] == 6.8 assert not {"interpretation", "referenceRange", "dataAbsentReason", "component"} & set(unscored) assert unmeasured["dataAbsentReason"]["coding"][0]["code"] == "not-performed" and "valueQuantity" not in unmeasured def test_the_quality_checks_are_a_code_system_of_the_analysis(client): """Pins down: `CodeSystem/tea-eeg-criterio` is the EEG analysis's code system (`urn:tea:validation`) with every check code and the catalog's label, and each metric has a text for every state, normal included. Fails if a check code the quality observations use has no concept, or a metric loses its normal effect. """ from core.tea.enums import CriterioEeg checks = get(client, "/tea/fhir/CodeSystem/tea-eeg-criterio") assert checks["url"] == "urn:tea:validation" assert {c["code"] for c in checks["concept"]} == {c.value for c in CriterioEeg} assert next(c for c in checks["concept"] if c["code"] == "clean-windows")["display"] == "Ventanas limpias" metrics = get(client, "/tea/fhir/CodeSystem/tea-eeg-metrica") assert all(any(p["code"] == "efecto-normal" for p in c["property"]) for c in metrics["concept"]) def test_an_answer_that_doesnt_conform_to_fhir_never_leaves(client): """Pins down: `fhir()` validates every answer against R4B; one that doesn't conform is a 500 `OperationOutcome`. Fails if a malformed resource reaches a client, or the check stops running. """ from webapi import create_app from webapi.fhir.common import fhir with create_app().test_request_context(): bad = fhir({"resourceType": "Observation", "id": "x"}) # no status, no code good = fhir({"resourceType": "Observation", "id": "x", "status": "final", "code": {"text": "t"}}) assert (bad.status_code, json.loads(bad.data)["resourceType"]) == (500, "OperationOutcome") assert (good.status_code, json.loads(good.data)["status"]) == (200, "final") def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client): """Pins down: errors are OperationOutcomes with the HTTP status: an unknown pseudonym (404), an unknown search parameter (400). Fails if an error goes back to `{"error": …}`.""" assert get(client, "/tea/fhir/Patient/P-NADIE/$resumen-tea", 404)["issue"][0]["code"] == "not-found" assert get(client, "/tea/fhir/EpisodeOfCare?color=azul", 400)["issue"][0]["code"] == "invalid"