100 lines
5.3 KiB
Python
100 lines
5.3 KiB
Python
"""What this module covers: `GET /cacu/pacientes/<pac_id>/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.cohort_repository.save_batch(
|
|
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.cohort_repository.change_state(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
|