Compare commits

..

8 Commits

Author SHA1 Message Date
edgar 4c8f3e620e Notebook de las rutas de indicadores de CaMa
Siembra CaCu, CaMa y TEA en bases temporales, revisa la lista, una figura por
semestre y por mes, los errores 400 y 404, y que /cacu y /tea siguen igual.

Pruebas: Core 25 passed; Persistance 31 passed; indicadores_kit 564 passed, 2 skipped; WebApi 74 passed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 06:29:26 +00:00
edgar 7577c99c62 Rutas de indicadores de CaMa: /cama sirve lo mismo que /cacu y /tea
CaMa registra registrar_indicadores en su blueprint. Pruebas de CaMa con SQLite
temporal sembrada con los fixtures del kit. README al día.

Pruebas: Core 25 passed; Persistance 31 passed; indicadores_kit 564 passed, 2 skipped; WebApi 74 passed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 06:29:26 +00:00
edgar a188bf66e1 Notebook de las rutas de indicadores de CaCu
Siembra una base temporal, levanta la app con el cliente de pruebas y revisa
la lista, una figura por semestre y por mes, y los errores 400 y 404.

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>
2026-10-11 06:29:04 +00:00
edgar cca67c837d 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>
2026-10-11 06:28:38 +00:00
edgar d76cb6cb20 README: una sola TEA_DATABASE_URL absoluta y pasos para cargar datos y calcular reportes antes de pedir figuras 2026-10-09 16:58:43 +00:00
edgar 84da0eb5fb Documentación: README de WebApi (estructura, flujo, rutas, cómo extender) 2026-10-09 04:07:16 +00:00
edgar ceca8a03b5 TEA: un KeyError interno de la figura no se vuelve 404
KeyError es subclase de LookupError. El except LookupError de la ruta
convertía cualquier error interno del kit en un 404 con su mensaje. Ahora
solo un periodo sin reporte da 404; lo demás es un error del servidor.
2026-10-09 02:23:34 +00:00
edgar 0355d21d47 WebApi: rutas de TEA con figuras del kit
- Dependencia editable indicadores-kit y Python >=3.12 (el kit lo pide).
- Dockerfile copia indicadores_kit/.
- GET /tea/indicadores y GET /tea/indicadores/<id>/figuras/<figura>
  (periodos y tema opcionales; 400 y 404 con {"error": ...}).
