Files
WebApi/tests/test_orquestacion_riesgos.py
T
Roberto Treviño Cervantes ae1ee4633f absorb Orquestacion into webapi.orquestacion
Orquestacion was a separate uv package with exactly one consumer
(webapi.indicadores_vivos) and no independent deployment: the Dockerfile
already copied it straight into this image and ran one uv sync for
everything. Folding it in removes a redundant pyproject.toml/uv.lock/venv
without losing the standalone CLI (python -m webapi.orquestacion ciclo/
confirmar-riesgos) or its test suite, which now runs as part of this
project's own pytest run.

417 tests pass (416 unchanged + the merged orquestacion suite); verified
live in a built image, where the indicadores worker completed a full
cacu/cama/tea cycle against webapi.orquestacion.ejecutor.
2026-10-31 00:51:41 -06:00

116 lines
5.0 KiB
Python

"""El paso `estimar` y la orden `confirmar-riesgos` (ADR-MD-008), con un estimador de prueba.
El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow.
"""
from dataclasses import dataclass
import pytest
from sqlalchemy import text
from webapi.orquestacion.__main__ import confirmar_riesgos, main
URL = "cacu/cohorte_vigilancia"
@dataclass(frozen=True)
class Procedencia:
modelo_nombre: str = "prueba"
modelo_version: str = "1"
mlflow_run_id: str = "sin-mlflow"
modelo_sha: str = "sha-de-prueba"
def como_dict(self):
return dict(self.__dict__)
class EstimadorFijo:
"""Cumple el contrato: un riesgo por miembro, `probabilidad` (0.1) al `horizonte` (0)."""
desenlace = "cin2_mas"
def __init__(self, cohorte_url=URL, horizonte=0.0, probabilidad=0.1):
self.cohorte_url, self.horizonte, self.probabilidad = cohorte_url, horizonte, probabilidad
self.columnas = None
def procedencia(self):
return Procedencia()
def estimar(self, columnas, filas):
self.columnas = columnas
return [(fila[0], self.horizonte, self.probabilidad, None, None) for fila in filas]
@pytest.fixture
def cacu(base):
base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True)
return base
def cuenta(base, sql):
with base.motor.connect() as con:
return con.execute(text(sql)).scalar_one()
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
estimador = EstimadorFijo()
(lote_id, nuevo) = cacu.correr("estimar", estimadores={URL: estimador})["estimar"][URL]
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
assert nuevo and miembros > 0
assert estimador.columnas[:2] == ["pac_id", "fecha_indice"] # el marco ancho de `leer_marco`
assert cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}") == miembros
assert cuenta(cacu, "SELECT COUNT(DISTINCT estado) FROM evaluacion_riesgo") == 1
assert cuenta(cacu, "SELECT MIN(estado) FROM evaluacion_riesgo") == "preliminary"
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
(primero, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
assert cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] == (primero, False)
assert cacu.correr("estimar")["estimar"] == {}
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
@pytest.mark.parametrize("proyecto", ["cacu"])
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
(lote_id, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
main(["confirmar-riesgos", "cacu", str(lote_id), "--motivo", "revisado"])
assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros
assert confirmar_riesgos("cacu", lote_id, "error de captura", anular=True) == miembros
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros
# Por proyecto: la cohorte, el horizonte de sus bandas y su resumen por banda. Desde T-21h solo CaCu arma
# su cohorte; las de TEA y CaMa son propuestas y su punta a punta está en `models` y en el kit.
DE_PUNTA_A_PUNTA = {
"cacu": (URL, 0.0, "cacu/CACU_RIESGO_BANDA"),
}
@pytest.mark.parametrize("proyecto", sorted(DE_PUNTA_A_PUNTA))
def test_el_lote_confirmado_sale_en_el_resumen_por_banda(base, proyecto, sin_supresion):
"""De punta a punta: la cohorte, estimar a su horizonte, confirmar y el resumen por banda."""
url, horizonte, measure = DE_PUNTA_A_PUNTA[proyecto]
base.correr("catalogos", "cargar", "cohortes", permitir_sin_definir=True)
estimador = EstimadorFijo(url, horizonte=horizonte, probabilidad=0.3) # 0.3 >= corte_alto: ALTO
(lote_id, _) = base.correr("estimar", estimadores={url: estimador})["estimar"][url]
confirmar_riesgos(proyecto, lote_id, "revisado")
# Sin supresión: los fixtures tienen menos miembros por semestre que el umbral (CaMa la tiene activa).
base.correr("vistas", "registro", "definiciones", "calcular", parametros=sin_supresion, permitir_sin_definir=True)
en_el_anio = cuenta(base, f"""SELECT COUNT(*) FROM cohorte_miembro
WHERE strftime('%Y', fecha_indice) = '{base.ctx.anio_inicio}'""")
altos = cuenta(base, f"""SELECT COALESCE(SUM(v.n), 0) FROM v_c2 v
JOIN v_measure_report_vigente r ON r.report_id = v.report_id
WHERE r.measure_url = '{measure}' AND r.periodo_id LIKE '%-S_'
AND v.categoria = 'ALTO' AND v.estrato_id = 'total'""")
assert en_el_anio > 0 and altos == en_el_anio