Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bc0b06e7b | |||
| 830d978a1b | |||
| b89b630c2e | |||
| fecb0247d1 | |||
| 4c8f3e620e | |||
| 7577c99c62 | |||
| a188bf66e1 | |||
| cca67c837d | |||
| d76cb6cb20 | |||
| 84da0eb5fb | |||
| ceca8a03b5 | |||
| 0355d21d47 |
+2
-1
@@ -1,5 +1,5 @@
|
||||
# Build context is the ISSSTELEON repo root (see root docker-compose.yml)
|
||||
# so this Dockerfile can COPY its sibling Core/, Persistance/ and models/.
|
||||
# so this Dockerfile can COPY its sibling Core/, Persistance/, models/ and indicadores_kit/.
|
||||
FROM python:3.12-slim
|
||||
|
||||
RUN pip install --no-cache-dir uv
|
||||
@@ -8,6 +8,7 @@ WORKDIR /app
|
||||
COPY Core/ Core/
|
||||
COPY Persistance/ Persistance/
|
||||
COPY models/ models/
|
||||
COPY indicadores_kit/ indicadores_kit/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
RUN cd Persistance && uv sync --no-dev
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
# WebApi
|
||||
|
||||
API REST en Flask para CaCu, CaMa y TEA. Lee datos con `../Persistance`,
|
||||
sirve figuras de indicadores con `../indicadores_kit` y llama a los modelos
|
||||
de `../models`.
|
||||
|
||||
## Estructura
|
||||
|
||||
```
|
||||
WebApi/
|
||||
├── main.py crea la app y la levanta en 0.0.0.0:5000
|
||||
├── webapi/
|
||||
│ ├── __init__.py create_app(): /health y los tres blueprints
|
||||
│ ├── indicadores.py rutas de indicadores, datos y figuras, comunes a los tres proyectos
|
||||
│ └── blueprints/
|
||||
│ ├── cacu.py cacu_bp, prefijo /cacu
|
||||
│ ├── cama.py cama_bp, prefijo /cama
|
||||
│ └── tea.py tea_bp, prefijo /tea
|
||||
├── tests/
|
||||
│ ├── conftest.py siembra una base de CaCu o CaMa con los fixtures del kit
|
||||
│ ├── test_app.py /health y rutas de CaCu, con SQLite temporal
|
||||
│ ├── test_cacu.py indicadores de CaCu, con SQLite temporal
|
||||
│ ├── test_cama.py indicadores de CaMa, con SQLite temporal
|
||||
│ └── test_tea.py rutas de TEA, con SQLite temporal y 18 indicadores
|
||||
├── Dockerfile imagen; el contexto es la raíz del repo padre
|
||||
└── docker-entrypoint.sh migra las tres bases y arranca main.py
|
||||
```
|
||||
|
||||
Un blueprint por dominio, con rutas de ejemplo (paciente y `predict`).
|
||||
Los tres sirven además los indicadores del kit: cada blueprint llama a
|
||||
`registrar_indicadores(blueprint, proyecto, get_<proyecto>_session)` de
|
||||
`webapi/indicadores.py`, que agrega el catálogo, los periodos, los datos,
|
||||
los metadatos y las figuras.
|
||||
|
||||
## Flujo de datos
|
||||
|
||||
Ruta de lectura simple (`/cacu/pacientes/<id>`):
|
||||
|
||||
```
|
||||
request -> blueprint -> repositorio de Persistance -> modelo -> JSON
|
||||
```
|
||||
|
||||
El repositorio abre y cierra su propia sesión.
|
||||
|
||||
Ruta de figura (la misma para `/cacu`, `/cama` y `/tea`):
|
||||
|
||||
```
|
||||
GET /<proyecto>/indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
│
|
||||
├─ valida indicador y figura (404 si no existen; figuras_de(medida))
|
||||
├─ valida tema y periodos (400 si están mal)
|
||||
├─ sesion = get_<proyecto>_session()
|
||||
├─ sin periodos: periodos_con_reporte(..., tipo=<primer tipo que publica>)
|
||||
├─ figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||
│ (indicadores_kit lee measure_report y arma el JSON de Plotly)
|
||||
└─ finally: sesion.close()
|
||||
│
|
||||
v
|
||||
Response(texto, mimetype="application/json")
|
||||
```
|
||||
|
||||
Las rutas de datos, periodos y metadatos siguen los mismos pasos, con
|
||||
`datos_de`, `periodos_de` y `metadatos_de` de
|
||||
`indicadores_kit.serving.datos` en lugar de `figura_json`.
|
||||
|
||||
La sesión se cierra siempre, en `finally`. Un `KeyError` interno no se
|
||||
convierte en 404: sube como error 500. Un `LookupError` (periodo sin
|
||||
reporte) sí da 404.
|
||||
|
||||
## Uso
|
||||
|
||||
### Instalar y probar
|
||||
|
||||
```bash
|
||||
cd WebApi
|
||||
uv sync
|
||||
uv run pytest
|
||||
```
|
||||
|
||||
`WebApi` depende de `../Persistance`, `../models` y `../indicadores_kit`
|
||||
(rutas editables en `pyproject.toml`). Requiere Python 3.12 o más.
|
||||
|
||||
### Variables de entorno
|
||||
|
||||
Las lee `Persistance` (ver su README). Por defecto cada base es un archivo
|
||||
SQLite **relativo al directorio actual**.
|
||||
|
||||
| Variable | Valor por defecto |
|
||||
| --- | --- |
|
||||
| `CACU_DATABASE_URL` | `sqlite:///cacu.db` |
|
||||
| `CAMA_DATABASE_URL` | `sqlite:///cama.db` |
|
||||
| `TEA_DATABASE_URL` | `sqlite:///tea.db` |
|
||||
|
||||
Atención: con el valor por defecto, `alembic` en `Persistance/` escribe
|
||||
`Persistance/<proyecto>.db` y la API en `WebApi/` abre `WebApi/<proyecto>.db`.
|
||||
Son dos bases distintas. La API crea la segunda vacía y falla con
|
||||
`no such table: measure_report`. Use siempre una ruta absoluta
|
||||
(`sqlite:////` con cuatro barras) y la misma en todos los pasos, en cada
|
||||
proyecto que vaya a servir:
|
||||
|
||||
```bash
|
||||
export TEA_DATABASE_URL=sqlite:////ruta/absoluta/tea.db
|
||||
export CACU_DATABASE_URL=sqlite:////ruta/absoluta/cacu.db
|
||||
export CAMA_DATABASE_URL=sqlite:////ruta/absoluta/cama.db
|
||||
```
|
||||
|
||||
### Correr en local
|
||||
|
||||
La API solo lee. Antes de pedir una figura, la base de TEA necesita las
|
||||
tablas, los datos y los reportes calculados. Hay dos caminos.
|
||||
|
||||
**A. Base de demostración (datos sintéticos del kit).** Una sola orden
|
||||
crea las tablas, carga el staging sintético y calcula los 18 indicadores
|
||||
en `2025-S1` y `2025-S2`. Necesita un archivo nuevo o vacío; no corra
|
||||
`alembic` antes en ese archivo.
|
||||
|
||||
```bash
|
||||
cd WebApi
|
||||
export TEA_DATABASE_URL=sqlite:////ruta/absoluta/tea_demo.db
|
||||
uv run python -c "import os; from sqlalchemy import create_engine; from indicadores_kit.tea.fixtures import base_de_prueba; base_de_prueba(create_engine(os.environ['TEA_DATABASE_URL']))"
|
||||
uv run python main.py # http://localhost:5000
|
||||
```
|
||||
|
||||
**B. Datos reales.** Con la misma `TEA_DATABASE_URL` en todos los pasos:
|
||||
|
||||
```bash
|
||||
cd Persistance
|
||||
uv run alembic -c persistance/tea/alembic.ini upgrade head # tablas
|
||||
# ... llene las tablas de staging de TEA (pacientes, evaluacion_psicologica, eeg_estudio, ...)
|
||||
cd ../WebApi
|
||||
uv run python -m indicadores_kit.tea.etl # staging -> hechos del kit
|
||||
uv run python -m indicadores_kit.correr tea K01_evaluacion_3_meses 2025-S1 2025-S2
|
||||
# repita `correr` por cada indicador (ids en /tea/indicadores)
|
||||
uv run python main.py # http://localhost:5000
|
||||
```
|
||||
|
||||
Cada `correr` agrega un reporte; no borra los anteriores.
|
||||
|
||||
**CaCu y CaMa** siguen los mismos pasos con su `alembic.ini`, su variable
|
||||
de entorno y el ETL de su proyecto (`python -m indicadores_kit.cacu.etl`).
|
||||
`correr` solo agrega semestres a `dim_periodo`; para tener también meses,
|
||||
prepare los dos tipos y calcule con los pasos del kit:
|
||||
|
||||
```bash
|
||||
uv run python -c "
|
||||
from datetime import date
|
||||
from indicadores_kit.pasos import calcular_periodos, preparar_registro
|
||||
from indicadores_kit.registry.measures import leer_measure, ruta_de_measure
|
||||
preparar_registro('cacu', 2025, 2025, tipos=('semestre', 'mes'))
|
||||
medida = leer_measure(ruta_de_measure('cacu', 'cacu_eu8'))
|
||||
for tipo in ('semestre', 'mes'):
|
||||
calcular_periodos('cacu', medida, tipo, date(2025, 1, 1), date(2026, 1, 1), permitir_sin_definir=True)
|
||||
"
|
||||
uv run python main.py
|
||||
```
|
||||
|
||||
Los ids son `cacu_eu8` y `cama_eu8`. En `tests/conftest.py` está la
|
||||
secuencia completa con los fixtures del kit.
|
||||
|
||||
### Correr con Docker
|
||||
|
||||
Desde la raíz del repo padre:
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
`docker-compose.yml` construye `WebApi/Dockerfile` con la raíz como
|
||||
contexto, publica el puerto 5000 y guarda las bases en el volumen `webapi_data` (`/data/cacu.db`,
|
||||
`/data/cama.db`, `/data/tea.db`). `docker-entrypoint.sh` corre
|
||||
`alembic upgrade head` en los tres dominios y después `main.py`. Las
|
||||
tablas quedan vacías: cargue y calcule como en el camino B. También
|
||||
levanta `webapp` en el puerto 4200.
|
||||
|
||||
### Rutas
|
||||
|
||||
| Método | Ruta | Respuesta |
|
||||
| --- | --- | --- |
|
||||
| GET | `/health` | 200 `{"status": "ok"}` |
|
||||
| GET | `/cacu/pacientes/<int:pac_id>` | 200 paciente; 404 `{"error": "not found"}` |
|
||||
| POST | `/cacu/predict` | 200 `{"prediction": ...}`; 501 si el modelo no está listo |
|
||||
| GET | `/cama/pacientes/<int:pac_id>` | igual que CaCu |
|
||||
| POST | `/cama/predict` | igual que CaCu |
|
||||
| GET | `/tea/pacientes/<int:pac_id>` | 200 paciente; 404 `{"error": "not found"}` |
|
||||
| POST | `/tea/predict` | igual que CaCu |
|
||||
| GET | `/<proyecto>/indicadores` | 200 lista de indicadores (`proyecto` = `cacu`, `cama` o `tea`) |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/periodos` | 200 periodos con reporte; 404 |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/datos` | 200 los números, sin figura; 400 o 404 |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/metadatos` | 200 ficha metodológica; 404 |
|
||||
| GET | `/<proyecto>/indicadores/<indicador>/figuras/<figura>` | 200 JSON de la figura; 400 o 404 |
|
||||
|
||||
Las rutas de `pac_id` solo aceptan enteros. Con otro valor (`/tea/pacientes/abc`)
|
||||
Flask no encuentra la ruta y da 404.
|
||||
|
||||
Ejemplos:
|
||||
|
||||
```bash
|
||||
curl localhost:5000/health
|
||||
curl localhost:5000/tea/pacientes/1
|
||||
curl localhost:5000/tea/indicadores
|
||||
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/figuras/fig_c1_grupos"
|
||||
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/figuras/fig_c1_grupos?periodos=2025-S1,2025-S2&tema=oscuro"
|
||||
curl localhost:5000/tea/indicadores/K01_evaluacion_3_meses/periodos
|
||||
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2025-S1,2025-S2"
|
||||
curl localhost:5000/tea/indicadores/K01_evaluacion_3_meses/metadatos
|
||||
curl localhost:5000/cacu/indicadores
|
||||
curl localhost:5000/cacu/indicadores/cacu_eu8/datos
|
||||
curl "localhost:5000/cacu/indicadores/cacu_eu8/figuras/fig_c1_puntos?periodos=2025-01,2025-02,2025-03"
|
||||
```
|
||||
|
||||
`/<proyecto>/indicadores` devuelve, por indicador: `id`, `titulo`,
|
||||
`version`, `contrato`, `unidad`, `sentido`, `figuras`, `estratos` y
|
||||
`tipos_periodo` (los que publica la definición en `extension.publicacion`). Las figuras dependen de la definición: con
|
||||
ficha (TEA) hay una por contrato (`fig_c1_grupos`, `fig_c2_apiladas`,
|
||||
`fig_c3r_caja`); sin ficha (CaCu, CaMa) es `fig_c1_puntos`, un punto por
|
||||
periodo.
|
||||
|
||||
Parámetros de la figura:
|
||||
|
||||
- `periodos`: lista separada por comas, todos de un mismo tipo y de un tipo
|
||||
que el indicador publique: `AAAA-S1` o `AAAA-S2` (semestre), `AAAA-MM`
|
||||
(mes), y así los demás de `registry/periodos.py`. Sin el parámetro se
|
||||
usan todos los periodos con reporte del primer tipo que publica la
|
||||
definición.
|
||||
- `tema`: `claro` (por defecto) u `oscuro`.
|
||||
|
||||
Códigos de la figura:
|
||||
|
||||
| Código | Causa |
|
||||
| --- | --- |
|
||||
| 200 | JSON de la figura |
|
||||
| 400 | `tema` desconocido, o `periodos` mal formado: coma al final, tipo que el indicador no publica, tipos mezclados |
|
||||
| 404 | indicador desconocido; figura que no es del contrato del indicador; el indicador no tiene reportes; algún periodo pedido no tiene reporte |
|
||||
| 500 | error interno (por ejemplo un `KeyError`) |
|
||||
|
||||
### Datos, periodos y metadatos
|
||||
|
||||
Para mostrar el número o graficar desde el frontend, sin Plotly. Salen de
|
||||
las mismas filas que las figuras y ya traen la supresión aplicada.
|
||||
|
||||
| Ruta | Qué devuelve |
|
||||
| --- | --- |
|
||||
| `/periodos` | `id`, `version` y `periodos`: por cada periodo con reporte, su `tipo`, sus fechas, su `report_id`, `generado_en` y `fecha_corte` |
|
||||
| `/datos?periodos=&estrato=` | `filas` (una por periodo y grupo), `grupos` y `categorias` con sus etiquetas, `reportes` con la procedencia de cada periodo |
|
||||
| `/metadatos` | la ficha, la unidad, los estándares y las reglas que usa el indicador, con su estado |
|
||||
|
||||
`periodos` se pide igual que en la figura. `estrato` es uno de los
|
||||
`estratos` del indicador. Toda fila de `/datos` trae `periodo`, `grupo`,
|
||||
`estrato` y `suprimido`, y después las columnas de su `contrato`:
|
||||
|
||||
| Contrato | Columnas |
|
||||
| --- | --- |
|
||||
| C1 (proporción) | `numerador`, `denominador`, `valor` (0 a 100), `ic_bajo`, `ic_alto` (Wilson al 95 %), `n_sin_evento`, `n_excluido` |
|
||||
| C2 (distribución) | `categoria`, `n`, `orden` |
|
||||
| C3r (tiempos) | `n`, `mediana`, `q1`, `q3`, `n_sin_evento`, `n_excluido`, `unidad` |
|
||||
|
||||
Una celda suprimida va con `suprimido` en 1 y sus números en `null`. En
|
||||
`reportes`, `periodo_fin` es el primer día que ya no entra en el periodo.
|
||||
|
||||
La forma de estas respuestas es un contrato con el frontend: no se quita
|
||||
ni se renombra un campo; solo se agregan.
|
||||
|
||||
Códigos: 400 si `periodos` está mal formado o `estrato` no es del
|
||||
indicador; 404 si el indicador no existe, no tiene reportes o algún
|
||||
periodo pedido no lo tiene.
|
||||
|
||||
## Cómo extender
|
||||
|
||||
### Agregar una ruta a un blueprint existente
|
||||
|
||||
1. Abre `webapi/blueprints/<dominio>.py`.
|
||||
2. Agrega la función con `@<dominio>_bp.get(...)` o `.post(...)`.
|
||||
3. Para leer una tabla, importa el repositorio de `persistance.<dominio>`.
|
||||
4. Si abres una sesión tú mismo (`get_<dominio>_session()`), ciérrala
|
||||
siempre en `finally`.
|
||||
5. Responde errores con `jsonify({"error": mensaje}), codigo`.
|
||||
6. Agrega pruebas (ver abajo) y la ruta a la tabla de este README.
|
||||
|
||||
### Agregar un blueprint (un dominio nuevo)
|
||||
|
||||
1. Crea `webapi/blueprints/<dominio>.py` con `Blueprint("<dominio>", __name__)`.
|
||||
2. Regístralo en `create_app()` de `webapi/__init__.py` con
|
||||
`app.register_blueprint(<dominio>_bp, url_prefix="/<dominio>")`.
|
||||
3. Agrega el dominio en `Persistance` primero (ver su README) y la variable
|
||||
`<DOMINIO>_DATABASE_URL` en el `Dockerfile`.
|
||||
4. Agrega su migración al `docker-entrypoint.sh`.
|
||||
|
||||
### Escribir pruebas
|
||||
|
||||
Las pruebas usan una base SQLite temporal, fijada con la variable de
|
||||
entorno o con el objeto `settings`. `Persistance` lee la configuración al
|
||||
importarse. Por eso importa `persistance` **dentro** de la fixture, no al
|
||||
inicio del archivo.
|
||||
|
||||
Patrón de `tests/test_app.py` (CaCu, con variable de entorno):
|
||||
|
||||
```python
|
||||
@pytest.fixture(scope="module")
|
||||
def client():
|
||||
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
|
||||
os.environ["CACU_DATABASE_URL"] = f"sqlite:///{db_path}"
|
||||
|
||||
from persistance.db import get_cacu_engine # import dentro de la fixture
|
||||
...
|
||||
from webapi import create_app
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as client:
|
||||
yield client
|
||||
```
|
||||
|
||||
Patrón de `tests/test_tea.py`, `test_cacu.py` y `test_cama.py` (con `monkeypatch` de `settings`;
|
||||
CaCu y CaMa lo comparten en `tests/conftest.py`):
|
||||
|
||||
```python
|
||||
from persistance.db import get_tea_engine
|
||||
from persistance.settings import settings
|
||||
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
|
||||
get_tea_engine.cache_clear() # el engine está en caché
|
||||
fixtures.base_de_prueba(get_tea_engine())
|
||||
...
|
||||
get_tea_engine().dispose()
|
||||
get_tea_engine.cache_clear()
|
||||
```
|
||||
|
||||
`fixtures.base_de_prueba` es de `indicadores_kit.tea.fixtures`: crea las
|
||||
tablas y deja los 18 indicadores calculados.
|
||||
|
||||
Si cambias la URL después de crear el engine, llama a
|
||||
`get_<dominio>_engine.cache_clear()`.
|
||||
+3
-1
@@ -2,16 +2,18 @@
|
||||
name = "webapi"
|
||||
version = "0.1.0"
|
||||
description = "Flask REST API fronting Persistance (reads) and models (train/predict) for CaCu, CaMa and TEA."
|
||||
requires-python = ">=3.11"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"flask>=3.0",
|
||||
"persistance",
|
||||
"models",
|
||||
"indicadores-kit",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Lo común de las pruebas de indicadores de CaCu y CaMa."""
|
||||
|
||||
import pytest
|
||||
|
||||
SEMESTRES = ["2025-S1", "2025-S2"]
|
||||
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||
|
||||
|
||||
def sembrar_base(proyecto: str, motor) -> None:
|
||||
"""La base de demostración del kit: staging sintético, carga y todos los indicadores calculados.
|
||||
|
||||
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para
|
||||
TEA: cada definición de `measures_de(proyecto)` queda calculada en los
|
||||
periodos de 2025 que publica (`SEMESTRES`, y los doce meses si publica
|
||||
meses).
|
||||
"""
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
|
||||
base_de_prueba(motor, proyecto)
|
||||
|
||||
|
||||
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,204 @@
|
||||
"""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=2024-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")
|
||||
|
||||
|
||||
# --- Todos los indicadores del proyecto ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura)
|
||||
|
||||
assert response.status_code == 200, (indicador, figura)
|
||||
assert set(response.get_json()) >= {"data", "layout"}
|
||||
|
||||
|
||||
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||
|
||||
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos"}
|
||||
|
||||
|
||||
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||
|
||||
|
||||
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||
|
||||
assert all(set(fila) == CATALOGO for fila in lista)
|
||||
fila = next(fila for fila in lista if fila["id"] == INDICADOR)
|
||||
medida = DEFINICIONES[INDICADOR]
|
||||
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||
assert fila["estratos"] == medida.extension.estratos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = _ruta(client, indicador, "periodos")
|
||||
datos = _ruta(client, indicador, "datos")
|
||||
metadatos = _ruta(client, indicador, "metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||
assert de_semestre == SEMESTRES
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||
|
||||
|
||||
def test_datos_con_meses(client):
|
||||
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["tipo_periodo"] == "mes"
|
||||
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||
|
||||
|
||||
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||
|
||||
(reporte,) = cuerpo["reportes"]
|
||||
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _ruta(client, INDICADOR, "datos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "ruta", "query"),
|
||||
[
|
||||
("NO_EXISTE", "datos", ""),
|
||||
("NO_EXISTE", "periodos", ""),
|
||||
("NO_EXISTE", "metadatos", ""),
|
||||
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||
],
|
||||
)
|
||||
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||
response = _ruta(client, indicador, ruta, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Rutas de indicadores de CAMA: 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 = "cama"
|
||||
INDICADOR = "cama_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"),
|
||||
[
|
||||
("CAMA_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=2024-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")
|
||||
|
||||
|
||||
# --- Todos los indicadores del proyecto ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura)
|
||||
|
||||
assert response.status_code == 200, (indicador, figura)
|
||||
assert set(response.get_json()) >= {"data", "layout"}
|
||||
|
||||
|
||||
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||
|
||||
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos"}
|
||||
|
||||
|
||||
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||
|
||||
|
||||
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||
|
||||
assert all(set(fila) == CATALOGO for fila in lista)
|
||||
fila = next(fila for fila in lista if fila["id"] == INDICADOR)
|
||||
medida = DEFINICIONES[INDICADOR]
|
||||
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||
assert fila["estratos"] == medida.extension.estratos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = _ruta(client, indicador, "periodos")
|
||||
datos = _ruta(client, indicador, "datos")
|
||||
metadatos = _ruta(client, indicador, "metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||
assert de_semestre == SEMESTRES
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||
|
||||
|
||||
def test_datos_con_meses(client):
|
||||
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["tipo_periodo"] == "mes"
|
||||
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||
|
||||
|
||||
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||
|
||||
(reporte,) = cuerpo["reportes"]
|
||||
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _ruta(client, INDICADOR, "datos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "ruta", "query"),
|
||||
[
|
||||
("NO_EXISTE", "datos", ""),
|
||||
("NO_EXISTE", "periodos", ""),
|
||||
("NO_EXISTE", "metadatos", ""),
|
||||
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||
],
|
||||
)
|
||||
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||
response = _ruta(client, indicador, ruta, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
@@ -0,0 +1,151 @@
|
||||
import pytest
|
||||
from indicadores_kit.registry.measures import measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
from indicadores_kit.tea import fixtures
|
||||
|
||||
DEFINICIONES = measures_de("tea")
|
||||
PERIODOS = ",".join(fixtures.PERIODOS)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""Una base de TEA temporal, con los 18 indicadores calculados, por `TEA_DATABASE_URL`."""
|
||||
# Dentro de la fixture: la configuración de Persistance se lee al importarla,
|
||||
# y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes.
|
||||
from persistance.db import get_tea_engine
|
||||
from persistance.settings import settings
|
||||
|
||||
ruta = tmp_path_factory.mktemp("tea") / "tea.db"
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
|
||||
get_tea_engine.cache_clear()
|
||||
try:
|
||||
fixtures.base_de_prueba(get_tea_engine())
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
get_tea_engine().dispose()
|
||||
get_tea_engine.cache_clear()
|
||||
|
||||
|
||||
def _figura(client, indicador: str, figura: str, query: str = ""):
|
||||
return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
|
||||
lista = response.get_json()
|
||||
assert [fila["id"] for fila in lista] == sorted(DEFINICIONES)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200, figura
|
||||
assert response.mimetype == "application/json"
|
||||
assert "data" in response.get_json()
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||
(figura,) = figuras_de(DEFINICIONES["K01_evaluacion_3_meses"])
|
||||
|
||||
response = _figura(client, "K01_evaluacion_3_meses", figura)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["K01_evaluacion_3_meses"].title
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=,",
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, "K01_evaluacion_3_meses", "fig_c1_grupos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("K99_no_existe", "fig_c1_grupos", ""),
|
||||
("K01_evaluacion_3_meses", "fig_c2_apiladas", ""), # figura de otro contrato
|
||||
("K01_evaluacion_3_meses", "fig_no_existe", ""),
|
||||
("K01_evaluacion_3_meses", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte
|
||||
("K01_evaluacion_3_meses", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"),
|
||||
],
|
||||
)
|
||||
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_paciente_por_id_entero(client):
|
||||
response = client.get("/tea/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "T-01"
|
||||
|
||||
assert client.get("/tea/pacientes/abc").status_code == 404
|
||||
|
||||
|
||||
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, "K01_evaluacion_3_meses", "fig_c1_grupos", "?periodos=2025-S1")
|
||||
|
||||
|
||||
# --- Los periodos, los datos y los metadatos ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = client.get(f"/tea/indicadores/{indicador}/periodos")
|
||||
datos = client.get(f"/tea/indicadores/{indicador}/datos?periodos={PERIODOS}")
|
||||
metadatos = client.get(f"/tea/indicadores/{indicador}/metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert [p["periodo"] for p in periodos.get_json()["periodos"]] == sorted(fixtures.PERIODOS)
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["id"], cuerpo["contrato"]) == (indicador, medida.extension.contrato)
|
||||
assert cuerpo["filas"] and {fila["periodo"] for fila in cuerpo["filas"]} == set(fixtures.PERIODOS)
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["ficha"]["codigo"] == medida.extension.ficha.codigo
|
||||
|
||||
|
||||
def test_los_grupos_de_los_datos_van_en_el_orden_de_la_ficha(client):
|
||||
response = client.get(f"/tea/indicadores/K01_evaluacion_3_meses/datos?periodos={PERIODOS}")
|
||||
|
||||
grupos = list(response.get_json()["grupos"])
|
||||
assert grupos != sorted(grupos) # el orden de la ficha, no el alfabético
|
||||
assert grupos[-1] == "TOTAL"
|
||||
@@ -2,9 +2,13 @@ from flask import Blueprint, jsonify
|
||||
|
||||
from models.cacu import CaCuModel
|
||||
from persistance.cacu import paciente_repository
|
||||
from persistance.db import get_cacu_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cacu_bp = Blueprint("cacu", __name__)
|
||||
|
||||
registrar_indicadores(cacu_bp, "cacu", get_cacu_session)
|
||||
|
||||
|
||||
@cacu_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
|
||||
@@ -2,9 +2,13 @@ from flask import Blueprint, jsonify
|
||||
|
||||
from models.cama import CaMaModel
|
||||
from persistance.cama import paciente_repository
|
||||
from persistance.db import get_cama_session
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
cama_bp = Blueprint("cama", __name__)
|
||||
|
||||
registrar_indicadores(cama_bp, "cama", get_cama_session)
|
||||
|
||||
|
||||
@cama_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
from flask import Blueprint, jsonify
|
||||
|
||||
from models.tea import TeaModel
|
||||
from persistance.db import get_tea_session
|
||||
from persistance.tea import pacientes_repository
|
||||
from webapi.indicadores import registrar_indicadores
|
||||
|
||||
tea_bp = Blueprint("tea", __name__)
|
||||
|
||||
registrar_indicadores(tea_bp, "tea", get_tea_session)
|
||||
|
||||
@tea_bp.get("/pacientes/<string:pac_id>")
|
||||
def get_paciente(pac_id: str):
|
||||
|
||||
@tea_bp.get("/pacientes/<int:pac_id>")
|
||||
def get_paciente(pac_id: int):
|
||||
paciente = pacientes_repository.get(pac_id)
|
||||
if paciente is None:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Las rutas de indicadores, iguales para cada proyecto (CaCu, CaMa, TEA).
|
||||
|
||||
`registrar_indicadores` agrega a un blueprint:
|
||||
|
||||
GET /indicadores catálogo de indicadores
|
||||
GET /indicadores/<id>/periodos periodos con reporte
|
||||
GET /indicadores/<id>/datos?periodos=&estrato= los números, sin figura
|
||||
GET /indicadores/<id>/metadatos ficha metodológica
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
|
||||
Las definiciones salen del kit (`measures_de`), los datos de
|
||||
`indicadores_kit.serving.datos` y las figuras de
|
||||
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||
se traducen los errores a códigos HTTP. La forma de cada respuesta es un
|
||||
contrato con el frontend: no se quita ni se renombra un campo.
|
||||
"""
|
||||
|
||||
import json
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.registry.measures import Measure, measures_de
|
||||
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.figuras import TEMAS, figura_json, figuras_de, periodos_con_reporte
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from sqlmodel import Session
|
||||
|
||||
# Cómo se escribe un periodo de cada tipo (`registry/periodos.py`) y un ejemplo para el mensaje.
|
||||
FORMATOS = {
|
||||
"dia": (re.compile(r"\d{4}-\d{2}-\d{2}"), "AAAA-MM-DD"),
|
||||
"semana_epidemiologica": (re.compile(r"\d{4}-SE\d{2}"), "AAAA-SEnn"),
|
||||
"semana_habil": (re.compile(r"\d{4}-SH\d{2}"), "AAAA-SHnn"),
|
||||
"semana_iso": (re.compile(r"\d{4}-W\d{2}"), "AAAA-Wnn"),
|
||||
"mes": (re.compile(r"\d{4}-\d{2}"), "AAAA-MM"),
|
||||
"bimestre": (re.compile(r"\d{4}-B[1-6]"), "AAAA-B1 a AAAA-B6"),
|
||||
"trimestre": (re.compile(r"\d{4}-T[1-4]"), "AAAA-T1 a AAAA-T4"),
|
||||
"semestre": (re.compile(r"\d{4}-S[12]"), "AAAA-S1 o AAAA-S2"),
|
||||
}
|
||||
|
||||
|
||||
def _error(mensaje: str, codigo: int):
|
||||
return jsonify({"error": mensaje}), codigo
|
||||
|
||||
|
||||
def _json(contenido) -> Response:
|
||||
"""Sin `jsonify`, que ordena las llaves: grupos y categorías van en su orden de presentación."""
|
||||
return Response(json.dumps(contenido, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
|
||||
def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||
"""El tipo, entre los que publica el indicador, al que pertenece el periodo (o `None`)."""
|
||||
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||
|
||||
|
||||
def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]:
|
||||
"""Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`.
|
||||
|
||||
Raises:
|
||||
ValueError: un periodo mal formado, de un tipo que el indicador no
|
||||
publica (`extension.publicacion.tipos_periodo`), o de tipos mezclados.
|
||||
"""
|
||||
if not texto:
|
||||
return [], None
|
||||
tipos = medida.extension.publicacion.tipos_periodo
|
||||
periodos = list(dict.fromkeys(texto.split(",")))
|
||||
encontrados = {_tipo_de(periodo, tipos) for periodo in periodos}
|
||||
if None in encontrados:
|
||||
formatos = "; ".join(FORMATOS[tipo][1] for tipo in tipos)
|
||||
raise ValueError(f"Periodos mal formados: {texto!r}; este indicador publica {formatos}.")
|
||||
if len(encontrados) > 1:
|
||||
raise ValueError(f"Periodos de tipos distintos: {texto!r}; pida un solo tipo a la vez.")
|
||||
return periodos, encontrados.pop()
|
||||
|
||||
|
||||
def registrar_indicadores(
|
||||
blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session]
|
||||
) -> None:
|
||||
"""Agrega las rutas de indicadores de `proyecto` al blueprint.
|
||||
|
||||
`get_session` es la fábrica de `Persistance` (`get_<proyecto>_session`):
|
||||
se llama en cada petición, no al registrar.
|
||||
"""
|
||||
definiciones = measures_de(proyecto) # fijas: se leen una vez
|
||||
tablas = tablas_de(proyecto)
|
||||
|
||||
def listar_indicadores():
|
||||
return _json([resumen_de(id_, medida) for id_, medida in definiciones.items()])
|
||||
|
||||
def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]:
|
||||
"""Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica."""
|
||||
if periodos:
|
||||
return periodos
|
||||
tipo = medida.extension.publicacion.tipos_periodo[0]
|
||||
return periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo)
|
||||
|
||||
def get_periodos(indicador: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
sesion = get_session()
|
||||
try:
|
||||
periodos = periodos_de(sesion, medida, tablas=tablas)
|
||||
finally:
|
||||
sesion.close()
|
||||
return _json({"id": indicador, "version": medida.version, "periodos": periodos})
|
||||
|
||||
def get_metadatos(indicador: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
sesion = get_session()
|
||||
try:
|
||||
metadatos = metadatos_de(sesion, medida, tablas=tablas)
|
||||
finally:
|
||||
sesion.close()
|
||||
return _json({"id": indicador, **metadatos})
|
||||
|
||||
def get_datos(indicador: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
estrato = request.args.get("estrato") or None
|
||||
if estrato is not None and estrato not in medida.extension.estratos:
|
||||
return _error(
|
||||
f"estrato desconocido {estrato!r}; este indicador tiene {medida.extension.estratos}",
|
||||
400,
|
||||
)
|
||||
try:
|
||||
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
sesion = get_session()
|
||||
try:
|
||||
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
except LookupError as error:
|
||||
return _error(str(error), 404)
|
||||
finally:
|
||||
sesion.close()
|
||||
return _json({"id": indicador, **datos})
|
||||
|
||||
def get_figura(indicador: str, figura: str):
|
||||
medida = definiciones.get(indicador)
|
||||
if medida is None:
|
||||
return _error("indicador desconocido", 404)
|
||||
if figura not in figuras_de(medida):
|
||||
return _error(
|
||||
f"figura {figura!r} no es del contrato {medida.extension.contrato}", 404
|
||||
)
|
||||
|
||||
tema = request.args.get("tema", "claro")
|
||||
if tema not in TEMAS:
|
||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||
try:
|
||||
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
sesion = get_session()
|
||||
try:
|
||||
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
except LookupError as error:
|
||||
return _error(str(error), 404)
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(texto, mimetype="application/json")
|
||||
|
||||
blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/periodos", "get_periodos", get_periodos)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/datos", "get_datos", get_datos)
|
||||
blueprint.add_url_rule("/indicadores/<indicador>/metadatos", "get_metadatos", get_metadatos)
|
||||
blueprint.add_url_rule(
|
||||
"/indicadores/<indicador>/figuras/<figura>", "get_figura", get_figura
|
||||
)
|
||||
Reference in New Issue
Block a user