Files
WebApi/tests/test_fhir_cacu_risk.py
edgar b63a253b19 FHIR: one RiskAssessment per outcome, and one with no prediction for a model that didn't score her
The patient's Bundle holds the current batch of each outcome (`CohortRepository.current_risks`), so a CIN2+ and a
cancer model are both shown. For a patient with some risk, each current model of another outcome that didn't score
her (`current_batches`) gives a RiskAssessment with no prediction and the extension `sin-estimacion` (its outcome and
why it may be so), so the record can tell "no model" from "not estimated for her".
2026-11-22 09:34:49 -06:00

162 lines
9.1 KiB
Python

"""What this module covers: `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cacu`): a patient's
current risk as a FHIR R4 `RiskAssessment` in a `searchset` Bundle, as TEA's patient resources are served: the
resource's shape (status, subject, method, one prediction per horizon from the risk's index date, the interval
extension), the `simulado` tag, an empty Bundle without a confirmed batch, a 400 without `subject`, and the
`CapabilityStatement` entry. The reads behind it are Persistance's, tested there.
Fixtures: `client`, the app in DEV (`DEV_REVISION`, so the patient routes exist) over the kit's CaCu demonstration
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a surveillance build with two of its patients, one
with a confirmed batch whose risks have the model's index date.
"""
import os
from datetime import date, datetime, timezone
import pytest
from conftest import cliente_de
MODEL_INDEX = date(2026, 6, 1)
@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")
with pytest.MonkeyPatch.context() as mp:
mp.setenv("DEV_REVISION", "pruebas")
yield from cliente_de("cacu", tmp_path_factory)
@pytest.fixture(scope="module")
def seeded(client):
"""Two demo patients in a new surveillance build; the first has a confirmed batch with risks at 0 and 3 years, the
3-year one with an interval. Returns (scored patient, member without risks)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
from persistance import cacu
from persistance.db import get_cacu_session
scored, unscored = [p.pac_id for p in cacu.persona_repository.list(limit=2)]
with get_cacu_session() as session:
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk", marco_sha="m",
n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
session.add(build)
session.flush()
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
for p in (scored, unscored)])
session.commit()
build_id = build.armado_id
batch, _ = cacu.cohort_repository.save_batch(
build_id, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
"cin2_mas", [(scored, MODEL_INDEX, 3.0, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.0, 0.08, None, None)],
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(batch, "final", "revisado")
return scored, unscored, batch
def test_a_scored_patient_gets_her_risk_assessment(client, seeded):
"""Pins down the resource: a `searchset` of one `RiskAssessment`, `final`, about `Patient/<pac_id>`, evaluated
when the batch was, by the registered model and version, with one prediction per horizon whose period starts at
the risk's index date (the model's, not the member's) and ends a horizon later; the interval in its extension;
tagged `simulado`. Fails if a field moves out of FHIR's shape or the period is anchored elsewhere."""
scored, _, batch = seeded
response = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}")
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
bundle = response.get_json()
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 1)
risk = bundle["entry"][0]["resource"]
assert bundle["entry"][0]["fullUrl"].endswith(f"/cacu/fhir/RiskAssessment/{batch}-{scored}")
assert (risk["resourceType"], risk["status"], risk["subject"]) == ("RiskAssessment", "final", {"reference": f"Patient/{scored}"})
assert risk["occurrenceDateTime"] == "2026-10-01T00:00:00Z"
assert risk["method"]["coding"][0]["code"] == "cacu-cin2_pim" and risk["method"]["coding"][0]["version"] == "3"
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["cin2_mas", "cin2_mas"]
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
(0.08, {"start": "2026-06-01", "end": "2026-06-01"}), (0.21, {"start": "2026-06-01", "end": "2029-06-01"})]
assert "extension" not in risk["prediction"][0]
assert risk["prediction"][1]["extension"][0]["valueRange"] == {"low": {"value": 0.15}, "high": {"value": 0.28}}
assert any(t["code"] == "simulado" for t in risk["meta"]["tag"])
def test_without_a_confirmed_batch_the_bundle_is_empty(client, seeded):
"""Pins down: a member with no confirmed risk, and an unknown patient, get an empty searchset, not an error.
Fails if a missing risk becomes a 404 or a resource with no predictions."""
_, unscored, _ = seeded
for subject in (f"Patient/{unscored}", "Patient/987654321"):
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject={subject}").get_json()
assert (bundle["total"], bundle.get("entry", [])) == (0, []) # R4B drops an empty `entry`
@pytest.mark.parametrize("query", ["", "?subject=Patient/abc", "?subject=Group/1"])
def test_the_risk_is_searched_by_patient(client, query):
"""Pins down: without `subject=Patient/<pac_id>` the answer is a 400 `OperationOutcome`. Fails if the route lists
every patient's risk."""
response = client.get(f"/cacu/fhir/RiskAssessment{query}")
assert response.status_code == 400 and response.get_json()["resourceType"] == "OperationOutcome"
def test_the_capability_statement_declares_the_search(client):
"""Pins down: CaCu's CapabilityStatement lists `RiskAssessment` with its `subject` search; TEA's patient
resources stay TEA's. Fails if the route exists without being declared, or the other way round."""
resources = client.get("/cacu/fhir/metadata").get_json()["rest"][0]["resource"]
risk = [r for r in resources if r["type"] == "RiskAssessment"]
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
def test_each_outcome_is_its_own_risk_assessment(client, seeded):
"""Pins down: with a confirmed cancer batch next to the CIN2+ one, the patient's Bundle holds one RiskAssessment
per outcome, the newest first, each with its own outcome code. Fails if the route goes back to one batch, which
hides the other outcome's risk. Runs last: it adds a batch to the module's database."""
from persistance import cacu
scored, _, batch = seeded
cancer, _ = cacu.cohort_repository.save_batch(
_build_of(batch),
{"modelo_nombre": "cacu-cancer_pim", "modelo_version": "1", "mlflow_run_id": "r2", "modelo_sha": "s2"},
"cancer", [(scored, MODEL_INDEX, 3.0, 0.02, 0.01, 0.04)], ahora=datetime(2026, 10, 2, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(cancer, "final", "revisado")
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()
found = [e["resource"] for e in bundle["entry"]]
assert bundle["total"] == 2 and [r["id"] for r in found] == [f"{cancer}-{scored}", f"{batch}-{scored}"]
assert [r["prediction"][0]["outcome"]["coding"][0]["code"] for r in found] == ["cancer", "cin2_mas"]
def _build_of(batch: int) -> int:
from core.cacu.indicadores.models import EvaluacionRiesgoLote
from persistance.db import get_cacu_session
with get_cacu_session() as session:
return session.get(EvaluacionRiesgoLote, batch).armado_id
def test_a_current_model_that_did_not_score_her_says_so(client, seeded):
"""Pins down: a confirmed batch of another outcome that scored only another patient gives the scored patient a
RiskAssessment with no prediction and the `sin-estimacion` extension, while a patient with no risk at all still
gets an empty Bundle. Fails if the record can't tell "no model" from "not estimated for her", or a patient with
no risk gets one. Runs after the cancer test: it adds another batch to the module's database."""
from persistance import cacu
from webapi.fhir.risk import NOT_SCORED
scored, unscored, batch = seeded
other, _ = cacu.cohort_repository.save_batch(
_build_of(batch), {"modelo_nombre": "cacu-survival", "modelo_version": "1", "mlflow_run_id": "r3",
"modelo_sha": "s3"},
"muerte", [(unscored, MODEL_INDEX, 1.0, 0.1, None, None)], ahora=datetime(2026, 10, 3, tzinfo=timezone.utc))
cacu.cohort_repository.change_state(other, "final", "revisado")
found = {e["resource"]["id"]: e["resource"] for e in
client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}").get_json()["entry"]}
missing = found[f"{other}-{scored}"]
marker = next(e for e in missing["extension"] if e["url"] == NOT_SCORED)
assert "prediction" not in missing and {"url": "desenlace", "valueCode": "muerte"} in marker["extension"]
assert len(found) == 3