From 72a8e761088629f69d7dc2b3608e3c30515ea35d Mon Sep 17 00:00:00 2001 From: edgar Date: Fri, 6 Nov 2026 00:37:44 -0600 Subject: [PATCH] GET /cacu/pacientes//riesgo, only in DEV: the patient's cohort membership and risks in the current batch, in the WebApp's contract --- tests/test_patient_risk.py | 99 ++++++++++++++++++++++++++++++++++++++ webapi/__init__.py | 7 ++- webapi/patient_risk.py | 49 +++++++++++++++++++ 3 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 tests/test_patient_risk.py create mode 100644 webapi/patient_risk.py diff --git a/tests/test_patient_risk.py b/tests/test_patient_risk.py new file mode 100644 index 0000000..8cd6f9b --- /dev/null +++ b/tests/test_patient_risk.py @@ -0,0 +1,99 @@ +"""What this module covers: `GET /cacu/pacientes//riesgo` (`webapi.patient_risk`): when the route exists, the +shape the WebApp's contract reads (`RiesgoPacienteCacu`), and its 404. The reads behind it are Persistance's, tested +there. + +Fixtures: `client`, a DEV client over the kit's CaCu demonstration database (`conftest.cliente_de`) plus `seeded`: +a surveillance build with two of its patients, one of them with variables and a confirmed batch; `fuera_de_dev`, the +same app without `DEV_REVISION`. +""" + +from datetime import date, datetime, timezone + +import pytest +from conftest import cliente_de + +COHORT_KEYS = {"url", "version", "fecha_indice", "tipo_censura", "c", "l", "r", "pap_0", "hpv_0"} +RISK_KEYS = {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "estado_lote", "horizontes"} +HORIZON_KEYS = {"horizonte_anios", "probabilidad", "ic_bajo", "ic_alto", "estado"} + + +@pytest.fixture(scope="module") +def client(tmp_path_factory): + with pytest.MonkeyPatch.context() as mp: + mp.setenv("DEV_REVISION", "prueba") + yield from cliente_de("cacu", tmp_path_factory) + + +@pytest.fixture(scope="module") +def seeded(client): + """Two patients of the demo data in a new surveillance build; the first has `pap_0`, `c` and a batch with risks at + 1 and 3 years, confirmed. Returns (scored patient, member without risks, patient outside the build).""" + from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, CohorteVariable + from persistance import cacu + from persistance.db import get_cacu_session + + scored, unscored, outside = [p.pac_id for p in cacu.persona_repository.list(limit=3)] + 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="risk-route", 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.flush() + session.add_all([CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="pap_0", valor_codigo="ASC-US"), + CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)]) + session.commit() + build_id = build.armado_id + batch, _ = cacu.cohorte_repository.guardar_lote( + build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"}, + "cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)], + ahora=datetime(2026, 10, 1, tzinfo=timezone.utc)) + cacu.cohorte_repository.cambiar_estado(batch, "final", "revisado") + return scored, unscored, outside + + +@pytest.fixture(scope="module") +def fuera_de_dev(tmp_path_factory): + with pytest.MonkeyPatch.context() as mp: + mp.delenv("DEV_REVISION", raising=False) + yield from cliente_de("cacu", tmp_path_factory) + + +def test_a_scored_member_has_the_contracts_shape(client, seeded): + """Pins down: the body has `simulado`, `cohorte` and `riesgo` with exactly the contract's fields, the horizons in + ascending order, probabilities in 0..1 and the date as ISO-8601 UTC. Fails if a field is renamed or dropped, which + would break the WebApp's validation.""" + response = client.get(f"/cacu/pacientes/{seeded[0]}/riesgo") + + body = response.get_json() + assert response.status_code == 200 and body["simulado"] is True + assert set(body["cohorte"]) == COHORT_KEYS and set(body["riesgo"]) == RISK_KEYS + assert (body["cohorte"]["pap_0"], body["cohorte"]["c"], body["cohorte"]["hpv_0"]) == ("ASC-US", 0.0, None) + assert body["riesgo"]["evaluado_en"] == "2026-10-01T00:00:00Z" and body["riesgo"]["estado_lote"] == "final" + horizons = body["riesgo"]["horizontes"] + assert all(set(h) == HORIZON_KEYS for h in horizons) + assert [(h["horizonte_anios"], h["probabilidad"], h["estado"]) for h in horizons] == [(1.0, 0.1, "final"), (3.0, 0.3, "final")] + + +def test_a_member_without_a_confirmed_batch_and_a_non_member(client, seeded): + """Pins down: a member nobody scored has `cohorte` and `riesgo: null`; a patient outside the latest build has both + null. Fails if either case errors or invents a risk.""" + member = client.get(f"/cacu/pacientes/{seeded[1]}/riesgo").get_json() + outside = client.get(f"/cacu/pacientes/{seeded[2]}/riesgo").get_json() + + assert member["cohorte"] is not None and member["riesgo"] is None + assert outside == {"simulado": True, "cohorte": None, "riesgo": None} + + +def test_an_unknown_patient_is_404(client, seeded): + """Pins down: a `pac_id` not in `persona` is 404. Fails if it answers with an empty body as if she existed.""" + assert client.get("/cacu/pacientes/987654321/riesgo").status_code == 404 + + +def test_outside_dev_the_route_does_not_exist(fuera_de_dev): + """Pins down: without `DEV_REVISION` the route isn't registered. Fails if patient-level risks are served outside + the simulated DEV deployment.""" + assert fuera_de_dev.get("/cacu/pacientes/1/riesgo").status_code == 404 diff --git a/webapi/__init__.py b/webapi/__init__.py index 5c922c5..b77c6a2 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -77,10 +77,15 @@ def create_app() -> Flask: app.register_blueprint(data_bp, url_prefix="/data") app.register_blueprint(governance_bp, url_prefix="/governance") app.register_blueprint(reportes_bp, url_prefix="/reportes") - # Patient-level follow-up list: only in DEV, with simulated data. + # Patient-level follow-up list and individual risk: only in DEV, with simulated data. if en_dev(): from persistance.db import get_cacu_session app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu") + from persistance import cacu as cacu_repositories + + from webapi.patient_risk import patient_risk_blueprint + + app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu") return app diff --git a/webapi/patient_risk.py b/webapi/patient_risk.py new file mode 100644 index 0000000..a0eb2f0 --- /dev/null +++ b/webapi/patient_risk.py @@ -0,0 +1,49 @@ +"""A CaCu patient's individual risk: `GET /cacu/pacientes//riesgo`, only in DEV. + +The contract the WebApp's patient record reads (`RiesgoPacienteCacu`): the patient's membership in the surveillance +cohort's latest build, with its variables, and its risks in the current batch, the newest one with a confirmed +evaluation. Patient data: **registered only in DEV** (`DEV_REVISION`), on simulated data, and every response carries +`simulado: true`. `pac_id` is the internal id; whoever calls is already inside the secure environment. A field is never +removed or renamed, only added. +""" + +from datetime import timezone + +from flask import Blueprint, jsonify + +COHORT_URL = "cacu/cohorte_vigilancia" +COHORT_VARIABLES = ("tipo_censura", "c", "l", "r", "pap_0", "hpv_0") + + +def patient_risk_blueprint(repositories) -> Blueprint: + """The blueprint, to register with `url_prefix="/cacu"` only in DEV. `repositories` is `persistance.cacu`.""" + blueprint = Blueprint("cacu_patient_risk", __name__) + + @blueprint.get("/pacientes//riesgo") + def get_patient_risk(pac_id: int): + """A patient's cohort membership and risks in the current batch (DEV only, simulated data).""" + if repositories.persona_repository.get(pac_id) is None: + return jsonify({"error": f"no existe la paciente {pac_id}"}), 404 + membership = repositories.cohorte_repository.membership(pac_id, COHORT_URL) + risk = repositories.cohorte_repository.current_risk(pac_id) + return jsonify({"simulado": True, "cohorte": _cohort(membership), "riesgo": _risk(risk)}) + + return blueprint + + +def _cohort(membership) -> dict | None: + if membership is None: + return None + return {"url": membership.url, "version": membership.version, "fecha_indice": membership.fecha_indice.isoformat(), + **{name: membership.variables.get(name) for name in COHORT_VARIABLES}} + + +def _risk(risk) -> dict | None: + if risk is None: + return None + evaluated = risk.evaluado_en if risk.evaluado_en.tzinfo else risk.evaluado_en.replace(tzinfo=timezone.utc) + return {"lote_id": risk.lote_id, "modelo_nombre": risk.modelo_nombre, "modelo_version": risk.modelo_version, + "evaluado_en": evaluated.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "estado_lote": risk.estado_lote, + "horizontes": [{"horizonte_anios": h.horizonte_anios, "probabilidad": h.probabilidad, "ic_bajo": h.ic_bajo, + "ic_alto": h.ic_alto, "estado": h.estado} for h in risk.horizontes]}