Rutas de indicadores de CaCu: /cacu y /tea comparten webapi/indicadores.py
registrar_indicadores(blueprint, proyecto, get_session) agrega GET /indicadores (con tipos_periodo) y GET /indicadores/<id>/figuras/<figura>. TEA pasa a ese módulo; los periodos se validan contra los tipos que publica cada definición (semestre, mes, ...) y las figuras salen de figuras_de(medida). Pruebas de CaCu con SQLite temporal sembrada con los fixtures del kit. Pruebas: Core 25 passed; Persistance 31 passed; indicadores_kit 564 passed, 2 skipped; WebApi 55 passed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
"""Lo común de las pruebas de indicadores de CaCu y CaMa."""
|
||||
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
from sqlmodel import Session, select
|
||||
|
||||
SEMESTRES = ["2025-S1", "2025-S2"]
|
||||
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||
|
||||
|
||||
def sembrar_base(proyecto: str, motor) -> None:
|
||||
"""Staging sintético del kit, tablas del kit, carga y el indicador de ejemplo calculado.
|
||||
|
||||
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para TEA,
|
||||
con los pasos del kit: parámetros, `dim_periodo` (semestres y meses de
|
||||
2025) y `<proyecto>_eu8` en `SEMESTRES` y `MESES`.
|
||||
"""
|
||||
from indicadores_kit.esquema import crear_esquema
|
||||
from indicadores_kit.mart.calculo import calcular_measure
|
||||
from indicadores_kit.registry.measures import leer_measure, ruta_de_measure
|
||||
from indicadores_kit.registry.parametros import RUTA_PARAMETROS, cargar_parametros
|
||||
from indicadores_kit.registry.periodos import generar_dim_periodo
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
fixtures = import_module(f"indicadores_kit.{proyecto}.fixtures")
|
||||
etl = import_module(f"indicadores_kit.{proyecto}.etl")
|
||||
base = import_module(f"core.{proyecto}.base")
|
||||
modelos = import_module(f"core.{proyecto}.models")
|
||||
tablas = tablas_de(proyecto)
|
||||
|
||||
getattr(base, "CaCuModel" if proyecto == "cacu" else "CaMaModel").metadata.create_all(motor)
|
||||
crear_esquema(motor, proyecto)
|
||||
cargar, tabla = (
|
||||
(etl.cargar_citologias, modelos.CitologiaCervical)
|
||||
if proyecto == "cacu"
|
||||
else (etl.cargar_mastografias, modelos.Mastografia)
|
||||
)
|
||||
with Session(motor) as sesion:
|
||||
fixtures.insertar(sesion)
|
||||
cargar(
|
||||
sesion,
|
||||
sesion.exec(select(modelos.Paciente)).all(),
|
||||
sesion.exec(select(tabla)).all(),
|
||||
)
|
||||
cargar_parametros(sesion, RUTA_PARAMETROS, tablas=tablas)
|
||||
generar_dim_periodo(sesion, 2025, 2025, tablas=tablas, tipos=("semestre", "mes"))
|
||||
medida = leer_measure(ruta_de_measure(proyecto, f"{proyecto}_eu8"))
|
||||
for periodo in SEMESTRES + MESES:
|
||||
calcular_measure(sesion, medida, periodo, tablas=tablas, permitir_sin_definir=True)
|
||||
|
||||
|
||||
def cliente_de(proyecto: str, tmp_path_factory):
|
||||
"""Generador para la fixture `client` de un proyecto: una base SQLite temporal ya sembrada."""
|
||||
from persistance import db
|
||||
from persistance.settings import settings
|
||||
|
||||
ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db"
|
||||
obtener_motor = getattr(db, f"get_{proyecto}_engine")
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
|
||||
obtener_motor.cache_clear()
|
||||
try:
|
||||
sembrar_base(proyecto, obtener_motor())
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
obtener_motor().dispose()
|
||||
obtener_motor.cache_clear()
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit."""
|
||||
|
||||
import pytest
|
||||
from conftest import MESES, SEMESTRES, cliente_de
|
||||
from indicadores_kit.registry.measures import measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
|
||||
PROYECTO = "cacu"
|
||||
INDICADOR = "cacu_eu8"
|
||||
DEFINICIONES = measures_de(PROYECTO)
|
||||
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
yield from cliente_de(PROYECTO, tmp_path_factory)
|
||||
|
||||
|
||||
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def _x(respuesta) -> list[str]:
|
||||
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get(f"/{PROYECTO}/indicadores")
|
||||
|
||||
assert response.status_code == 200
|
||||
lista = response.get_json()
|
||||
assert [fila["id"] for fila in lista] == sorted(DEFINICIONES)
|
||||
fila = next(fila for fila in lista if fila["id"] == INDICADOR)
|
||||
medida = DEFINICIONES[INDICADOR]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida) == [FIGURA]
|
||||
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||
|
||||
|
||||
def test_figura_con_semestres(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.mimetype == "application/json"
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
|
||||
assert set(_x(response)) == set(SEMESTRES)
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
|
||||
response = _figura(client)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
|
||||
|
||||
|
||||
def test_figura_con_meses(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(MESES)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S3",
|
||||
"?periodos=2025-13x",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=2025-T1", # un tipo que el indicador no publica
|
||||
"?periodos=2025-S1,2025-03", # tipos mezclados
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, query=query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("CACU_NO_EXISTE", FIGURA, ""),
|
||||
(INDICADOR, "fig_c2_apiladas", ""), # figura de otro contrato
|
||||
(INDICADOR, "fig_no_existe", ""),
|
||||
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||
(INDICADOR, FIGURA, "?periodos=2025-11"), # un mes sin reporte
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, query="?periodos=2025-S1")
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
import pytest
|
||||
from indicadores_kit.registry.measures import measures_de
|
||||
from indicadores_kit.serving.figuras_tea import FIGURAS_TEA
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
from indicadores_kit.tea import fixtures
|
||||
|
||||
DEFINICIONES = measures_de("tea")
|
||||
@@ -47,12 +47,12 @@ def test_listar_indicadores(client):
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == sorted(FIGURAS_TEA[medida.extension.contrato])
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
(figura,) = FIGURAS_TEA[DEFINICIONES[indicador].extension.contrato]
|
||||
(figura,) = figuras_de(DEFINICIONES[indicador])
|
||||
|
||||
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||
|
||||
@@ -62,7 +62,7 @@ def test_figura_de_cada_indicador(client, indicador):
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||
(figura,) = FIGURAS_TEA["C1"]
|
||||
(figura,) = figuras_de(DEFINICIONES["K01_evaluacion_3_meses"])
|
||||
|
||||
response = _figura(client, "K01_evaluacion_3_meses", figura)
|
||||
|
||||
@@ -113,11 +113,11 @@ def test_paciente_por_id_entero(client):
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi.blueprints import tea
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(tea, "figura_json_tea", falla)
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, "K01_evaluacion_3_meses", "fig_c1_grupos", "?periodos=2025-S1")
|
||||
|
||||
Reference in New Issue
Block a user