- GET /tea/pacientes/<int:pac_id>.
- Pruebas de TEA con base temporal por TEA_DATABASE_URL.
2026-10-09 01:59:37 +00:00
22 changed files with 2161 additions and 884 deletions
+2 -2
View File
@@ -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
@@ -16,7 +17,6 @@ RUN cd WebApi && uv sync --no-dev
ENV CACU_DATABASE_URL=sqlite:////data/cacu.db
ENV CAMA_DATABASE_URL=sqlite:////data/cama.db
ENV TEA_DATABASE_URL=sqlite:////data/tea.db
ENV AUTH_DATABASE_URL=sqlite:////data/auth.db
RUN chmod +x /app/WebApi/docker-entrypoint.sh
+289
View File
@@ -0,0 +1,289 @@
# 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 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 `/indicadores` 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")
```
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>/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/cacu/indicadores
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`,
`contrato`, `figuras` 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`) |
## 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()`.
-25
View File
@@ -1,24 +1,6 @@
#!/bin/sh
set -e
case "${AUTH_LITE_ENABLED-false}" in
true|false)
;;
*)
echo "AUTH_LITE_ENABLED must be exactly 'true' or 'false'" >&2
exit 1
;;
esac
case "${AUTH_LITE_SEED_DEMO_USERS-false}" in
true|false)
;;
*)
echo "AUTH_LITE_SEED_DEMO_USERS must be exactly 'true' or 'false'" >&2
exit 1
;;
esac
mkdir -p /data
cd /app/Persistance
@@ -26,12 +8,5 @@ uv run alembic -c persistance/cacu/alembic.ini upgrade head
uv run alembic -c persistance/cama/alembic.ini upgrade head
uv run alembic -c persistance/tea/alembic.ini upgrade head
if [ "${AUTH_LITE_ENABLED-false}" = "true" ]; then
uv run alembic -c persistance/auth/alembic.ini upgrade head
fi
cd /app/WebApi
if [ "${AUTH_LITE_ENABLED-false}" = "true" ] && [ "${AUTH_LITE_SEED_DEMO_USERS-false}" = "true" ]; then
uv run python -m webapi.auth_demo_seed --ensure
fi
exec uv run python main.py
+59
View File
@@ -0,0 +1,59 @@
"""Apoyo de los notebooks: montar la base de un dominio en una carpeta temporal.
Hace lo mismo que el fixture `base_del_dominio` de `tests/test_produccion.py`:
apunta Persistance a un archivo SQLite, migra con Alembic y llena el
staging con los fixtures del kit. Desde ahí, los pasos de
`indicadores_kit.pasos` corren por el camino de producción (repositorios
de Persistance). No es parte del paquete.
"""
from pathlib import Path
import persistance
import persistance.db
from alembic import command
from alembic.config import Config
from persistance.settings import settings
from indicadores_kit.cacu import fixtures as fixtures_cacu
from indicadores_kit.cama import fixtures as fixtures_cama
from indicadores_kit.pasos import fabrica_por_defecto
from indicadores_kit.registry.parametros import RUTA_PARAMETROS
FIXTURES = {"cacu": fixtures_cacu, "cama": fixtures_cama}
MOTORES = (
persistance.db.get_cacu_engine,
persistance.db.get_cama_engine,
persistance.db.get_tea_engine,
)
def montar(proyecto: str, carpeta: Path) -> str:
"""La base del proyecto en `carpeta`, migrada y con staging sintético. Devuelve su URL.
Es lo que hacen `<PROYECTO>_DATABASE_URL` y `alembic upgrade head`.
El ajuste se cambia en memoria porque Persistance lo lee al importarse.
"""
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
setattr(settings, f"{proyecto}_database_url", url)
for motor in MOTORES:
motor.cache_clear()
alembic_ini = Path(persistance.__file__).parent / proyecto / "alembic.ini"
command.upgrade(Config(str(alembic_ini)), "head")
with fabrica_por_defecto(proyecto)() as sesion:
FIXTURES[proyecto].insertar(sesion)
return url
def parametros_sin_supresion(carpeta: Path) -> Path:
"""Una copia de `parametros.toml` con el umbral de supresión en 1.
Con 4 o 5 pacientes por periodo, el umbral de 5 ocultaría casi todo.
Es lo que hacen las pruebas de producción.
"""
ruta = carpeta / "parametros.toml"
ruta.write_text(
RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"),
encoding="utf-8",
)
return ruta
+544
View File
@@ -0,0 +1,544 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "f0fbce7e",
"metadata": {},
"source": [
"**Qué revisa este notebook.** Las rutas de indicadores de CaCu (tarea WA-2), el análogo de las de TEA: `webapi/indicadores.py` registra en el blueprint `/cacu`\n",
"\n",
"| Ruta | Qué devuelve |\n",
"|---|---|\n",
"| `GET /cacu/indicadores` | id, título, contrato, figuras y tipos de periodo que publica cada indicador |\n",
"| `GET /cacu/indicadores/<id>/figuras/<figura>?periodos=&tema=` | JSON de Plotly; 404 si el indicador, la figura o el reporte no existen; 400 si el tema o los periodos están mal |\n",
"\n",
"Por qué: antes solo TEA servía indicadores y su lógica vivía en su blueprint; ahora es un solo código para todos los proyectos. Los periodos se validan contra los `tipos_periodo` que publica la definición (semestre `AAAA-S1`, mes `AAAA-MM`).\n",
"\n",
"Todo corre en una carpeta temporal, con la app de Flask dentro del proceso (cliente de pruebas, sin servidor); no deja archivos en el repositorio. Cada sección termina en `assert`."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "2335c99f",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:28:58.077856Z",
"iopub.status.busy": "2026-10-11T06:28:58.076999Z",
"iopub.status.idle": "2026-10-11T06:28:58.933116Z",
"shell.execute_reply": "2026-10-11T06:28:58.932355Z"
}
},
"outputs": [],
"source": [
"import tempfile\n",
"from datetime import date\n",
"from pathlib import Path\n",
"\n",
"import pandas as pd\n",
"\n",
"import apoyo\n",
"from indicadores_kit.pasos import calcular_periodos, cargar, fabrica_por_defecto, preparar_registro, vistas\n",
"from indicadores_kit.registry.measures import leer_measure, ruta_de_measure\n",
"\n",
"carpeta = Path(tempfile.mkdtemp(prefix=\"cacu_ind_\"))\n",
"parametros = apoyo.parametros_sin_supresion(carpeta)\n",
"\n",
"\n",
"def sembrar(proyecto):\n",
" \"\"\"Base migrada con staging sintético, cargada, con `<proyecto>_eu8` calculado en semestres y meses.\"\"\"\n",
" apoyo.montar(proyecto, carpeta)\n",
" cargar(proyecto)\n",
" vistas(fabrica_por_defecto(proyecto), proyecto)\n",
" preparar_registro(proyecto, 2025, 2025, ruta=parametros, tipos=(\"semestre\", \"mes\"))\n",
" medida = leer_measure(ruta_de_measure(proyecto, f\"{proyecto}_eu8\"))\n",
" return {\n",
" tipo: len(calcular_periodos(proyecto, medida, tipo, date(2025, 1, 1), date(2026, 1, 1), permitir_sin_definir=True))\n",
" for tipo in (\"semestre\", \"mes\")\n",
" }"
]
},
{
"cell_type": "markdown",
"id": "e0e2fd4c",
"metadata": {},
"source": [
"## 1. Sembrar y calcular\n",
"\n",
"`apoyo.montar` apunta Persistance a un SQLite temporal, migra con Alembic y llena el staging con los fixtures del kit. Luego los pasos del kit: carga, vistas, `dim_periodo` con semestres y meses, y el cálculo en los dos tipos de periodo."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "31755e66",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:28:58.934834Z",
"iopub.status.busy": "2026-10-11T06:28:58.934605Z",
"iopub.status.idle": "2026-10-11T06:28:59.262772Z",
"shell.execute_reply": "2026-10-11T06:28:59.262146Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Context impl SQLiteImpl.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Will assume non-transactional DDL.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade -> 79fe432d52a2, create cacu tables\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 79fe432d52a2 -> cbb31acf322d, add biometria hematica\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade cbb31acf322d -> 9952833a0048, add indicadores_kit tables\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 9952833a0048 -> b4a35a200913, add dim_fecha and dim_grupo_edad\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade b4a35a200913 -> 04fa57d42fec, add indicador_definicion\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 04fa57d42fec -> 1b350354d5ed, add measure_report.parametros_sha\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 1b350354d5ed -> cbd8fed23729, measure_report kit_version replaces sql_sha\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade cbd8fed23729 -> 8e7534131c73, add result tables\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>reportes calculados</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>semestre</th>\n",
" <td>2</td>\n",
" </tr>\n",
" <tr>\n",
" <th>mes</th>\n",
" <td>12</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" reportes calculados\n",
"semestre 2\n",
"mes 12"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"calculados = sembrar(\"cacu\")\n",
"assert calculados == {\"semestre\": 2, \"mes\": 12}\n",
"pd.Series(calculados, name=\"reportes calculados\").to_frame()"
]
},
{
"cell_type": "markdown",
"id": "3742a259",
"metadata": {},
"source": [
"## 2. Levantar la app"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "dd463639",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:28:59.264658Z",
"iopub.status.busy": "2026-10-11T06:28:59.264546Z",
"iopub.status.idle": "2026-10-11T06:28:59.539493Z",
"shell.execute_reply": "2026-10-11T06:28:59.539048Z"
}
},
"outputs": [],
"source": [
"from webapi import create_app\n",
"\n",
"app = create_app()\n",
"app.config.update(TESTING=True)\n",
"cliente = app.test_client()\n",
"assert cliente.get(\"/health\").status_code == 200"
]
},
{
"cell_type": "markdown",
"id": "dece2719",
"metadata": {},
"source": [
"## 3. `GET /cacu/indicadores`\n",
"\n",
"La lista sale de las definiciones del kit. CaCu no tiene ficha: su figura es un punto por periodo."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "bc5fe03c",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:28:59.541734Z",
"iopub.status.busy": "2026-10-11T06:28:59.541594Z",
"iopub.status.idle": "2026-10-11T06:28:59.549005Z",
"shell.execute_reply": "2026-10-11T06:28:59.548360Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>contrato</th>\n",
" <th>figuras</th>\n",
" <th>id</th>\n",
" <th>tipos_periodo</th>\n",
" <th>titulo</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>C1</td>\n",
" <td>[fig_c1_puntos]</td>\n",
" <td>cacu_eu8</td>\n",
" <td>[semestre, mes]</td>\n",
" <td>Tasa de referencia a repetir citología</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" contrato figuras id tipos_periodo \\\n",
"0 C1 [fig_c1_puntos] cacu_eu8 [semestre, mes] \n",
"\n",
" titulo \n",
"0 Tasa de referencia a repetir citología "
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"respuesta = cliente.get(\"/cacu/indicadores\")\n",
"assert respuesta.status_code == 200\n",
"(fila,) = respuesta.get_json()\n",
"assert fila[\"id\"] == \"cacu_eu8\"\n",
"assert fila[\"contrato\"] == \"C1\" and fila[\"figuras\"] == [\"fig_c1_puntos\"]\n",
"assert fila[\"tipos_periodo\"] == [\"semestre\", \"mes\"]\n",
"pd.DataFrame([fila])"
]
},
{
"cell_type": "markdown",
"id": "b04a81c8",
"metadata": {},
"source": [
"## 4. Una figura por semestre y una por mes\n",
"\n",
"Sin `?periodos=` se usan los periodos con reporte del primer tipo que publica la definición (semestre). Con meses, se piden explícitos."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "91e6686f",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:28:59.550578Z",
"iopub.status.busy": "2026-10-11T06:28:59.550464Z",
"iopub.status.idle": "2026-10-11T06:28:59.791898Z",
"shell.execute_reply": "2026-10-11T06:28:59.791286Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"(['2025-S1', '2025-S2'], ['2025-01', '2025-02', '2025-03'])"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def eje_x(respuesta):\n",
" return sorted({x for trazo in respuesta.get_json()[\"data\"] for x in trazo[\"x\"]})\n",
"\n",
"base = \"/cacu/indicadores/cacu_eu8/figuras/fig_c1_puntos\"\n",
"semestres = cliente.get(base)\n",
"assert semestres.status_code == 200 and semestres.mimetype == \"application/json\"\n",
"assert eje_x(semestres) == [\"2025-S1\", \"2025-S2\"]\n",
"meses = cliente.get(base + \"?periodos=2025-01,2025-02,2025-03&tema=oscuro\")\n",
"assert meses.status_code == 200\n",
"assert eje_x(meses) == [\"2025-01\", \"2025-02\", \"2025-03\"]\n",
"eje_x(semestres), eje_x(meses)"
]
},
{
"cell_type": "markdown",
"id": "a0cc37ed",
"metadata": {},
"source": [
"## 5. Los errores\n",
"\n",
"400: tema o periodos mal formados, un tipo que el indicador no publica o tipos mezclados. 404: indicador o figura desconocidos, o un periodo sin reporte."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "3293057d",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:28:59.793886Z",
"iopub.status.busy": "2026-10-11T06:28:59.793756Z",
"iopub.status.idle": "2026-10-11T06:28:59.804684Z",
"shell.execute_reply": "2026-10-11T06:28:59.804012Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>caso</th>\n",
" <th>código</th>\n",
" <th>error</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>tema desconocido</td>\n",
" <td>400</td>\n",
" <td>tema desconocido 'rojo'; use claro u oscuro</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>periodo mal formado</td>\n",
" <td>400</td>\n",
" <td>Periodos mal formados: '2025-1'; este indicado...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>tipo que no publica</td>\n",
" <td>400</td>\n",
" <td>Periodos mal formados: '2025-T1'; este indicad...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>tipos mezclados</td>\n",
" <td>400</td>\n",
" <td>Periodos de tipos distintos: '2025-S1,2025-03'...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>indicador desconocido</td>\n",
" <td>404</td>\n",
" <td>indicador desconocido</td>\n",
" </tr>\n",
" <tr>\n",
" <th>5</th>\n",
" <td>figura de otro contrato</td>\n",
" <td>404</td>\n",
" <td>figura 'fig_c2_apiladas' no es del contrato C1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>6</th>\n",
" <td>semestre sin reporte</td>\n",
" <td>404</td>\n",
" <td>No hay reporte de cacu/CACU_EU8 0.1.0 para 203...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7</th>\n",
" <td>mes sin reporte</td>\n",
" <td>404</td>\n",
" <td>No hay reporte de cacu/CACU_EU8 0.1.0 para 203...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" caso código \\\n",
"0 tema desconocido 400 \n",
"1 periodo mal formado 400 \n",
"2 tipo que no publica 400 \n",
"3 tipos mezclados 400 \n",
"4 indicador desconocido 404 \n",
"5 figura de otro contrato 404 \n",
"6 semestre sin reporte 404 \n",
"7 mes sin reporte 404 \n",
"\n",
" error \n",
"0 tema desconocido 'rojo'; use claro u oscuro \n",
"1 Periodos mal formados: '2025-1'; este indicado... \n",
"2 Periodos mal formados: '2025-T1'; este indicad... \n",
"3 Periodos de tipos distintos: '2025-S1,2025-03'... \n",
"4 indicador desconocido \n",
"5 figura 'fig_c2_apiladas' no es del contrato C1 \n",
"6 No hay reporte de cacu/CACU_EU8 0.1.0 para 203... \n",
"7 No hay reporte de cacu/CACU_EU8 0.1.0 para 203... "
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"casos = {\n",
" \"tema desconocido\": (base + \"?tema=rojo\", 400),\n",
" \"periodo mal formado\": (base + \"?periodos=2025-1\", 400),\n",
" \"tipo que no publica\": (base + \"?periodos=2025-T1\", 400),\n",
" \"tipos mezclados\": (base + \"?periodos=2025-S1,2025-03\", 400),\n",
" \"indicador desconocido\": (\"/cacu/indicadores/NO_EXISTE/figuras/fig_c1_puntos\", 404),\n",
" \"figura de otro contrato\": (\"/cacu/indicadores/cacu_eu8/figuras/fig_c2_apiladas\", 404),\n",
" \"semestre sin reporte\": (base + \"?periodos=2030-S1\", 404),\n",
" \"mes sin reporte\": (base + \"?periodos=2030-11\", 404),\n",
"}\n",
"filas = []\n",
"for nombre, (ruta, esperado) in casos.items():\n",
" respuesta = cliente.get(ruta)\n",
" assert respuesta.status_code == esperado, (nombre, respuesta.status_code)\n",
" assert \"error\" in respuesta.get_json()\n",
" filas.append({\"caso\": nombre, \"código\": respuesta.status_code, \"error\": respuesta.get_json()[\"error\"]})\n",
"pd.DataFrame(filas)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.14.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+692
View File
@@ -0,0 +1,692 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "08979bf1",
"metadata": {},
"source": [
"**Qué revisa este notebook.** Las rutas de indicadores de CaMa (tarea WA-2), el análogo de las de TEA: `webapi/indicadores.py` registra en el blueprint `/cama`\n",
"\n",
"| Ruta | Qué devuelve |\n",
"|---|---|\n",
"| `GET /cama/indicadores` | id, título, contrato, figuras y tipos de periodo que publica cada indicador |\n",
"| `GET /cama/indicadores/<id>/figuras/<figura>?periodos=&tema=` | JSON de Plotly; 404 si el indicador, la figura o el reporte no existen; 400 si el tema o los periodos están mal |\n",
"\n",
"Por qué: antes solo TEA servía indicadores y su lógica vivía en su blueprint; ahora es un solo código para todos los proyectos. Los periodos se validan contra los `tipos_periodo` que publica la definición (semestre `AAAA-S1`, mes `AAAA-MM`).\n",
"\n",
"Todo corre en una carpeta temporal, con la app de Flask dentro del proceso (cliente de pruebas, sin servidor); no deja archivos en el repositorio. Cada sección termina en `assert`."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "d5ad084c",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:12.636812Z",
"iopub.status.busy": "2026-10-11T06:29:12.636595Z",
"iopub.status.idle": "2026-10-11T06:29:13.532062Z",
"shell.execute_reply": "2026-10-11T06:29:13.531521Z"
}
},
"outputs": [],
"source": [
"import tempfile\n",
"from datetime import date\n",
"from pathlib import Path\n",
"\n",
"import pandas as pd\n",
"\n",
"import apoyo\n",
"from indicadores_kit.pasos import calcular_periodos, cargar, fabrica_por_defecto, preparar_registro, vistas\n",
"from indicadores_kit.registry.measures import leer_measure, ruta_de_measure\n",
"\n",
"carpeta = Path(tempfile.mkdtemp(prefix=\"cama_ind_\"))\n",
"parametros = apoyo.parametros_sin_supresion(carpeta)\n",
"\n",
"\n",
"def sembrar(proyecto):\n",
" \"\"\"Base migrada con staging sintético, cargada, con `<proyecto>_eu8` calculado en semestres y meses.\"\"\"\n",
" apoyo.montar(proyecto, carpeta)\n",
" cargar(proyecto)\n",
" vistas(fabrica_por_defecto(proyecto), proyecto)\n",
" preparar_registro(proyecto, 2025, 2025, ruta=parametros, tipos=(\"semestre\", \"mes\"))\n",
" medida = leer_measure(ruta_de_measure(proyecto, f\"{proyecto}_eu8\"))\n",
" return {\n",
" tipo: len(calcular_periodos(proyecto, medida, tipo, date(2025, 1, 1), date(2026, 1, 1), permitir_sin_definir=True))\n",
" for tipo in (\"semestre\", \"mes\")\n",
" }"
]
},
{
"cell_type": "markdown",
"id": "8a047caf",
"metadata": {},
"source": [
"## 1. Sembrar CaCu, CaMa y TEA\n",
"\n",
"CaMa es lo que se revisa; CaCu y TEA se siembran para comprobar al final que siguen respondiendo."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "2d1f6b64",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:13.534349Z",
"iopub.status.busy": "2026-10-11T06:29:13.534069Z",
"iopub.status.idle": "2026-10-11T06:29:14.164492Z",
"shell.execute_reply": "2026-10-11T06:29:14.163897Z"
}
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Context impl SQLiteImpl.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Will assume non-transactional DDL.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade -> 79fe432d52a2, create cacu tables\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 79fe432d52a2 -> cbb31acf322d, add biometria hematica\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade cbb31acf322d -> 9952833a0048, add indicadores_kit tables\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 9952833a0048 -> b4a35a200913, add dim_fecha and dim_grupo_edad\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade b4a35a200913 -> 04fa57d42fec, add indicador_definicion\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 04fa57d42fec -> 1b350354d5ed, add measure_report.parametros_sha\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 1b350354d5ed -> cbd8fed23729, measure_report kit_version replaces sql_sha\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade cbd8fed23729 -> 8e7534131c73, add result tables\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Context impl SQLiteImpl.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Will assume non-transactional DDL.\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade -> 61636717f659, create cama tables\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 61636717f659 -> c6939a6f23da, add biometria hematica\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade c6939a6f23da -> 0616858b7434, add indicadores_kit tables\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 0616858b7434 -> 1006aa43f896, add dim_fecha and dim_grupo_edad\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 1006aa43f896 -> b47d340c39f9, add indicador_definicion\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade b47d340c39f9 -> 2568e85ae55a, add measure_report.parametros_sha\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade 2568e85ae55a -> b3ef4834fd39, measure_report kit_version replaces sql_sha\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"INFO [alembic.runtime.migration] Running upgrade b3ef4834fd39 -> 4a8f75c95c04, add result tables\n"
]
},
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>cacu</th>\n",
" <th>cama</th>\n",
" </tr>\n",
" <tr>\n",
" <th>reportes por tipo</th>\n",
" <th></th>\n",
" <th></th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>semestre</th>\n",
" <td>2</td>\n",
" <td>2</td>\n",
" </tr>\n",
" <tr>\n",
" <th>mes</th>\n",
" <td>12</td>\n",
" <td>12</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" cacu cama\n",
"reportes por tipo \n",
"semestre 2 2\n",
"mes 12 12"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"calculados = {p: sembrar(p) for p in (\"cacu\", \"cama\")}\n",
"pd.DataFrame(calculados).rename_axis(\"reportes por tipo\")"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "4b139a71",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:14.166372Z",
"iopub.status.busy": "2026-10-11T06:29:14.166264Z",
"iopub.status.idle": "2026-10-11T06:29:16.964747Z",
"shell.execute_reply": "2026-10-11T06:29:16.963671Z"
}
},
"outputs": [],
"source": [
"assert calculados[\"cacu\"] == calculados[\"cama\"] == {\"semestre\": 2, \"mes\": 12}\n",
"\n",
"from indicadores_kit.tea import fixtures as fixtures_tea\n",
"from persistance.db import get_tea_engine\n",
"from persistance.settings import settings\n",
"\n",
"settings.tea_database_url = f\"sqlite:///{carpeta / 'tea.db'}\"\n",
"get_tea_engine.cache_clear()\n",
"assert len(fixtures_tea.base_de_prueba(get_tea_engine())) == 18"
]
},
{
"cell_type": "markdown",
"id": "26625d23",
"metadata": {},
"source": [
"## 2. Levantar la app"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "43b83c90",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:16.967133Z",
"iopub.status.busy": "2026-10-11T06:29:16.966937Z",
"iopub.status.idle": "2026-10-11T06:29:17.182927Z",
"shell.execute_reply": "2026-10-11T06:29:17.182429Z"
}
},
"outputs": [],
"source": [
"from webapi import create_app\n",
"\n",
"app = create_app()\n",
"app.config.update(TESTING=True)\n",
"cliente = app.test_client()\n",
"assert cliente.get(\"/health\").status_code == 200"
]
},
{
"cell_type": "markdown",
"id": "a4b9236d",
"metadata": {},
"source": [
"## 3. `GET /cama/indicadores`\n",
"\n",
"La lista sale de las definiciones del kit. CaMa no tiene ficha: su figura es un punto por periodo."
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "a7b6352a",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:17.185036Z",
"iopub.status.busy": "2026-10-11T06:29:17.184883Z",
"iopub.status.idle": "2026-10-11T06:29:17.193594Z",
"shell.execute_reply": "2026-10-11T06:29:17.192992Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>contrato</th>\n",
" <th>figuras</th>\n",
" <th>id</th>\n",
" <th>tipos_periodo</th>\n",
" <th>titulo</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>C1</td>\n",
" <td>[fig_c1_puntos]</td>\n",
" <td>cama_eu8</td>\n",
" <td>[semestre, mes]</td>\n",
" <td>Proporción de exámenes técnicamente aceptables</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" contrato figuras id tipos_periodo \\\n",
"0 C1 [fig_c1_puntos] cama_eu8 [semestre, mes] \n",
"\n",
" titulo \n",
"0 Proporción de exámenes técnicamente aceptables "
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"respuesta = cliente.get(\"/cama/indicadores\")\n",
"assert respuesta.status_code == 200\n",
"(fila,) = respuesta.get_json()\n",
"assert fila[\"id\"] == \"cama_eu8\"\n",
"assert fila[\"contrato\"] == \"C1\" and fila[\"figuras\"] == [\"fig_c1_puntos\"]\n",
"assert fila[\"tipos_periodo\"] == [\"semestre\", \"mes\"]\n",
"pd.DataFrame([fila])"
]
},
{
"cell_type": "markdown",
"id": "8c8c5a96",
"metadata": {},
"source": [
"## 4. Una figura por semestre y una por mes\n",
"\n",
"Sin `?periodos=` se usan los periodos con reporte del primer tipo que publica la definición (semestre). Con meses, se piden explícitos."
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "bdacb5d2",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:17.195892Z",
"iopub.status.busy": "2026-10-11T06:29:17.195747Z",
"iopub.status.idle": "2026-10-11T06:29:17.473353Z",
"shell.execute_reply": "2026-10-11T06:29:17.472652Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"(['2025-S1', '2025-S2'], ['2025-01', '2025-02', '2025-03'])"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"def eje_x(respuesta):\n",
" return sorted({x for trazo in respuesta.get_json()[\"data\"] for x in trazo[\"x\"]})\n",
"\n",
"base = \"/cama/indicadores/cama_eu8/figuras/fig_c1_puntos\"\n",
"semestres = cliente.get(base)\n",
"assert semestres.status_code == 200 and semestres.mimetype == \"application/json\"\n",
"assert eje_x(semestres) == [\"2025-S1\", \"2025-S2\"]\n",
"meses = cliente.get(base + \"?periodos=2025-01,2025-02,2025-03&tema=oscuro\")\n",
"assert meses.status_code == 200\n",
"assert eje_x(meses) == [\"2025-01\", \"2025-02\", \"2025-03\"]\n",
"eje_x(semestres), eje_x(meses)"
]
},
{
"cell_type": "markdown",
"id": "209f6915",
"metadata": {},
"source": [
"## 5. Los errores\n",
"\n",
"400: tema o periodos mal formados, un tipo que el indicador no publica o tipos mezclados. 404: indicador o figura desconocidos, o un periodo sin reporte."
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "3aaa513e",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:17.474906Z",
"iopub.status.busy": "2026-10-11T06:29:17.474786Z",
"iopub.status.idle": "2026-10-11T06:29:17.485833Z",
"shell.execute_reply": "2026-10-11T06:29:17.485313Z"
}
},
"outputs": [
{
"data": {
"text/html": [
"<div>\n",
"<style scoped>\n",
" .dataframe tbody tr th:only-of-type {\n",
" vertical-align: middle;\n",
" }\n",
"\n",
" .dataframe tbody tr th {\n",
" vertical-align: top;\n",
" }\n",
"\n",
" .dataframe thead th {\n",
" text-align: right;\n",
" }\n",
"</style>\n",
"<table border=\"1\" class=\"dataframe\">\n",
" <thead>\n",
" <tr style=\"text-align: right;\">\n",
" <th></th>\n",
" <th>caso</th>\n",
" <th>código</th>\n",
" <th>error</th>\n",
" </tr>\n",
" </thead>\n",
" <tbody>\n",
" <tr>\n",
" <th>0</th>\n",
" <td>tema desconocido</td>\n",
" <td>400</td>\n",
" <td>tema desconocido 'rojo'; use claro u oscuro</td>\n",
" </tr>\n",
" <tr>\n",
" <th>1</th>\n",
" <td>periodo mal formado</td>\n",
" <td>400</td>\n",
" <td>Periodos mal formados: '2025-1'; este indicado...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>2</th>\n",
" <td>tipo que no publica</td>\n",
" <td>400</td>\n",
" <td>Periodos mal formados: '2025-T1'; este indicad...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>3</th>\n",
" <td>tipos mezclados</td>\n",
" <td>400</td>\n",
" <td>Periodos de tipos distintos: '2025-S1,2025-03'...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>4</th>\n",
" <td>indicador desconocido</td>\n",
" <td>404</td>\n",
" <td>indicador desconocido</td>\n",
" </tr>\n",
" <tr>\n",
" <th>5</th>\n",
" <td>figura de otro contrato</td>\n",
" <td>404</td>\n",
" <td>figura 'fig_c2_apiladas' no es del contrato C1</td>\n",
" </tr>\n",
" <tr>\n",
" <th>6</th>\n",
" <td>semestre sin reporte</td>\n",
" <td>404</td>\n",
" <td>No hay reporte de cama/CAMA_EU8 0.1.0 para 203...</td>\n",
" </tr>\n",
" <tr>\n",
" <th>7</th>\n",
" <td>mes sin reporte</td>\n",
" <td>404</td>\n",
" <td>No hay reporte de cama/CAMA_EU8 0.1.0 para 203...</td>\n",
" </tr>\n",
" </tbody>\n",
"</table>\n",
"</div>"
],
"text/plain": [
" caso código \\\n",
"0 tema desconocido 400 \n",
"1 periodo mal formado 400 \n",
"2 tipo que no publica 400 \n",
"3 tipos mezclados 400 \n",
"4 indicador desconocido 404 \n",
"5 figura de otro contrato 404 \n",
"6 semestre sin reporte 404 \n",
"7 mes sin reporte 404 \n",
"\n",
" error \n",
"0 tema desconocido 'rojo'; use claro u oscuro \n",
"1 Periodos mal formados: '2025-1'; este indicado... \n",
"2 Periodos mal formados: '2025-T1'; este indicad... \n",
"3 Periodos de tipos distintos: '2025-S1,2025-03'... \n",
"4 indicador desconocido \n",
"5 figura 'fig_c2_apiladas' no es del contrato C1 \n",
"6 No hay reporte de cama/CAMA_EU8 0.1.0 para 203... \n",
"7 No hay reporte de cama/CAMA_EU8 0.1.0 para 203... "
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"casos = {\n",
" \"tema desconocido\": (base + \"?tema=rojo\", 400),\n",
" \"periodo mal formado\": (base + \"?periodos=2025-1\", 400),\n",
" \"tipo que no publica\": (base + \"?periodos=2025-T1\", 400),\n",
" \"tipos mezclados\": (base + \"?periodos=2025-S1,2025-03\", 400),\n",
" \"indicador desconocido\": (\"/cama/indicadores/NO_EXISTE/figuras/fig_c1_puntos\", 404),\n",
" \"figura de otro contrato\": (\"/cama/indicadores/cama_eu8/figuras/fig_c2_apiladas\", 404),\n",
" \"semestre sin reporte\": (base + \"?periodos=2030-S1\", 404),\n",
" \"mes sin reporte\": (base + \"?periodos=2030-11\", 404),\n",
"}\n",
"filas = []\n",
"for nombre, (ruta, esperado) in casos.items():\n",
" respuesta = cliente.get(ruta)\n",
" assert respuesta.status_code == esperado, (nombre, respuesta.status_code)\n",
" assert \"error\" in respuesta.get_json()\n",
" filas.append({\"caso\": nombre, \"código\": respuesta.status_code, \"error\": respuesta.get_json()[\"error\"]})\n",
"pd.DataFrame(filas)"
]
},
{
"cell_type": "markdown",
"id": "83cc8e7d",
"metadata": {},
"source": [
"## 6. CaCu y TEA siguen respondiendo\n",
"\n",
"El código es el mismo para los tres proyectos; el blueprint de CaMa no cambió a los otros."
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "277c2d8a",
"metadata": {
"execution": {
"iopub.execute_input": "2026-10-11T06:29:17.487716Z",
"iopub.status.busy": "2026-10-11T06:29:17.487598Z",
"iopub.status.idle": "2026-10-11T06:29:17.603918Z",
"shell.execute_reply": "2026-10-11T06:29:17.603263Z"
}
},
"outputs": [
{
"data": {
"text/plain": [
"404"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"cacu = cliente.get(\"/cacu/indicadores/cacu_eu8/figuras/fig_c1_puntos?periodos=2025-03\")\n",
"assert cacu.status_code == 200\n",
"lista = cliente.get(\"/tea/indicadores\").get_json()\n",
"assert len(lista) == 18\n",
"tea = next(f for f in lista if f[\"id\"] == \"K01_evaluacion_3_meses\")\n",
"figura = cliente.get(f\"/tea/indicadores/{tea['id']}/figuras/{tea['figuras'][0]}?periodos=2025-S1,2025-S2\")\n",
"assert figura.status_code == 200 and \"data\" in figura.get_json()\n",
"cliente.get(\"/cacu/indicadores/NO_EXISTE/figuras/fig_c1_puntos\").status_code"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.14.5"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
+3 -1
View File
@@ -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"]
+74
View File
@@ -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()
+13 -22
View File
@@ -7,38 +7,29 @@ import pytest
@pytest.fixture(scope="module")
def client():
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
isolation = pytest.MonkeyPatch()
isolation.setenv("CACU_DATABASE_URL", f"sqlite:///{db_path}")
isolation.setenv("AUTH_LITE_ENABLED", "false")
os.environ["CACU_DATABASE_URL"] = f"sqlite:///{db_path}"
from core.cacu.base import CaCuModel
from core.cacu.models import Paciente
from persistance.db import get_cacu_engine
from persistance.settings import settings
isolation.setattr(settings, "cacu_database_url", f"sqlite:///{db_path}")
get_cacu_engine.cache_clear()
engine = get_cacu_engine()
try:
CaCuModel.metadata.create_all(engine)
CaCuModel.metadata.create_all(engine)
from sqlmodel import Session
from sqlmodel import Session
with Session(engine) as session:
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino"))
session.commit()
with Session(engine) as session:
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino"))
session.commit()
from webapi import create_app
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as client:
yield client
finally:
engine.dispose()
get_cacu_engine.cache_clear()
os.unlink(db_path)
isolation.undo()
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as client:
yield client
os.unlink(db_path)
def test_health(client):
-500
View File
@@ -1,500 +0,0 @@
import json
from contextlib import closing
from pathlib import Path
import pytest
from alembic import command
from alembic.config import Config
from sqlalchemy import text
from werkzeug.security import check_password_hash, generate_password_hash
from persistance.db import get_auth_engine
from persistance.settings import settings
from webapi import create_app, parse_auth_lite_enabled
from webapi.auth_bootstrap import bootstrap, main
from webapi.auth_token import TOKEN_MAX_AGE, issue_token, serializer
ALEMBIC_INI = Path(__file__).resolve().parents[2] / "Persistance/persistance/auth/alembic.ini"
TEST_SECRET = "fictitious-test-secret-only"
TEST_PASSWORD = "fictitious-password-only"
@pytest.fixture
def storage(tmp_path, monkeypatch):
path = tmp_path / "auth.sqlite"
monkeypatch.setattr(settings, "auth_database_url", f"sqlite:///{path.as_posix()}")
monkeypatch.setenv("AUTH_LITE_ENABLED", "true")
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET)
get_auth_engine.cache_clear()
try:
command.upgrade(Config(str(ALEMBIC_INI)), "head")
yield path
finally:
if get_auth_engine.cache_info().currsize:
get_auth_engine().dispose()
get_auth_engine.cache_clear()
path.unlink(missing_ok=True)
assert not path.exists()
@pytest.fixture
def client(storage):
with get_auth_engine().begin() as connection:
connection.execute(text("INSERT INTO user(username,password_hash) VALUES (:name,:hash)"),
{"name": "sample.user", "hash": generate_password_hash(TEST_PASSWORD, method="scrypt")})
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (1,'TEA'),(1,'CAMA')"))
app = create_app()
app.config["TESTING"] = True
with app.test_client() as client:
yield client
def login(client, **changes):
return client.post("/auth/login", json={"username": "sample.user", "password": TEST_PASSWORD, **changes})
def bearer(token):
return {"Authorization": f"Bearer {token}"}
@pytest.mark.parametrize("value,expected", [(None, False), ("false", False), ("true", True)])
def test_flag(value, expected):
assert parse_auth_lite_enabled(value) is expected
@pytest.mark.parametrize("value", ["1", "0", "yes", "no", "on", "off", "TRUE", "False", "", " true "])
def test_invalid_flag(value, monkeypatch):
with pytest.raises(ValueError, match="AUTH_LITE_ENABLED"):
parse_auth_lite_enabled(value)
monkeypatch.setenv("AUTH_LITE_ENABLED", value)
with pytest.raises(ValueError, match="AUTH_LITE_ENABLED"):
create_app()
@pytest.mark.parametrize("flag", [None, "false"])
@pytest.mark.parametrize("isolated_config", ["none", "secret", "url"])
def test_disabled_never_touches_storage(flag, isolated_config, monkeypatch, tmp_path):
import persistance.db as db
import persistance.auth.repository as repository
from webapi import auth_token
def forbidden(*args, **kwargs):
pytest.fail("Auth storage was touched while disabled")
monkeypatch.delenv("AUTH_LITE_ENABLED", raising=False)
if flag is not None:
monkeypatch.setenv("AUTH_LITE_ENABLED", flag)
monkeypatch.delenv("AUTH_LITE_SECRET_KEY", raising=False)
monkeypatch.delenv("AUTH_DATABASE_URL", raising=False)
if isolated_config == "secret":
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET)
if isolated_config == "url":
monkeypatch.setenv("AUTH_DATABASE_URL", "invalid://unusable")
path = tmp_path / "never-created.sqlite"
monkeypatch.setattr(settings, "auth_database_url", f"sqlite:///{path.as_posix()}")
for name in ("get_auth_engine", "get_auth_session"):
monkeypatch.setattr(db, name, forbidden)
for name in ("get_user_by_username", "get_user_with_roles_by_id", "get_auth_session"):
monkeypatch.setattr(repository, name, forbidden)
monkeypatch.setattr(auth_token, "validate_auth_storage", forbidden)
from persistance.cacu import paciente_repository as cacu
from persistance.cama import paciente_repository as cama
from persistance.tea import pacientes_repository as tea
for repo in (cacu, cama, tea):
monkeypatch.setattr(repo, "get", lambda key: None)
app = create_app()
assert "auth" not in app.blueprints
assert {"cacu", "cama", "tea"} <= set(app.blueprints)
with app.test_client() as client:
assert client.get("/health").status_code == 200
assert client.post("/auth/login", json={}).status_code == 404
assert client.get("/auth/me").status_code == 404
for domain in ("cacu", "cama", "tea"):
response = client.get(f"/{domain}/pacientes/999")
assert response.status_code == 404
assert response.json == {"error": "not found"}
assert client.post(f"/{domain}/predict").status_code == 501
assert not path.exists()
@pytest.mark.parametrize("secret", [None, "", " "])
def test_enabled_requires_secret(storage, monkeypatch, secret):
monkeypatch.delenv("AUTH_LITE_SECRET_KEY", raising=False)
if secret is not None:
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", secret)
with pytest.raises(ValueError, match="AUTH_LITE_SECRET_KEY"):
create_app()
@pytest.mark.parametrize("kind", ["missing", "unmigrated", "corrupt", "invalid_url", "inaccessible"])
def test_enabled_requires_migrated_storage(tmp_path, monkeypatch, kind):
import sqlite3
monkeypatch.setenv("AUTH_LITE_ENABLED", "true")
monkeypatch.setenv("AUTH_LITE_SECRET_KEY", TEST_SECRET)
path = tmp_path / "unusable.sqlite"
if kind == "unmigrated":
with closing(sqlite3.connect(path)) as connection:
connection.execute("CREATE TABLE unrelated(id INTEGER)")
connection.commit()
elif kind == "corrupt":
path.write_text("not a database", encoding="utf-8")
elif kind == "inaccessible":
path = tmp_path / "missing-parent" / "unusable.sqlite"
url = "invalid://unusable" if kind == "invalid_url" else f"sqlite:///{path.as_posix()}"
monkeypatch.setattr(settings, "auth_database_url", url)
get_auth_engine.cache_clear()
try:
with pytest.raises(ValueError, match="accessible migrated SQLite"):
create_app()
if kind in ("missing", "inaccessible"):
assert not path.exists()
if kind == "unmigrated":
with closing(sqlite3.connect(path)) as connection:
assert connection.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall() == [("unrelated",)]
finally:
if get_auth_engine.cache_info().currsize:
get_auth_engine().dispose()
get_auth_engine.cache_clear()
path.unlink(missing_ok=True)
def test_login_and_me(client):
response = login(client, username=" SAMPLE.User ")
assert response.status_code == 200
body = response.json
assert set(body) == {"token", "expires_in", "user"}
assert body["expires_in"] == TOKEN_MAX_AGE
expected = {"id": 1, "username": "sample.user", "roles": ["CAMA", "TEA"]}
assert body["user"] == expected
assert serializer(TEST_SECRET).loads(body["token"]) == {"user_id": 1, "v": 1}
assert "password" not in json.dumps(body) and "hash" not in json.dumps(body)
assert response.headers["Cache-Control"] == "no-store"
me = client.get("/auth/me", headers=bearer(body["token"]))
assert me.status_code == 200 and me.json == {"user": expected}
assert me.headers["Cache-Control"] == "no-store"
@pytest.mark.parametrize("condition", ["missing", "wrong_password", "inactive"])
def test_generic_credentials(client, condition):
changes = {}
if condition == "missing":
changes["username"] = "absent.user"
elif condition == "wrong_password":
changes["password"] = "incorrect"
else:
with get_auth_engine().begin() as connection:
connection.execute(text("UPDATE user SET activo=0 WHERE id=1"))
response = login(client, **changes)
assert response.status_code == 401 and response.json == {"error": "invalid_credentials"}
assert response.headers["Cache-Control"] == "no-store"
@pytest.mark.parametrize("body", [None, [], "text", 1, {}, {"username": "sample.user"},
{"password": TEST_PASSWORD}, {"username": 1, "password": TEST_PASSWORD},
{"username": "sample.user", "password": []},
*[{"username": name, "password": TEST_PASSWORD} for name in ("", "ab", "bad!", "ábc", "x" * 65)],
{"username": "sample.user", "password": ""}, {"username": "sample.user", "password": "x" * 129}])
def test_invalid_login_body(client, body):
response = client.post("/auth/login", data=json.dumps(body), content_type="application/json")
assert response.status_code == 400 and response.json == {"error": "invalid_request"}
assert response.headers["Cache-Control"] == "no-store"
def test_no_json_and_malformed_json(client):
for kwargs in ({"data": "plain"}, {"data": "{", "content_type": "application/json"}):
response = client.post("/auth/login", **kwargs)
assert response.status_code == 400
assert response.headers["Cache-Control"] == "no-store"
@pytest.mark.parametrize("header", [None, "Basic abc", "Bearer", "Bearer ", "Bearer garbage", "Bearer a b"])
def test_bad_authorization(client, header):
response = client.get("/auth/me", headers={} if header is None else {"Authorization": header})
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
assert response.headers["Cache-Control"] == "no-store"
@pytest.mark.parametrize("payload", [None, [], 1, {}, {"user_id": 1}, {"user_id": 1, "v": 2},
{"user_id": 1, "v": True}, {"user_id": 1, "v": 1, "roles": []},
*[{"user_id": value, "v": 1} for value in (None, "1", True, 0, -1, 1.0, 2**63)]])
def test_bad_signed_payload(client, payload):
response = client.get("/auth/me", headers=bearer(serializer(TEST_SECRET).dumps(payload)))
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
def test_altered_and_wrong_secret(client):
token = issue_token(TEST_SECRET, 1)
pieces = token.split(".")
pieces[-1] = ("A" if pieces[-1][0] != "A" else "B") + pieces[-1][1:]
for invalid in (".".join(pieces), issue_token("different-fictitious-secret", 1)):
assert client.get("/auth/me", headers=bearer(invalid)).status_code == 401
def test_expired_deterministically(client, monkeypatch):
from itsdangerous import TimestampSigner
monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100000)
token = issue_token(TEST_SECRET, 1)
monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100000 + TOKEN_MAX_AGE)
assert client.get("/auth/me", headers=bearer(token)).status_code == 200
monkeypatch.setattr(TimestampSigner, "get_timestamp", lambda self: 100001 + TOKEN_MAX_AGE)
response = client.get("/auth/me", headers=bearer(token))
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
@pytest.mark.parametrize("change", ["inactive", "deleted", "roles"])
def test_me_revalidates(client, change):
token = login(client).json["token"]
with get_auth_engine().begin() as connection:
if change == "inactive":
connection.execute(text("UPDATE user SET activo=0 WHERE id=1"))
elif change == "deleted":
connection.execute(text("DELETE FROM user WHERE id=1"))
else:
connection.execute(text("DELETE FROM user_role WHERE user_id=1"))
connection.execute(text("INSERT INTO user_role(user_id,role_code) VALUES (1,'CACU')"))
response = client.get("/auth/me", headers=bearer(token))
if change == "roles":
assert response.status_code == 200 and response.json["user"]["roles"] == ["CACU"]
else:
assert response.status_code == 401 and response.json == {"error": "unauthorized"}
def test_enabled_clinical_routes_are_independent(client, monkeypatch):
from persistance.cacu import paciente_repository as cacu
from persistance.cama import paciente_repository as cama
from persistance.tea import pacientes_repository as tea
for domain, repo in (("cacu", cacu), ("cama", cama), ("tea", tea)):
monkeypatch.setattr(repo, "get", lambda key: None)
assert client.get(f"/{domain}/pacientes/999").status_code == 404
assert client.post(f"/{domain}/predict").status_code == 501
assert client.get("/health").status_code == 200
assert client.get("/auth/login").headers["Cache-Control"] == "no-store"
assert client.get("/auth/missing").headers["Cache-Control"] == "no-store"
def test_bootstrap_creation_repeat_and_update(storage, monkeypatch, capsys):
from webapi import auth_bootstrap
monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: TEST_PASSWORD)
assert main(["--username", " NEW.User ", "--roles", "TEA", "CAMA", "CAMA"]) == 0
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
user = get_user_by_username("new.user")
assert user.password_hash.startswith("scrypt:") and check_password_hash(user.password_hash, TEST_PASSWORD)
assert get_user_with_roles_by_id(user.id)[1] == ["CAMA", "TEA"]
old_hash = user.password_hash
assert main(["--username", "new.user", "--roles", "ADMIN"]) == 1
assert get_user_by_username("new.user").password_hash == old_hash
with get_auth_engine().begin() as connection:
connection.execute(text("UPDATE user SET activo=0 WHERE id=:id"), {"id": user.id})
new_password = "another-fictitious-password"
monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: new_password)
assert main(["--username", "new.user", "--roles", "ADMIN", "--update"]) == 0
updated = get_user_by_username("new.user")
assert updated.id == user.id and not updated.activo
assert check_password_hash(updated.password_hash, new_password)
assert get_user_with_roles_by_id(user.id)[1] == ["ADMIN"]
output = capsys.readouterr()
assert all(value not in output.out + output.err for value in (TEST_PASSWORD, new_password, old_hash, updated.password_hash))
@pytest.mark.parametrize("username,roles,password", [
("bad!", ["CAMA"], TEST_PASSWORD), (None, ["CAMA"], TEST_PASSWORD),
("good.user", [], TEST_PASSWORD), ("good.user", ["OTHER"], TEST_PASSWORD),
*[("good.user", ["CAMA"], value) for value in (None, "", "short", "x" * 129)]])
def test_bootstrap_invalid(storage, username, roles, password):
with pytest.raises(ValueError):
bootstrap(username, roles, password)
with get_auth_engine().connect() as connection:
assert connection.execute(text("SELECT count(*) FROM user")).scalar_one() == 0
def test_bootstrap_atomic_rollback(storage):
from sqlalchemy.exc import IntegrityError
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
user_id = bootstrap("atomic.user", ["CAMA"], TEST_PASSWORD)
original_hash = get_user_by_username("atomic.user").password_hash
with get_auth_engine().begin() as connection:
connection.execute(text("DELETE FROM role WHERE code='TEA'"))
for name, update in (("new.user", False), ("atomic.user", True)):
with pytest.raises(IntegrityError):
bootstrap(name, ["ADMIN", "TEA"], "different-fictitious-password", update=update)
assert get_user_by_username("new.user") is None
assert get_user_by_username("atomic.user").password_hash == original_hash
assert get_user_with_roles_by_id(user_id)[1] == ["CAMA"]
def test_bootstrap_cli_rejects_role_and_password_argument(storage):
for args in (["--username", "sample.user", "--roles", "OTHER"],
["--username", "sample.user", "--roles", "CAMA", "--password", "dummy"]):
with pytest.raises(SystemExit) as error:
main(args)
assert error.value.code == 2
def test_bootstrap_cli_invalid_password(storage, monkeypatch, capsys):
from webapi import auth_bootstrap
monkeypatch.setattr(auth_bootstrap, "getpass", lambda prompt: "short")
assert main(["--username", "sample.user", "--roles", "CAMA"]) == 1
assert "short" not in capsys.readouterr().out
# Fase J: all demo credentials are consumed from the single seed definition.
from webapi import auth_demo_seed as demo
def demo_snapshot():
with get_auth_engine().connect() as connection:
return (connection.execute(text("SELECT * FROM user ORDER BY id")).fetchall(),
connection.execute(text("SELECT * FROM user_role ORDER BY user_id,role_code")).fetchall())
def test_demo_definition():
accounts = demo.validate_demo_users()
assert [(a["username"], a["roles"]) for a in accounts] == [
("admin", ("ADMIN",)), ("cacu", ("CACU",)), ("cama", ("CAMA",)), ("tea", ("TEA",))]
def test_demo_ensure_hashes_roles_http_and_idempotence(storage, capsys):
assert demo.main(["--ensure"]) == 0
original = demo_snapshot()
assert len(original[0]) == 4
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
app = create_app()
with app.test_client() as client:
for account in demo.DEMO_USERS:
user = get_user_by_username(account["username"])
assert user.password_hash != account["password"]
assert user.password_hash.startswith("scrypt:")
assert check_password_hash(user.password_hash, account["password"])
assert get_user_with_roles_by_id(user.id)[1] == list(account["roles"])
response = client.post("/auth/login", json={"username": account["username"], "password": account["password"]})
assert response.status_code == 200
assert response.json["user"]["roles"] == list(account["roles"])
assert demo.main(["--ensure"]) == 0
assert demo_snapshot() == original
output = capsys.readouterr().out
assert output.count("-> created") == 4 and output.count("-> skipped") == 4
assert all(a["password"] not in output for a in demo.DEMO_USERS)
assert all(row.password_hash not in output for row in original[0])
@pytest.mark.parametrize("roles,active", [(["TEA"], True), (["CAMA", "TEA"], False), (["ADMIN"], False)])
def test_demo_partial_preserves_every_existing_field(storage, roles, active):
bootstrap(" ADMIN ", roles, TEST_PASSWORD)
with get_auth_engine().begin() as connection:
connection.execute(text("UPDATE user SET activo=:active WHERE username='admin'"), {"active": active})
original = demo_snapshot()
result = demo.seed_demo_users()
assert [r[2] for r in result] == ["skipped", "created", "created", "created"]
after = demo_snapshot()
assert after[0][0] == original[0][0]
assert [r for r in after[1] if r.user_id == original[0][0].id] == original[1]
assert check_password_hash(after[0][0].password_hash, TEST_PASSWORD)
def test_demo_normalizes_before_lookup(storage, monkeypatch):
bootstrap("admin", ["TEA"], TEST_PASSWORD)
monkeypatch.setattr(demo, "DEMO_USERS", tuple({**a, "username": f" {a['username'].upper()} "} for a in demo.DEMO_USERS))
result = demo.seed_demo_users()
assert result[0] == ("admin", ("ADMIN",), "skipped")
assert len(demo_snapshot()[0]) == 4
@pytest.mark.parametrize("invalid", [
{"username": "bad!"}, {"password": ""}, {"password": "short"},
{"roles": ()}, {"roles": ("OTHER",)}, {"roles": ("ADMIN", "ADMIN")},
{"roles": "ADMIN"}, {"roles": (None,)}, {"username": None},
])
@pytest.mark.parametrize("replace", [False, True])
def test_demo_invalid_configuration_never_changes_db(storage, monkeypatch, invalid, replace):
bootstrap("existing.user", ["TEA"], TEST_PASSWORD)
original = demo_snapshot()
monkeypatch.setattr(demo, "DEMO_USERS", (*demo.DEMO_USERS[:-1], {**demo.DEMO_USERS[-1], **invalid}))
with pytest.raises(ValueError):
demo.seed_demo_users(replace_all=replace)
assert demo_snapshot() == original
def test_demo_duplicate_normalized_username(storage, monkeypatch):
monkeypatch.setattr(demo, "DEMO_USERS", (*demo.DEMO_USERS, {**demo.DEMO_USERS[0], "username": " ADMIN "}))
with pytest.raises(ValueError, match="duplicate"):
demo.seed_demo_users()
assert demo_snapshot() == ([], [])
@pytest.mark.parametrize("replace", [False, True])
def test_demo_missing_roles_before_mutation(storage, replace):
bootstrap("existing.user", ["ADMIN"], TEST_PASSWORD)
with get_auth_engine().begin() as connection:
connection.execute(text("DELETE FROM role WHERE code='TEA'"))
original = demo_snapshot()
with pytest.raises(ValueError, match="roles are missing"):
demo.seed_demo_users(replace_all=replace)
assert demo_snapshot() == original
def test_demo_replace_confirmed_cascade_schema_and_output(storage, monkeypatch, capsys):
bootstrap("foreign.user", ["CAMA", "TEA"], TEST_PASSWORD)
monkeypatch.setattr("builtins.input", lambda prompt: "REPLACE")
with get_auth_engine().connect() as connection:
schema = connection.execute(text("SELECT name,sql FROM sqlite_master ORDER BY name")).fetchall()
version = connection.execute(text("SELECT * FROM alembic_version")).fetchall()
assert demo.main(["--replace-all"]) == 0
users, associations = demo_snapshot()
assert {r.username for r in users} == {a["username"] for a in demo.DEMO_USERS}
assert len(associations) == 4
with get_auth_engine().connect() as connection:
assert connection.execute(text("PRAGMA foreign_keys")).scalar_one() == 1
assert connection.execute(text("PRAGMA foreign_key_check")).fetchall() == []
assert connection.execute(text("SELECT name,sql FROM sqlite_master ORDER BY name")).fetchall() == schema
assert connection.execute(text("SELECT * FROM alembic_version")).fetchall() == version
assert connection.execute(text("SELECT count(*) FROM role")).scalar_one() == 4
assert storage.is_file()
output = capsys.readouterr().out
assert "WARNING" in output and "replaced" in output
assert all(a["password"] not in output for a in demo.DEMO_USERS)
@pytest.mark.parametrize("answer", ["", "replace", " REPLACE", "REPLACE ", "NO", None])
def test_demo_cancelled_before_storage(storage, monkeypatch, answer, capsys):
bootstrap("foreign.user", ["TEA"], TEST_PASSWORD)
original = demo_snapshot()
def confirm(prompt):
if answer is None:
raise EOFError
return answer
monkeypatch.setattr("builtins.input", confirm)
monkeypatch.setattr(demo, "validate_auth_storage", lambda: pytest.fail("cancel touched storage"))
assert demo.main(["--replace-all"]) == 0
assert demo_snapshot() == original
assert "cancelled" in capsys.readouterr().out
@pytest.mark.parametrize("replace", [False, True])
def test_demo_insert_failure_rolls_back_everything(storage, monkeypatch, replace):
from sqlmodel import Session
bootstrap("foreign.user", ["TEA", "CAMA"], TEST_PASSWORD)
original = demo_snapshot()
original_flush = Session.flush
calls = 0
def failing_flush(self, *args, **kwargs):
nonlocal calls
calls += 1
result = original_flush(self, *args, **kwargs)
if calls == 5:
raise RuntimeError("injected after mutation")
return result
monkeypatch.setattr(Session, "flush", failing_flush)
with pytest.raises(RuntimeError):
demo.seed_demo_users(replace_all=replace)
assert calls >= 5
assert demo_snapshot() == original
@pytest.mark.parametrize("mode", ["--ensure", "--replace-all"])
def test_demo_disabled_never_touches_storage(monkeypatch, mode, capsys):
monkeypatch.setenv("AUTH_LITE_ENABLED", "false")
monkeypatch.setenv("AUTH_LITE_SEED_DEMO_USERS", "true")
monkeypatch.setattr(demo, "validate_auth_storage", lambda: pytest.fail("disabled touched storage"))
monkeypatch.setattr("builtins.input", lambda prompt: pytest.fail("disabled requested confirmation"))
assert demo.main([mode]) == 0
assert "disabled" in capsys.readouterr().out
+110
View File
@@ -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")
+110
View File
@@ -0,0 +1,110 @@
"""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=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")
+123
View File
@@ -0,0 +1,123 @@
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):
(figura,) = figuras_de(DEFINICIONES[indicador])
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
assert response.status_code == 200
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")
+1 -28
View File
@@ -1,20 +1,10 @@
import os
from flask import Flask, request
from flask import Flask
from webapi.blueprints.cacu import cacu_bp
from webapi.blueprints.cama import cama_bp
from webapi.blueprints.tea import tea_bp
def parse_auth_lite_enabled(value: str | None) -> bool:
if value is None or value == "false":
return False
if value == "true":
return True
raise ValueError("AUTH_LITE_ENABLED must be exactly 'true' or 'false'")
def create_app() -> Flask:
app = Flask(__name__)
@@ -26,21 +16,4 @@ def create_app() -> Flask:
app.register_blueprint(cama_bp, url_prefix="/cama")
app.register_blueprint(tea_bp, url_prefix="/tea")
if parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")):
from webapi.auth_token import validate_auth_storage
from webapi.blueprints.auth import auth_bp
secret = os.environ.get("AUTH_LITE_SECRET_KEY")
if not secret or not secret.strip():
raise ValueError("AUTH_LITE_SECRET_KEY is required when Auth-Lite is enabled")
validate_auth_storage()
app.config["AUTH_LITE_SECRET_KEY"] = secret
app.register_blueprint(auth_bp, url_prefix="/auth")
@app.after_request
def auth_no_store(response):
if request.path == "/auth" or request.path.startswith("/auth/"):
response.headers["Cache-Control"] = "no-store"
return response
return app
-67
View File
@@ -1,67 +0,0 @@
"""Explicit interactive account bootstrap; never accepts a password argument."""
import argparse
from getpass import getpass
from sqlalchemy import delete
from sqlmodel import select
from werkzeug.security import generate_password_hash
from core.auth.models import User, UserRole
from persistance.db import get_auth_engine, get_auth_session
from webapi.auth_token import normalize_username, validate_auth_storage, validate_password
ALLOWED_ROLES = {"ADMIN", "CACU", "CAMA", "TEA"}
def bootstrap(username: str, roles: list[str], password: str, update: bool = False) -> int:
username = normalize_username(username)
validate_password(password, minimum=8)
if not roles or any(role not in ALLOWED_ROLES for role in roles):
raise ValueError("at least one role from ADMIN/CACU/CAMA/TEA is required")
validate_auth_storage()
with get_auth_session() as session:
with session.begin():
user = session.exec(select(User).where(User.username == username)).first()
if user is not None and not update:
raise ValueError("user already exists; use --update explicitly")
password_hash = generate_password_hash(password, method="scrypt")
if user is None:
user = User(username=username, password_hash=password_hash)
session.add(user)
session.flush()
else:
user.password_hash = password_hash
session.add(user)
session.exec(delete(UserRole).where(UserRole.user_id == user.id))
for role in sorted(set(roles)):
session.add(UserRole(user_id=user.id, role_code=role))
user_id = user.id
return user_id
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Bootstrap an Auth-Lite account interactively")
parser.add_argument("--username", required=True)
parser.add_argument("--roles", nargs="+", required=True, choices=sorted(ALLOWED_ROLES))
parser.add_argument("--update", action="store_true")
args = parser.parse_args(argv)
try:
username = normalize_username(args.username)
validate_auth_storage()
bootstrap(username, args.roles, getpass("Password: "), update=args.update)
print("Auth-Lite account saved.")
return 0
except ValueError as error:
print(str(error))
return 1
except Exception:
print("Auth-Lite bootstrap failed; transaction rolled back.")
return 1
finally:
if get_auth_engine.cache_info().currsize:
get_auth_engine().dispose()
get_auth_engine.cache_clear()
if __name__ == "__main__":
raise SystemExit(main())
-117
View File
@@ -1,117 +0,0 @@
"""Explicit, transactional demo account provisioning; never suitable for production."""
import argparse
import os
from sqlalchemy import delete
from sqlmodel import select
from werkzeug.security import generate_password_hash
from core.auth.models import Role, User, UserRole
from persistance.db import get_auth_engine, get_auth_session
from webapi import parse_auth_lite_enabled
from webapi.auth_bootstrap import ALLOWED_ROLES
from webapi.auth_token import normalize_username, validate_auth_storage, validate_password
# DEMO-ONLY credentials. These credentials are intentionally simple and public
# for demonstrations. Do not enable the demo seed in production.
DEMO_USERS = (
{"username": "admin", "password": "Admin1234", "roles": ("ADMIN",)},
{"username": "cacu", "password": "Cacu1234", "roles": ("CACU",)},
{"username": "cama", "password": "Cama1234", "roles": ("CAMA",)},
{"username": "tea", "password": "Tea12345", "roles": ("TEA",)},
)
def validate_demo_users():
"""Validate the entire editable definition, including skipped accounts."""
validated = []
usernames = set()
if not DEMO_USERS:
raise ValueError("demo configuration must contain accounts")
for entry in DEMO_USERS:
if not isinstance(entry, dict) or set(entry) != {"username", "password", "roles"}:
raise ValueError("invalid demo account definition")
username = normalize_username(entry["username"])
password = validate_password(entry["password"], minimum=8)
roles = entry["roles"]
if (not isinstance(roles, (tuple, list)) or not roles
or any(not isinstance(role, str) or role not in ALLOWED_ROLES for role in roles)
or len(set(roles)) != len(roles)):
raise ValueError("demo roles must be unique and from ADMIN/CACU/CAMA/TEA")
if username in usernames:
raise ValueError("duplicate normalized demo username")
usernames.add(username)
validated.append({"username": username, "password": password, "roles": tuple(roles)})
return validated
def seed_demo_users(*, replace_all: bool = False):
"""Complete missing accounts, or replace all, in one transaction.
The explicit CLI requires Auth enabled. The internal function is also usable
with migrated temporary storage in tests; it never creates/migrates storage.
"""
accounts = validate_demo_users()
validate_auth_storage()
results = []
with get_auth_session() as session:
with session.begin():
required = {role for account in accounts for role in account["roles"]}
if not required <= set(session.exec(select(Role.code))):
raise ValueError("required demo roles are missing; apply Auth migration first")
existing = set(session.exec(select(User.username)))
missing = accounts if replace_all else [a for a in accounts if a["username"] not in existing]
# Hash every new password before any delete/insert. No plaintext enters DB.
hashes = {a["username"]: generate_password_hash(a["password"], method="scrypt") for a in missing}
if replace_all:
session.exec(delete(User)) # FK ON DELETE CASCADE clears user_role.
for account in accounts:
username, roles = account["username"], account["roles"]
if username not in hashes:
results.append((username, roles, "skipped"))
continue
user = User(username=username, password_hash=hashes[username])
session.add(user)
session.flush()
for role in roles:
session.add(UserRole(user_id=user.id, role_code=role))
results.append((username, roles, "created"))
return results
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="DEMO ONLY: provision public Auth-Lite accounts")
modes = parser.add_mutually_exclusive_group(required=True)
modes.add_argument("--ensure", action="store_true", help="create only missing usernames")
modes.add_argument("--replace-all", action="store_true", help="delete EVERY Auth user; requires REPLACE")
args = parser.parse_args(argv)
try:
if not parse_auth_lite_enabled(os.environ.get("AUTH_LITE_ENABLED")):
print("Auth-Lite is disabled; demo seed skipped.")
return 0
if args.replace_all:
print("WARNING: this will delete every Auth-Lite user.")
try:
confirmation = input("Type REPLACE to continue: ")
except EOFError:
confirmation = ""
if confirmation != "REPLACE":
print("Auth-Lite demo replacement cancelled; no changes.")
return 0
results = seed_demo_users(replace_all=args.replace_all)
print("Auth-Lite demo users replaced." if args.replace_all else "Auth-Lite demo seed:")
for username, roles, status in results:
print(f"{username} [{','.join(roles)}] -> {status}")
return 0
except Exception:
# Editable configuration and DB exceptions may include sensitive values.
print("Auth-Lite demo seed failed; transaction rolled back. Check configuration and migrated storage.")
return 1
finally:
if get_auth_engine.cache_info().currsize:
get_auth_engine().dispose()
get_auth_engine.cache_clear()
if __name__ == "__main__":
raise SystemExit(main())
-76
View File
@@ -1,76 +0,0 @@
"""Auth-Lite token, input and explicit storage validation helpers."""
from pathlib import Path
import re
from itsdangerous import BadData, URLSafeTimedSerializer
from sqlalchemy import inspect
from sqlalchemy.engine import make_url
TOKEN_MAX_AGE = 28800
TOKEN_SALT = "auth-lite-session-v1"
def normalize_username(value: str) -> str:
if not isinstance(value, str):
raise ValueError("username must be a string")
value = value.strip().lower()
if not re.fullmatch(r"[a-z0-9._-]{3,64}", value):
raise ValueError("username must contain 3-64 characters from [a-z0-9._-]")
return value
def validate_password(value: str, minimum: int = 1) -> str:
if not isinstance(value, str) or not minimum <= len(value) <= 128:
raise ValueError(f"password must contain {minimum}-128 characters")
return value
def validate_auth_storage() -> None:
from persistance.db import get_auth_engine
from persistance.settings import settings
try:
url = make_url(settings.auth_database_url)
if url.get_backend_name() != "sqlite":
raise ValueError("SQLite required")
if not url.database or url.database == ":memory:" or not Path(url.database).is_file():
raise ValueError("existing SQLite required")
engine = get_auth_engine()
if not {"user", "role", "user_role", "alembic_version"} <= set(inspect(engine).get_table_names()):
raise ValueError("migration required")
# Validate the columns needed by login/bootstrap, without creating schema.
from sqlalchemy import text
with engine.connect() as connection:
connection.execute(text("SELECT id, username, password_hash, activo FROM user LIMIT 0"))
connection.execute(text("SELECT code FROM role LIMIT 0"))
connection.execute(text("SELECT user_id, role_code FROM user_role LIMIT 0"))
except Exception:
if get_auth_engine.cache_info().currsize:
get_auth_engine().dispose()
get_auth_engine.cache_clear()
raise ValueError("Auth-Lite storage must be an accessible migrated SQLite database") from None
def serializer(secret: str) -> URLSafeTimedSerializer:
return URLSafeTimedSerializer(secret, salt=TOKEN_SALT)
def issue_token(secret: str, user_id: int) -> str:
return serializer(secret).dumps({"user_id": user_id, "v": 1})
def read_token(secret: str, token: str) -> int | None:
try:
payload = serializer(secret).loads(token, max_age=TOKEN_MAX_AGE)
except BadData:
return None
if not isinstance(payload, dict) or set(payload) != {"user_id", "v"}:
return None
if type(payload["v"]) is not int or payload["v"] != 1:
return None
user_id = payload["user_id"]
return user_id if type(user_id) is int and 0 < user_id <= 9223372036854775807 else None
def user_dto(user, roles: list[str]) -> dict:
return {"id": user.id, "username": user.username, "roles": sorted(roles)}
-44
View File
@@ -1,44 +0,0 @@
from flask import Blueprint, current_app, request
from werkzeug.security import check_password_hash
from persistance.auth.repository import get_user_by_username, get_user_with_roles_by_id
from webapi.auth_token import (
TOKEN_MAX_AGE, issue_token, normalize_username, read_token, user_dto, validate_password,
)
auth_bp = Blueprint("auth", __name__)
@auth_bp.post("/login")
def login():
body = request.get_json(silent=True)
try:
if not isinstance(body, dict):
raise ValueError("JSON object required")
username = normalize_username(body.get("username"))
password = validate_password(body.get("password"))
except ValueError:
return {"error": "invalid_request"}, 400
user = get_user_by_username(username)
if user is None or not user.activo or not check_password_hash(user.password_hash, password):
return {"error": "invalid_credentials"}, 401
identity = get_user_with_roles_by_id(user.id)
if identity is None or not identity[0].activo:
return {"error": "invalid_credentials"}, 401
return {
"token": issue_token(current_app.config["AUTH_LITE_SECRET_KEY"], user.id),
"expires_in": TOKEN_MAX_AGE,
"user": user_dto(*identity),
}
@auth_bp.get("/me")
def me():
parts = request.headers.get("Authorization", "").split()
if len(parts) != 2 or parts[0].lower() != "bearer":
return {"error": "unauthorized"}, 401
user_id = read_token(current_app.config["AUTH_LITE_SECRET_KEY"], parts[1])
identity = get_user_with_roles_by_id(user_id) if user_id is not None else None
if identity is None or not identity[0].activo:
return {"error": "unauthorized"}, 401
return {"user": user_dto(*identity)}
+4
View File
@@ -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):
+4
View File
@@ -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):
+6 -2
View File
@@ -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
+127
View File
@@ -0,0 +1,127 @@
"""Las rutas de indicadores, iguales para cada proyecto (CaCu, CaMa, TEA).
`registrar_indicadores` agrega a un blueprint:
GET /indicadores lista de indicadores
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
Las definiciones salen del kit (`measures_de`) 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.
"""
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.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 _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 dos 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 jsonify(
[
{
"id": id_,
"titulo": medida.title,
"contrato": medida.extension.contrato,
"figuras": figuras_de(medida),
"tipos_periodo": medida.extension.publicacion.tipos_periodo,
}
for id_, medida in definiciones.items()
]
)
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:
if not periodos:
# El primer tipo que publica el indicador.
tipo = medida.extension.publicacion.tipos_periodo[0]
periodos = periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo)
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>/figuras/<figura>", "get_figura", get_figura
)