e2ecaa027c
webapi/fhir/risk.py builds a patient's RiskAssessment for CaCu and CaMa; GET /cama/modelo/curvas serves the production version's survival curves; the cycle's estimator is generic by scenario; silver persona carries the date of death for CaMa; the import schema accepts it; the CaMa risk batches can be confirmed and voided.
110 lines
6.3 KiB
Python
110 lines
6.3 KiB
Python
"""What this module covers: `GET /cama/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cama`, built by
|
|
`webapi.fhir.risk` as CaCu's is): a patient's current mortality risk as a FHIR R4 `RiskAssessment` in a `searchset`
|
|
Bundle: its shape (status, subject, method, one prediction per horizon from the model's own 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 CaMa demonstration
|
|
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a total-cohort build with two of its patients, one
|
|
with a confirmed batch whose risks, at 0.5 and 1.5 years, 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("cama", 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.5 and 1.5 years, the
|
|
1.5-year one with an interval. Returns (scored patient, member without risks)."""
|
|
from core.cama.indicadores.models import CohorteArmado, CohorteMiembro
|
|
from persistance import cama
|
|
from persistance.db import get_cama_session
|
|
|
|
scored, unscored = [p.pac_id for p in cama.persona_repository.list(limit=2)]
|
|
with get_cama_session() as session:
|
|
build = CohorteArmado(url="cama/cohorte_total", version="0.1.0", definicion_sha="d", reglas_sha="r",
|
|
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk-cama", 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="biopsiamama", indice_fuente_id=str(p))
|
|
for p in (scored, unscored)])
|
|
session.commit()
|
|
build_id = build.armado_id
|
|
batch, _ = cama.cohort_repository.save_batch(
|
|
build_id, {"modelo_nombre": "cama-survival", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
|
|
"muerte", [(scored, MODEL_INDEX, 1.5, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.5, 0.08, None, None)],
|
|
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
|
cama.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"/cama/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"/cama/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"] == "cama-survival" and risk["method"]["coding"][0]["version"] == "3"
|
|
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["muerte", "muerte"]
|
|
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
|
|
(0.08, {"start": "2026-06-01", "end": "2026-12-01"}), (0.21, {"start": "2026-06-01", "end": "2027-12-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"/cama/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"/cama/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: CaMa'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("/cama/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"]
|