Compare commits
118 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9a62ddcdaf | |||
| 26f2b35338 | |||
| 0c1b383da2 | |||
| 7d06f9db9d | |||
| c86c530703 | |||
| 553d25fa54 | |||
| 6b8af821a3 | |||
| d35e8bbae9 | |||
| 7101913fff | |||
| 084fe2e8d3 | |||
| b1bbbc25b4 | |||
| 0571b5e6af | |||
| 0a7234f5ef | |||
| 9737b5a67f | |||
| 854a2e9c55 | |||
| b8045e7481 | |||
| 6dce665d93 | |||
| 461d651805 | |||
| 790879513b | |||
| 73cbf0cfb8 | |||
| 64d3d721e3 | |||
| cea74e1566 | |||
| 113b792a7b | |||
| f183e495fb | |||
| 9775a22c57 | |||
| 7d5c79f520 | |||
| e224b8b2aa | |||
| 205bc214fa | |||
| 4fc822d5c7 | |||
| 73b1db1121 | |||
| ea228da7b4 | |||
| e19121bc42 | |||
| 8f84253205 | |||
| ce67de17bc | |||
| e41a2b7127 | |||
| 0f9433949f | |||
| a0407e41d6 | |||
| 59fe94ad97 | |||
| edd12df144 | |||
| 96a29cfb19 | |||
| 7d0213eda7 | |||
| 1710cd5ca2 | |||
| 3c28a43cb1 | |||
| 21e6533dab | |||
| b9adedbf6f | |||
| 0cbe390b25 | |||
| c430a5bd11 | |||
| 270e229a51 | |||
| 82504bd0bf | |||
| 2296598896 | |||
| 0f00a975fa | |||
| f74ccf5496 | |||
| 72a8e76108 | |||
| 01ac568c22 | |||
| 429275547b | |||
| 28eba44e9c | |||
| fad503ef56 | |||
| b452a35759 | |||
| 1dcbb74247 | |||
| c7c4e01006 | |||
| 8499427650 | |||
| 70a018a8fb | |||
| fe9ba433ec | |||
| fce6ccd40a | |||
| ae1ee4633f | |||
| 2b2c290f58 | |||
| 168edb30f5 | |||
| f65d5f3f4d | |||
| f0133e4f90 | |||
| be9b528c5f | |||
| 329e93bec3 | |||
| 83c7c7f1d3 | |||
| c799e2ad90 | |||
| 043f7635f4 | |||
| e97ed1a5a0 | |||
| 460a5039f1 | |||
| 10964e9e45 | |||
| 8c582347f9 | |||
| 8984c901c8 | |||
| df7f529e39 | |||
| fff2765810 | |||
| 9852e397da | |||
| 615f63cb7c | |||
| dcdcc34c46 | |||
| 0ee2916e1c | |||
| 72c4b38593 | |||
| 37a7a102f2 | |||
| 2d0bb8eed3 | |||
| b8253dda56 | |||
| 0f10a36f0d | |||
| 0d74f3a513 | |||
| 5b1dd30356 | |||
| 50d53c86fd | |||
| 73fcccea80 | |||
| ba583b6391 | |||
| 705b356f3f | |||
| aabdfa4013 | |||
| 0079f38446 | |||
| 9e92e25813 | |||
| 46c66406df | |||
| a2727f06ad | |||
| b660c77191 | |||
| a15ca94564 | |||
| 6eec071f3a | |||
| 9c0bff0cfe | |||
| 8bc0b06e7b | |||
| 830d978a1b | |||
| b89b630c2e | |||
| fecb0247d1 | |||
| 4c8f3e620e | |||
| 7577c99c62 | |||
| a188bf66e1 | |||
| cca67c837d | |||
| d76cb6cb20 | |||
| 84da0eb5fb | |||
| ceca8a03b5 | |||
| 0355d21d47 | |||
| c1444e2b8d |
@@ -1,2 +1,10 @@
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
*.egg-info/
|
||||
.env
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
# Build context is the repo root (see docker-compose.yml) so the sibling
|
||||
# packages Core/, Persistance/, Extraction/ and models/
|
||||
# can be copied, and Transformation/ compiled.
|
||||
|
||||
# dbt's manifest: the measures' definitions and the compiled SQL of their event
|
||||
# models. The API serves the measures from it and the indicator cycle creates
|
||||
# the views. The manifest built here is SQLite's, the image's default engine;
|
||||
# the same environments compile it again at start-up against MySQL/MariaDB,
|
||||
# PostgreSQL or SQL Server when *_DATABASE_URL points there (docker-entrypoint.sh),
|
||||
# because those adapters open a connection to compile. dbt-mysql needs an
|
||||
# older dbt-core, so it gets an environment of its own.
|
||||
FROM python:3.12-slim AS manifest
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
WORKDIR /app/Transformation
|
||||
COPY Transformation/ ./
|
||||
RUN uv sync --group sqlite --group sqlserver --group postgres \
|
||||
&& UV_PROJECT_ENVIRONMENT=.venv-mysql uv sync --only-group mysql \
|
||||
&& uv run --no-sync dbt compile --profiles-dir . --profile cacu --target sqlite --no-introspect
|
||||
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Tesseract (with Spanish data) for scanned documents; pytesseract only wraps the binary.
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
tesseract-ocr tesseract-ocr-spa \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=ghcr.io/astral-sh/uv:0.7.9 /uv /uvx /bin/
|
||||
|
||||
WORKDIR /app
|
||||
COPY Core/ Core/
|
||||
COPY Persistance/ Persistance/
|
||||
COPY Extraction/ Extraction/
|
||||
COPY models/ models/
|
||||
COPY WebApi/ WebApi/
|
||||
|
||||
# One environment for the API, the migrations and the indicator cycle. The SQL
|
||||
# drivers serve both the import sources and *_DATABASE_URL on MySQL/PostgreSQL/SQL Server.
|
||||
RUN cd WebApi && uv sync --locked --no-dev --extra sql-drivers
|
||||
|
||||
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 GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
|
||||
# MLflow model registry and artifacts, next to the databases so backups cover them.
|
||||
ENV MLFLOW_TRACKING_URI=sqlite:////data/mlflow.db
|
||||
ENV MLFLOW_ARTIFACT_ROOT=/data/mlflow-artefactos
|
||||
# No usage telemetry from MLflow: the server runs on a closed network.
|
||||
ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true
|
||||
# Aggregate import log and the live indicator queue (webapi.recomputation).
|
||||
ENV WEBAPI_REPORT_DIR=/data/reportes
|
||||
ENV INDICADORES_DIR=/data/indicadores
|
||||
ENV MLFLOW_DISABLE_AGENT_HINT=1
|
||||
# Without it the measure routes (/<domain>/indicadores, /<domain>/fhir) aren't
|
||||
# registered. The entrypoint replaces it with one compiled against the
|
||||
# deployment's engine when that engine isn't SQLite (webapi.dbt_manifest).
|
||||
COPY --from=manifest /app/Transformation /app/Transformation
|
||||
ENV DBT_MANIFEST=/app/Transformation/target/manifest.json
|
||||
ENV TRANSFORMATION_DIR=/app/Transformation
|
||||
|
||||
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
||||
|
||||
EXPOSE 5000
|
||||
ENTRYPOINT ["/app/WebApi/docker-entrypoint.sh"]
|
||||
@@ -0,0 +1,120 @@
|
||||
# WebApi
|
||||
|
||||
API REST de ISSSTELEON en Flask. Importa datos clínicos de varias fuentes a
|
||||
las bases de CaCu, CaMa y TEA, publica los indicadores ya calculados, guarda
|
||||
una bitácora agregada de cada importación y expone la gobernanza de modelos
|
||||
y de OCR. Usa `Persistance` para las bases, `Extraction` para documentos y
|
||||
EEG y `models` para las cohortes. Los indicadores se definen en dbt (`Transformation`) y se
|
||||
responden bajo pedido (`/<dominio>/indicadores`); `orchestration` carga la plata, las tablas de
|
||||
referencia y las vistas de dbt.
|
||||
|
||||
## Estructura
|
||||
|
||||
```
|
||||
webapi/
|
||||
├── __init__.py create_app(): blueprints, límites de carga, CORS, /health y /api
|
||||
├── blueprints/
|
||||
│ ├── imports.py /imports: fuentes, vista previa, validación y carga
|
||||
│ ├── data.py /data: lectura paginada de cada tabla importable
|
||||
│ ├── cacu.py, cama.py, tea.py /<dominio>/indicadores
|
||||
│ ├── reportes.py /reportes: bitácora de importaciones y estado del recálculo
|
||||
│ └── governance.py /governance: versiones de modelos, notebooks y cola de OCR
|
||||
├── imports/
|
||||
│ ├── connectors/ una clase por tipo de fuente (@register_connector)
|
||||
│ ├── schemas/ un esquema pydantic por tabla destino; registry.py los enlista
|
||||
│ ├── mapping/ sugerencia de mapeo de columnas
|
||||
│ ├── services/ validación, combinación de fuentes, enlace de llaves, escritura
|
||||
│ │ y aprendizaje de las correcciones de documentos (review_learning.py)
|
||||
│ └── audit.py bitácora agregada (sin datos de pacientes)
|
||||
├── nlp.py python -m webapi.nlp evaluate|train: extracción contra una clave de respuestas
|
||||
├── indicadores.py rutas de indicadores (del equipo de indicadores)
|
||||
├── recomputation.py cola y servicio que recalcula indicadores tras cada carga
|
||||
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
|
||||
```
|
||||
|
||||
Agregar un tipo de fuente es agregar una clase en `imports/connectors/` con
|
||||
`@register_connector`; `GET /imports/connectors` la anuncia a la interfaz.
|
||||
Agregar una tabla destino es agregar su esquema en `imports/schemas/<dominio>/`
|
||||
y una entrada en `imports/schemas/registry.py`.
|
||||
|
||||
## Rutas
|
||||
|
||||
`GET /api` lista todas las rutas con su descripción.
|
||||
|
||||
| Prefijo | Para qué |
|
||||
|---|---|
|
||||
| `/imports` | Catálogo de fuentes y destinos, vista previa (archivos, SQL, PDF, documentos, EEG), `POST /imports/validate` y `POST /imports/commit` |
|
||||
| `/data/<dominio>.<Tabla>` | Filas de una tabla importable, paginadas (`limit`, `offset`) |
|
||||
| `/<dominio>/indicadores` | Catálogo de indicadores y, por indicador, `/periodos`, `/datos`, `/metadatos` y `/figuras/<figura>` |
|
||||
| `/reportes` | `GET /reportes/importaciones` (resumen y últimos intentos), `/importaciones/descarga`, `GET /reportes/indicadores`, `POST /reportes/indicadores/<dominio>/recalcular` |
|
||||
| `/governance` | Versiones de modelos en MLflow (registro, revisión, promoción, retiro, descarga de sus archivos), notebooks corridos sobre una cohorte exportada (`/governance/experiments`, `/governance/cohort-files`) y cola de revisión de OCR |
|
||||
| `/health` | Verificación de vida |
|
||||
|
||||
Los errores de la solicitud se responden con `{"error": "..."}` y código 400
|
||||
(404 si no existe el recurso).
|
||||
|
||||
## Variables de entorno
|
||||
|
||||
| Variable | Por omisión | Uso |
|
||||
|---|---|---|
|
||||
| `CACU_DATABASE_URL`, `CAMA_DATABASE_URL`, `TEA_DATABASE_URL`, `GOVERNANCE_DATABASE_URL` | archivos SQLite | Bases de la aplicación (cualquier URL de SQLAlchemy) |
|
||||
| `MLFLOW_TRACKING_URI` | `./mlruns` | Registro de modelos de MLflow |
|
||||
| `MLFLOW_ARTIFACT_ROOT` | el de MLflow | Carpeta de artefactos de los experimentos nuevos |
|
||||
| `WEBAPI_MAX_UPLOAD_MB` | `200` | Tamaño máximo de una solicitud |
|
||||
| `WEBAPI_CORS_ORIGINS` | sin CORS | Orígenes permitidos, separados por comas |
|
||||
| `WEBAPI_SQL_ALLOWED_DIALECTS` | `mysql,mariadb,postgresql,mssql` | Motores aceptados como fuente SQL |
|
||||
| `WEBAPI_SQL_ALLOWED_HOSTS` | cualquiera | Servidores aceptados como fuente SQL |
|
||||
| `WEBAPI_REPORT_DIR` | `reportes` | Carpeta de la bitácora (`importaciones.jsonl`, `indicadores.jsonl`) |
|
||||
| `WEBAPI_REPORT_MIN_COUNT` | `5` | Filas mínimas para que un valor rechazado aparezca textual en la bitácora |
|
||||
| `INDICADORES_DIR` | `indicadores` | Cola y estado del recálculo |
|
||||
| `INDICADORES_DESDE`, `INDICADORES_HASTA` | hace 5 años, este año | Años que recalcula el servicio |
|
||||
| `INDICADORES_INTERVALO_S` | `20` | Cada cuánto revisa la cola |
|
||||
| `INDICADORES_AL_INICIAR` | `1` | Recalcular los tres dominios al arrancar |
|
||||
| `EEG_ANALYSIS_CLUSTER` | `auto` | Where TEA's cycle analyses the stored EDFs before loading silver: `auto` (`DASK_SCHEDULER_ADDRESS` if set, otherwise a local Dask cluster), `local`, `remote`, `sync` (in the service's own process) or `off` (only `python -m models tea analyze` and `POST /governance/eeg/run` analyse) |
|
||||
| `PORT`, `WEBAPI_WORKERS`, `WEBAPI_TIMEOUT` | `5000`, `2`, `600` | gunicorn en el contenedor |
|
||||
| `NOTEBOOK_JOBS_DIR` | sin carpeta | Carpeta compartida con el servicio `notebooks`; con ella los notebooks corren aislados en ese contenedor |
|
||||
| `NOTEBOOK_EXECUTOR` | `contenedor` con `NOTEBOOK_JOBS_DIR`, si no `local` | Dónde corren los notebooks; `local` es en el propio proceso, sin aislar (desarrollo) |
|
||||
| `NOTEBOOK_RUNNER_UID` | ninguno | Usuario del contenedor `notebooks`, dueño de cada carpeta de trabajo |
|
||||
| `NOTEBOOK_JOB_TIMEOUT`, `NOTEBOOK_CELL_TIMEOUT` | `21600`, `1800` | Segundos que espera un notebook completo y una celda |
|
||||
| `NOTEBOOK_MAX_IMPORT_MB` | `500` | Tope de archivos que se importan de lo que entrenó un notebook |
|
||||
| `WEBAPI_NOTEBOOK_WORKERS` | `1` | Notebooks a la vez por proceso de la API |
|
||||
| `EXTRACTION_RANKER` | `auto` | Ranker de extracción de documentos: `auto` (el de producción, si no el último), `produccion` (solo el de producción) o `ninguno` |
|
||||
| `EXTRACTION_LEARNING` | `1` | `0` deja de aprender de las correcciones hechas al revisar documentos |
|
||||
| `NOTEBOOK_RENDERER` | `quarto` si está instalado, si no `jupyter` | Con qué se corre y se arma la página |
|
||||
|
||||
## Ejecución
|
||||
|
||||
En local (las migraciones se aplican a mano):
|
||||
|
||||
```bash
|
||||
uv sync --extra sql-drivers
|
||||
for d in cacu cama tea governance; do
|
||||
uv run alembic -c ../Persistance/persistance/$d/alembic.ini upgrade head
|
||||
done
|
||||
uv run python main.py # http://localhost:5050
|
||||
uv run python -m webapi.recomputation # recálculo de indicadores, en otra terminal
|
||||
```
|
||||
|
||||
Medir la extracción de documentos contra una clave de respuestas (por documento y
|
||||
destino, el valor correcto de cada campo revisado; `null` si debe quedar vacío)
|
||||
y entrenar con ella el ranker del dominio (`Extraction/README.md`):
|
||||
|
||||
```bash
|
||||
uv run python -m webapi.nlp evaluate --documents carpeta/ --key clave.json [--with-values] [--no-ranker]
|
||||
uv run python -m webapi.nlp train --documents carpeta/ --key clave.json
|
||||
```
|
||||
|
||||
Con Docker, desde la raíz del repositorio: `docker compose up --build`. La
|
||||
imagen se construye con `WebApi/Dockerfile` (contexto: la raíz, para copiar
|
||||
los paquetes hermanos); `docker-entrypoint.sh` aplica las migraciones y
|
||||
arranca gunicorn, o el servicio de recálculo con el argumento `indicadores`.
|
||||
|
||||
## Pruebas
|
||||
|
||||
```bash
|
||||
uv sync --extra sql-drivers
|
||||
uv run pytest -q
|
||||
```
|
||||
|
||||
Las pruebas contra MySQL en vivo se activan con `MYSQL_TEST_URL`; sin ella
|
||||
se omiten.
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
|
||||
# The notebook runner shares the image but runs with no network, a read-only
|
||||
# system and only the jobs folder (models.reports.notebook_jobs): it never touches /data.
|
||||
if [ "$1" = "notebooks" ]; then
|
||||
exec /app/WebApi/.venv/bin/python -m models notebooks serve
|
||||
fi
|
||||
|
||||
mkdir -p /data
|
||||
|
||||
# SQLite won't create a missing parent directory for its database file.
|
||||
for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVERNANCE_DATABASE_URL"; do
|
||||
case "$url" in
|
||||
sqlite:///*) mkdir -p "$(dirname "${url#sqlite:///}")" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
cd /app/WebApi
|
||||
|
||||
# dbt's manifest for the deployment's engine: the image's is SQLite's; on
|
||||
# another engine it's compiled now, against the configured databases, into
|
||||
# /data (webapi.dbt_manifest prints the path to use, or nothing to keep the
|
||||
# image's).
|
||||
if compiled="$(uv run --no-sync python -m webapi.dbt_manifest)"; then
|
||||
[ -n "$compiled" ] && export DBT_MANIFEST="$compiled"
|
||||
else
|
||||
echo "dbt manifest: compilation failed; the measure routes will stay unregistered" >&2
|
||||
fi
|
||||
|
||||
# The live indicator worker (webapi.recomputation) shares the image; the
|
||||
# API container runs the migrations, so the worker starts after it.
|
||||
if [ "$1" = "indicadores" ]; then
|
||||
exec uv run --no-sync python -m webapi.recomputation
|
||||
fi
|
||||
|
||||
# One-shot training of the CaCu model on the loaded data (compose profile
|
||||
# `entrenar`): the trained version goes into production and the worker's next
|
||||
# cycle estimates with it. `--source dbt` (dbt's cohort, not the kit's numbered
|
||||
# builds) is required: a PROD run needs its cohort build named (ML-03), and
|
||||
# --export --source dbt is the only way to do that without knowing the build
|
||||
# number ahead of time; it also makes the promotion gate's cohort-link check
|
||||
# portable (tag-based, no live lookup of a local build row), unlike the kit's.
|
||||
if [ "$1" = "entrenar" ]; then
|
||||
exec uv run --no-sync python -m models run cacu cin2_logistic --export --source dbt --manifest "$DBT_MANIFEST" \
|
||||
--environment prod --train --promote
|
||||
fi
|
||||
|
||||
# --no-sync: the environment was synced at build time; syncing at startup
|
||||
# would try to reach the package index (and pull dev deps).
|
||||
for domain in cacu cama tea governance; do
|
||||
uv run --no-sync alembic -c "/app/Persistance/persistance/$domain/alembic.ini" upgrade head
|
||||
done
|
||||
|
||||
PORT="${PORT:-5000}"
|
||||
# gunicorn, not Flask's development server. Long timeout: OCR over a
|
||||
# multi-page scanned PDF runs inside a single request.
|
||||
exec uv run --no-sync gunicorn \
|
||||
--bind "0.0.0.0:${PORT}" \
|
||||
--workers "${WEBAPI_WORKERS:-2}" \
|
||||
--timeout "${WEBAPI_TIMEOUT:-600}" \
|
||||
--access-logfile - \
|
||||
"webapi:create_app()"
|
||||
@@ -0,0 +1,74 @@
|
||||
# CaMa descriptive analysis
|
||||
|
||||
Counts and proportions of the BI-RADS cohort, by group and over time, under `/cama/analisis`. It describes the
|
||||
patients of the cohort; it estimates no incidence, survival or risk. The cohort is the follow-up list's (see
|
||||
`cama-follow-up.md`): each patient through her latest reported mammogram, kept when its BI-RADS is 4 to 6.
|
||||
|
||||
## Routes
|
||||
|
||||
All `GET`, with the selection of the follow-up list (all routes but the trend): `corte` (default today), `meses` (`0` whole cohort, default; `1`, `3`,
|
||||
`6`, `12`), the filters `birads`, `grupo_edad` and `biopsia`, and the context `cohorte`, `escenario`, `revision` together.
|
||||
Unknown, repeated or empty parameters are a 400. The trend takes only `corte`, `tipo` and `periodos`: a window, a filter or the cohort
|
||||
context sent to it is a 400, never ignored.
|
||||
|
||||
| Route | Own parameters | Answers |
|
||||
| --- | --- | --- |
|
||||
| `/cama/analisis` | | Dimensions with their options, measures, horizons (30, 90, 180, 365 days), period types, sections and the analyses that are not available, each with its reason |
|
||||
| `/cama/analisis/resumen` | `horizonte` (default 90) | The indicator cards |
|
||||
| `/cama/analisis/distribucion` | `por`: `birads`, `grupo_edad`, `biopsia` | Patients per category: count, share and its Wilson interval, and the filter that opens them in the list |
|
||||
| `/cama/analisis/comparacion` | `por`: `birads`, `grupo_edad`; `medida`: `maligno` (default), `invasor` | Per group, cases among the patients with a known biopsy result, its interval, and the chi-square test of homogeneity |
|
||||
| `/cama/analisis/mapa` | `filas`, `columnas` (two different of `birads`, `grupo_edad`); `medida` | Cells of the two crossed: patients and the share of cases |
|
||||
| `/cama/analisis/tendencia` | `tipo`: `mes`, `semestre`; `periodos`: 1 to 36 (12 months, 6 semesters by default) | Reports of mammogram and biopsy per period and the share of malignant results; general activity, not the cohort |
|
||||
| `/cama/analisis/indicadores` | | The cohort's patients by BI-RADS category, with `simulado: true` (the aggregate the tab has always read); a category is published only from the threshold, so an empty one is not published either |
|
||||
|
||||
Every answer carries `cohorte`, `escenario`, `revision`, `corte`, `ventana`, `filtros` and `umbral_supresion`, and only
|
||||
`/indicadores` carries `simulado`. Errors as in the list: 400, 403 (`motivo: supresion`), 409 (`motivo: revision`) and 503
|
||||
(`motivo: cohorte`, the cohort view is missing).
|
||||
|
||||
A proportion is `{estado, casos, total, valor, ic_bajo, ic_alto}` with values in percent; `estado` is `disponible`,
|
||||
`suprimido` or `sin_datos` (nobody in the denominator). An item with `seleccion` gives the list's filters that open its
|
||||
patients; the page adds the selection's own filters.
|
||||
|
||||
## Definitions (working conventions, for review)
|
||||
|
||||
* **Result** of a patient: the grade of the biopsy the list shows (latest report at the cut-off); `SIN_BIOPSIA` without a
|
||||
report, `SIN_DATO` for a report without a grade. **Known**: benign, in situ or invasive. **Malignant**: a grade in
|
||||
`cama.biopsia_cancer`; **invasive**: `CARCINOMA_INVASOR`.
|
||||
* **Cards.** Cohort (patients). With a biopsy report: of the cohort. Malignant and invasive among the known results: not
|
||||
an incidence, the denominator is patients already biopsied. Biopsy reported within `h` days and malignant result within
|
||||
`h` days of the mammogram: of the cohort's mammograms that have had `h` days by the cut-off (a recent one isn't read as
|
||||
one without a biopsy); the earliest report counts. Days from the mammogram to the first biopsy report: median and
|
||||
quartiles (linear interpolation) among the patients with a report, from five of them.
|
||||
* **Comparison and map.** The proportion's denominator is the patients with a known result; the test needs two or more
|
||||
published groups and every expected count of at least 5, otherwise it says why it is not given.
|
||||
* **Trend.** General activity, not the cohort. It counts reports (`unidad: "reportes"`), not patients: each mammogram report
|
||||
with a BI-RADS and each biopsy report in its period, over every patient; a patient with several reports counts several
|
||||
times. It depends only on `corte`, `tipo` and `periodos`, so it doesn't change with the window or filters of the other
|
||||
sections, and its answer carries no cohort, revision, window or filters. Biopsies: only those that can be linked to a
|
||||
mammogram with a reported BI-RADS (mammogram, order, report); a biopsy without a linked mammogram isn't counted
|
||||
(`alcance_biopsias`). The share is malignant among the biopsy reports with a known grade. The period the cut-off falls in is
|
||||
marked `incompleto`. Counts and shares are descriptive: no test is applied, because reports of one patient aren't
|
||||
independent. The answer needs the cohort view (503 without it) and a `corte` not after today.
|
||||
* **Intervals.** Wilson, 95 %. Shares of the selection (distribution) are descriptive proportions of the patients.
|
||||
|
||||
## Suppression
|
||||
|
||||
Same threshold as the list (`comun.umbral_supresion`, 5). Applied here as:
|
||||
|
||||
* A count of 1 to 4 is never published. A hidden cell takes the smallest published one of its line with it, until the
|
||||
hidden patients are at least 5, so a published total minus the published cells gives nothing away. Tables do the same
|
||||
along every row and column. Zero is published.
|
||||
* A proportion is published only when its group, its cases and its non-cases are each zero or at least 5.
|
||||
* A period's total is published from 5 reports.
|
||||
* The selection itself follows the list's rule (a window or filter that selects 1 to 4 patients is a 403).
|
||||
|
||||
Residual risk: the list shows individual rows of every selection it allows, so what an aggregate hides can be read from
|
||||
the list. The rule bounds the aggregates, not the list.
|
||||
|
||||
## Not available
|
||||
|
||||
Survival, recurrence, treatment adherence, time-to-event curves (cumulative incidence, Kaplan-Meier), hazard ratios, log-rank
|
||||
and restricted mean survival, and BRCA, stage and tumour size. The sources hold no vital status, recurrence, treatment or
|
||||
follow-up visits, and a patient without the event is not known to have been followed: censoring and a common time zero
|
||||
cannot be established. In the synthetic data every malignant biopsy report falls 12 to 42 days after its mammogram, so a
|
||||
24-month curve would be an extrapolation of a diagnostic work-up, not a follow-up.
|
||||
@@ -0,0 +1,94 @@
|
||||
# CaMa follow-up list
|
||||
|
||||
Patient-level list of the BI-RADS cohort, and the file of the same selection. Every response carries
|
||||
`simulado: true`: the list is for synthetic data and local use. Who may read it on real data is an access rule that does
|
||||
not exist yet; nothing here authorizes it.
|
||||
|
||||
## Routes
|
||||
|
||||
`GET /cama/seguimiento` and `GET /cama/seguimiento/exportacion` (the second takes no `page` or `page_size`).
|
||||
|
||||
Compatibility with dev: `GET /cama/pacientes/<pac_id>` accepts the same selection as the export and returns
|
||||
`item` instead of `items`. It applies suppression to the full selection before locating the patient (404 when absent),
|
||||
and uses the list's revision. The existing optional `CAMA_COHORT_ACCESS` callback is honored on the new follow-up
|
||||
and analysis routes; no new authentication mechanism is introduced. `cama_analysis_legacy` retains the former
|
||||
blueprints for explicit consumers, while `create_app` registers only the new routes, without duplicates.
|
||||
|
||||
| Parameter | Meaning |
|
||||
| --- | --- |
|
||||
| `corte` | Cut-off date `AAAA-MM-DD`, not after today. Default: today. |
|
||||
| `meses` | Window: `0` (the whole cohort, from its earliest mammogram), `1`, `3`, `6` or `12`. Default: `3`. |
|
||||
| `page`, `page_size` | From 1; `page_size` from 1 to 200 (default 50). List only. |
|
||||
| `birads`, `grupo_edad`, `biopsia` | Filters, combined with AND. The values are in `filtros_disponibles`. |
|
||||
| `cohorte`, `escenario`, `revision` | The context of an earlier answer, the three together. |
|
||||
|
||||
Unknown, repeated or empty parameters are a 400, before anything is counted.
|
||||
|
||||
Response: `simulado`, `cohorte` (`cama_birads_v1`), `escenario` (`diagnostico`), `revision`, `corte`,
|
||||
`ventana` (`meses`, `desde`, `hasta`), `filtros` (each filter, `null` when not applied), `filtros_disponibles`,
|
||||
`columnas`, `paginacion` and `items`; the file has `total_items` instead of `paginacion`. Each item has `pac_id` (the
|
||||
platform's key as decimal text), `grupo_edad`, `birads`, `mastografia_fecha`, `biopsia` and `biopsia_fecha`. Nothing
|
||||
else: no status, priority, days to diagnosis or prognosis, because the data holds none of them.
|
||||
|
||||
| Code | When |
|
||||
| --- | --- |
|
||||
| 400 | A parameter outside the contract, or the context without all three parts |
|
||||
| 403 | The selection has fewer patients than `comun.umbral_supresion` (`motivo: supresion`) |
|
||||
| 404 | A page past the last one, with patients |
|
||||
| 409 | The cohort, scenario or revision quoted is not the one the server holds (`motivo: revision`) |
|
||||
| 413 | A file of more than 5000 patients |
|
||||
| 503 | The cohort view is missing: the indicator cycle that creates the event views hasn't run (`motivo: cohorte`) |
|
||||
|
||||
## The cohort
|
||||
|
||||
`cama_cohorte_birads` (dbt, `models/cama/gold/seguimiento`) holds one row per mammogram with a reported BI-RADS and each
|
||||
biopsy report that mammogram led to. A view takes no parameter, so the cut-off is applied by `webapi.cama_follow_up`:
|
||||
|
||||
* A patient counts once, through her latest mammogram whose report is dated on or before the cut-off (date taken, then
|
||||
source id, then report date, then report id: the same data always gives the same cohort).
|
||||
* She is in the cohort when that BI-RADS is one of `cama.birads_4_a_6`.
|
||||
* The biopsy shown is the latest report of a biopsy that mammogram led to, dated on or before the cut-off and not before
|
||||
the mammogram. `SIN_BIOPSIA`: none; `SIN_DATO`: a report without a result.
|
||||
* The age group is `cama.grupos_edad` at the cut-off; `SIN_DATO` without a birth date.
|
||||
* Facts are read as silver holds them now. The list is not a reconstruction of what was known on the cut-off.
|
||||
|
||||
## Suppression
|
||||
|
||||
A selection (window and filters applied) of 1 to `umbral_supresion` - 1 patients is never served, as a page or as a file.
|
||||
A selection with a window or a filter and no patients is refused alike, so a refusal never tells a small group from an
|
||||
empty one. The whole cohort (window `0`, no filter) is the only selection that can be empty. Combinations of window and
|
||||
filters are evaluated on the final selection, so they cannot isolate a small group. The file applies the same rule.
|
||||
|
||||
## Revision
|
||||
|
||||
`sha256(cohorte | version | construcción | corte)`. The build is the last load that added or changed rows
|
||||
(`carga-<id>`): a recalculation that changes nothing keeps it, new data changes it. A client that quotes another
|
||||
revision gets a 409.
|
||||
|
||||
## Limits of the revision and of concurrent writes
|
||||
|
||||
The revision pins the cohort, its version, the last load that added or changed rows and the cut-off. It is a marker, not a
|
||||
snapshot: nothing keeps the previous cohort. While no load writes, every page and the file of one selection come from the
|
||||
same data, so pages concatenate to the file and repeated requests give the same answer. A load that adds or changes rows
|
||||
between two requests changes the build, and the next request that quotes the old revision is a 409. A load that is still
|
||||
running when a request arrives is not detected until it records its rows. Until snapshots exist, run reads and files with no
|
||||
concurrent writes.
|
||||
|
||||
Two contradictory facts are resolved the same way whatever the row order: a report with two different BI-RADS counts
|
||||
through the more severe (`cama.birads_gravedad`), and a biopsy report with two grades on the same date through the more
|
||||
severe grade (benign, in situ, invasive). The synthetic data holds no such duplicates.
|
||||
|
||||
## Provisional decisions
|
||||
|
||||
These are working conventions for review, not clinical definitions.
|
||||
|
||||
1. Individual lists are served in the local environment with synthetic data only; the routes are registered like CaCu's and
|
||||
marked `simulado`, with no access rule.
|
||||
2. Threshold of 5 (`comun.umbral_supresion`, itself provisional).
|
||||
3. The cohort rule above (latest reported mammogram, BI-RADS 4 to 6) and the biopsy that is shown.
|
||||
4. The knowledge cut-off is the present: a mammogram or a biopsy loaded after the cut-off date still counts if its own date
|
||||
is on or before it. Data loaded today would otherwise make every earlier cut-off empty.
|
||||
5. Age groups and the BI-RADS list come from the platform parameters, not from this module.
|
||||
6. Residual risk: the suppression rule bounds the size of each selection, not the differences between selections. Two
|
||||
allowed selections can still reveal a small remainder by subtraction. Rows of allowed selections are individual
|
||||
records by design.
|
||||
@@ -0,0 +1,59 @@
|
||||
# CaMa: tasa de detección, resultado a diagnóstico y resultado histopatológico por BI-RADS
|
||||
|
||||
Tres medidas FHIR de CaMa, calculadas a pedido desde la capa semántica de dbt como las demás (`GET /cama/fhir/Measure`,
|
||||
`GET /cama/fhir/MeasureReport?measure=<canónico>&tipo-periodo=<semestre|mes>`). Sus definiciones son convenciones de
|
||||
trabajo, no definiciones clínicas aprobadas; los analistas deben confirmarlas (ver `INFORME_L3_RESUMEN_HISTORICO_CAMA.md`).
|
||||
|
||||
| Medida | Contrato | Unidad | Modelo de eventos (vista) |
|
||||
| --- | --- | --- | --- |
|
||||
| `CAMA-TASA-DETECCION-HISTOPATOLOGICA` | C1 (proporción) | reporte de biopsia | `cama_deteccion_biopsia` |
|
||||
| `CAMA-DIAS-RESULTADO-DIAGNOSTICO` | C3r (duración) | mastografía con reporte | `cama_resultado_diagnostico` |
|
||||
| `CAMA-HISTOPATOLOGIA-BIRADS` | C2 por BI-RADS (composición) | paciente | `cama_resultado_biopsia` |
|
||||
|
||||
## Tasa de detección histopatológica
|
||||
|
||||
* Unidad: el **reporte de biopsia**, fechado por su reporte (`fecha_reporte`) y conocido al inicio de la carga que lo escribió.
|
||||
* Denominador: reportes con resultado conocido (`BENIGNO`, `CARCINOMA_IN_SITU`, `CARCINOMA_INVASOR`); un reporte sin grado, o con
|
||||
un grado que el catálogo no conoce, no entra. Numerador: los de `CARCINOMA_IN_SITU` o `CARCINOMA_INVASOR`.
|
||||
* Las marcas `con_resultado` y `maligno` son de la vista y salen de las variables de dbt `cama.biopsia_gravedad` y
|
||||
`cama.grados_cancer` (esta última, igual a la regla `cama.biopsia_cancer` de `parametros.toml`; una prueba lo verifica). Así la
|
||||
medida no necesita reglas nuevas en la tabla de parámetros de una base ya instalada.
|
||||
* **No** es la tasa de detección de CaCu (`CACU_EU13`: pacientes con lesión confirmada entre las tamizadas), **ni** la
|
||||
proporción de confirmación de CaMa (`CAMA_CONFIRMACION_BIRADS45`: mastografías de sospecha con biopsia reportada), **ni** una
|
||||
proporción dentro de la cohorte de Seguimiento. Es la proporción de resultados malignos entre las biopsias con resultado.
|
||||
|
||||
## Tiempo de resultado a diagnóstico
|
||||
|
||||
* Una fila por mastografía con reporte, fechada por el reporte. Observación: días naturales del reporte a la **primera nota
|
||||
diagnóstica de la paciente con fecha igual o posterior al reporte**, dentro del horizonte (`horizonte_toma_diagnostico_dias`,
|
||||
180) y a la fecha de corte. Nota diagnóstica: un diagnóstico CIE-10 de `cama.cie_diagnostico` escrito por una especialidad de
|
||||
`cama.especialidades_diagnostico` (la misma que usa `CAMA_DIAS_TOMA_DIAGNOSTICO`).
|
||||
* Si una toma tiene varios reportes, se selecciona el primero por `fecha_reporte`, después `reporte_id` y
|
||||
`reporte_carga_id`. Una toma aporta una observación y pertenece al periodo de ese reporte; las correcciones posteriores
|
||||
no crean otra observación. La nota se busca desde ese reporte seleccionado. El horizonte es semiabierto:
|
||||
se admiten 0 a 179 días; el día 180 ya queda fuera. La unidad usa `procedimiento_id`, igual que la identidad del reporte
|
||||
en la tasa de biopsias; `fuente_id` puede repetirse entre fuentes.
|
||||
* La nota es de la paciente: **no está ligada a la mastografía** (las notas no traen episodio) **y no es la fecha de la biopsia**.
|
||||
* Una mastografía sin nota dentro del horizonte no se mide; se cuenta como excluida solo cuando su horizonte ya pasó (la misma
|
||||
regla que `CAMA_EU38A`). Se excluyen las de pacientes con un diagnóstico de cáncer de mama anterior a la toma.
|
||||
* Misma nota que el tiempo de la toma al diagnóstico: cuando la primera nota es posterior al reporte, los días desde el reporte
|
||||
son los de la toma menos los de la toma al reporte.
|
||||
|
||||
## Resultado histopatológico por categoría BI-RADS
|
||||
|
||||
* Una paciente por periodo (periodo de la toma): su mastografía **más grave** del periodo con reporte a la fecha de corte, la misma
|
||||
regla de `CAMA_BIRADS456_PACIENTE` (así las dos tarjetas del Resumen cuentan las mismas pacientes). Solo cuenta si ese BI-RADS
|
||||
está en `cama.birads_4_a_6`.
|
||||
* Resultado: el grado de la biopsia más grave que esa mastografía originó y que se reportó a la fecha de corte (entre iguales, la
|
||||
más reciente); `SIN_BIOPSIA` si no hay ninguna reportada al corte; `SIN_DATO` si la biopsia no trae grado.
|
||||
* El reporte publica el cruce BI-RADS × resultado como un estratificador con dos componentes (`birads`, `biopsia_grado`), además del
|
||||
estratificador de categorías. Solo se listan las celdas con pacientes; las demás son cero.
|
||||
* La categoría «lesión de riesgo (B3)» de la maqueta no existe en las fuentes (los grados son benigno, in situ e invasor): no se
|
||||
publica ni se inventa.
|
||||
|
||||
## Corrección en el cálculo de composiciones
|
||||
|
||||
La biopsia que sigue a la mastografía elegida se compara con la fecha de conocimiento (`corte_conocimiento`) como fecha y hora. Antes,
|
||||
la columna de esa fecha se leía como texto y, con el corte de conocimiento en el mismo día de la carga, la comparación daba falso y
|
||||
toda paciente quedaba «sin biopsia». Afectaba a toda composición con seguimiento (CaCu: `CACU_CONFIRMACION_CITOLOGIA`) cuyos
|
||||
reportes aún no estuvieran guardados; los ya guardados no cambian hasta que se recalculen.
|
||||
@@ -0,0 +1 @@
|
||||
2026-11-22T10:18:21+00:00
|
||||
@@ -0,0 +1,9 @@
|
||||
import os
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 5000 is taken by AirPlay on macOS.
|
||||
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5050)))
|
||||
+45
-19
@@ -1,28 +1,54 @@
|
||||
[project]
|
||||
name = "webapi"
|
||||
version = "0.0.0"
|
||||
description = "FastAPI: FHIR routes, control routes, the auth dependency."
|
||||
version = "0.1.0"
|
||||
description = "ISSSTELEON REST API: data import, indicators, import log and model governance for CaCu, CaMa and TEA."
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"core",
|
||||
"flask>=3.0",
|
||||
"persistance",
|
||||
"fastapi[standard]",
|
||||
"dagster-graphql",
|
||||
"authlib>=1.6",
|
||||
"fastapi-users[sqlalchemy]>=15",
|
||||
"aiosqlite>=0.20",
|
||||
"asyncpg>=0.30",
|
||||
"fpdf2>=2.8",
|
||||
"openpyxl>=3.1.5",
|
||||
"models[notebooks,seer-survival]",
|
||||
"extraction",
|
||||
"apache-hamilton>=1.90",
|
||||
"pandas>=2.0",
|
||||
"openpyxl>=3.1",
|
||||
"sqlalchemy>=2.0",
|
||||
"pydantic>=2.0",
|
||||
"pdfplumber>=0.11",
|
||||
"pytesseract>=0.3.10",
|
||||
"Pillow>=10.0",
|
||||
"flask-cors>=4.0",
|
||||
"gunicorn>=23.0",
|
||||
"sqlglot>=25.0",
|
||||
"rapidfuzz>=3.9",
|
||||
"watchdog>=6.0",
|
||||
# Every FHIR answer is validated against R4B's models before it leaves (`webapi.fhir.common`).
|
||||
"fhir-resources>=8.3",
|
||||
# The EEG quality checks' code system and interpretations in TEA's FHIR answers (`webapi.fhir.tea`, `webapi.fhir.terminology`).
|
||||
"tea",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["uv_build>=0.12,<0.13"]
|
||||
build-backend = "uv_build"
|
||||
[project.optional-dependencies]
|
||||
sql-drivers = [
|
||||
"psycopg2-binary>=2.9",
|
||||
"pymysql>=1.1",
|
||||
"pymssql>=2.3",
|
||||
]
|
||||
|
||||
[tool.uv.build-backend]
|
||||
module-name = "webapi"
|
||||
module-root = ""
|
||||
[tool.uv.sources]
|
||||
core = { workspace = true }
|
||||
persistance = { workspace = true }
|
||||
persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
tea = { path = "../models/libs/tea", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["webapi"]
|
||||
|
||||
[dependency-groups]
|
||||
dev = [
|
||||
"pytest>=8.0.0",
|
||||
"reportlab>=4.0",
|
||||
]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,153 @@
|
||||
"""Shared test wiring.
|
||||
|
||||
`persistance.settings.settings` is a module-level singleton and the
|
||||
`persistance.db.get_<domain>_engine` functions are `@lru_cache`d, so changing
|
||||
`<DOMAIN>_DATABASE_URL` alone has no effect once an engine exists.
|
||||
`wire_domain` resets all three (env var, singleton, cache).
|
||||
|
||||
The `base`/`base_de` family (below `ANIO`) is for `webapi.orchestration`:
|
||||
una base del dominio por prueba, migrada por el paso `migrate`, con el staging
|
||||
sintético del kit.
|
||||
"""
|
||||
import os
|
||||
import tempfile
|
||||
from dataclasses import dataclass, replace
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
from webapi.orchestration import Context, run
|
||||
from webapi.orchestration.connection import point_to
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql")
|
||||
# The import log and the indicator queue write files; keep them out of the tree.
|
||||
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
|
||||
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
|
||||
os.environ.setdefault("INDICADORES_DIR", os.path.join(_STATE_DIR, "indicadores"))
|
||||
# Extraction ranks by confidence and learns nothing unless a test sets up a
|
||||
# model registry of its own (test_review_learning.py).
|
||||
os.environ.setdefault("EXTRACTION_RANKER", "ninguno")
|
||||
os.environ.setdefault("EXTRACTION_LEARNING", "0")
|
||||
|
||||
ANIO = 2025
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Base:
|
||||
"""El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance."""
|
||||
|
||||
proyecto: str
|
||||
ctx: Context
|
||||
dominio: object
|
||||
motor: object
|
||||
|
||||
def run(self, *pasos: str, **cambios) -> dict:
|
||||
"""Corre estos pasos (en el orden del ciclo) con el contexto cambiado. Devuelve el resumen de cada una."""
|
||||
return {p.name: p.summary for p in run(replace(self.ctx, **cambios), only=pasos)}
|
||||
|
||||
def staging(self):
|
||||
"""Una sesión sobre la base, para cambiar el staging como lo haría la ingesta."""
|
||||
return Session(self.motor)
|
||||
|
||||
|
||||
def base_de(proyecto: str, carpeta, datos=None) -> Base:
|
||||
"""A migrated domain database in `carpeta`, with the kit's synthetic staging or, with `datos`, what it inserts."""
|
||||
url = f"sqlite:///{carpeta / f'{proyecto}.db'}"
|
||||
point_to(proyecto, url)
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
ctx = Context(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositories_of(proyecto))
|
||||
run(ctx, only=["migrate"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
(datos or import_module(f"staging.{proyecto}").insertar)(sesion)
|
||||
sesion.commit()
|
||||
return Base(proyecto, ctx, import_module(f"persistance.{proyecto}"), motor)
|
||||
|
||||
|
||||
@pytest.fixture(params=["cacu", "cama", "tea"])
|
||||
def proyecto(request):
|
||||
return request.param
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(proyecto, tmp_path):
|
||||
base = base_de(proyecto, tmp_path)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sin_supresion(tmp_path):
|
||||
"""`parametros.toml` con umbral de supresión 1, para ver los conteos pequeños del fixture."""
|
||||
ruta = tmp_path / "parametros.toml"
|
||||
ruta.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
|
||||
return ruta
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def wire_domain():
|
||||
"""Factory fixture: `wire_domain("cacu")` points the domain at a fresh temp
|
||||
SQLite file for this module and returns its path. Temp files are removed
|
||||
when the module finishes."""
|
||||
created_paths: list[str] = []
|
||||
|
||||
def _wire(domain: str) -> str:
|
||||
db_path = tempfile.NamedTemporaryFile(suffix=".db", delete=False).name
|
||||
url = f"sqlite:///{db_path}"
|
||||
os.environ[f"{domain.upper()}_DATABASE_URL"] = url
|
||||
|
||||
from persistance import db as persistance_db
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
setattr(persistance_settings.settings, f"{domain}_database_url", url)
|
||||
getattr(persistance_db, f"get_{domain}_engine").cache_clear()
|
||||
created_paths.append(db_path)
|
||||
_migrate(domain)
|
||||
return db_path
|
||||
|
||||
yield _wire
|
||||
|
||||
for path in created_paths:
|
||||
os.unlink(path)
|
||||
|
||||
|
||||
def _migrate(domain: str) -> None:
|
||||
"""Builds the schema with the Alembic migrations rather than
|
||||
`metadata.create_all`, so tests run against the deployed schema and a
|
||||
broken migration fails the suite."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
import persistance
|
||||
|
||||
ini = Path(persistance.__file__).parent / domain / "alembic.ini"
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
|
||||
|
||||
# Indicator-route tests (vendored from the fork's WebApi tests): the kit's
|
||||
# demonstration database, seeded into a temporary SQLite file per domain.
|
||||
SEMESTRES = ["2025-S1", "2025-S2"]
|
||||
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||
|
||||
|
||||
def cliente_de(proyecto: str, tmp_path_factory):
|
||||
"""Yields a client over a temporary SQLite database the cycle loaded from the kit's synthetic staging."""
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
base = base_de(proyecto, carpeta)
|
||||
base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True)
|
||||
try:
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
@@ -1,153 +0,0 @@
|
||||
"""What the FHIR gate checks with: every resource the API serves, the HL7 validator over
|
||||
them, and the follow-up list read the way the WebApp reads it."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from core import fhir
|
||||
|
||||
VALIDATOR = os.environ.get("FHIR_VALIDATOR_JAR", "/opt/fhir/validator_cli.jar")
|
||||
PAGES = 100 # a search with more pages than this is a paging bug
|
||||
E = fhir.EXTENSION
|
||||
|
||||
|
||||
def pages(api, path: str, params=None) -> list[dict]:
|
||||
"""Every page of a search, following `next` to the end."""
|
||||
found, url = [], path
|
||||
for _ in range(PAGES):
|
||||
response = api.get(url, params=params)
|
||||
assert response.status_code == 200, response.text
|
||||
assert response.headers["content-type"].startswith("application/fhir+json")
|
||||
found.append(bundle := response.json())
|
||||
url = next((x["url"] for x in bundle["link"] if x["relation"] == "next"), None)
|
||||
params = None # the next link carries the query
|
||||
if url is None:
|
||||
return found
|
||||
raise AssertionError(f"{path}: more than {PAGES} pages")
|
||||
|
||||
|
||||
def served(api, base: str, periods: list[str], patients: list[str]) -> list[dict]:
|
||||
"""Every kind of resource the base serves, each search paged to the end: metadata,
|
||||
the measures and their reports, the follow-up list with what it includes, a read of
|
||||
each patient, and each clinical search for them."""
|
||||
found = [api.get(f"{base}/metadata").json()]
|
||||
found += pages(api, f"{base}/Measure")
|
||||
for measure in [e["resource"]["id"] for b in found[1:] for e in b["entry"]]:
|
||||
found += pages(api, f"{base}/MeasureReport",
|
||||
{"measure": measure, "reporting-period": ",".join(periods)}) # fmt: skip
|
||||
found += pages(api, f"{base}/Patient", [
|
||||
("follow-up-window", 12), ("_count", 25), ("_revinclude", "DiagnosticReport:subject"),
|
||||
("_revinclude", "RiskAssessment:subject"), ("_include:iterate", "DiagnosticReport:result"),
|
||||
]) # fmt: skip
|
||||
found += [api.get(f"{base}/Patient/{p}").json() for p in patients]
|
||||
for kind in ("DiagnosticReport", "Observation", "Condition", "Procedure", "RiskAssessment"):
|
||||
found += pages(api, f"{base}/{kind}", {"subject": ",".join(patients), "_count": 40})
|
||||
return found
|
||||
|
||||
|
||||
def validate(resources: list[dict], folder: Path) -> tuple[list[dict], list[dict]]:
|
||||
"""The HL7 validator (offline: no terminology server) over the resources, with our
|
||||
conformance resources loaded: its errors and its warnings."""
|
||||
data, ig = folder / "served", folder / "ig"
|
||||
data.mkdir()
|
||||
ig.mkdir()
|
||||
for i, resource in enumerate(resources):
|
||||
(data / f"{i:05d}.json").write_text(json.dumps(resource))
|
||||
for resource in fhir.conformance():
|
||||
(ig / f"{resource.get_resource_type()}-{resource.id}.json").write_text(
|
||||
resource.model_dump_json(exclude_none=True)) # fmt: skip
|
||||
out = folder / "outcome.json"
|
||||
subprocess.run(["java", "-jar", VALIDATOR, str(data), str(ig), "-version", fhir.FHIR_VERSION,
|
||||
"-tx", "n/a", "-ig", str(ig), "-output", str(out)],
|
||||
check=False, capture_output=True) # fmt: skip
|
||||
outcome = json.loads(out.read_text())
|
||||
outcomes = [e["resource"] for e in outcome.get("entry", [])] or [outcome]
|
||||
issues = [i for o in outcomes for i in o.get("issue", [])]
|
||||
errors = [i for i in issues if i["severity"] in ("error", "fatal")]
|
||||
return errors, [i for i in issues if i["severity"] == "warning"]
|
||||
|
||||
|
||||
SCORE_REQUIRED = "A measureScore is required when the Measure.scoring="
|
||||
|
||||
|
||||
def unscored(issue: dict, resources: list[dict]) -> bool:
|
||||
"""The validator's one allowed error: a summary report of a period with nothing to
|
||||
score (no denominator, nothing measured) has no score, since the rate or median is
|
||||
undefined. FHIR's validator asks for one anyway."""
|
||||
text = issue.get("details", {}).get("text", "")
|
||||
where = " ".join(issue.get("expression", []))
|
||||
if not text.startswith(SCORE_REQUIRED) or "/*MeasureReport/" not in where:
|
||||
return False
|
||||
report_id = where.split("/*MeasureReport/")[1].split("*/")[0]
|
||||
everything = [r for b in resources for r in [b, *(e["resource"] for e in b.get("entry", []))]]
|
||||
reports = [r for r in everything if r.get("id") == report_id
|
||||
and r.get("resourceType") == "MeasureReport"] # fmt: skip
|
||||
counts = {p["code"]["coding"][0]["code"]: p["count"]
|
||||
for r in reports for p in r["group"][0]["population"]} # fmt: skip
|
||||
nothing = counts.get("denominator", counts.get("measure-observation")) == 0
|
||||
scored = any("measureScore" in r["group"][0] for r in reports)
|
||||
return bool(reports) and nothing and not scored
|
||||
|
||||
|
||||
def _ext(resource: dict, name: str) -> dict | None:
|
||||
return next((x for x in resource.get("extension", []) if x["url"] == E + name), None)
|
||||
|
||||
|
||||
def _code(concept: dict) -> str:
|
||||
return concept["coding"][0]["code"]
|
||||
|
||||
|
||||
def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]:
|
||||
"""The follow-up list as the WebApp shows it, in order: per patient, her status, her
|
||||
latest cytology and HPV sampled in the window, her days to diagnosis, and her latest
|
||||
reported biopsy."""
|
||||
included = {(e["resource"]["resourceType"], e["resource"]["id"]): e["resource"]
|
||||
for b in bundles for e in b.get("entry", [])} # fmt: skip
|
||||
rows = []
|
||||
for b in bundles:
|
||||
for patient in (e["resource"] for e in b.get("entry", [])
|
||||
if e["search"]["mode"] == "match"): # fmt: skip
|
||||
reports = [r for (kind, _), r in included.items() if kind == "DiagnosticReport"
|
||||
and r["subject"]["reference"] == f"Patient/{patient['id']}"] # fmt: skip
|
||||
|
||||
def results(report: dict) -> dict:
|
||||
return {_code(o["code"]): o for o in (
|
||||
included[("Observation", x["reference"].split("/")[1])]
|
||||
for x in report.get("result", []))} # fmt: skip
|
||||
|
||||
cytologies = sorted(
|
||||
(r for r in reports if _code(r["code"]) == "cervical_cytology"
|
||||
and start <= r["effectiveDateTime"] <= cutoff),
|
||||
key=lambda r: r["effectiveDateTime"]) # fmt: skip
|
||||
hpv = [r for r in cytologies if "cervical_cytology.hpv" in results(r)]
|
||||
biopsies = sorted((r for r in reports if _code(r["code"]) == "cervical_biopsy"
|
||||
and _ext(r, "report-date")),
|
||||
key=lambda r: _ext(r, "report-date")["valueDate"]) # fmt: skip
|
||||
status = _ext(patient, "follow-up-status")["valueCoding"]["code"]
|
||||
row = {"person": patient["id"], "status": status, "cytology": None, "hpv": None,
|
||||
"days_to_diagnosis": None, "biopsy": None} # fmt: skip
|
||||
if cytologies:
|
||||
last, found = cytologies[-1], results(cytologies[-1])
|
||||
row["cytology"] = {"date": last["effectiveDateTime"], **{
|
||||
k: _code(found[c]["valueCodeableConcept"]) if c in found else None
|
||||
for k, c in (("result", "cervical_cytology.result"),
|
||||
("adequacy", "cervical_cytology.adequacy"))}} # fmt: skip
|
||||
days = _ext(last, "days-to-diagnosis")
|
||||
row["days_to_diagnosis"] = days and days["valueInteger"]
|
||||
if hpv:
|
||||
found = results(hpv[-1])
|
||||
typed = ("cervical_cytology.hpv_16", "cervical_cytology.hpv_18")
|
||||
types = [found[k]["valueBoolean"] for k in typed if k in found]
|
||||
row["hpv"] = {"date": hpv[-1]["effectiveDateTime"],
|
||||
"positive": found["cervical_cytology.hpv"]["valueBoolean"],
|
||||
"types_16_18": any(types) if types else None} # fmt: skip
|
||||
if biopsies:
|
||||
last, found = biopsies[-1], results(biopsies[-1])
|
||||
grade = found.get("cervical_biopsy.histology")
|
||||
histology = grade and _code(grade["valueCodeableConcept"])
|
||||
row["biopsy"] = {"date": _ext(last, "report-date")["valueDate"],
|
||||
"histology": histology} # fmt: skip
|
||||
rows.append(row)
|
||||
return rows
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
# Casos de CACU_CONFIRMACION_CITOLOGIA (confirmación por biopsia según resultado citológico, C2).
|
||||
# La unidad es la paciente cuya última citología válida del periodo es de alto grado
|
||||
# (`cacu.citologia_alto_grado`); la última válida es la de EU7 (`cacu.calidad_insatisfactoria`).
|
||||
# Cada categoría es `cat:<grado>` de la biopsia más grave que originó esa citología (ligada por
|
||||
# `cit_id`); sin biopsia reportada al corte, `cat:SIN_BIOPSIA`; con biopsia sin grado, `cat:SIN_DATO`.
|
||||
# `estratos` dice el valor de cada paciente en `citologia_alto_grado`: la fila del panel. Sin `corte`,
|
||||
# es el día de la carga del caso (2026-01-01).
|
||||
|
||||
measure = "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
|
||||
[[caso]]
|
||||
nombre = "una paciente con ASC-H y biopsia LIEAG cuenta en LIEAG dentro de la fila ASC-H"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-H" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:LIEAG" = 1, "cat:NORMAL" = 1 }
|
||||
unidades."2025-S1" = { "cat:LIEAG" = ["1"], "cat:NORMAL" = ["2"] } # la 2 es un falso positivo de la fila LIEAG
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H", "2" = "LIEAG" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "la última citología válida manda y no la peor"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 2, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEBG" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:LIEBG" = 1 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "con varias biopsias de la toma cuenta la más grave y no la más reciente"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01, bx_cin_grado = "LIEBG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 3, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-05-01, bx_cin_grado = "NORMAL" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:CIS" = 1, "cat:LIEBG" = 0, "cat:NORMAL" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una biopsia con grado gana a una sin grado; solo sin grado es sin dato"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "NORMAL" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-04-01 },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "CIS" },
|
||||
{ tabla = "biopsiacervical", bx_id = 3, pac_id = 2, cit_id = 2, bx_fecha_reporte = 2025-03-01 },
|
||||
]
|
||||
espera."2025-S1" = { "cat:NORMAL" = 1, "cat:SIN_DATO" = 1, "cat:SIN_BIOPSIA" = 0 }
|
||||
unidades."2025-S1" = { "cat:SIN_DATO" = ["2"] }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una biopsia reportada después del corte todavía no existe: sin biopsia aún"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" },
|
||||
]
|
||||
corte = 2025-07-31
|
||||
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:LIEAG" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el día del corte la biopsia ya existe"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "LIEAG" },
|
||||
]
|
||||
corte = 2025-08-01
|
||||
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 0, "cat:LIEAG" = 1 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una biopsia de otra toma no cuenta"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "ASC-H" },
|
||||
{ tabla = "biopsiacervical", bx_id = 2, pac_id = 1, bx_fecha_reporte = 2025-06-01, bx_cin_grado = "LIEAG" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:SIN_BIOPSIA" = 1, "cat:CIS" = 0, "cat:LIEAG" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "ASC-H" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una insatisfactoria posterior no es la última válida"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "LIEAG" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "INSATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:LIEAG" = 1 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "LIEAG" }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una paciente cuya última citología es NORMAL no entra aunque antes tuviera LIEAG"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "LIEAG" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-03-01, bx_cin_grado = "CIS" },
|
||||
{ tabla = "citologiacervical", cit_id = 2, pac_id = 1, cit_fecha_toma = 2025-05-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-05-10, cit_celulas_escamosas = "NORMAL" },
|
||||
{ tabla = "citologiacervical", cit_id = 3, pac_id = 2, cit_fecha_toma = 2025-02-01, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-02-10, cit_celulas_escamosas = "ASC-US" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:CIS" = 0, "cat:SIN_BIOPSIA" = 0, "cat:NORMAL" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = {}
|
||||
|
||||
[[caso]]
|
||||
nombre = "la citología cuenta en el periodo de su toma y no en el del reporte de la biopsia"
|
||||
filas = [
|
||||
{ tabla = "citologiacervical", cit_id = 1, pac_id = 1, cit_fecha_toma = 2025-06-20, cit_calidad_especimen = "SATISFACTORIO", cit_fecha_reporte = 2025-06-25, cit_celulas_escamosas = "CIS" },
|
||||
{ tabla = "biopsiacervical", bx_id = 1, pac_id = 1, cit_id = 1, bx_fecha_reporte = 2025-08-01, bx_cin_grado = "CARCINOMA" },
|
||||
]
|
||||
espera."2025-S1" = { "cat:CARCINOMA" = 1 }
|
||||
espera."2025-S2" = { "cat:CARCINOMA" = 0 }
|
||||
estratos."2025-S1".citologia_alto_grado = { "1" = "CIS" }
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
# Casos de CACU_RIESGO_BANDA (pacientes en vigilancia por banda de riesgo, C2). PROPUESTA (MD-Q5).
|
||||
# Cuenta a las miembros del armado del lote vigente (el mayor con alguna evaluación `final` al
|
||||
# horizonte) con fecha índice en el periodo, por la banda de la versión más reciente de su
|
||||
# evaluación. Con los parámetros de `parametros.toml`: BAJO < 0.04 <= INTERMEDIO < 0.25 <= ALTO,
|
||||
# horizonte 0. `cat:SIN_DATO`: sin evaluación `final` en el lote.
|
||||
|
||||
measure = "cacu/CACU_RIESGO_BANDA"
|
||||
|
||||
[plantillas]
|
||||
armado = [
|
||||
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/cohorte_vigilancia", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 4, armado_en = 2026-01-01T00:00:00Z },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 2, fecha_indice = 2025-03-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "2" },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 3, fecha_indice = 2025-04-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "3" },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 4, fecha_indice = 2025-08-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "4" },
|
||||
]
|
||||
lote_final = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 3, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 4, fecha_indice = 2025-08-01, horizonte_anios = 0.0, probabilidad = 0.3, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
|
||||
[[caso]]
|
||||
nombre = "cada paciente en la banda de su riesgo; sin evaluación es sin dato"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
espera."2025-S1" = { "cat:BAJO" = 1, "cat:INTERMEDIO" = 1, "cat:ALTO" = 0, "cat:SIN_DATO" = 1 }
|
||||
unidades."2025-S1" = { "cat:SIN_DATO" = [3] }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el periodo es el de la fecha índice"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
espera."2025-S2" = { "cat:ALTO" = 1, "cat:BAJO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el periodo es el de la fecha índice del riesgo, no la del miembro"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-09-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0 }
|
||||
espera."2025-S2" = { "cat:BAJO" = 1 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "los cortes son parámetros"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = []
|
||||
parametros = { "comun.riesgos.corte_intermedio" = 0.01, "comun.riesgos.corte_alto" = 0.05 }
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:INTERMEDIO" = 1, "cat:ALTO" = 1 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "un lote preliminar más nuevo no desplaza al vigente"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 2, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "2", mlflow_run_id = "sin-mlflow", modelo_sha = "s2", desenlace = "c", evaluado_en = 2026-02-01T00:00:00Z, n_evaluaciones = 1, huella = "l2" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 2, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.9, version = 1, estado = "preliminary", registrado_en = 2026-02-01T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 1, "cat:ALTO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una evaluación anulada en su versión 2 queda sin dato"
|
||||
incluye = ["armado", "lote_final"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 2, fecha_indice = 2025-03-01, horizonte_anios = 0.0, probabilidad = 0.1, version = 2, estado = "entered-in-error", motivo = "caso", registrado_en = 2026-01-03T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:INTERMEDIO" = 0, "cat:SIN_DATO" = 2 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "una evaluación a otro horizonte no cuenta"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 1.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "sin lote confirmado no hay población"
|
||||
incluye = ["armado"]
|
||||
filas = [
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "preliminary", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0, "cat:SIN_DATO" = 0 }
|
||||
|
||||
[[caso]]
|
||||
nombre = "el lote de otra cohorte no cuenta"
|
||||
filas = [
|
||||
{ tabla = "cohorte_armado", armado_id = 1, url = "cacu/otra", version = "0.1.0", definicion_sha = "d", reglas_sha = "r", parametros = "{}", datos_as_of = 2025-12-31, huella = "a1", marco_sha = "m1", n_miembros = 1, armado_en = 2026-01-01T00:00:00Z },
|
||||
{ tabla = "cohorte_miembro", armado_id = 1, pac_id = 1, fecha_indice = 2025-02-01, indice_fuente_tabla = "citologiacervical", indice_fuente_id = "1" },
|
||||
{ tabla = "evaluacion_riesgo_lote", lote_id = 1, armado_id = 1, modelo_nombre = "sustituto", modelo_version = "1", mlflow_run_id = "sin-mlflow", modelo_sha = "s", desenlace = "c", evaluado_en = 2026-01-02T00:00:00Z, n_evaluaciones = 1, huella = "l1" },
|
||||
{ tabla = "evaluacion_riesgo", lote_id = 1, pac_id = 1, fecha_indice = 2025-02-01, horizonte_anios = 0.0, probabilidad = 0.02, version = 1, estado = "final", registrado_en = 2026-01-02T00:00:00Z },
|
||||
]
|
||||
espera."2025-S1" = { "cat:BAJO" = 0 }
|
||||
+1264
File diff suppressed because it is too large
Load Diff
+387
@@ -0,0 +1,387 @@
|
||||
[
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-02-03",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-02-10",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-02-20",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-03-01",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "N871",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "1",
|
||||
"fecha": "2025-10-02",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "9"
|
||||
},
|
||||
{
|
||||
"pac_id": "2",
|
||||
"fecha": "2025-03-05",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "INSATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "2",
|
||||
"fecha": "2025-09-15",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "C53",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2024-12-01",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "C539",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-01-20",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "INSATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-02-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "ASC-US",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-02-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "POSITIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-02-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph_genotipo_16_18",
|
||||
"codigo": "vph_genotipo_16_18",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": "1.0",
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-10",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-15",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-25",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "LIEBG",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-25",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "POSITIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-04-25",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph_genotipo_16_18",
|
||||
"codigo": "vph_genotipo_16_18",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": "0.0",
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-05-01",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "3",
|
||||
"fecha": "2025-05-20",
|
||||
"clase": "medicion",
|
||||
"tipo": "biopsia",
|
||||
"codigo": "cin",
|
||||
"valor_codigo": "CIN1",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-05-30",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "5"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-06-09",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "5"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-06-25",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-01",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-11",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "LIEAG",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-11",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "POSITIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-11",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph_genotipo_16_18",
|
||||
"codigo": "vph_genotipo_16_18",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": "1.0",
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "6"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-07-15",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-08-01",
|
||||
"clase": "medicion",
|
||||
"tipo": "biopsia",
|
||||
"codigo": "cin",
|
||||
"valor_codigo": "CIN2",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "2"
|
||||
},
|
||||
{
|
||||
"pac_id": "4",
|
||||
"fecha": "2025-08-10",
|
||||
"clase": "diagnostico",
|
||||
"tipo": "nota_medica",
|
||||
"codigo": "nota_medica",
|
||||
"valor_codigo": "D069",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "notamedica",
|
||||
"fuente_id": "1"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-08-12",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "SATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "7"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-08-22",
|
||||
"clase": "medicion",
|
||||
"tipo": "bethesda",
|
||||
"codigo": "bethesda",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "7"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-08-22",
|
||||
"clase": "medicion",
|
||||
"tipo": "vph",
|
||||
"codigo": "vph",
|
||||
"valor_codigo": "NEGATIVO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "7"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-09-01",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": null,
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "biopsiacervical",
|
||||
"fuente_id": "3"
|
||||
},
|
||||
{
|
||||
"pac_id": "5",
|
||||
"fecha": "2025-12-01",
|
||||
"clase": "orden",
|
||||
"tipo": "orden",
|
||||
"codigo": "orden",
|
||||
"valor_codigo": "SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "ordenesestudio",
|
||||
"fuente_id": "4"
|
||||
},
|
||||
{
|
||||
"pac_id": "6",
|
||||
"fecha": "2025-09-01",
|
||||
"clase": "procedimiento",
|
||||
"tipo": "citologia",
|
||||
"codigo": "citologia_cervical",
|
||||
"valor_codigo": "INSATISFACTORIO",
|
||||
"valor_numerico": null,
|
||||
"fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "8"
|
||||
}
|
||||
]
|
||||
Vendored
+7735
File diff suppressed because it is too large
Load Diff
Vendored
+6242
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
"""Synthetic staging rows for the tests, one module per domain: written by hand, never real data."""
|
||||
@@ -0,0 +1,187 @@
|
||||
"""Filas sintéticas del staging de CaCu, escritas a mano. Nunca datos reales.
|
||||
|
||||
Seis pacientes y nueve citologías en dos semestres de 2025. Los textos de
|
||||
calidad son provisionales: los valores reales están sin confirmar.
|
||||
|
||||
Pacientes tamizadas: 4 en 2025-S1 y 4 en 2025-S2; de ellas, con muestra
|
||||
insatisfactoria, 2 y 1. Lo que da cada indicador va abajo (`ESPERADO_*`).
|
||||
|
||||
Casos que ejercita: H-003 tiene dos citologías en S1 y cuenta una vez;
|
||||
H-004 tiene una el 1 de julio, que ya es S2; H-001 aparece en los dos
|
||||
semestres.
|
||||
|
||||
Resultados (v0.5.0, T-4): seis citologías tienen reporte y cuatro, VPH;
|
||||
las dos insatisfactorias de H-002 y H-006 no tienen reporte, y la última
|
||||
de H-001 todavía no. Tres biopsias, cada una con la citología que la
|
||||
originó: dos reportadas y una pendiente. Los textos de resultado también
|
||||
son provisionales.
|
||||
|
||||
Cinco notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical, NotaMedica, OrdenesEstudio, Paciente
|
||||
from sqlmodel import Session, select
|
||||
|
||||
SATISFACTORIO = "SATISFACTORIO"
|
||||
INSATISFACTORIO = "INSATISFACTORIO"
|
||||
|
||||
PACIENTES = ("H-001", "H-002", "H-003", "H-004", "H-005", "H-006")
|
||||
|
||||
# (pac_id_hospital, fecha de toma, calidad del espécimen)
|
||||
CITOLOGIAS = (
|
||||
("H-001", date(2025, 2, 10), SATISFACTORIO),
|
||||
("H-002", date(2025, 3, 5), INSATISFACTORIO),
|
||||
("H-003", date(2025, 1, 20), INSATISFACTORIO),
|
||||
("H-003", date(2025, 4, 15), SATISFACTORIO),
|
||||
("H-004", date(2025, 5, 30), SATISFACTORIO),
|
||||
("H-004", date(2025, 7, 1), SATISFACTORIO),
|
||||
("H-005", date(2025, 8, 12), SATISFACTORIO),
|
||||
("H-006", date(2025, 9, 1), INSATISFACTORIO),
|
||||
("H-001", date(2025, 10, 2), SATISFACTORIO),
|
||||
)
|
||||
|
||||
# Índice en CITOLOGIAS -> (fecha de reporte, células escamosas, VPH, genotipo 16, genotipo 18).
|
||||
RESULTADOS = {
|
||||
0: (date(2025, 2, 20), "NEGATIVO", None, None, None),
|
||||
2: (date(2025, 2, 1), "ASC-US", "POSITIVO", 1, 0),
|
||||
3: (date(2025, 4, 25), "LIEBG", "POSITIVO", 0, 0),
|
||||
4: (date(2025, 6, 9), "NEGATIVO", None, None, None),
|
||||
5: (date(2025, 7, 11), "LIEAG", "POSITIVO", 0, 1),
|
||||
6: (date(2025, 8, 22), "NEGATIVO", "NEGATIVO", None, None),
|
||||
}
|
||||
|
||||
# (índice de la citología que la originó, fecha de solicitud, fecha de reporte, grado CIN)
|
||||
BIOPSIAS = (
|
||||
(3, date(2025, 5, 1), date(2025, 5, 20), "CIN1"),
|
||||
(5, date(2025, 7, 15), date(2025, 8, 1), "CIN2"),
|
||||
(6, date(2025, 9, 1), None, None),
|
||||
)
|
||||
|
||||
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
|
||||
COLPOSCOPIA, ONCOLOGIA, FAMILIAR = "CLINICA DE MUJER Y COLPOSCOPIA", "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
NOTAS = (
|
||||
("H-004", date(2025, 8, 10), "D06.9", COLPOSCOPIA), # 72 días de su toma de mayo y 40 de la de julio
|
||||
("H-003", date(2024, 12, 1), "C53.9", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
|
||||
("H-001", date(2025, 3, 1), "N87.1", FAMILIAR), # displasia, pero de medicina familiar: no resuelve
|
||||
("H-002", date(2025, 9, 15), "C53", ONCOLOGIA), # a 194 días de su toma: fuera del horizonte
|
||||
("H-005", date(2026, 1, 20), "c539", COLPOSCOPIA), # 161 días de su toma, pero después del corte de fin de año
|
||||
)
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la especialidad de la tercera no está en el catálogo de Core
|
||||
# y queda sin reconocer; la cuarta está pedida y todavía no tiene citología.
|
||||
ORDENES = (
|
||||
(50001, "H-001", date(2025, 2, 3), "MEDICINA FAMILIAR"),
|
||||
(50002, "H-003", date(2025, 4, 10), "CLINICA DE MUJER Y COLPOSCOPIA"),
|
||||
(50003, "H-004", date(2025, 6, 25), "Dermatología"),
|
||||
(50004, "H-005", date(2025, 12, 1), "MEDICINA FAMILIAR"),
|
||||
)
|
||||
|
||||
# Índice en CITOLOGIAS -> número de su orden. Las demás citologías no traen número; la de
|
||||
# H-005 trae uno que no existe entre las órdenes.
|
||||
ORDEN_DE_CITOLOGIA = {0: 50001, 3: 50002, 5: 50003, 6: 59999}
|
||||
|
||||
# periodo -> (denominador, numerador) de IND1, con la lista de `cacu.citologia_anomala`
|
||||
# (ASC-US, ASC-H, LIEBG, LIEAG, CIS). En S1 solo H-003 (su ASC-US y su LIEBG; cuenta una
|
||||
# vez); en S2 solo H-004 (su LIEAG del 1 de julio).
|
||||
ESPERADO_IND1 = {"2025-S1": (4, 1), "2025-S2": (4, 1)}
|
||||
|
||||
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CACU_EU_TIEMPO_REPORTE,
|
||||
# con horizonte de 60 días. Días de toma a resultado: S1 10, 12, 10, 10 (la toma del 5 de
|
||||
# marzo no tiene resultado y a fin de año ya pasó el horizonte: cuenta en la inicial y no en
|
||||
# n); S2 10, 10. A mediados de octubre las tomas de septiembre y octubre sin resultado siguen
|
||||
# dentro del horizonte: no se miden. A mediados de agosto el resultado del 22 todavía no existe.
|
||||
ESPERADO_CACU_TIEMPO = {
|
||||
("2025-S1", "2025-12-31"): (5, 4, 10.0, 10.0, 10.5),
|
||||
("2025-S2", "2025-12-31"): (4, 2, 10.0, 10.0, 10.0),
|
||||
("2025-S2", "2025-10-15"): (2, 2, 10.0, 10.0, 10.0),
|
||||
("2025-S2", "2025-08-15"): (1, 1, 10.0, 10.0, 10.0),
|
||||
}
|
||||
|
||||
# periodo -> (denominador, numerador) de CACU_EU13, con la lista de arranque de
|
||||
# `cacu.deteccion_grados` (LIEAG, CIS, CARCINOMA). Los grados de las biopsias de
|
||||
# este fixture (CIN1, CIN2) son textos provisionales que no están en esa lista:
|
||||
# el numerador es cero. El distinto de cero se prueba con filas escritas a mano
|
||||
# en `cacu/familias/eu13/casos.toml`.
|
||||
ESPERADO_CACU_EU13 = {"2025-S1": (4, 0), "2025-S2": (4, 0)}
|
||||
|
||||
# periodo -> {categoría: pacientes} de CACU_EU7 (solo las que tienen alguna). En S1, H-003
|
||||
# cuenta con el LIEBG de abril (su ASC-US de enero es de una muestra insatisfactoria y,
|
||||
# además, anterior) y H-002 no tiene resultado; en S2, H-006 no tiene resultado y la de
|
||||
# octubre de H-001 todavía no. «NEGATIVO» es un texto provisional de este fixture: no está
|
||||
# en el catálogo (que usa NORMAL, como Core) y sale después de SIN_DATO.
|
||||
ESPERADO_CACU_EU7 = {
|
||||
"2025-S1": {"NEGATIVO": 2, "LIEBG": 1, "SIN_DATO": 1},
|
||||
"2025-S2": {"NEGATIVO": 1, "LIEAG": 1, "SIN_DATO": 2},
|
||||
}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Inserta pacientes, órdenes, citologías y biopsias. `pac_id` se resuelve por `pac_id_hospital`."""
|
||||
pacientes = {
|
||||
hospital: Paciente(
|
||||
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1980, 1, 1)
|
||||
)
|
||||
for hospital in PACIENTES
|
||||
}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
OrdenesEstudio(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=numero,
|
||||
ord_tipo_estudio="SOLICITUD DE PAPANICOLAO EN BASE LIQUIDA",
|
||||
ord_fecha=fecha,
|
||||
ord_especialidad=especialidad,
|
||||
)
|
||||
for numero, hospital, fecha, especialidad in ORDENES
|
||||
)
|
||||
citologias = []
|
||||
for indice, (hospital, toma, calidad) in enumerate(CITOLOGIAS):
|
||||
reporte, escamosas, vph, genotipo_16, genotipo_18 = RESULTADOS.get(indice, (None,) * 5)
|
||||
citologias.append(
|
||||
CitologiaCervical(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=ORDEN_DE_CITOLOGIA.get(indice),
|
||||
cit_fecha_toma=toma,
|
||||
cit_calidad_especimen=calidad,
|
||||
cit_fecha_reporte=reporte,
|
||||
cit_celulas_escamosas=escamosas,
|
||||
cit_vph_resultado=vph,
|
||||
cit_vph_genotipo_16=genotipo_16,
|
||||
cit_vph_genotipo_18=genotipo_18,
|
||||
)
|
||||
)
|
||||
sesion.add_all(citologias)
|
||||
sesion.flush()
|
||||
for indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
citologia = citologias[indice]
|
||||
sesion.add(
|
||||
BiopsiaCervical(
|
||||
pac_id=citologia.pac_id,
|
||||
pac_id_hospital=citologia.pac_id_hospital,
|
||||
cit_id=citologia.cit_id,
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_cin_grado=grado,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
NotaMedica(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
nm_id_hospital=f"NM-{numero:03d}",
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
sesion.commit()
|
||||
@@ -0,0 +1,213 @@
|
||||
"""Filas sintéticas del staging de CaMa, escritas a mano. Nunca datos reales.
|
||||
|
||||
Seis pacientes y nueve mastografías en dos semestres de 2025. Los textos
|
||||
de calidad son provisionales: los valores reales están sin confirmar.
|
||||
|
||||
Mastografías: 5 en 2025-S1 y 4 en 2025-S2; de ellas, satisfactorias, 4 y 2.
|
||||
Lo que da cada indicador va abajo (`ESPERADO_*`).
|
||||
|
||||
Casos que ejercita: H-001 tiene dos mastografías en S1 y cuentan las dos;
|
||||
una del 1 de julio ya es S2; una de S2 no tiene calidad y cuenta en el
|
||||
denominador pero no en el numerador.
|
||||
|
||||
Resultados (v0.5.0, T-4): cada mastografía trae su BI-RADS; tiene fecha
|
||||
de reporte una semana después de la toma, salvo la que no tiene calidad
|
||||
ni BI-RADS y la última, todavía sin reporte.
|
||||
|
||||
Tres biopsias, cada una con la mastografía que la originó: dos con
|
||||
reporte y grado, y una solicitada que todavía no lo tiene.
|
||||
|
||||
Seis notas médicas con su CIE-10, para el tiempo de la toma al diagnóstico
|
||||
(`NOTAS`; sus casos están en `familias/dias_toma_diagnostico/casos.toml`).
|
||||
|
||||
Texts the silver load reads results from (`TEXTOS`, `INFORME_DE_PATOLOGIA`, `DIAGNOSTICO_DE_NOTA`):
|
||||
H-003's B4A carries density C and a 14 mm lesion, its biopsy a PDF with an invasive ductal carcinoma, grade 2,
|
||||
ER+ 90 %, PR- 0 %, HER2 3+ and Ki-67 25 %, and its oncology note stage IIA. H-101's first mammography says
|
||||
density "tipo E", which the catalog doesn't know: it stays as source text, out of catalog.
|
||||
|
||||
H-001 y H-003 también están en el fixture de CaCu, con otro `pac_id`:
|
||||
lo único común entre los dos sistemas es `pac_id_hospital`.
|
||||
|
||||
Apoyo de pruebas: escribe en la sesión que se le da, nunca en la base del dominio.
|
||||
"""
|
||||
|
||||
import io
|
||||
from datetime import date, timedelta
|
||||
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, OrdenesEstudio, Paciente
|
||||
from sqlmodel import Session, select
|
||||
|
||||
SATISFACTORIO = "SATISFACTORIO"
|
||||
INSATISFACTORIO = "INSATISFACTORIO"
|
||||
|
||||
PACIENTES = ("H-101", "H-102", "H-001", "H-003", "H-103", "H-104")
|
||||
|
||||
# (pac_id_hospital, fecha de toma, calidad de imagen, BI-RADS)
|
||||
MASTOGRAFIAS = (
|
||||
("H-101", date(2025, 1, 15), SATISFACTORIO, "B1"),
|
||||
("H-102", date(2025, 2, 20), SATISFACTORIO, "B2"),
|
||||
("H-001", date(2025, 3, 10), INSATISFACTORIO, "B0"),
|
||||
("H-001", date(2025, 4, 2), SATISFACTORIO, "B1"),
|
||||
("H-003", date(2025, 6, 30), SATISFACTORIO, "B4A"),
|
||||
("H-103", date(2025, 7, 1), SATISFACTORIO, "B1"),
|
||||
("H-103", date(2025, 9, 9), None, None),
|
||||
("H-104", date(2025, 11, 11), INSATISFACTORIO, "B0"),
|
||||
("H-102", date(2025, 12, 31), SATISFACTORIO, "B2"),
|
||||
)
|
||||
|
||||
# (índice de la mastografía que la originó, fecha de solicitud, fecha de reporte, grado histológico)
|
||||
BIOPSIAS = (
|
||||
(2, date(2025, 3, 20), date(2025, 4, 5), "BENIGNO"),
|
||||
(4, date(2025, 7, 10), date(2025, 7, 28), "CARCINOMA_INVASOR"),
|
||||
(7, date(2025, 11, 20), None, None),
|
||||
)
|
||||
|
||||
# Notas médicas: (paciente, fecha de la nota, CIE-10 y especialidad como los escribe el hospital).
|
||||
# La de H-003 llega con minúscula y punto; la de H-104 no tiene fecha y la de H-101 es de
|
||||
# medicina familiar, que no resuelve la toma.
|
||||
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
NOTAS = (
|
||||
("H-003", date(2025, 8, 4), "c50.4", ONCOLOGIA), # 35 días de su B4A del 30 de junio
|
||||
("H-001", date(2025, 3, 1), "D05.1", FAMILIAR), # cáncer anterior a sus dos tomas: no es un caso nuevo
|
||||
("H-102", date(2025, 9, 30), "C50.9", ONCOLOGIA), # a 222 días de su toma de febrero: fuera del horizonte
|
||||
("H-103", date(2025, 7, 20), "C50.9", ONCOLOGIA), # 19 días de su toma del 1 de julio
|
||||
("H-101", date(2025, 1, 15), "Z12.3", FAMILIAR), # normal, pero de medicina familiar: no resuelve
|
||||
("H-104", None, "C50", ONCOLOGIA), # sin fecha: no cuenta
|
||||
)
|
||||
|
||||
# Index in MASTOGRAFIAS -> the radiologist's interpretation.
|
||||
TEXTOS = {
|
||||
0: "Densidad mamaria: tipo E\nSin hallazgos.",
|
||||
4: "Densidad mamaria: heterogéneamente densas (C).\nNódulo irregular en CSE.\nTamaño de la lesión: 14 mm.",
|
||||
}
|
||||
# Index in BIOPSIAS -> the lines of its pathology report, as a PDF with a text layer.
|
||||
INFORME_DE_PATOLOGIA = {
|
||||
1: (
|
||||
"DIAGNÓSTICO: Carcinoma ductal infiltrante",
|
||||
"Grado histológico: 2 (moderadamente diferenciado)",
|
||||
"Receptores de estrógeno: Positivo (90%)",
|
||||
"Receptores de progesterona: Negativo (0%)",
|
||||
"HER2: 3+",
|
||||
"Ki-67: 25%",
|
||||
),
|
||||
}
|
||||
# Patient -> the diagnosis text of their note.
|
||||
DIAGNOSTICO_DE_NOTA = {"H-003": "Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)"}
|
||||
|
||||
|
||||
def pdf_de(lineas) -> bytes:
|
||||
"""A one-page PDF with these lines as its text layer."""
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
hoja = canvas.Canvas(buffer, pagesize=letter)
|
||||
for i, linea in enumerate(lineas):
|
||||
hoja.drawString(72, 720 - 18 * i, linea)
|
||||
hoja.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
# Órdenes de estudio: (número, paciente, fecha de la orden, especialidad como la escribe el hospital).
|
||||
# La segunda no es de tamizaje; la tercera está pedida y todavía no tiene mastografía.
|
||||
ORDENES = (
|
||||
(60001, "H-101", date(2025, 1, 10), "MEDICINA FAMILIAR"),
|
||||
(60002, "H-003", date(2025, 6, 20), "CIRUGIA ONCOLOGICA"),
|
||||
(60003, "H-104", date(2025, 12, 5), "MEDICINA FAMILIAR"),
|
||||
)
|
||||
|
||||
# Índice en MASTOGRAFIAS -> número de su orden. Las demás no traen número; la de H-102 trae
|
||||
# uno que no existe entre las órdenes.
|
||||
ORDEN_DE_MASTOGRAFIA = {0: 60001, 4: 60002, 1: 69999}
|
||||
|
||||
# periodo -> {categoría: pacientes} de CAMA_BIRADS (solo las que tienen alguna).
|
||||
# H-001 tiene B0 y B1 en S1: cuenta en B0, la más grave. H-103 tiene B1 y una toma sin
|
||||
# reporte: cuenta en B1. H-102 tiene en S2 solo una toma sin reporte: SIN_DATO.
|
||||
ESPERADO_CAMA_BIRADS = {
|
||||
"2025-S1": {"B0": 1, "B1": 1, "B2": 1, "B4A": 1},
|
||||
"2025-S2": {"B0": 1, "B1": 1, "SIN_DATO": 1},
|
||||
}
|
||||
|
||||
# (periodo, fecha de corte) -> (población inicial, n, q1, mediana, q3) de CAMA_EU38A, con
|
||||
# horizonte de 60 días. Todo reporte llega siete días después de la toma. A fin de año la
|
||||
# toma del 9 de septiembre ya pasó el horizonte sin reporte (cuenta en la inicial y no en n)
|
||||
# y la del 31 de diciembre sigue en observación. El 15 de septiembre ninguna toma de S2
|
||||
# posterior a julio tiene reporte ni ha vencido: solo se mide la del 1 de julio.
|
||||
ESPERADO_CAMA_EU38A = {
|
||||
("2025-S1", "2025-12-31"): (5, 5, 7.0, 7.0, 7.0),
|
||||
("2025-S2", "2025-12-31"): (3, 2, 7.0, 7.0, 7.0),
|
||||
("2025-S2", "2025-09-15"): (1, 1, 7.0, 7.0, 7.0),
|
||||
}
|
||||
|
||||
# periodo -> (denominador, numerador) de CAMA_CONFIRMACION_BIRADS45, con la lista de arranque de
|
||||
# `cama.birads_sospecha` (B4 con o sin subcategoría, B5). La única mastografía de sospecha es la B4A de H-003 del 30 de
|
||||
# junio, y su biopsia se reportó el 28 de julio: cuenta en S1, el semestre de la mastografía.
|
||||
# Las otras dos biopsias salen de mastografías B0, que no están en la lista. En S2 no hay
|
||||
# ninguna de sospecha: sin denominador, el reporte sale suprimido y no se compara.
|
||||
ESPERADO_CAMA_CONFIRMACION_BIRADS45 = {"2025-S1": (1, 1)}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Inserta pacientes, órdenes, mastografías, biopsias y notas. `pac_id` se resuelve por `pac_id_hospital`."""
|
||||
pacientes = {
|
||||
hospital: Paciente(
|
||||
pac_id_hospital=hospital, pac_sexo="Femenino", pac_fecha_nacimiento=date(1975, 1, 1)
|
||||
)
|
||||
for hospital in PACIENTES
|
||||
}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
sesion.add_all(
|
||||
OrdenesEstudio(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=numero,
|
||||
ord_tipo_estudio="MASTOGRAFIA",
|
||||
ord_fecha=fecha,
|
||||
ord_especialidad=especialidad,
|
||||
)
|
||||
for numero, hospital, fecha, especialidad in ORDENES
|
||||
)
|
||||
mastografias = []
|
||||
for indice, (hospital, toma, calidad, birads) in enumerate(MASTOGRAFIAS):
|
||||
sin_reporte = birads is None or indice == len(MASTOGRAFIAS) - 1
|
||||
mastografias.append(
|
||||
Mastografia(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
ord_numero_hospital=ORDEN_DE_MASTOGRAFIA.get(indice),
|
||||
mast_fecha_toma=toma,
|
||||
mast_calidad_imagen=calidad,
|
||||
mast_birads=birads,
|
||||
mast_fecha_reporte=None if sin_reporte else toma + timedelta(days=7),
|
||||
mast_interpretacion=TEXTOS.get(indice),
|
||||
)
|
||||
)
|
||||
sesion.add_all(mastografias)
|
||||
sesion.flush()
|
||||
for numero, (indice, solicitud, reporte, grado) in enumerate(BIOPSIAS):
|
||||
mastografia = mastografias[indice]
|
||||
sesion.add(
|
||||
BiopsiaMama(
|
||||
pac_id=mastografia.pac_id,
|
||||
pac_id_hospital=mastografia.pac_id_hospital,
|
||||
mast_id=mastografia.mast_id,
|
||||
bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte,
|
||||
bx_grado_histologico=grado,
|
||||
bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[numero]) if numero in INFORME_DE_PATOLOGIA else None,
|
||||
)
|
||||
)
|
||||
sesion.add_all(
|
||||
NotaMedica(
|
||||
pac_id=pacientes[hospital].pac_id,
|
||||
pac_id_hospital=hospital,
|
||||
nm_id_hospital=f"NM-{numero:03d}",
|
||||
nm_fecha=fecha,
|
||||
nm_cie_codigo=cie,
|
||||
nm_especialidad=especialidad,
|
||||
nm_diagnostico_texto=DIAGNOSTICO_DE_NOTA.get(hospital) if especialidad == ONCOLOGIA else None,
|
||||
)
|
||||
for numero, (hospital, fecha, cie, especialidad) in enumerate(NOTAS, start=1)
|
||||
)
|
||||
sesion.commit()
|
||||
@@ -0,0 +1,160 @@
|
||||
"""TEA's synthetic staging, written by hand. Never real data.
|
||||
|
||||
Seven children screened in 2025, each one exercising a rule of the screening's chain (M-CHAT, psychology note
|
||||
with the ADOS-2, neuropediatrics note, good-quality EEG). Ages are at the first M-CHAT, in completed months:
|
||||
|
||||
- 1, H-T01, 19 months (16 to 23): the whole chain. M-CHAT 10 Jan, ADOS-2 5 Feb, F84.0 note 12 Mar, a bad EEG
|
||||
2 Apr, a good EEG 20 May with a slow posterior rhythm, then a second good EEG 1 Sep that changes nothing. Leaves
|
||||
after May. Its EEG has an order.
|
||||
- 2, H-T02, 26 months (24 to 29): M-CHAT 20 Jan, ADOS-2 1 Mar, a note with F84 without subcode 10 Apr (not a
|
||||
confirmation), no EEG: stays at neuropediatrics.
|
||||
- 3, H-T03, 35 months (30 to 36): M-CHAT 14 Feb (a second one 10 Jun doesn't count), ADOS-2 28 Feb, nothing else:
|
||||
stays at psychology.
|
||||
- 4, H-T04, 39 months: out of the cohort, never counted.
|
||||
- 5, H-T05, 21 months: M-CHAT 15 Jun, a F84.0 note 1 Jul and a good EEG 20 Jul without the ADOS-2: steps go in
|
||||
order, so it stays at M-CHAT and in process.
|
||||
- 6, H-T06, 26 months: M-CHAT 5 Apr, ADOS-2 20 Apr, a good EEG 1 Jun before its F84.0 note of 2 Jun: the EEG
|
||||
step is dated by the note, so it reaches EEG on 2 Jun and leaves after June.
|
||||
- 7, H-T07, without birth date: in the cohort with age group `sin_dato`. M-CHAT 1 May, nothing else.
|
||||
|
||||
Every EEG's verdict and quality checks are written as its analysis would: a good EEG has its study-wide checks
|
||||
within their limits; a bad one has too few clean windows and a dead channel (T3).
|
||||
|
||||
Test support: writes in the session it's given, never in the domain's database.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
from core.tea.models import (
|
||||
Ados2,
|
||||
Eeg,
|
||||
EegCriterio,
|
||||
EegMetrica,
|
||||
EegMetricaElectrodo,
|
||||
EvaluacionNeuropediatrica,
|
||||
Mchat,
|
||||
OrdenesEstudio,
|
||||
Pacientes,
|
||||
)
|
||||
from sqlmodel import Session
|
||||
|
||||
# (pac_id, pac_id_hospital, birth date)
|
||||
PACIENTES = (
|
||||
(1, "H-T01", date(2023, 6, 1)),
|
||||
(2, "H-T02", date(2022, 11, 15)),
|
||||
(3, "H-T03", date(2022, 3, 1)),
|
||||
(4, "H-T04", date(2021, 12, 1)),
|
||||
(5, "H-T05", date(2023, 9, 1)),
|
||||
(6, "H-T06", date(2023, 1, 10)),
|
||||
(7, "H-T07", None),
|
||||
)
|
||||
|
||||
# (pac_id, date, score)
|
||||
MCHATS = (
|
||||
(1, date(2025, 1, 10), 12),
|
||||
(2, date(2025, 1, 20), 9),
|
||||
(3, date(2025, 2, 14), 15),
|
||||
(3, date(2025, 6, 10), 4),
|
||||
(4, date(2025, 3, 3), 11),
|
||||
(5, date(2025, 6, 15), 8),
|
||||
(6, date(2025, 4, 5), 14),
|
||||
(7, date(2025, 5, 1), 7),
|
||||
)
|
||||
|
||||
# (pac_id, date, module, CSS, classification)
|
||||
ADOS2 = (
|
||||
(1, date(2025, 2, 5), "MODULO_1", 7, "AUTISMO"),
|
||||
(2, date(2025, 3, 1), "Toddler", 4, "espectro autista"),
|
||||
(3, date(2025, 2, 28), "MODULO_2", 2, "NO_TEA"),
|
||||
(6, date(2025, 4, 20), "MODULO_1", 8, "AUTISMO"),
|
||||
)
|
||||
|
||||
# (pac_id, date, ICD-10 as the hospital writes it)
|
||||
NOTAS = (
|
||||
(1, date(2025, 3, 12), "F84.0"),
|
||||
(2, date(2025, 4, 10), "F84"),
|
||||
(5, date(2025, 7, 1), "f84.0"),
|
||||
(6, date(2025, 6, 2), "F84.0"),
|
||||
)
|
||||
|
||||
# The analysis's verdict, triage level, clean fraction, bad channels and line noise, and its checks:
|
||||
# (code, electrode, value, text, unit, low, high, decisive, abnormal).
|
||||
GOOD = {"valido": 1, "nivel": "completo", "limpia": 0.95, "malos": 0, "linea": 3.5, "criterios": (
|
||||
("clean-windows", None, 95.0, None, "%", 60.0, None, 1, 0),
|
||||
("usable-scalp", None, 19.0, None, "electrodes", 12.0, None, 1, 0),
|
||||
("triage-level", None, None, "completo", None, None, None, 1, 0),
|
||||
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
|
||||
)}
|
||||
BAD = {"valido": 0, "nivel": "parcial", "limpia": 0.4, "malos": 1, "linea": 3.5, "criterios": (
|
||||
("dead-channel", "T3", None, "dead channel", None, None, None, 0, 1),
|
||||
("clean-windows", None, 40.0, None, "%", 60.0, None, 1, 1),
|
||||
("usable-scalp", None, 18.0, None, "electrodes", 12.0, None, 1, 0),
|
||||
("line-noise", None, 3.5, None, "dB", None, 45.0, 0, 0),
|
||||
)}
|
||||
|
||||
# (eeg id, pac_id, date, laboratory id, analysis, with sleep)
|
||||
EEGS = (
|
||||
("eeg-1a", 1, date(2025, 4, 2), "LAB-1A", BAD, 0),
|
||||
("eeg-1b", 1, date(2025, 5, 20), "LAB-1B", GOOD, 1),
|
||||
("eeg-1c", 1, date(2025, 9, 1), "LAB-1C", GOOD, 1),
|
||||
("eeg-5", 5, date(2025, 7, 20), "LAB-5", GOOD, 0),
|
||||
("eeg-6", 6, date(2025, 6, 1), "LAB-6", GOOD, 1),
|
||||
)
|
||||
|
||||
# (metric id, eeg id, code, value, deviation): a null value can't be evaluated. The deviation is the analysis's
|
||||
# against the metric's age baseline: (z, -1/0/+1, p5, median, p95). Child 1's slow posterior rhythm is below p5.
|
||||
METRICAS = (
|
||||
("met-1b-rp", "eeg-1b", "RITMO_POSTERIOR", 3.2, (-4.08, -1, 4.5, 5.75, 7.0)),
|
||||
("met-1b-n2", "eeg-1b", "HUSOS_SUENO_N2", 4.0, (-0.5, 0, 2.5, 4.5, 6.5)),
|
||||
("met-1b-pp", "eeg-1b", "PICOS_PAROXISTICOS", 0.4, (-0.4, 0, 0.0, 0.5, 1.0)),
|
||||
("met-1a-rp", "eeg-1a", "RITMO_POSTERIOR", 2.0, (-6.0, -1, 4.5, 5.75, 7.0)),
|
||||
("met-6-rp", "eeg-6", "RITMO_POSTERIOR", 6.5, (0.4, 0, 5.0, 6.25, 7.5)),
|
||||
("met-6-n2", "eeg-6", "HUSOS_SUENO_N2", None, (None, None, None, None, None)),
|
||||
("met-6-gr", "eeg-6", "GRADIENTE_ANTEROPOSTERIOR", 2.6, (0.27, 0, 1.75, 2.5, 3.25)),
|
||||
)
|
||||
|
||||
# (electrode value id, metric id, electrode, value, z-score)
|
||||
ELECTRODOS = (
|
||||
("mel-1", "met-1b-rp", "O1", 3.0, -2.8),
|
||||
("mel-2", "met-1b-rp", "O2", 3.1, -2.4),
|
||||
("mel-3", "met-1b-rp", "Pz", 3.6, -1.1),
|
||||
)
|
||||
|
||||
# The EEG of child 1 that completes the chain hangs from an order.
|
||||
ORDENES = (("ord-1b", 1, "ORD-T01-EEG", "ELECTROENCEFALOGRAMA", date(2025, 5, 2)),)
|
||||
ORDEN_DE = {"eeg-1b": "ord-1b"}
|
||||
|
||||
# What the load gives (`test_orquestacion_plata`): a bad channel is a part of its EEG, as an electrode value is.
|
||||
CANALES_MALOS = sum(1 for *_, analisis, _ in EEGS for c in analisis["criterios"] if c[1] is not None)
|
||||
PROCEDIMIENTOS = len(ORDENES) + len(MCHATS) + len(ADOS2) + len(NOTAS) + len(EEGS) + len(ELECTRODOS) + CANALES_MALOS
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
"""Writes the children, their orders and their studies."""
|
||||
sesion.add_all(Pacientes(pac_id=p, pac_id_hospital=h, pac_fecha_nacimiento=n) for p, h, n in PACIENTES)
|
||||
sesion.add_all(OrdenesEstudio(ord_id=i, ord_pac_id=p, ord_id_hospital=h, ord_tipo_estudio=t, ord_fecha=f)
|
||||
for i, p, h, t, f in ORDENES)
|
||||
sesion.add_all(Mchat(mch_id=f"mch-{k}", mch_pac_id=p, mch_fecha=f, mch_puntaje=s)
|
||||
for k, (p, f, s) in enumerate(MCHATS, 1))
|
||||
for k, (p, f, modulo, css, clasificacion) in enumerate(ADOS2, 1):
|
||||
items = {f"ado_sa_b{n}": n % 3 for n in range(1, 6)} | {"ado_rrb_d1": 2, "ado_rrb_d2": 1}
|
||||
sesion.add(Ados2(ado_id=f"ado-{k}", ado_pac_id=p, ado_fecha=f, ado_modulo=modulo, ado_css=css,
|
||||
ado_clasificacion=clasificacion, ado_algoritmo="Pocas o ninguna palabra", **items))
|
||||
sesion.add_all(EvaluacionNeuropediatrica(neu_id=f"neu-{k}", neu_pac_id=p, neu_fecha=f, neu_cie_codigo=c)
|
||||
for k, (p, f, c) in enumerate(NOTAS, 1))
|
||||
for i, p, f, lab, analisis, sueno in EEGS:
|
||||
sesion.add(Eeg(
|
||||
eeg_id=i, eeg_pac_id=p, eeg_fecha_estudio=f, eeg_id_registro_laboratorio=lab, eeg_ord_id=ORDEN_DE.get(i),
|
||||
eeg_con_sueno=sueno, eeg_canales=19, eeg_duracion_min=25.0, eeg_valido=analisis["valido"],
|
||||
eeg_nivel=analisis["nivel"], eeg_fraccion_limpia=analisis["limpia"], eeg_canales_malos=analisis["malos"],
|
||||
eeg_ruido_linea_db=analisis["linea"],
|
||||
))
|
||||
sesion.add_all(EegCriterio(cri_id=f"cri-{i}-{k}", cri_eeg_id=i, cri_codigo=c, cri_electrodo=e, cri_valor=v,
|
||||
cri_valor_texto=t, cri_unidad=u, cri_bajo=lo, cri_alto=hi, cri_decisivo=d,
|
||||
cri_anormal=a)
|
||||
for k, (c, e, v, t, u, lo, hi, d, a) in enumerate(analisis["criterios"], 1))
|
||||
sesion.add_all(EegMetrica(met_id=i, met_eeg_id=e, met_codigo=c, met_valor=v, met_z=z, met_fuera=fuera, met_p5=p5,
|
||||
met_mediana=mediana, met_p95=p95)
|
||||
for i, e, c, v, (z, fuera, p5, mediana, p95) in METRICAS)
|
||||
sesion.add_all(EegMetricaElectrodo(mel_id=i, mel_met_id=m, mel_electrodo=e, mel_valor=v, mel_z=z)
|
||||
for i, m, e, v, z in ELECTRODOS)
|
||||
@@ -0,0 +1,20 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as client:
|
||||
yield client
|
||||
|
||||
|
||||
def test_health(client):
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"status": "ok"}
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
"""Backups (persistance.backup): a platform's data backed up while it holds a site's
|
||||
configuration comes back whole into an empty platform, on SQLite and PostgreSQL; a damaged
|
||||
backup restores nothing; restoring over a platform needs --force and keeps what was there."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
FIXTURES = Path(__file__).parents[2] / "tests" / "fixtures"
|
||||
STORED = "select pipeline_id, version, doc from config.{kind} order by pipeline_id, version"
|
||||
|
||||
|
||||
def _stored(platform) -> list:
|
||||
"""Every saved version of every pipeline and concept map (a kind never saved: none)."""
|
||||
found = []
|
||||
for kind in ("pipelines", "concept_maps"):
|
||||
try:
|
||||
found += [tuple(r) for r in platform.query(STORED.format(kind=kind))]
|
||||
except Exception as e: # its table appears with its first save
|
||||
if "no such table" not in str(e) and "does not exist" not in str(e):
|
||||
raise
|
||||
return found
|
||||
|
||||
|
||||
def _backup(platform, cli: str, *args: str) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
["python", "-m", "persistance.backup", cli, *args],
|
||||
env=platform.env, cwd=platform.env["ISSSTELEON_DATA"], capture_output=True, text=True,
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _made(platform, tmp_path_factory) -> Path:
|
||||
"""A backup of the platform, outside its data folder; its folder."""
|
||||
made = _backup(platform, "create", "--to", str(tmp_path_factory.mktemp("backups")))
|
||||
assert made.returncode == 0, made.stderr
|
||||
return Path(made.stdout.strip())
|
||||
|
||||
|
||||
def _reset(platform) -> None:
|
||||
"""The platform emptied, as on a new machine: its data folder and (PostgreSQL) schemas."""
|
||||
data = Path(platform.env["ISSSTELEON_DATA"])
|
||||
for p in data.iterdir():
|
||||
if p.name.startswith("platform") or p.name in ("dlt", "mlflow.db"):
|
||||
subprocess.run(["rm", "-rf", str(p)], check=True)
|
||||
if "postgres" in platform.env["PLATFORM_DATABASE_URL"]:
|
||||
for schema in ("bronze", "silver", "gold", "config"):
|
||||
subprocess.run(["psql", platform.env["PLATFORM_DATABASE_URL"], "-qc",
|
||||
f"drop schema if exists {schema} cascade"], check=True) # fmt: skip
|
||||
|
||||
|
||||
def test_a_backup_restores_the_site_whole(platform, tmp_path_factory):
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json")
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") # v2
|
||||
platform.save("concept_maps", "erick_site", FIXTURES / "concept_maps" / "erick_site.json")
|
||||
before = _stored(platform)
|
||||
assert len(before) == 3
|
||||
|
||||
made = _backup(platform, "create", "--to", str(tmp_path_factory.mktemp("backups")))
|
||||
assert made.returncode == 0, made.stderr
|
||||
folder = Path(made.stdout.strip())
|
||||
manifest = json.loads((folder / "manifest.json").read_text())
|
||||
assert all(len(f["sha256"]) == 64 for f in manifest["files"].values())
|
||||
assert _backup(platform, "verify", str(folder)).stdout.strip() == "ok"
|
||||
|
||||
# over a platform: refused without --force
|
||||
refused = _backup(platform, "restore", str(folder))
|
||||
assert refused.returncode != 0 and "--force" in refused.stderr
|
||||
|
||||
_reset(platform)
|
||||
assert not any(n.startswith("platform") for n in
|
||||
(p.name for p in Path(platform.env["ISSSTELEON_DATA"]).iterdir())) # fmt: skip
|
||||
restored = _backup(platform, "restore", str(folder))
|
||||
assert restored.returncode == 0, restored.stderr
|
||||
assert _stored(platform) == before
|
||||
|
||||
|
||||
def test_a_damaged_backup_restores_nothing(platform, tmp_path_factory):
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json")
|
||||
folder = _made(platform, tmp_path_factory)
|
||||
damaged = next(p for p in folder.rglob("*") if p.is_file() and p.name != "manifest.json")
|
||||
damaged.write_bytes(damaged.read_bytes() + b"\0") # one byte more
|
||||
checked = _backup(platform, "verify", str(folder))
|
||||
assert checked.returncode == 1 and "changed since the backup" in checked.stdout
|
||||
|
||||
restored = _backup(platform, "restore", str(folder), "--force")
|
||||
assert restored.returncode != 0 and "damaged" in restored.stderr
|
||||
assert len(_stored(platform)) == 1 # the platform as it was
|
||||
|
||||
|
||||
def test_restoring_over_a_platform_keeps_what_was_there(fresh_platform, tmp_path_factory):
|
||||
"""SQLite: what the data folder held is set aside, not mixed with the backup's."""
|
||||
platform = fresh_platform
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json")
|
||||
folder = _made(platform, tmp_path_factory)
|
||||
platform.save("pipelines", "erick", FIXTURES / "pipelines" / "erick_site.json") # newer
|
||||
assert _backup(platform, "restore", str(folder), "--force").returncode == 0
|
||||
assert len(_stored(platform)) == 1 # the backup's moment, nothing newer mixed in
|
||||
aside = list(Path(platform.env["ISSSTELEON_DATA"]).glob(".before-restore-*"))
|
||||
assert len(aside) == 1 and any(aside[0].glob("platform__config.db"))
|
||||
@@ -1,338 +0,0 @@
|
||||
"""Phase 2 gate, CaCu: the synthetic hospital, loaded through one drawn pipeline, gives what
|
||||
the current platform gives on the same hospital (the reference fixtures): its cohorts, its
|
||||
indicators, and, trained by the platform's own jobs, its models' predictions. Promotion
|
||||
needs the three reports. Real API, Dagster and MLflow; nothing faked.
|
||||
|
||||
Phase 3 adds the FHIR gate: every resource the API serves passes the HL7 validator, and
|
||||
the follow-up list is the current platform's.
|
||||
|
||||
Fixed on purpose, so compared differently:
|
||||
- cin2_pim_post_colposcopy scores each patient at her post-colposcopy index; the current
|
||||
one scores at her first event (its cohort's index), so only its members are compared.
|
||||
- cin2_logistic's index date is the index sample's, not 1970-01-01.
|
||||
- survival indexes at the first biopsy reported as carcinoma or carcinoma in situ; the current
|
||||
index read only invasive carcinoma and indexed nobody (its reference was captured with that
|
||||
one rule fixed).
|
||||
- One rule, one value: a diagnosis note assesses a sample within SAMPLE_TO_DIAGNOSIS_DAYS
|
||||
(120). The current follow-up status reads the same rule as 180 days, so one patient
|
||||
(198) is post-colposcopy there and pre-colposcopy here.
|
||||
- FHIR asks every summary report for a score: a composition scores its count. A period
|
||||
with nothing measured keeps its counts and has no score, the validator's one allowed
|
||||
error (see fhir_checks.unscored).
|
||||
"""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from fhir_checks import follow_up, pages, served, unscored, validate
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cacu"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
|
||||
REFERENCE_CUTOFF = "2026-11-23" # the current platform's cohort cut-off (follow-up ends)
|
||||
CAPTURED_ON = "2026-11-25" # the day the indicators were captured: durations counted to it
|
||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||
COHORTS = {
|
||||
"cacu_cohort_total": "cohorte_total",
|
||||
"cacu_cohort_surveillance": "cohorte_vigilancia",
|
||||
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
|
||||
}
|
||||
CODES = { # platform code -> the current platform's
|
||||
"NILM": "NORMAL", "LSIL": "LIEBG", "HSIL": "LIEAG", "carcinoma": "CARCINOMA",
|
||||
"normal": "NORMAL", "no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA",
|
||||
"post_treatment": "POST_TRATAMIENTO", "post_colposcopy": "POST_COLPOSCOPIA",
|
||||
"pre_colposcopy": "PRE_COLPOSCOPIA", "case": "CASO", "satisfactory": "SATISFACTORIO",
|
||||
"unsatisfactory": "INSATISFACTORIO",
|
||||
} # fmt: skip
|
||||
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
|
||||
"result": "citologia_alto_grado"} # fmt: skip
|
||||
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
|
||||
# Measures with no legacy reference fixture: checked by invariants.
|
||||
NEW_MEASURES = {
|
||||
"CACU_VPH",
|
||||
"CACU_VPH_GENOTIPO",
|
||||
"CACU_BIOPSIA_RESULTADOS",
|
||||
"CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
|
||||
"CACU_TIEMPO_DIAGNOSTICO_CIE10",
|
||||
"CACU_VPP_COLPOSCOPIA",
|
||||
"CACU_VPP_BIOPSIA",
|
||||
}
|
||||
NEW_STRATA = {"screening_round", "result_initial", "result_subsequent"} # of CACU_EU7
|
||||
RESULTS = set(CODES) | set(CODES.values()) | {"ASC-US", "ASC-H", "AGC", "CIS", "adenocarcinoma"}
|
||||
|
||||
|
||||
def _count(stratum: dict, key: str, code: str = "initial-population") -> int:
|
||||
return stratum.get(key, {}).get(code, 0)
|
||||
|
||||
|
||||
def _check_eu7_rounds(populations: dict, strata: dict, where: tuple) -> None:
|
||||
"""The screening rounds partition the evaluated patients, and each round's results do too."""
|
||||
rounds = strata.get("screening_round", {})
|
||||
assert (
|
||||
sum(c["initial-population"] for c in rounds.values()) == populations["initial-population"]
|
||||
), where
|
||||
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
|
||||
for rnd in ("initial", "subsequent"):
|
||||
results = strata.get(f"result_{rnd}", {})
|
||||
assert sum(c["initial-population"] for c in results.values()) == _count(rounds, rnd), where
|
||||
assert set(results) <= RESULTS, where
|
||||
|
||||
|
||||
def _check_ppv(populations: dict, score, extensions: dict, strata: dict, where: tuple) -> None:
|
||||
"""A referral PPV: counts of patients, one denominator, nested numerators and groups."""
|
||||
total, den = populations["numerator"], populations["denominator"]
|
||||
assert populations["initial-population"] == den and 0 <= total <= den, where
|
||||
if den:
|
||||
assert (
|
||||
score == pytest.approx(total / den)
|
||||
and 0 <= extensions["ic-bajo"] <= score <= extensions["ic-alto"] <= 1
|
||||
), where
|
||||
else:
|
||||
assert score is None and not extensions, where
|
||||
levels = strata.get("histology_level", {})
|
||||
if den:
|
||||
assert set(levels) == {"LIEBG+", "LIEAG+", "invasive"}, where
|
||||
assert all(c["denominator"] == den for c in levels.values()), where
|
||||
low, high, invasive = (levels[k]["numerator"] for k in ("LIEBG+", "LIEAG+", "invasive"))
|
||||
assert total == low >= high >= invasive >= 0, where
|
||||
cytology = strata.get("referral_cytology", {})
|
||||
nested = [_count(cytology, g, "denominator") for g in ("ASCUS+", "LSIL+", "HSIL+")]
|
||||
assert nested == sorted(nested, reverse=True), where
|
||||
for cell in cytology.values():
|
||||
assert 0 <= cell["numerator"] <= cell["denominator"] <= den, where
|
||||
hpv = strata.get("referral_hpv", {})
|
||||
assert set(hpv) <= {"positive", "negative", "hpv_16", "hpv_18", "SIN_DATO"}, where
|
||||
for cell in hpv.values():
|
||||
assert 0 <= cell["numerator"] <= cell["denominator"] <= den, where
|
||||
# a patient is in "no data" or in a result of her referring cytology, never both
|
||||
decided = sum(_count(hpv, g, "denominator") for g in ("SIN_DATO", "positive", "negative"))
|
||||
assert decided == den, where
|
||||
rounds = strata.get("screening_round", {})
|
||||
assert sum(c["denominator"] for c in rounds.values()) == den, where
|
||||
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
|
||||
|
||||
|
||||
def _patients(q) -> dict[str, int]:
|
||||
"""Each person's patient id in the hospital (for comparing only)."""
|
||||
with sqlite3.connect(HOSPITAL / "hospital_cacu.db") as con:
|
||||
number = {n.replace("-", ""): p for p, n in con.execute(
|
||||
"select pac_id, pac_id_hospital from paciente")} # fmt: skip
|
||||
rows = q("select distinct person_id, record_number from bronze.staged__identity")
|
||||
return {person: number[record] for person, record in rows}
|
||||
|
||||
|
||||
def _report(entry: dict, measure: str) -> tuple:
|
||||
group = entry["resource"]["group"][0]
|
||||
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
||||
score = group.get("measureScore", {})
|
||||
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
|
||||
strata = {}
|
||||
for s in group.get("stratifier", []):
|
||||
if len(s["code"]) > 1: # crossed with the category: not in the reference
|
||||
continue
|
||||
code = s["code"][0]
|
||||
name = code["coding"][0]["code"] if "coding" in code else code["text"]
|
||||
name = CATEGORY.get(measure, "banda") if name == "category" else STRATA.get(name, name)
|
||||
strata[name] = {CODES.get(x["value"]["text"], x["value"]["text"]): {
|
||||
p["code"]["coding"][0]["code"]: p["count"] for p in x["population"]}
|
||||
for x in s.get("stratum", [])} # fmt: skip
|
||||
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
|
||||
|
||||
|
||||
def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path):
|
||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
||||
put_concept_map(api, "hospital_cacu")
|
||||
ok(api.put("/ingest/pipelines/cacu", json=pipeline))
|
||||
wait_for(api, ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"])
|
||||
q = platform.query
|
||||
patient = _patients(q)
|
||||
|
||||
# Cohorts: the same patients, indexed on the same day.
|
||||
for ours, theirs in COHORTS.items():
|
||||
sql = f"select person_id, index_date from gold.{ours} where excluded_by is null"
|
||||
found = {(patient[p], str(d)) for p, d in q(sql)}
|
||||
frame = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / theirs / "dbt" / "1.parquet")
|
||||
frame["fecha_indice"] = frame["fecha_indice"].astype(str)
|
||||
assert found == set(frame[["pac_id", "fecha_indice"]].drop_duplicates()
|
||||
.itertuples(index=False, name=None)), ours # fmt: skip
|
||||
current = json.loads((REFERENCE / "models.json").read_text())
|
||||
post_colposcopy = current["cin2_pim_post_colposcopy"]["version"]["metrics"]
|
||||
members = q("select count(*) from gold.cacu_cohort_post_colposcopy where excluded_by is null")
|
||||
assert members[0][0] == post_colposcopy["n_train"] + post_colposcopy["n_test"]
|
||||
|
||||
# Indicators: every measure, every semester, as the current platform answers them
|
||||
# (no risk batch yet, so the risk bands are empty as they were).
|
||||
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
||||
(measures,) = pages(api, "/cacu/fhir/Measure")
|
||||
published = {e["resource"]["name"] for e in measures["entry"]}
|
||||
assert published == set(reference) | NEW_MEASURES
|
||||
for measure in [e["resource"] for e in measures["entry"]]:
|
||||
if measure["name"] not in reference: # New measures have no legacy fixture.
|
||||
if measure["name"].startswith("CACU_VPP_"):
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
reports = [
|
||||
e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]
|
||||
]
|
||||
assert len(reports) == len(PERIODS), measure["name"]
|
||||
for entry in reports:
|
||||
populations, score, extensions, strata = _report(entry, measure["name"])
|
||||
_check_ppv(
|
||||
populations,
|
||||
score,
|
||||
extensions,
|
||||
strata,
|
||||
(measure["name"], entry["resource"]["period"]["start"]),
|
||||
)
|
||||
if measure["name"] == "CACU_VPH": # the patients' latest HPV sample, one each
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
for b in pages(api, "/cacu/fhir/MeasureReport", params):
|
||||
for entry in b["entry"]:
|
||||
populations, _, _, strata = _report(entry, measure["name"])
|
||||
where = (measure["name"], entry["resource"]["period"]["start"])
|
||||
total = populations["initial-population"]
|
||||
category = strata.get(
|
||||
"banda", {}
|
||||
) # _report names the category so; none: nobody
|
||||
assert set(category) <= {"positive", "negative"}, where
|
||||
assert sum(c["initial-population"] for c in category.values()) == total, (
|
||||
where
|
||||
)
|
||||
for name in ("hpv_16", "hpv_18"):
|
||||
assert set(strata.get(name, {})) <= {"positive", "negative"}, where
|
||||
assert (
|
||||
sum(c["initial-population"] for c in strata.get(name, {}).values())
|
||||
<= total
|
||||
), where
|
||||
rounds = sum(
|
||||
c["initial-population"]
|
||||
for k in ("hpv_initial", "hpv_subsequent")
|
||||
for c in strata.get(k, {}).values()
|
||||
)
|
||||
assert rounds <= total, where
|
||||
continue
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
|
||||
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
|
||||
name = measure["name"]
|
||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
||||
a, b = _report(ours, name), _report(theirs, name)
|
||||
where = (name, ours["resource"]["period"]["start"])
|
||||
legacy = {k: v for k, v in a[3].items() if name != "CACU_EU7" or k not in NEW_STRATA}
|
||||
assert a[0] == b[0] and legacy == b[3], where
|
||||
if name == "CACU_EU7": # the new round breakdowns leave every legacy figure as it was
|
||||
_check_eu7_rounds(a[0], a[3], where)
|
||||
if cohort: # scores its count; the current platform gave none
|
||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
||||
continue
|
||||
assert (a[1] is None) == (b[1] is None), where
|
||||
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
|
||||
assert a[2] == pytest.approx(b[2]), where
|
||||
|
||||
# Models: one training run gives a version of each, with its two generated reports;
|
||||
# none is promoted without the clinical validation.
|
||||
wait_for(api, ok(api.post("/models/cacu/train", json={"as_of": REFERENCE_CUTOFF}))["run_id"])
|
||||
names = [m["name"] for m in ok(api.get("/models/cacu"))]
|
||||
assert set(names) == set(current)
|
||||
for name in names:
|
||||
(version,) = ok(api.get(f"/models/cacu/{name}/versions"))
|
||||
assert version["reports"] == ["interpretability", "technical_validation"]
|
||||
for metric in ("n_train", "n_test"):
|
||||
assert version["metrics"][metric] == current[name]["version"]["metrics"][metric]
|
||||
assert api.post(f"/models/cacu/{name}/versions/1/promote").status_code == 409
|
||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
||||
ok(api.post(f"/models/cacu/{name}/versions/1/reports/clinical_validation", files=files))
|
||||
assert ok(api.post(f"/models/cacu/{name}/versions/1/promote")) == {"champion": 1}
|
||||
|
||||
# Risks: the champions score their cohorts with the current models' predictions.
|
||||
wait_for(api, ok(api.post("/models/cacu/score"))["run_id"])
|
||||
for name in names:
|
||||
risks = pd.DataFrame(q(
|
||||
"select person_id, index_date, horizon_years, probability, ci_low, ci_high "
|
||||
f"from gold.cacu_risk where model = 'cacu.{name}'"
|
||||
), columns=["person_id", "index_date", "horizon_years", "probability", "ci_low",
|
||||
"ci_high"]) # fmt: skip
|
||||
risks["pac_id"] = risks["person_id"].map(patient)
|
||||
expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
||||
if name == "cin2_pim_post_colposcopy": # fixed: scored at her own index
|
||||
cohort = q("select person_id, index_date from gold.cacu_cohort_post_colposcopy "
|
||||
"where excluded_by is null") # fmt: skip
|
||||
assert set(map(tuple, risks[["person_id", "index_date"]].astype(str).values)) == {
|
||||
(p, str(d)) for p, d in cohort} # fmt: skip
|
||||
continue
|
||||
both = risks.merge(expected, left_on=["pac_id", "horizon_years"],
|
||||
right_on=["pac_id", "horizonte_anios"], how="outer",
|
||||
indicator=True) # fmt: skip
|
||||
assert (both["_merge"] == "both").all(), name
|
||||
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
|
||||
("ci_high", "ic_alto")]: # fmt: skip
|
||||
if theirs in both:
|
||||
np.testing.assert_allclose(both[ours].astype(float), both[theirs], rtol=1e-6)
|
||||
|
||||
# The risk band now has the surveillance cohort's scored members.
|
||||
params = {"measure": "cacu-riesgo-banda", "reporting-period": "2025-S1"}
|
||||
(bands,) = pages(api, "/cacu/fhir/MeasureReport", params)
|
||||
assert bands["entry"][0]["resource"]["group"][0]["population"][0]["count"] > 0
|
||||
|
||||
# The follow-up list: the current platform's, at its cut-off, with the same window.
|
||||
page = json.loads((REFERENCE / "pages.json").read_text())
|
||||
theirs = page["/cacu/seguimiento?page_size=200"]["body"]
|
||||
window, cutoff = theirs["ventana"], theirs["corte"]
|
||||
params = [("follow-up-window", window["meses"]), ("follow-up-cutoff", cutoff),
|
||||
("_count", 20), ("_revinclude", "DiagnosticReport:subject"),
|
||||
("_include:iterate", "DiagnosticReport:result")] # fmt: skip
|
||||
ours = follow_up(pages(api, "/cacu/fhir/Patient", params), window["desde"], cutoff)
|
||||
assert [r["cytology"]["date"] for r in ours] == [
|
||||
i["ultima_citologia"]["fecha"] for i in theirs["items"]
|
||||
] # same order (ties aside)
|
||||
expected = {int(i["pac_id"]): i for i in theirs["items"]}
|
||||
assert {patient[r["person"]] for r in ours} == set(expected)
|
||||
for row in ours:
|
||||
cytology, hpv, biopsy = row["cytology"], row["hpv"], row["biopsy"]
|
||||
shown = {
|
||||
"estatus": CODES[row["status"]],
|
||||
"ultima_citologia": {"fecha": cytology["date"],
|
||||
"bethesda": CODES.get(cytology["result"], cytology["result"]),
|
||||
"calidad": CODES.get(cytology["adequacy"])},
|
||||
"ultimo_vph": hpv and {"fecha": hpv["date"], "genotipo_16_18": hpv["types_16_18"],
|
||||
"resultado": "POSITIVO" if hpv["positive"] else "NEGATIVO"},
|
||||
"dias_toma_diagnostico": row["days_to_diagnosis"],
|
||||
"ultima_biopsia": biopsy and {
|
||||
"fecha": biopsy["date"],
|
||||
"grado": CODES.get(biopsy["histology"], biopsy["histology"]),
|
||||
},
|
||||
} # fmt: skip
|
||||
item = expected[patient[row["person"]]]
|
||||
if patient[row["person"]] == 198: # fixed: one horizon (120 days), not 180
|
||||
assert (shown["estatus"], item["estatus"]["codigo"]) == (
|
||||
"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA") # fmt: skip
|
||||
shown["estatus"] = "POST_COLPOSCOPIA"
|
||||
assert shown == {**{k: item[k] for k in shown}, "estatus": item["estatus"]["codigo"]}
|
||||
|
||||
# Every resource the API serves, every search paged to the end, passes the HL7
|
||||
# validator (offline: structure, cardinality, profiles; no terminology server).
|
||||
people = [r["person"] for r in ours[:10]]
|
||||
# The stages of each cytology's route, known by the cut-off, are the report's extensions.
|
||||
stage_params = [("subject", ",".join(f"Patient/{p}" for p in people)), ("stage-cutoff", cutoff)]
|
||||
stage_reports = [e["resource"] for b in pages(api, "/cacu/fhir/DiagnosticReport", stage_params)
|
||||
for e in b["entry"]] # fmt: skip
|
||||
stages = [x["url"].rsplit("/", 1)[1] for r in stage_reports for x in r.get("extension", [])
|
||||
if "/stage-" in x["url"]] # fmt: skip
|
||||
known = {
|
||||
f"stage-{s}-{k}" for s in ("colposcopy", "biopsy", "diagnosis") for k in ("state", "date")
|
||||
}
|
||||
assert stages and set(stages) <= known
|
||||
resources = served(api, "/cacu/fhir", PERIODS, people)
|
||||
errors, warnings = validate(resources, tmp_path)
|
||||
print(f"HL7 validator: {len(warnings)} warnings")
|
||||
assert [e for e in errors if not unscored(e, resources)] == []
|
||||
@@ -1,139 +0,0 @@
|
||||
"""CaCu's PDF and Excel exports: what the WebApp sends already formatted is laid out, never
|
||||
computed; limits are enforced; every cell is text (nothing becomes a formula); a long query
|
||||
runs over several pages with the institutional frame on each; absent values stay absent."""
|
||||
|
||||
import re
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from webapi import exports, pdf_report
|
||||
|
||||
COLUMNS = ["Paciente", "Edad", "Estatus", "Etapas", "Última citología", "VPH", "Biopsia",
|
||||
"Riesgo", "Riesgo cáncer", "Días a diagnóstico"] # fmt: skip
|
||||
STAGES = [
|
||||
{"state": "Registrada", "date": "2026-11-01"},
|
||||
{"state": "Desconocida"},
|
||||
{"state": "Pendiente"},
|
||||
{"state": "Ambigua"},
|
||||
{"state": "Registrada", "date": "2026-11-09", "provenance": "Inferida temporalmente"},
|
||||
]
|
||||
|
||||
|
||||
def pages(pdf: bytes) -> int:
|
||||
return len(re.findall(rb"/Type\s*/Page\b", pdf))
|
||||
|
||||
|
||||
def listing(n: int, **extra) -> exports.Document:
|
||||
rows = [[f"Paciente {i}\nCURP{i}", "40", "Precolposcopia", "x", "—", "—", "—",
|
||||
"No disponible", "0.0 %", "—"] for i in range(n)] # fmt: skip
|
||||
return exports.Document(
|
||||
title="Resultados de seguimiento",
|
||||
parameters=[["Fecha de corte", "2026-11-22"]],
|
||||
columns=COLUMNS,
|
||||
rows=rows,
|
||||
row_stages=[STAGES] * n,
|
||||
**extra,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
app = FastAPI()
|
||||
app.include_router(exports.router)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_the_assets_ship_with_the_package():
|
||||
for name in ("isssteleon-logo.png", "fonts/Roboto-Regular.ttf", "fonts/Roboto-Medium.ttf",
|
||||
"fonts/Roboto-Italic.ttf", "fonts/Roboto-MediumItalic.ttf",
|
||||
"fonts/LICENSE-Roboto-OFL.txt"): # fmt: skip
|
||||
assert (pdf_report.ASSETS / name).is_file(), name
|
||||
|
||||
|
||||
def test_the_limits_are_published(client):
|
||||
assert client.get("/cacu/exports/capabilities").json() == {
|
||||
"xlsx_limit": 5000, "pdf_limit": 1000, "version": 1} # fmt: skip
|
||||
|
||||
|
||||
def test_excel_cells_are_text_so_nothing_runs_as_a_formula():
|
||||
doc = exports.Document(title="x", parameters=[["Filtro", "=1+1"]], columns=["=2+2"],
|
||||
rows=[["=1+1"], ["+cmd"], ["@SUM(A1)"]]) # fmt: skip
|
||||
book = load_workbook(BytesIO(exports.export("xlsx", doc).body))
|
||||
assert book.sheetnames == ["Resultados", "Parámetros"]
|
||||
cells = [book["Resultados"]["A1"], book["Resultados"]["A2"], book["Resultados"]["A4"],
|
||||
book["Parámetros"]["B2"]] # fmt: skip
|
||||
assert {c.data_type for c in cells} == {"s"}
|
||||
assert book["Resultados"]["A2"].value == "=1+1"
|
||||
|
||||
|
||||
def test_excel_keeps_every_row_of_the_query_up_to_its_limit():
|
||||
doc = listing(5000).model_copy(update={"row_stages": []})
|
||||
sheet = load_workbook(BytesIO(exports.export("xlsx", doc).body))["Resultados"]
|
||||
assert sheet.max_row == 5001 # the header and every patient
|
||||
with pytest.raises(ValueError): # the model itself refuses more
|
||||
exports.Document.model_validate({**doc.model_dump(), "rows": doc.rows + [doc.rows[0]]})
|
||||
|
||||
|
||||
def test_pdf_stops_at_a_thousand_records_and_columns_must_agree():
|
||||
too_many = exports.Document(title="x", parameters=[], columns=["a"], rows=[["x"]] * 1001)
|
||||
with pytest.raises(exports.HTTPException) as caught:
|
||||
exports.export("pdf", too_many)
|
||||
assert caught.value.status_code == 422
|
||||
with pytest.raises(exports.HTTPException):
|
||||
exports.export("xlsx", exports.Document(title="x", parameters=[], columns=["a"],
|
||||
rows=[["x", "y"]])) # fmt: skip
|
||||
with pytest.raises(exports.HTTPException) as unknown:
|
||||
exports.export("docx", too_many)
|
||||
assert unknown.value.status_code == 404
|
||||
|
||||
|
||||
def test_a_long_listing_runs_over_several_pages_and_keeps_its_rows_and_stages():
|
||||
body = exports.export("pdf", listing(120)).body
|
||||
assert body.startswith(b"%PDF")
|
||||
assert pages(body) > 4
|
||||
short = exports.export("pdf", listing(2)).body
|
||||
assert pages(short) < pages(body)
|
||||
with pytest.raises(exports.HTTPException): # one stage line per row, or none
|
||||
exports.export("pdf", listing(5).model_copy(update={"row_stages": [STAGES] * 3}))
|
||||
|
||||
|
||||
def test_a_listing_with_nothing_found_and_with_absent_values_still_renders():
|
||||
empty = exports.Document(title="Resultados de seguimiento", parameters=[], columns=COLUMNS,
|
||||
rows=[]) # fmt: skip
|
||||
assert exports.export("pdf", empty).body.startswith(b"%PDF")
|
||||
blank = listing(3).model_copy(update={"row_stages": [[{}] * 5] * 3})
|
||||
assert exports.export("pdf", blank).body.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_the_record_pdf_draws_extreme_and_absent_risks():
|
||||
scales = [
|
||||
{"label": "a", "value": v, "outcome": "Cáncer", "model": "M", "horizon": "Inmediato"}
|
||||
for v in (0, 0.02, 0.5, 0.98, 1)
|
||||
]
|
||||
scales.append({"label": "Riesgo a 5 años: No disponible"})
|
||||
doc = exports.Document(
|
||||
title="Ficha individual",
|
||||
parameters=[],
|
||||
columns=["Sección", "Información"],
|
||||
rows=[
|
||||
["Identificador", "1"],
|
||||
["Historial", "2026-01-01 · Diagnóstico · " + "texto " * 300],
|
||||
],
|
||||
timeline=[{"state": "Registrada", "label": "Toma de muestra", "date": "2026-01-01"}] * 5,
|
||||
risk_scales=scales,
|
||||
)
|
||||
assert exports.export("pdf", doc).body.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_the_http_route_returns_the_documents(client):
|
||||
payload = listing(3).model_dump()
|
||||
pdf = client.post("/cacu/exports/pdf", json=payload)
|
||||
assert pdf.status_code == 200 and pdf.headers["content-type"] == "application/pdf"
|
||||
xlsx = client.post("/cacu/exports/xlsx", json=payload)
|
||||
assert xlsx.status_code == 200 and "spreadsheetml" in xlsx.headers["content-type"]
|
||||
assert client.post("/cacu/exports/csv", json=payload).status_code == 404
|
||||
assert client.post("/cacu/exports/pdf", json={**payload, "columns": []}).status_code == 422
|
||||
@@ -1,209 +0,0 @@
|
||||
"""Phase 4 gate, CaMa: the synthetic hospital, loaded through one drawn pipeline, gives what
|
||||
the current platform gives on the same hospital (the reference fixtures, captured at the last
|
||||
load): its indicators, its follow-up list and, trained by the platform's own jobs, its
|
||||
models' predictions. Real API, Dagster and MLflow; nothing faked.
|
||||
|
||||
Fixed on purpose, so compared differently:
|
||||
- Survival follows each patient up to the day it is trained (`as_of`), not to the day the
|
||||
job happens to run: the reference was trained on 2026-11-24.
|
||||
- BI-RADS 4A, 4B and 4C are kept as reported. The current platform folds them into 4 when it
|
||||
loads them, so here they are summed into its B4, and only here.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
from fhir_checks import pages, served, unscored, validate
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cama"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cama.json"
|
||||
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
|
||||
TRAINED_ON = "2026-11-24" # survival's follow-up ended the day the reference was trained
|
||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||
CODES = { # platform code -> the current platform's
|
||||
**{c: f"B{c}" for c in ("0", "1", "2", "3", "4", "5", "6")},
|
||||
"4A": "B4", "4B": "B4", "4C": "B4",
|
||||
"benign": "BENIGNO", "in_situ": "CARCINOMA_IN_SITU", "invasive": "CARCINOMA_INVASOR",
|
||||
"no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA",
|
||||
} # fmt: skip
|
||||
CATEGORY = {"CAMA_BIOPSIAS": "grado", "CAMA_HISTOPATOLOGIA_BIRADS": "biopsia_grado"}
|
||||
STATUS = {"cancer": "Diagnóstico confirmado, sin tratamiento registrado",
|
||||
"pending_biopsy": "Pendiente de biopsia", "biopsy_no_result": "Biopsia sin resultado",
|
||||
"benign_biopsy": "Biopsia benigna"} # fmt: skip
|
||||
PRIORITY = {"high": "Alta", "medium": "Media", "low": "Baja"}
|
||||
E = "https://isssteleon.org/fhir/StructureDefinition/"
|
||||
|
||||
|
||||
def _patients(q) -> dict[str, str]:
|
||||
"""Each person's patient id in the hospital (for comparing only)."""
|
||||
with sqlite3.connect(HOSPITAL / "hospital_cama.db") as con:
|
||||
number = {n.replace("-", ""): str(p) for p, n in con.execute(
|
||||
"select pac_id, pac_id_hospital from paciente")} # fmt: skip
|
||||
rows = q("select distinct person_id, record_number from bronze.staged__identity")
|
||||
return {person: number[record] for person, record in rows}
|
||||
|
||||
|
||||
def _ext(resource: dict, name: str):
|
||||
found = next((x for x in resource.get("extension", []) if x["url"] == E + name), None)
|
||||
return found and next(v for k, v in found.items() if k.startswith("value"))
|
||||
|
||||
|
||||
def _follow_up(bundles: list[dict], cutoff: str, patient: dict[str, str]) -> list[dict]:
|
||||
"""The follow-up list as the WebApp shows it: per patient, her status and priority, her
|
||||
latest mammogram reported by the cut-off, and the latest reported biopsy it led to."""
|
||||
resources = [e["resource"] for b in bundles for e in b.get("entry", [])]
|
||||
observations = {r["id"]: r for r in resources if r["resourceType"] == "Observation"}
|
||||
|
||||
def values(report: dict) -> dict:
|
||||
found = {}
|
||||
for x in report.get("result", []):
|
||||
o = observations[x["reference"].split("/")[1]]
|
||||
value = o.get("valueDateTime") or o.get("valueCodeableConcept", {})
|
||||
found[o["code"]["coding"][0]["code"].split(".")[1]] = (
|
||||
value if isinstance(value, str) else value["coding"][0]["code"]
|
||||
)
|
||||
return found # fmt: skip
|
||||
|
||||
rows = []
|
||||
for p in (r for r in resources if r["resourceType"] == "Patient"):
|
||||
mine = [r for r in resources if r["resourceType"] == "DiagnosticReport"
|
||||
and r["subject"]["reference"] == f"Patient/{p['id']}"] # fmt: skip
|
||||
mammograms = [(r["effectiveDateTime"], values(r)) for r in mine
|
||||
if r["code"]["coding"][0]["code"] == "mammography"
|
||||
and (_ext(r, "report-date") or "9") <= cutoff] # fmt: skip
|
||||
exam, mammogram = max(mammograms, key=lambda m: m[0])
|
||||
biopsies = sorted((_ext(r, "report-date"), values(r)) for r in mine
|
||||
if r["code"]["coding"][0]["code"] == "breast_biopsy"
|
||||
and _ext(r, "report-date")
|
||||
and exam <= _ext(r, "report-date") <= cutoff) # fmt: skip
|
||||
biopsies = [b for b in biopsies if b[1].get("mammogram_exam_date") == exam]
|
||||
last = biopsies[-1] if biopsies else (None, {})
|
||||
rows.append({
|
||||
"pac_id": patient[p["id"]], "mastografia_fecha": exam,
|
||||
"birads": "BIRADS_" + mammogram["birads"][:1],
|
||||
"estatus": STATUS[_ext(p, "follow-up-status")["code"]],
|
||||
"prioridad": PRIORITY[_ext(p, "follow-up-priority")["code"]],
|
||||
"biopsia": CODES.get(last[1].get("histology")), "biopsia_fecha": last[0],
|
||||
}) # fmt: skip
|
||||
return rows
|
||||
|
||||
|
||||
def _report(entry: dict, measure: str) -> tuple:
|
||||
group = entry["resource"]["group"][0]
|
||||
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
||||
score = group.get("measureScore", {})
|
||||
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
|
||||
strata = {}
|
||||
for s in group.get("stratifier", []):
|
||||
if len(s["code"]) > 1: # crossed with the category: not in the reference
|
||||
continue
|
||||
code = s["code"][0]
|
||||
name = code["coding"][0]["code"] if "coding" in code else code["text"]
|
||||
name = CATEGORY.get(measure, "birads") if name == "category" else name
|
||||
cells: dict = defaultdict(lambda: defaultdict(int))
|
||||
for x in s.get("stratum", []):
|
||||
for p in x["population"]:
|
||||
cells[CODES.get(x["value"]["text"], x["value"]["text"])][
|
||||
p["code"]["coding"][0]["code"]] += p["count"] # fmt: skip
|
||||
strata[name] = {k: dict(v) for k, v in cells.items()}
|
||||
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
|
||||
|
||||
|
||||
def test_cama_from_the_hospital_to_indicators(api, platform, tmp_path):
|
||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
||||
put_concept_map(api, "hospital_cama")
|
||||
ok(api.put("/ingest/pipelines/cama", json=pipeline))
|
||||
wait_for(api, ok(api.post("/ingest/pipelines/cama/runs", json={}))["run_id"])
|
||||
|
||||
# Indicators: every measure, every semester, as the current platform answers them.
|
||||
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
||||
(measures,) = pages(api, "/cama/fhir/Measure")
|
||||
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
|
||||
for measure in [e["resource"] for e in measures["entry"]]:
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
found = [e for b in pages(api, "/cama/fhir/MeasureReport", params) for e in b["entry"]]
|
||||
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
|
||||
name = measure["name"]
|
||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
||||
a, b = _report(ours, name), _report(theirs, name)
|
||||
where = (name, ours["resource"]["period"]["start"])
|
||||
assert a[0] == b[0] and a[3] == b[3], (where, a, b)
|
||||
if cohort: # scores its count; the current platform gave none
|
||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
||||
continue
|
||||
assert (a[1] is None) == (b[1] is None), where
|
||||
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
|
||||
assert a[2] == pytest.approx(b[2]), where
|
||||
|
||||
# The follow-up list: who, in which order, where her biopsy stands and how soon.
|
||||
theirs = json.loads((REFERENCE / "pages.json").read_text())["/cama/seguimiento"]["body"]
|
||||
window = theirs["ventana"]
|
||||
params = {"follow-up-window": window["meses"], "follow-up-cutoff": window["hasta"],
|
||||
"_revinclude": "DiagnosticReport:subject",
|
||||
"_include:iterate": "DiagnosticReport:result", "_count": 200} # fmt: skip
|
||||
ours = _follow_up(pages(api, "/cama/fhir/Patient", params), window["hasta"],
|
||||
_patients(platform.query)) # fmt: skip
|
||||
keys = ("pac_id", "mastografia_fecha", "birads", "estatus", "prioridad", "biopsia",
|
||||
"biopsia_fecha") # fmt: skip
|
||||
order = lambda r: (r["mastografia_fecha"], -int(r["pac_id"])) # noqa: E731
|
||||
expected = [{k: r[k] for k in keys} for r in theirs["items"]]
|
||||
assert sorted(ours, key=order, reverse=True) == sorted(expected, key=order, reverse=True)
|
||||
assert [r["mastografia_fecha"] for r in ours] == [r["mastografia_fecha"] for r in expected]
|
||||
|
||||
# Models: one training run gives a version of each, with its two generated reports;
|
||||
# none is promoted without the clinical validation.
|
||||
current = json.loads((REFERENCE / "models.json").read_text())
|
||||
wait_for(api, ok(api.post("/models/cama/train", json={"as_of": TRAINED_ON}))["run_id"])
|
||||
names = [m["name"] for m in ok(api.get("/models/cama"))]
|
||||
assert set(names) == {n for n, m in current.items() if m["status"] == "ok"}
|
||||
for name in names:
|
||||
(version,) = ok(api.get(f"/models/cama/{name}/versions"))
|
||||
assert version["reports"] == ["interpretability", "technical_validation"]
|
||||
for metric in ("n_train", "n_test"):
|
||||
assert version["metrics"][metric] == current[name]["version"]["metrics"][metric]
|
||||
assert api.post(f"/models/cama/{name}/versions/1/promote").status_code == 409
|
||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
||||
ok(api.post(f"/models/cama/{name}/versions/1/reports/clinical_validation", files=files))
|
||||
assert ok(api.post(f"/models/cama/{name}/versions/1/promote")) == {"champion": 1}
|
||||
report = api.get(f"/models/cama/{name}/versions/1/reports/interpretability")
|
||||
assert report.headers["content-type"] == "application/json"
|
||||
assert [c["name"] for c in report.json()["curves"]][0].startswith("Kaplan-Meier")
|
||||
pdf = api.get(f"/models/cama/{name}/versions/1/reports/clinical_validation")
|
||||
assert pdf.headers["content-type"] == "application/pdf" and pdf.content.startswith(b"%PDF")
|
||||
|
||||
# Risks: the champions score their cohorts with the current models' predictions.
|
||||
wait_for(api, ok(api.post("/models/cama/score"))["run_id"])
|
||||
patient = _patients(platform.query)
|
||||
for name in names:
|
||||
risks = pd.DataFrame(platform.query(
|
||||
"select person_id, index_date, horizon_years, probability "
|
||||
f"from gold.cama_risk where model = 'cama.{name}'"
|
||||
), columns=["person_id", "index_date", "horizon_years", "probability"]) # fmt: skip
|
||||
risks["pac_id"] = risks["person_id"].map(patient).astype(int)
|
||||
expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
|
||||
both = risks.merge(expected, left_on=["pac_id", "horizon_years"],
|
||||
right_on=["pac_id", "horizonte_anios"], validate="1:1") # fmt: skip
|
||||
assert len(both) == len(expected) == len(risks), name
|
||||
assert (both["index_date"].astype(str) == both["fecha_indice"].astype(str)).all()
|
||||
np.testing.assert_allclose(both["probability"].astype(float), both["probabilidad"],
|
||||
rtol=1e-6) # fmt: skip
|
||||
|
||||
# Every resource the API serves, every search paged to the end, passes the HL7
|
||||
# validator (offline: structure, cardinality, profiles; no terminology server).
|
||||
people = [r["id"] for b in pages(api, "/cama/fhir/Patient", {"follow-up-window": 12})
|
||||
for r in (e["resource"] for e in b["entry"])][:10] # fmt: skip
|
||||
resources = served(api, "/cama/fhir", PERIODS, people)
|
||||
errors, warnings = validate(resources, tmp_path)
|
||||
print(f"HL7 validator: {len(warnings)} warnings")
|
||||
assert [e for e in errors if not unscored(e, resources)] == []
|
||||
@@ -0,0 +1,258 @@
|
||||
"""What this module covers: the routes of CaMa's descriptive analysis (`/cama/analisis`) over the same invented CaMa database
|
||||
as the follow-up list: contract, selection and suppression shared with the list, consistency between the endpoints,
|
||||
states without data, validation and the trend by period.
|
||||
|
||||
Fixtures: `base` and `app`, a CaMa database loaded from `test_cama_follow_up.insertar` (17 invented patients, 15 in the
|
||||
BI-RADS cohort at 2025-12-31) through the cycle up to `event_models`, behind a Flask app with the analysis and follow-up
|
||||
blueprints; needs `DBT_MANIFEST`. The calculations themselves are checked, with exact counts, in
|
||||
`test_cama_analysis_calculations.py`.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlmodel import Session
|
||||
|
||||
from conftest import base_de
|
||||
from test_cama_follow_up import CORTE, UNTIL_MODELS, insertar
|
||||
from webapi.cama_analysis.routes import analysis_blueprint
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
|
||||
base = base_de("cama", tmp_path_factory.mktemp("cama_analisis"), datos=insertar)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(base):
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
|
||||
flask.register_blueprint(analysis_blueprint(lambda: Session(base.motor)), url_prefix="/cama/analisis")
|
||||
return flask.test_client()
|
||||
|
||||
|
||||
def get(app, ruta, **params):
|
||||
return app.get("/cama/analisis" + ruta, query_string={"corte": CORTE, "meses": 0, **params})
|
||||
|
||||
|
||||
def tend(app, **params):
|
||||
"""The trend takes only the cut-off: no window, no filters."""
|
||||
return app.get("/cama/analisis/tendencia", query_string={"corte": CORTE, **params})
|
||||
|
||||
|
||||
def test_the_catalog_lists_what_the_analysis_offers_and_what_it_cannot_calculate(app):
|
||||
"""Pins down: the catalog names the dimensions with their options, the measures, the horizons, the five sections and the
|
||||
analyses that are not available with their reasons, and carries the cohort context. Fails if the tab is given
|
||||
something to draw that has no endpoint, or an unavailable analysis loses its reason."""
|
||||
c = get(app, "").get_json()
|
||||
assert [d["clave"] for d in c["dimensiones"]] == ["birads", "grupo_edad", "biopsia"]
|
||||
assert c["horizontes_dias"] == [30, 90, 180, 365] and c["tipos_periodo"] == ["mes", "semestre"]
|
||||
assert [s["clave"] for s in c["secciones"]] == ["resumen", "distribucion", "comparacion", "mapa", "tendencia"]
|
||||
assert {x["clave"] for x in c["no_disponibles"]} >= {"supervivencia", "recaida", "curvas_tiempo_a_evento"}
|
||||
assert c["cohorte"] == "cama_birads_v1" and re.fullmatch(r"[0-9a-f]{64}", c["revision"]) and c["umbral_supresion"] == 5
|
||||
assert "simulado" not in c
|
||||
|
||||
|
||||
def test_the_cards_distribution_list_and_legacy_aggregate_agree_on_who_is_in_the_cohort(app):
|
||||
"""Pins down: the cohort card, the total of the distribution by each dimension, the list's total and the legacy aggregate's
|
||||
categories all describe the same 15 patients, under one revision. Fails if two parts of the tab count different patients."""
|
||||
resumen = get(app, "/resumen").get_json()
|
||||
total = next(i for i in resumen["indicadores"] if i["clave"] == "cohorte")["valor"]
|
||||
lista = app.get("/cama/seguimiento", query_string={"corte": CORTE, "meses": 0}).get_json()
|
||||
assert total == lista["paginacion"]["total_items"] == 15
|
||||
for por in ("birads", "grupo_edad", "biopsia"):
|
||||
d = get(app, "/distribucion", por=por).get_json()
|
||||
assert d["total"] == 15 and d["revision"] == resumen["revision"] == lista["revision"]
|
||||
publicados = sum(i["n"] for i in d["items"] if not i["suprimido"])
|
||||
assert publicados <= 15
|
||||
legado = get(app, "/indicadores").get_json()
|
||||
por_birads = {i["codigo"]: i for i in get(app, "/distribucion", por="birads").get_json()["items"]}
|
||||
# The legacy contract publishes a category only from the threshold, so an empty one reads as not published.
|
||||
assert {g["codigo"]: g["n"] for g in legado["grupos"]} == {c: (i["n"] or None) for c, i in por_birads.items()}
|
||||
assert all(g["n"] is None or g["n"] >= legado["umbral_supresion"] for g in legado["grupos"])
|
||||
assert legado["simulado"] is True and legado["umbral_supresion"] == 5
|
||||
|
||||
|
||||
def test_small_cohort_figures_are_states_not_numbers(app):
|
||||
"""Pins down: with 4 patients with a biopsy report and 3 with a known result, the cards of proportions are `suprimido`
|
||||
without value or interval, the cohort card shows 15, the cards that need a denominator of zero are `sin_datos`, and the
|
||||
cards of what the data cannot hold are listed apart. Fails if a small group is shown through a card."""
|
||||
r = get(app, "/resumen", horizonte=90).get_json()
|
||||
t = {i["clave"]: i for i in r["indicadores"]}
|
||||
assert t["cohorte"]["valor"] == 15 and t["cohorte"]["estado"] == "disponible"
|
||||
assert t["con_biopsia"]["estado"] == "suprimido" and t["con_biopsia"]["valor"] is None
|
||||
assert t["maligno_conocido"]["estado"] == "suprimido" and t["maligno_conocido"]["ic_bajo"] is None
|
||||
assert r["horizonte_dias"] == 90 and "maligno_90d" in t and {x["clave"] for x in r["no_disponibles"]}
|
||||
|
||||
|
||||
def test_the_distribution_by_biopsy_result_names_every_category_and_opens_its_patients(app):
|
||||
"""Pins down: by biopsy result the categories are benign, in situ, invasive, report without grade and no biopsy, each with
|
||||
the Seguimiento filter that opens its patients. Four groups of one patient hide with the group of 11 without biopsy, so
|
||||
the difference to the total hides them. Fails if a category is missing, a small group can be recovered by subtraction,
|
||||
or the key is not one the list accepts."""
|
||||
d = get(app, "/distribucion", por="biopsia").get_json()
|
||||
assert [i["codigo"] for i in d["items"]] == ["BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR", "SIN_DATO", "SIN_BIOPSIA"]
|
||||
sin_biopsia = d["items"][-1]
|
||||
# Four categories of one patient each hide, and the 11 without biopsy goes with them so the difference can't give them away.
|
||||
assert all(i["suprimido"] and i["n"] is None for i in d["items"])
|
||||
assert sin_biopsia["seleccion"] == {"biopsia": "SIN_BIOPSIA"}
|
||||
abierta = app.get("/cama/seguimiento", query_string={"corte": CORTE, "meses": 0, **sin_biopsia["seleccion"]}).get_json()
|
||||
assert abierta["paginacion"]["total_items"] == 11, "the list accepts the key the distribution gives"
|
||||
|
||||
|
||||
def test_comparison_and_map_say_no_data_instead_of_a_test_or_a_cell_they_cannot_support(app):
|
||||
"""Pins down: on this small cohort the comparison has no valid test (it says why) and its groups are suppressed; the
|
||||
map has every cell with a state and no proportions that leak; both refuse the biopsy result as a dimension. Fails if a
|
||||
p-value is given on a table of fewer than five known results."""
|
||||
c = get(app, "/comparacion", por="birads", medida="maligno").get_json()
|
||||
assert c["prueba"]["valida"] is False and c["prueba"]["motivo"]
|
||||
assert all(g["estado"] in ("suprimido", "sin_datos") for g in c["grupos"])
|
||||
m = get(app, "/mapa", filas="birads", columnas="grupo_edad").get_json()
|
||||
assert len(m["celdas"]) == len(m["filas"]["categorias"]) * len(m["columnas"]["categorias"])
|
||||
assert all(c["resultado"]["valor"] is None for c in m["celdas"])
|
||||
assert get(app, "/comparacion", por="biopsia").status_code == 400
|
||||
assert get(app, "/mapa", filas="biopsia", columnas="birads").status_code == 400
|
||||
assert get(app, "/mapa", filas="birads", columnas="birads").status_code == 400
|
||||
|
||||
|
||||
def test_the_trend_counts_reports_per_period_and_flags_the_period_the_cutoff_cuts(app):
|
||||
"""Pins down: by month the reports of mammogram and biopsy fall in their months, small counts are hidden, the answer names
|
||||
its population, unit and biopsy scope, and a cut-off inside a period marks it as incomplete. Fails if a report is counted
|
||||
in another period, a partial period is presented as whole or the answer carries a test or a cohort it doesn't use."""
|
||||
t = tend(app, tipo="mes", periodos=12).get_json()
|
||||
assert [p["periodo"] for p in t["periodos"]][-1] == "2025-12" and len(t["periodos"]) == 12
|
||||
assert all(p["incompleto"] is False for p in t["periodos"])
|
||||
assert t["unidad"] == "reportes" and t["poblacion"] and t["alcance_biopsias"] and t["corte"] == CORTE
|
||||
assert not {"prueba", "cohorte", "revision", "ventana", "filtros"} & set(t)
|
||||
diciembre = t["periodos"][-1]
|
||||
assert diciembre["reportes_mastografia"]["total"] in (None, *range(5, 40))
|
||||
for p in t["periodos"]:
|
||||
categorias = p["reportes_biopsia"]["por_grado"]
|
||||
ocultos = [k for k, v in categorias.items() if v["suprimido"]]
|
||||
assert len(ocultos) != 1 or p["reportes_biopsia"]["total"] is None, "a lone hidden category would be the total minus the published ones"
|
||||
parcial = app.get("/cama/analisis/tendencia", query_string={"corte": "2025-12-15", "tipo": "mes", "periodos": 3}).get_json()
|
||||
assert parcial["periodos"][-1]["periodo"] == "2025-12" and parcial["periodos"][-1]["incompleto"] is True
|
||||
semestres = tend(app, tipo="semestre", periodos=2).get_json()
|
||||
assert [p["periodo"] for p in semestres["periodos"]] == ["2025-S1", "2025-S2"]
|
||||
|
||||
|
||||
def test_the_trend_is_the_same_whatever_the_cohort_selection_and_refuses_to_take_one(app):
|
||||
"""Pins down: the trend is general activity, so a window, a filter or the cohort context are 400 instead of being silently
|
||||
ignored, and the answer of the same cut-off doesn't change with what the other sections have selected. Fails if the trend
|
||||
attributes a filter or window it doesn't apply."""
|
||||
base = tend(app, tipo="mes", periodos=6)
|
||||
assert base.status_code == 200
|
||||
for extra in ({"meses": 3}, {"birads": "BIRADS_5"}, {"grupo_edad": "50_59"}, {"cohorte": "x", "escenario": "y", "revision": "z"}, {"horizonte": 90}):
|
||||
assert tend(app, tipo="mes", periodos=6, **extra).status_code == 400, extra
|
||||
cuerpo = get(app, "/resumen").get_json()
|
||||
get(app, "/distribucion", por="grupo_edad", birads="BIRADS_5")
|
||||
assert tend(app, tipo="mes", periodos=6).get_json() == base.get_json()
|
||||
assert cuerpo["cohorte"] not in str(base.get_json())
|
||||
|
||||
|
||||
def test_a_period_without_reports_has_zero_counts_and_no_proportion(app):
|
||||
"""Pins down: months before the first report have zero reports, a proportion `sin_datos` and no hidden flag on a zero.
|
||||
Fails if an empty month turns into a suppressed or a zero-percent figure."""
|
||||
t = tend(app, tipo="mes", periodos=12).get_json()
|
||||
vacio = t["periodos"][0]
|
||||
assert vacio["periodo"] == "2025-01" and vacio["reportes_biopsia"]["por_grado"]["BENIGNO"] == {"n": 0, "suprimido": False}
|
||||
assert vacio["maligno"]["estado"] == "sin_datos" and vacio["maligno"]["valor"] is None
|
||||
|
||||
|
||||
def test_an_empty_cohort_is_an_answer_with_no_data_in_every_part(app):
|
||||
"""Pins down: before the first mammogram every endpoint answers 200 with zero patients and states without data, never an
|
||||
error or a figure. Fails if an empty cohort breaks a part of the tab."""
|
||||
vacia = {"corte": "2025-01-01", "meses": 0}
|
||||
resumen = app.get("/cama/analisis/resumen", query_string=vacia).get_json()
|
||||
t = {i["clave"]: i for i in resumen["indicadores"]}
|
||||
assert t["cohorte"]["valor"] == 0 and t["maligno_conocido"]["estado"] == "sin_datos" and t["biopsia_90d"]["estado"] == "sin_datos"
|
||||
d = app.get("/cama/analisis/distribucion", query_string={**vacia, "por": "birads"}).get_json()
|
||||
assert d["total"] == 0 and all(i["n"] == 0 and i["porcentaje"] is None for i in d["items"])
|
||||
assert app.get("/cama/analisis/comparacion", query_string={**vacia, "por": "grupo_edad"}).status_code == 200
|
||||
assert app.get("/cama/analisis/mapa", query_string={**vacia, "filas": "birads", "columnas": "grupo_edad"}).status_code == 200
|
||||
|
||||
|
||||
def test_the_selection_rules_of_the_list_apply_to_the_analysis(app):
|
||||
"""Pins down: a window or filter selecting fewer than five patients is a 403 with the reason `supresion`, a stale revision a
|
||||
409, a context quoted in part a 400, and the endpoints share the list's window and filters. Fails if the analysis
|
||||
answers a group the list refuses."""
|
||||
assert get(app, "/distribucion", por="birads", birads="BIRADS_6").status_code == 403
|
||||
assert get(app, "/resumen", meses=1, birads="BIRADS_5").status_code == 403
|
||||
cuerpo = get(app, "/resumen").get_json()
|
||||
contexto = {k: cuerpo[k] for k in ("cohorte", "escenario", "revision")}
|
||||
assert get(app, "/resumen", **contexto).status_code == 200
|
||||
assert get(app, "/resumen", **{**contexto, "revision": "0" * 64}).status_code == 409
|
||||
assert get(app, "/resumen", cohorte=contexto["cohorte"]).status_code == 400
|
||||
filtrado = get(app, "/distribucion", por="grupo_edad", birads="BIRADS_5").get_json()
|
||||
assert filtrado["filtros"]["birads"] == "BIRADS_5" and filtrado["total"] in (6, 7)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ruta, params", [
|
||||
("/distribucion", {}), ("/distribucion", {"por": "edad"}), ("/resumen", {"horizonte": 45}), ("/resumen", {"horizonte": "x"}),
|
||||
("/comparacion", {"por": "birads", "medida": "otra"}), ("/resumen", {"meses": 0, "periodos": 3}), ("/resumen", {"por": "birads"}), ("/resumen", {"estatus": "ALTA"}), ("/distribucion", {"por": ""}),
|
||||
])
|
||||
def test_a_badly_written_request_is_a_400(app, ruta, params):
|
||||
"""Pins down: a missing or unknown dimension, an unadmitted horizon or period count, a parameter of another route and
|
||||
the retired status are all 400. Fails if validation lets an unknown request through."""
|
||||
assert get(app, ruta, **params).status_code == 400
|
||||
|
||||
|
||||
@pytest.mark.parametrize("meses", [0, 1, 3, 6, 12])
|
||||
@pytest.mark.parametrize("por", ["birads", "grupo_edad", "biopsia"])
|
||||
def test_each_published_group_opens_exactly_the_patients_it_counts_in_every_window(app, meses, por):
|
||||
"""Pins down: for the whole cohort and for the windows of 1, 3, 6 and 12 months, every published group of the distribution
|
||||
opens in the follow-up list, with its key, the same window and the cohort context, onto as many patients as it counts, and
|
||||
a selection the list suppresses is not published. Fails if a bar leads to a different population than it represents."""
|
||||
respuesta = get(app, "/distribucion", por=por, meses=meses)
|
||||
if respuesta.status_code == 403:
|
||||
assert meses != 0, "only a window may leave the cohort too small"
|
||||
return
|
||||
d = respuesta.get_json()
|
||||
assert d["ventana"]["meses"] == meses
|
||||
contexto = {k: d[k] for k in ("cohorte", "escenario", "revision")}
|
||||
abiertos = 0
|
||||
for item in d["items"]:
|
||||
if item["suprimido"] or not item["n"]:
|
||||
continue
|
||||
lista = app.get("/cama/seguimiento", query_string={"corte": d["corte"], "meses": d["ventana"]["meses"], **contexto, **item["seleccion"]})
|
||||
assert lista.status_code == 200, (item["codigo"], lista.get_json())
|
||||
assert lista.get_json()["paginacion"]["total_items"] == item["n"], (meses, por, item["codigo"])
|
||||
abiertos += 1
|
||||
assert abiertos or meses != 0 or por == "biopsia", "the whole cohort publishes groups"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("params", [{"tipo": "dia"}, {"periodos": 0}, {"periodos": 99}, {"periodos": "x"}, {"corte": "2999-01-01"}])
|
||||
def test_a_badly_written_trend_request_is_a_400(app, params):
|
||||
"""Pins down: an unknown period type, a period count out of range and a cut-off in the future are refused. Fails if the
|
||||
trend answers a request it can't define."""
|
||||
assert tend(app, **{"tipo": "mes", **params}).status_code == 400
|
||||
|
||||
|
||||
def test_a_repeated_parameter_is_a_400_and_the_answers_are_not_cached(app):
|
||||
"""Pins down: `por` twice is refused, and every answer says `no-store`. Fails if a client's choice is ambiguous or a
|
||||
patient-level selection can be cached."""
|
||||
assert app.get("/cama/analisis/distribucion?corte=2025-12-31&meses=0&por=birads&por=grupo_edad").status_code == 400
|
||||
assert get(app, "/resumen").headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_without_the_cohort_view_the_analysis_answers_503(tmp_path):
|
||||
"""Pins down: a database whose indicator cycle hasn't created the cohort view answers 503 with the reason `cohorte`.
|
||||
Fails if a missing view is a server error."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
|
||||
sin_ciclo = base_de("cama", tmp_path, datos=insertar)
|
||||
try:
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(analysis_blueprint(lambda: Session(sin_ciclo.motor)), url_prefix="/cama/analisis")
|
||||
respuesta = flask.test_client().get("/cama/analisis/resumen", query_string={"corte": CORTE, "meses": 0})
|
||||
assert respuesta.status_code == 503 and respuesta.get_json()["motivo"] == "cohorte"
|
||||
finally:
|
||||
sin_ciclo.motor.dispose()
|
||||
@@ -0,0 +1,226 @@
|
||||
"""What this module covers: the statistics, the suppression rule and the calculations of CaMa's descriptive analysis
|
||||
(`webapi.cama_analysis`), as pure functions: no database, no HTTP.
|
||||
|
||||
Fixtures: none. The cohort rows are built here with the exact counts each test needs (`fila`), invented inputs whose
|
||||
expected figures are written out in the tests; nothing is read from a database.
|
||||
"""
|
||||
|
||||
import math
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.cama_analysis import calculations as calc
|
||||
from webapi.cama_analysis.stats import chi2_homogeneidad, chi2_sf, cuantil, wilson
|
||||
from webapi.cama_analysis.suppression import proporcion_publicable, suprimir_categorias, suprimir_tabla
|
||||
from webapi.cama_follow_up.cohort import Fila
|
||||
|
||||
CORTE = date(2025, 12, 31)
|
||||
MAST = date(2025, 1, 1)
|
||||
MALIGNOS = {"CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"}
|
||||
CATEGORIAS_BIRADS = [("BIRADS_4A", "BI-RADS 4A"), ("BIRADS_5", "BI-RADS 5"), ("BIRADS_6", "BI-RADS 6")]
|
||||
CATEGORIAS_EDAD = [("40-49", "40 a 49 años"), ("50-59", "50 a 59 años")]
|
||||
|
||||
|
||||
def fila(i, birads="BIRADS_5", edad="50-59", grado=None, con_reporte=None, dias_biopsia=None, dias_maligno=None, mast=MAST):
|
||||
"""One patient: `grado` is the shown biopsy result, `dias_*` the days from the mammogram to the earliest biopsy report and
|
||||
to the earliest malignant one."""
|
||||
reporte = con_reporte if con_reporte is not None else grado is not None
|
||||
return Fila(pac_id=i, mastografia_fecha=mast, birads=birads, grupo_edad=edad, biopsia=grado,
|
||||
biopsia_fecha=mast + timedelta(days=dias_biopsia or 9) if reporte else None,
|
||||
primera_biopsia_fecha=mast + timedelta(days=dias_biopsia) if dias_biopsia is not None else None,
|
||||
primer_maligno_fecha=mast + timedelta(days=dias_maligno) if dias_maligno is not None else None)
|
||||
|
||||
|
||||
def cohorte():
|
||||
"""70 patients: 40 with a known result (30 benign, 5 in situ, 5 invasive), 10 with a report and no grade, 20 without
|
||||
a biopsy. Days to the first biopsy report: 20 benign at 10 days, 6 malignant at 20 days, the other 24 with a report at 100 days."""
|
||||
filas, i = [], 0
|
||||
for grado, n in (("BENIGNO", 30), ("CARCINOMA_IN_SITU", 5), ("CARCINOMA_INVASOR", 5)):
|
||||
for _ in range(n):
|
||||
i += 1
|
||||
filas.append(fila(i, grado=grado))
|
||||
for k, f in enumerate(filas):
|
||||
pronto = k < 20 or (grado_es(f) and k % 10 < 6)
|
||||
dias = 10 if k < 20 else 20 if pronto else 100
|
||||
maligno = (20 if pronto else 120) if grado_es(f) else None
|
||||
filas[k] = fila(f.pac_id, grado=f.biopsia, dias_biopsia=dias, dias_maligno=maligno)
|
||||
for _ in range(10):
|
||||
i += 1
|
||||
filas.append(fila(i, grado=None, con_reporte=True, dias_biopsia=100))
|
||||
for _ in range(20):
|
||||
i += 1
|
||||
filas.append(fila(i))
|
||||
return filas
|
||||
|
||||
|
||||
def grado_es(f):
|
||||
return f.biopsia in MALIGNOS
|
||||
|
||||
|
||||
def test_wilson_matches_the_closed_form_and_stays_inside_zero_and_one():
|
||||
"""Pins down: the Wilson interval of 10 of 40 is (14.1 %, 40.3 %), the interval of 0 of n starts at 0 and of n of n ends at
|
||||
1, and it is symmetric around the midpoint of k and n-k. Fails if the formula or its continuity is changed."""
|
||||
bajo, alto = wilson(10, 40)
|
||||
assert (bajo, alto) == pytest.approx((0.1410, 0.4028), abs=0.001)
|
||||
assert wilson(0, 30)[0] == 0 and wilson(30, 30)[1] == 1
|
||||
assert wilson(10, 40)[0] == pytest.approx(1 - wilson(30, 40)[1])
|
||||
with pytest.raises(ValueError):
|
||||
wilson(5, 0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("gl, critico", [(1, 3.841458820694124), (2, 5.991464547107979), (3, 7.814727903251179), (4, 9.487729036781154), (9, 16.918977604620448)])
|
||||
def test_chi_square_tail_at_the_five_percent_critical_values(gl, critico):
|
||||
"""Pins down: the tail probability at the textbook 5 % critical value of each degree of freedom is 0.05, and at 0 it is
|
||||
1. Fails if the incomplete gamma function is wrong in its series or its continued fraction."""
|
||||
assert chi2_sf(critico, gl) == pytest.approx(0.05, abs=1e-9)
|
||||
assert chi2_sf(0, gl) == 1
|
||||
|
||||
|
||||
def test_the_homogeneity_test_gives_the_statistic_and_refuses_what_the_approximation_cannot_carry():
|
||||
"""Pins down: groups 20 of 40 and 8 of 40 give chi-square 7.912 with 1 degree of freedom and p 0.0049; two groups with an
|
||||
expected count under 5, a single group, or one outcome only are not tested, with the reason. Fails if a p-value is
|
||||
given where the approximation isn't valid."""
|
||||
prueba = chi2_homogeneidad([(20, 40), (8, 40)])
|
||||
assert prueba["valida"] and prueba["gl"] == 1 and prueba["estadistico"] == pytest.approx(7.912, abs=0.001)
|
||||
assert prueba["p"] == pytest.approx(0.00492, abs=0.0001)
|
||||
assert not chi2_homogeneidad([(1, 10), (2, 10)])["valida"]
|
||||
assert not chi2_homogeneidad([(20, 40)])["valida"]
|
||||
assert not chi2_homogeneidad([(0, 40), (0, 40)])["valida"]
|
||||
|
||||
|
||||
def test_quantiles_interpolate_between_the_order_statistics():
|
||||
"""Pins down: the median of 1 to 4 is 2.5 and the quartiles of 1 to 5 are 2 and 4. Fails if the interpolation changes."""
|
||||
assert cuantil([4, 1, 3, 2], .5) == 2.5
|
||||
assert (cuantil([1, 2, 3, 4, 5], .25), cuantil([1, 2, 3, 4, 5], .75)) == (2, 4)
|
||||
|
||||
|
||||
def test_a_proportion_is_published_only_when_the_group_the_cases_and_the_rest_are_not_small():
|
||||
"""Pins down: 10 of 40 is published; 3 of 40 (3 cases), 38 of 40 (2 non-cases) and 4 of 4 (a group under 5) are not;
|
||||
0 of 40 is published because zero describes nobody. Fails if a small cell can be read from a proportion."""
|
||||
assert proporcion_publicable(10, 40, 5) and proporcion_publicable(0, 40, 5)
|
||||
assert not proporcion_publicable(3, 40, 5) and not proporcion_publicable(38, 40, 5) and not proporcion_publicable(4, 4, 5)
|
||||
|
||||
|
||||
def test_a_hidden_cell_takes_the_smallest_published_one_with_it_until_the_difference_hides_nothing():
|
||||
"""Pins down: with cells 30, 12, 8, 2 and a published total, the 2 is hidden and so is the 8 (2 + 8 >= 5), so the
|
||||
difference between the total and the published cells is 10 patients and says nothing of the 2; cells with no small
|
||||
count hide nothing; zeros are not small. Fails if one hidden cell can be recovered by subtraction."""
|
||||
assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 2}, 5) == {"c", "d"}
|
||||
assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 7}, 5) == set()
|
||||
assert suprimir_categorias({"a": 30, "b": 0, "c": 8}, 5) == set()
|
||||
assert suprimir_categorias({"a": 3, "b": 2}, 5) == {"a", "b"}
|
||||
|
||||
|
||||
def test_a_table_hides_along_rows_and_columns_until_no_line_gives_a_small_cell_away():
|
||||
"""Pins down: in a 2 x 2 table with one cell of 1, the secondary suppression covers its row and its column, so the
|
||||
hidden cells total at least 5 in each line. Fails if a marginal total and the visible cells reveal a hidden cell."""
|
||||
conteos = {("a", "x"): 20, ("a", "y"): 1, ("b", "x"): 9, ("b", "y"): 30}
|
||||
ocultas = suprimir_tabla(conteos, 5)
|
||||
assert ("a", "y") in ocultas
|
||||
for fila_ in ("a", "b"):
|
||||
ocultos = sum(conteos[k] for k in ocultas if k[0] == fila_)
|
||||
assert ocultos == 0 or ocultos >= 5
|
||||
for columna in ("x", "y"):
|
||||
ocultos = sum(conteos[k] for k in ocultas if k[1] == columna)
|
||||
assert ocultos == 0 or ocultos >= 5
|
||||
|
||||
|
||||
def test_the_cards_state_their_numerator_denominator_and_interval():
|
||||
"""Pins down, on a cohort of 70 (40 with a known result, 10 with a report without a grade, 20 without biopsy): cohort 70;
|
||||
with a biopsy report 50 of 70; malignant among the known 10 of 40 (25 %) with its Wilson interval; invasive 5 of 40;
|
||||
a biopsy within 90 days 26 of 70; a malignant result within 90 days 6 of 70; the median days to the report 20 (n 50).
|
||||
Fails if a numerator, a denominator or a definition changes."""
|
||||
t = {x["clave"]: x for x in calc.resumen(cohorte(), CORTE, 90, MALIGNOS, 5)}
|
||||
assert t["cohorte"]["valor"] == 70
|
||||
assert (t["con_biopsia"]["n"], t["con_biopsia"]["denominador"]) == (50, 70)
|
||||
assert (t["maligno_conocido"]["n"], t["maligno_conocido"]["denominador"], t["maligno_conocido"]["valor"]) == (10, 40, 25.0)
|
||||
assert (t["maligno_conocido"]["ic_bajo"], t["maligno_conocido"]["ic_alto"]) == pytest.approx((14.1, 40.3), abs=0.2)
|
||||
assert (t["invasor_conocido"]["n"], t["invasor_conocido"]["denominador"]) == (5, 40)
|
||||
assert (t["biopsia_90d"]["n"], t["biopsia_90d"]["denominador"]) == (26, 70)
|
||||
assert (t["maligno_90d"]["n"], t["maligno_90d"]["denominador"]) == (6, 70)
|
||||
assert (t["dias_a_biopsia"]["valor"], t["dias_a_biopsia"]["n"]) == (20, 50)
|
||||
assert all(x["estado"] == "disponible" for x in t.values())
|
||||
|
||||
|
||||
def test_a_horizon_counts_only_the_mammograms_that_have_had_the_time():
|
||||
"""Pins down: with a 365-day horizon and the cut-off 364 days after the mammograms nobody has had the time, so the
|
||||
denominator is zero and the card has no data, not a zero percent; a mammogram that is recent at the cut-off is left
|
||||
out of the 90-day denominator. Fails if a recent mammogram is read as one without a biopsy."""
|
||||
t = {x["clave"]: x for x in calc.resumen(cohorte(), MAST + timedelta(days=364), 365, MALIGNOS, 5)}
|
||||
assert t["biopsia_365d"]["estado"] == "sin_datos" and t["biopsia_365d"]["valor"] is None
|
||||
recientes = cohorte() + [fila(900 + k, mast=CORTE - timedelta(days=10)) for k in range(6)]
|
||||
t = {x["clave"]: x for x in calc.resumen(recientes, CORTE, 90, MALIGNOS, 5)}
|
||||
assert t["biopsia_90d"]["denominador"] == 70 and t["cohorte"]["valor"] == 76
|
||||
|
||||
|
||||
def test_a_small_numerator_or_denominator_hides_the_figure_and_its_interval():
|
||||
"""Pins down: 3 malignant among 20 known results, and 4 patients with a known result, are not published (state
|
||||
`suprimido`, no value, no interval); an empty cohort has no data. Fails if a small group is shown through a figure."""
|
||||
pocas = [fila(i, grado="CARCINOMA_INVASOR") for i in range(1, 4)] + [fila(10 + i, grado="BENIGNO") for i in range(17)]
|
||||
t = {x["clave"]: x for x in calc.resumen(pocas, CORTE, 90, MALIGNOS, 5)}
|
||||
assert t["maligno_conocido"]["estado"] == "suprimido" and t["maligno_conocido"]["valor"] is None and t["maligno_conocido"]["ic_bajo"] is None
|
||||
cuatro = {x["clave"]: x for x in calc.resumen([fila(i, grado="BENIGNO") for i in range(4)], CORTE, 90, MALIGNOS, 5)}
|
||||
assert cuatro["maligno_conocido"]["estado"] == "suprimido"
|
||||
vacia = {x["clave"]: x for x in calc.resumen([], CORTE, 90, MALIGNOS, 5)}
|
||||
assert vacia["cohorte"]["valor"] == 0 and vacia["maligno_conocido"]["estado"] == "sin_datos"
|
||||
|
||||
|
||||
def test_the_distribution_adds_up_to_the_selection_and_hides_small_groups_by_complement():
|
||||
"""Pins down: 30 + 12 + 8 + 2 patients by BI-RADS: the total is 52, shares are of the selection with Wilson intervals,
|
||||
the 2 and the 8 are not published. Fails if the cells and the total disagree or a hidden cell can be subtracted."""
|
||||
filas = ([fila(i, birads="BIRADS_5") for i in range(30)] + [fila(100 + i, birads="BIRADS_4A") for i in range(12)]
|
||||
+ [fila(200 + i, birads="BIRADS_6") for i in range(2)])
|
||||
d = calc.distribucion(filas, "birads", [("BIRADS_4A", "4A"), ("BIRADS_5", "5"), ("BIRADS_6", "6")], 5)
|
||||
por = {i["codigo"]: i for i in d["items"]}
|
||||
assert d["total"] == 44 and por["BIRADS_5"]["n"] == 30 and por["BIRADS_5"]["porcentaje"] == pytest.approx(68.18, abs=0.01)
|
||||
assert por["BIRADS_6"]["suprimido"] and por["BIRADS_6"]["n"] is None and por["BIRADS_6"]["ic_bajo"] is None
|
||||
assert por["BIRADS_4A"]["suprimido"], "the smallest published cell is hidden with the small one"
|
||||
assert sum(i["n"] for i in d["items"] if not i["suprimido"]) == 30
|
||||
assert por["BIRADS_5"]["seleccion"] == {"birads": "BIRADS_5"}
|
||||
|
||||
|
||||
def test_the_comparison_shares_the_denominator_of_known_results_and_tests_only_valid_tables():
|
||||
"""Pins down: by BI-RADS, 20 of 40 and 8 of 40 known results are malignant (50 % and 20 %), the test is the chi-square 7.9
|
||||
with p 0.005, patients without a result are not in the denominator, and a group of fewer than five known results is
|
||||
suppressed and left out of the test. Fails if the denominator includes patients without biopsy or the test uses a hidden group."""
|
||||
filas = ([fila(i, birads="BIRADS_4A", grado="CARCINOMA_INVASOR") for i in range(20)] + [fila(30 + i, birads="BIRADS_4A", grado="BENIGNO") for i in range(20)]
|
||||
+ [fila(100 + i, birads="BIRADS_5", grado="CARCINOMA_IN_SITU") for i in range(8)] + [fila(130 + i, birads="BIRADS_5", grado="BENIGNO") for i in range(32)]
|
||||
+ [fila(300 + i, birads="BIRADS_5") for i in range(25)] + [fila(400 + i, birads="BIRADS_6", grado="BENIGNO") for i in range(3)])
|
||||
c = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "maligno", MALIGNOS, 5)
|
||||
g = {x["codigo"]: x for x in c["grupos"]}
|
||||
assert (g["BIRADS_4A"]["casos"], g["BIRADS_4A"]["total"], g["BIRADS_4A"]["valor"]) == (20, 40, 50.0)
|
||||
assert (g["BIRADS_5"]["casos"], g["BIRADS_5"]["total"], g["BIRADS_5"]["valor"]) == (8, 40, 20.0)
|
||||
assert g["BIRADS_6"]["estado"] == "suprimido"
|
||||
assert c["prueba"]["valida"] and c["prueba"]["p"] == pytest.approx(0.00492, abs=0.0001)
|
||||
invasor = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "invasor", MALIGNOS, 5)
|
||||
assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_4A"] == 20
|
||||
assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_5"] == 0
|
||||
|
||||
|
||||
def test_the_map_crosses_two_dimensions_and_its_cells_add_up_to_the_selection():
|
||||
"""Pins down: BI-RADS by age group: each patient is in one cell, the published cells never exceed the selection, the
|
||||
proportion of a cell is among its known results and a hidden cell, secondary ones included, has neither count nor proportion. Fails if a patient
|
||||
is counted twice or a hidden cell leaks through its proportion."""
|
||||
filas = ([fila(i, birads="BIRADS_5", edad="50-59", grado="BENIGNO") for i in range(12)]
|
||||
+ [fila(100 + i, birads="BIRADS_5", edad="40-49", grado="CARCINOMA_INVASOR") for i in range(7)]
|
||||
+ [fila(200 + i, birads="BIRADS_4A", edad="50-59") for i in range(9)] + [fila(300, birads="BIRADS_4A", edad="40-49")])
|
||||
m = calc.mapa(filas, "birads", "grupo_edad", CATEGORIAS_BIRADS, CATEGORIAS_EDAD, "maligno", MALIGNOS, 5)
|
||||
celdas = {(c["fila"], c["columna"]): c for c in m["celdas"]}
|
||||
assert celdas[("BIRADS_5", "50-59")]["n"] == 12 and celdas[("BIRADS_5", "50-59")]["resultado"]["casos"] == 0
|
||||
oculta = celdas[("BIRADS_4A", "40-49")]
|
||||
assert oculta["suprimido"] and oculta["n"] is None and oculta["resultado"]["valor"] is None
|
||||
# The 40-49 column then holds a hidden 1 and a published 7: the 7 goes with it, so the column can't give the 1 away.
|
||||
assert celdas[("BIRADS_5", "40-49")]["suprimido"] and celdas[("BIRADS_5", "40-49")]["resultado"]["valor"] is None
|
||||
assert celdas[("BIRADS_4A", "50-59")]["suprimido"], "and the 4A row hides its 9 for the same reason"
|
||||
assert sum(c["n"] for c in m["celdas"] if not c["suprimido"]) <= len(filas)
|
||||
assert celdas[("BIRADS_5", "50-59")]["seleccion"] == {"birads": "BIRADS_5", "grupo_edad": "50-59"}
|
||||
|
||||
|
||||
def test_the_catalog_of_unavailable_analyses_names_a_reason_for_each():
|
||||
"""Pins down: survival, recurrence, treatment adherence, the time-to-event curves and their tests, and BRCA, stage and
|
||||
size are listed as unavailable, each with its reason. Fails if one of them is dropped or loses its reason."""
|
||||
assert {x["clave"] for x in calc.NO_DISPONIBLES} == {"supervivencia", "recaida", "adherencia_tratamiento", "curvas_tiempo_a_evento",
|
||||
"riesgos_proporcionales", "brca_estadio_tamano"}
|
||||
assert all(x["motivo"] and x["titulo"] for x in calc.NO_DISPONIBLES)
|
||||
assert not math.isnan(wilson(1, 2)[0])
|
||||
@@ -0,0 +1,193 @@
|
||||
"""What this module covers: `CamaCohort.rows` (`webapi.cama_cohort`) and the `/cama/analisis`, `/cama/seguimiento`
|
||||
and `/cama/pacientes` routes over it: eligibility (BI-RADS 4-6, dated and known by the cutoff), the biopsy link
|
||||
(mammogram -> order -> report, never across patients or before the mammogram), pagination, export, patient detail
|
||||
and access control.
|
||||
|
||||
Fixtures: `cohort_db`, an isolated SQLite engine with six synthetic patients' `Persona`/`Carga`/`Procedimiento`/
|
||||
`Observacion` rows (`webapi.orchestration.tables.cama.TABLAS`), one load from 2025 and one from 2027; `client`, a
|
||||
minimal Flask app registering only the two CaMa blueprints over `cohort_db`, with an always-authorized access
|
||||
callback.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
from webapi.cama_analysis import analysis
|
||||
from webapi.cama_cohort import CamaCohort
|
||||
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cohort_db():
|
||||
"""Six eligible people, one linked biopsy and one biopsy without a link."""
|
||||
t = TABLAS
|
||||
engine = create_engine('sqlite:///:memory:')
|
||||
for model in (t.Persona, t.Carga, t.Procedimiento, t.Observacion):
|
||||
model.__table__.create(engine)
|
||||
with Session(engine) as session:
|
||||
session.add_all([
|
||||
t.Carga(carga_id=1, fuente='test', inicio=datetime(2025, 1, 1, tzinfo=timezone.utc)),
|
||||
t.Carga(carga_id=2, fuente='test', inicio=datetime(2027, 1, 1, tzinfo=timezone.utc)),
|
||||
])
|
||||
for patient in range(1, 7):
|
||||
session.add(t.Persona(pac_id=patient, pac_id_hospital=f'T-{patient}', fecha_nacimiento=date(1970, 1, 1)))
|
||||
session.add(t.Procedimiento(procedimiento_id=patient * 10, fuente_tabla='mastografia', fuente_id=str(patient),
|
||||
carga_id=1, pac_id=patient, estudio_id='mastografia', clase='toma', fecha=date(2025, 2, 1)))
|
||||
session.add(t.Procedimiento(procedimiento_id=patient * 10 + 1, padre_id=patient * 10, fuente_tabla='mastografia',
|
||||
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='mastografia',
|
||||
clase='reporte', fecha=date(2025, 2, 2)))
|
||||
session.add(t.Observacion(observacion_id=patient, procedimiento_id=patient * 10 + 1, carga_id=1,
|
||||
pac_id=patient, resultado_id='mastografia.birads', valor_fuente='B5'))
|
||||
for patient, parent, load in ((1, 10, 1), (2, None, 1), (3, 30, 2), (4, 40, 1)):
|
||||
report_date = date(2027, 2, 15) if patient == 4 else date(2025, 2, 15)
|
||||
session.add(t.Procedimiento(procedimiento_id=100 + patient * 2, padre_id=parent, fuente_tabla='biopsiamama',
|
||||
fuente_id=str(patient), carga_id=1, pac_id=patient, estudio_id='biopsia',
|
||||
clase='orden', fecha=date(2025, 2, 10)))
|
||||
session.add(t.Procedimiento(procedimiento_id=101 + patient * 2, padre_id=100 + patient * 2,
|
||||
fuente_tabla='biopsiamama', fuente_id=str(patient), carga_id=1, pac_id=patient,
|
||||
estudio_id='biopsia', clase='reporte', fecha=report_date))
|
||||
session.add(t.Observacion(observacion_id=100 + patient, procedimiento_id=101 + patient * 2, carga_id=load,
|
||||
pac_id=patient, resultado_id='biopsia.grado', valor_fuente='BENIGNO'))
|
||||
session.commit()
|
||||
yield engine
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(cohort_db):
|
||||
"""Configure an explicitly synthetic reader and an authorized test principal."""
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(analysis, url_prefix='/cama')
|
||||
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
|
||||
def read(cutoff):
|
||||
with Session(cohort_db) as session:
|
||||
return CamaCohort(session).rows(cutoff)
|
||||
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=read, CAMA_COHORT_ACCESS=lambda req: True)
|
||||
return app.test_client()
|
||||
|
||||
|
||||
QUERY = '?cohorte=cama_birads_v1&escenario=diagnostico&corte=2026-10-20&meses=0&birads=BIRADS_5'
|
||||
|
||||
|
||||
def query(client, cutoff='2026-10-20'):
|
||||
revision = client.get('/cama/analisis/indicadores?corte=' + cutoff).get_json()['revision']
|
||||
return QUERY.replace('2026-10-20', cutoff) + '&revision=' + revision
|
||||
|
||||
|
||||
def test_aggregate_list_detail_and_export_have_one_selection(client):
|
||||
"""The published aggregate reconciles with pages, patient details and export."""
|
||||
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 6
|
||||
selection = query(client)
|
||||
first = client.get('/cama/seguimiento' + selection + '&page_size=2').get_json()
|
||||
assert first['ventana'] == {'meses': 0, 'desde': '2025-02-01', 'hasta': '2026-10-20'}
|
||||
items = []
|
||||
for page in (1, 2, 3):
|
||||
data = client.get('/cama/seguimiento' + selection + f'&page_size=2&page={page}').get_json()
|
||||
items.extend(data['items'])
|
||||
exported = client.get('/cama/seguimiento/exportacion' + selection).get_json()
|
||||
assert exported['items'] == items and exported['total_items'] == 6
|
||||
for item in items:
|
||||
detail = client.get('/cama/pacientes/' + item['pac_id'] + selection).get_json()
|
||||
assert detail['item'] == item and detail['corte'] == aggregate['corte']
|
||||
assert sum(item['biopsia'] == 'BENIGNO' for item in items) == 1
|
||||
assert client.get('/cama/seguimiento' + selection).get_json()['items'] == items
|
||||
|
||||
|
||||
def test_rejects_unknown_and_suppressed_selections_and_denies_access(client):
|
||||
"""Unknown filters and small groups cannot silently broaden patient access."""
|
||||
selection = query(client)
|
||||
assert client.get('/cama/seguimiento' + selection + '&estadio=IV').status_code == 400
|
||||
assert client.get('/cama/seguimiento' + selection.replace('BIRADS_5', 'BIRADS_4A')).status_code == 403
|
||||
assert client.get('/cama/seguimiento' + selection.replace('cama_birads_v1', 'otra')).status_code == 400
|
||||
assert client.get('/cama/seguimiento' + selection.replace(selection[-64:], '0' * 64)).status_code == 409
|
||||
client.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
|
||||
assert client.get('/cama/seguimiento' + selection).status_code == 403
|
||||
assert client.get('/cama/seguimiento/exportacion' + selection).status_code == 403
|
||||
assert client.get('/cama/pacientes/some-id' + selection).status_code == 403
|
||||
|
||||
|
||||
def test_cutoff_excludes_later_clinical_and_load_dates(client):
|
||||
"""A report or observation not yet known at the cutoff cannot appear."""
|
||||
early = query(client, '2025-02-09')
|
||||
rows = client.get('/cama/seguimiento' + early).get_json()['items']
|
||||
assert len(rows) == 6 and all(row['biopsia'] is None for row in rows)
|
||||
empty = query(client, '2025-02-01').replace('&birads=BIRADS_5', '')
|
||||
response = client.get('/cama/seguimiento' + empty).get_json()
|
||||
assert response['items'] == [] and response['ventana']['desde'] == '2025-02-01'
|
||||
|
||||
|
||||
def test_links_and_load_dates_are_distinct(client, cohort_db):
|
||||
"""A missing link and a late load cannot supply a diagnosis before cutoff."""
|
||||
ids = {i: str(i) for i in range(1, 5)}
|
||||
data = client.get('/cama/seguimiento' + query(client)).get_json()
|
||||
rows = {item['pac_id']: item for item in data['items']}
|
||||
assert rows[ids[1]]['biopsia'] == 'BENIGNO'
|
||||
assert rows[ids[2]]['biopsia'] is None and rows[ids[2]]['biopsia_fecha'] is None
|
||||
assert rows[ids[3]]['biopsia'] is None and rows[ids[3]]['biopsia_fecha'] == '2025-02-15'
|
||||
assert rows[ids[4]]['biopsia'] is None and rows[ids[4]]['biopsia_fecha'] is None
|
||||
later = client.get('/cama/seguimiento' + query(client, '2027-12-01')).get_json()
|
||||
rows_later = {item['pac_id']: item for item in later['items']}
|
||||
assert rows_later[ids[3]]['biopsia'] == 'BENIGNO'
|
||||
assert rows_later[ids[4]]['biopsia_fecha'] == '2027-02-15'
|
||||
assert set(rows) == set(rows_later)
|
||||
|
||||
|
||||
def test_full_application_registers_cohort_and_regular_followup(client):
|
||||
"""The regular follow-up uses the configured reader instead of unrelated fixture rows."""
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(client.application.config)
|
||||
full = app.test_client()
|
||||
assert full.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 200
|
||||
assert full.get('/cama/seguimiento?corte=2026-10-20&meses=0').get_json()['paginacion']['total_items'] == 6
|
||||
assert full.get('/cama/seguimiento?meses=12&resultado=INVASOR').status_code == 400
|
||||
|
||||
|
||||
def test_windows_and_disabled_provider(client):
|
||||
"""Regular windows remain available and a missing reader returns unavailable."""
|
||||
selection = query(client).replace('&meses=0', '&meses=1').replace('&birads=BIRADS_5', '')
|
||||
body = client.get('/cama/seguimiento' + selection).get_json()
|
||||
assert body['items'] == [] and body['ventana']['desde'] == '2026-09-21'
|
||||
client.application.config['CAMA_COHORT_READER'] = None
|
||||
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
|
||||
|
||||
|
||||
def test_newer_noneligible_result_changes_revision_and_excludes_patient(client, cohort_db):
|
||||
"""The latest reported result is selected before checking BI-RADS eligibility."""
|
||||
previous = query(client)
|
||||
with Session(cohort_db) as session:
|
||||
session.add(TABLAS.Procedimiento(procedimiento_id=200, fuente_tabla='mastografia', fuente_id='new',
|
||||
carga_id=1, pac_id=6, estudio_id='mastografia', clase='toma', fecha=date(2025, 4, 1)))
|
||||
session.add(TABLAS.Procedimiento(procedimiento_id=201, padre_id=200, fuente_tabla='mastografia', fuente_id='new',
|
||||
carga_id=1, pac_id=6, estudio_id='mastografia', clase='reporte', fecha=date(2025, 4, 2)))
|
||||
session.add(TABLAS.Observacion(observacion_id=200, procedimiento_id=201, carga_id=1, pac_id=6,
|
||||
resultado_id='mastografia.birads', valor_fuente='B1'))
|
||||
session.commit()
|
||||
assert client.get('/cama/seguimiento' + previous).status_code == 409
|
||||
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||
assert next(g for g in aggregate['grupos'] if g['codigo'] == 'BIRADS_5')['n'] == 5
|
||||
assert len(client.get('/cama/seguimiento' + query(client)).get_json()['items']) == 5
|
||||
|
||||
|
||||
def test_cross_patient_links_and_observations_are_not_used(cohort_db):
|
||||
"""A mismatched patient or an order before the mammogram cannot supply a result."""
|
||||
with Session(cohort_db) as session:
|
||||
# The biopsy order is linked to patient 1's mammogram but belongs to patient 2.
|
||||
session.get(TABLAS.Procedimiento, 102).pac_id = 2
|
||||
# Patient 3's otherwise linked biopsy order predates the mammogram.
|
||||
session.get(TABLAS.Procedimiento, 106).fecha = date(2025, 1, 1)
|
||||
# The BI-RADS observation belongs to a different patient.
|
||||
session.get(TABLAS.Observacion, 6).pac_id = 5
|
||||
session.commit()
|
||||
reader = CamaCohort(session)
|
||||
rows = {row['pac_id']: row for row in reader.rows(date(2027, 12, 1))}
|
||||
assert '6' not in rows
|
||||
assert rows['1']['biopsia'] is None
|
||||
assert rows['3']['biopsia'] is None
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Integration with dev: no duplicate routes, retained access hook and individual contract."""
|
||||
from test_cama_analysis import app, base
|
||||
from test_cama_follow_up import CORTE
|
||||
|
||||
|
||||
def test_application_has_one_handler_per_cama_route():
|
||||
from webapi import create_app
|
||||
application = create_app()
|
||||
assert application.config['CAMA_COHORT_READER']._cama_default_reader is True
|
||||
rules = list(application.url_map.iter_rules())
|
||||
for path in ('/cama/seguimiento', '/cama/seguimiento/exportacion',
|
||||
'/cama/analisis/indicadores', '/cama/pacientes/<pac_id>'):
|
||||
assert len([r for r in rules if r.rule == path]) == 1
|
||||
assert application.test_client().get('/health').get_json() == {'status': 'ok'}
|
||||
|
||||
|
||||
def test_individual_route_is_a_row_of_the_selected_list(app):
|
||||
q = {'corte': CORTE, 'meses': 0}
|
||||
listing = app.get('/cama/seguimiento', query_string=q).get_json()
|
||||
q.update({k: listing[k] for k in ('cohorte', 'escenario', 'revision')})
|
||||
patient = listing['items'][0]
|
||||
detail = app.get('/cama/pacientes/' + patient['pac_id'], query_string=q)
|
||||
assert detail.status_code == 200
|
||||
assert detail.get_json()['item'] == patient
|
||||
assert detail.get_json()['revision'] == listing['revision']
|
||||
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={**q, 'page': 2, 'page_size': 2}).get_json()['item'] == patient
|
||||
assert app.get('/cama/pacientes/999999999', query_string=q).status_code == 404
|
||||
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={**q, 'revision': '0'*64}).status_code == 409
|
||||
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={'corte': CORTE, 'meses': 0, 'birads': 'BIRADS_6'}).status_code == 403
|
||||
|
||||
|
||||
def test_configured_access_hook_is_preserved(app):
|
||||
app.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
|
||||
for path in ('/cama/seguimiento', '/cama/pacientes/1', '/cama/analisis/resumen'):
|
||||
assert app.get(path).status_code == 403
|
||||
|
||||
|
||||
def test_explicit_dev_reader_keeps_list_detail_and_aggregate_consistent():
|
||||
from webapi import create_app
|
||||
application = create_app()
|
||||
rows = [dict(pac_id=str(i), mastografia_fecha='2026-01-01', birads='BIRADS_5',
|
||||
grupo_edad='50-59', biopsia=None, biopsia_fecha=None) for i in range(1, 7)]
|
||||
application.config['CAMA_COHORT_READER'] = lambda cutoff: rows
|
||||
client = application.test_client()
|
||||
query = {'corte': '2026-10-20', 'meses': 0}
|
||||
listing = client.get('/cama/seguimiento', query_string=query).get_json()
|
||||
assert listing['paginacion']['total_items'] == 6
|
||||
assert client.get('/cama/pacientes/1', query_string=query).get_json()['item'] == rows[0]
|
||||
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
|
||||
assert aggregate['revision'] == listing['revision']
|
||||
application.config['CAMA_COHORT_READER'] = None
|
||||
assert client.get('/cama/seguimiento', query_string=query).status_code == 503
|
||||
@@ -0,0 +1,370 @@
|
||||
"""What this module covers: CaMa's follow-up list and its file (`webapi.cama_follow_up`): who is in the BI-RADS cohort
|
||||
at a cut-off, the window and filters, suppression of small selections, pages, revision and request validation.
|
||||
|
||||
Fixtures: `app`, a Flask app with only the follow-up blueprint over a CaMa database loaded from `insertar` through the
|
||||
cycle up to `event_models` (needs `DBT_MANIFEST`: the cohort view comes from dbt's manifest). `insertar` writes 17
|
||||
invented patients with the cases below; their names (`P01`...) are the source ids. Nothing here touches real data.
|
||||
|
||||
Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6):
|
||||
BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day.
|
||||
P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from core.cama.models import BiopsiaMama, Mastografia, Paciente
|
||||
from flask import Flask
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from conftest import base_de
|
||||
from webapi.cama_follow_up import cohort, listing
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
CORTE = "2025-12-31"
|
||||
D = date
|
||||
|
||||
# patient -> (birth date, [(mammogram date, BI-RADS, report date or None)])
|
||||
PACIENTES = {
|
||||
"P01": (D(1960, 5, 5), [(D(2025, 12, 1), "B5", D(2025, 12, 8))]),
|
||||
"P02": (D(1975, 1, 1), [(D(2025, 11, 20), "B5", D(2025, 11, 27))]),
|
||||
"P03": (D(1975, 1, 1), [(D(2025, 11, 5), "B5", D(2025, 11, 12))]),
|
||||
"P04": (D(1976, 1, 1), [(D(2025, 10, 10), "B5", D(2025, 10, 17))]),
|
||||
"P05": (D(1980, 3, 3), [(D(2025, 9, 1), "B5", D(2025, 9, 8))]),
|
||||
"P06": (D(1950, 1, 1), [(D(2025, 8, 15), "B5", D(2025, 8, 22))]),
|
||||
"P07": (D(1975, 1, 1), [(D(2025, 12, 10), "B4A", D(2025, 12, 17))]),
|
||||
"P08": (D(1975, 1, 1), [(D(2025, 12, 2), "B4A", D(2025, 12, 9))]),
|
||||
"P09": (D(1965, 6, 6), [(D(2025, 11, 1), "B4A", D(2025, 11, 8))]),
|
||||
"P10": (D(1965, 6, 6), [(D(2025, 10, 1), "B4A", D(2025, 10, 8))]),
|
||||
"P11": (D(1965, 6, 6), [(D(2025, 7, 1), "B4A", D(2025, 7, 8))]),
|
||||
"P12": (D(1985, 1, 1), [(D(2025, 12, 15), "B6", D(2025, 12, 22))]),
|
||||
"P13": (D(1985, 1, 1), [(D(2025, 6, 1), "B6", D(2025, 6, 8))]),
|
||||
"P14": (D(1975, 1, 1), [(D(2025, 12, 20), "B4", D(2025, 12, 27))]),
|
||||
"P15": (D(1975, 1, 1), [(D(2025, 6, 1), "B5", D(2025, 6, 8)), (D(2025, 12, 5), "B2", D(2025, 12, 12))]),
|
||||
"P16": (D(1975, 1, 1), [(D(2025, 5, 1), "B1", D(2025, 5, 8)), (D(2025, 12, 20), "B5", D(2026, 1, 5))]),
|
||||
"P17": (D(1975, 1, 1), [(D(2025, 12, 12), "B4A", D(2025, 12, 19)), (D(2025, 12, 12), "B5", D(2025, 12, 19))]),
|
||||
}
|
||||
# (patient, index of its mammogram, request date, report date, grade)
|
||||
BIOPSIAS = (
|
||||
("P01", 0, D(2025, 12, 5), D(2025, 12, 20), "CARCINOMA_INVASOR"),
|
||||
("P02", 0, D(2025, 12, 1), D(2026, 1, 10), "CARCINOMA_IN_SITU"), # reported after the cut-off
|
||||
("P04", 0, D(2025, 10, 15), D(2025, 10, 30), "BENIGNO"),
|
||||
("P05", 0, D(2025, 9, 10), D(2025, 9, 25), None), # a report without a grade
|
||||
("P06", 0, D(2025, 9, 1), D(2025, 9, 10), "BENIGNO"), # two biopsies of one mammogram: the later report is shown
|
||||
("P06", 0, D(2025, 10, 1), D(2025, 10, 20), "CARCINOMA_IN_SITU"),
|
||||
)
|
||||
EN_COHORTE = {f"P{n:02d}" for n in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17)}
|
||||
|
||||
|
||||
def insertar(sesion: Session) -> None:
|
||||
pacientes = {h: Paciente(pac_id_hospital=h, pac_sexo="Femenino", pac_fecha_nacimiento=n)
|
||||
for h, (n, _) in PACIENTES.items()}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
mastografias: dict[tuple[str, int], Mastografia] = {}
|
||||
for hospital, (_, tomas) in PACIENTES.items():
|
||||
for indice, (toma, birads, reporte) in enumerate(tomas):
|
||||
mastografias[hospital, indice] = Mastografia(
|
||||
pac_id=pacientes[hospital].pac_id, pac_id_hospital=hospital, mast_fecha_toma=toma,
|
||||
mast_calidad_imagen="SATISFACTORIO", mast_birads=birads, mast_fecha_reporte=reporte)
|
||||
sesion.add_all(mastografias.values())
|
||||
sesion.flush()
|
||||
for hospital, indice, solicitud, reporte, grado in BIOPSIAS:
|
||||
m = mastografias[hospital, indice]
|
||||
sesion.add(BiopsiaMama(pac_id=m.pac_id, pac_id_hospital=hospital, mast_id=m.mast_id, bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte, bx_grado_histologico=grado))
|
||||
sesion.commit()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base = base_de("cama", tmp_path_factory.mktemp("cama"), datos=insertar)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def app(base):
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
|
||||
return flask.test_client()
|
||||
|
||||
|
||||
def get(app, ruta="/cama/seguimiento", **params):
|
||||
return app.get(ruta, query_string={"corte": CORTE, "meses": 0, **params})
|
||||
|
||||
|
||||
def pacs(respuesta) -> list[str]:
|
||||
return [i["pac_id"] for i in respuesta.get_json()["items"]]
|
||||
|
||||
|
||||
def hospital_de(base) -> dict[str, str]:
|
||||
"""pac_id (text) -> the source id, to translate the invented names back."""
|
||||
with Session(base.motor) as sesion:
|
||||
return {str(p.pac_id): p.pac_id_hospital for p in sesion.exec(select(Paciente))}
|
||||
|
||||
|
||||
def test_the_cohort_holds_each_patient_once_through_her_latest_reported_mammogram(base, app):
|
||||
"""Pins down: the cohort at 2025-12-31 is exactly the patients whose latest mammogram reported by then is BI-RADS
|
||||
4 to 6, once each: P15's latest is a 2 and P16's 5 is reported after the cut-off. Fails if a patient is listed twice,
|
||||
if an earlier BI-RADS 5 outlives a later 2, or if a report after the cut-off counts."""
|
||||
cuerpo = get(app, page_size=200).get_json()
|
||||
nombres = hospital_de(base)
|
||||
assert {nombres[p] for p in pacs(get(app, page_size=200))} == EN_COHORTE
|
||||
assert len(pacs(get(app, page_size=200))) == len(set(pacs(get(app, page_size=200)))) == 15
|
||||
assert cuerpo["paginacion"]["total_items"] == 15
|
||||
|
||||
|
||||
def test_the_same_data_gives_the_same_cohort_and_a_later_cutoff_adds_what_was_reported(base, app):
|
||||
"""Pins down: asking twice gives the same rows in the same order, including P17 (two mammograms the same day, one
|
||||
row), and a cut-off after P16's report brings its BI-RADS 5 in. Fails if the choice depends on row order, or if the
|
||||
cut-off doesn't move the cohort."""
|
||||
primero, segundo = get(app, page_size=200).get_json(), get(app, page_size=200).get_json()
|
||||
assert primero["items"] == segundo["items"]
|
||||
nombres = hospital_de(base)
|
||||
despues = get(app, corte="2026-01-31", page_size=200)
|
||||
assert "P16" in {nombres[p] for p in pacs(despues)}
|
||||
assert [i["birads"] for i in despues.get_json()["items"] if nombres[i["pac_id"]] == "P16"] == ["BIRADS_5"]
|
||||
|
||||
|
||||
def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app):
|
||||
"""Pins down: P01's invasive carcinoma shows with its report date; P02's biopsy, reported in 2026, doesn't exist at
|
||||
2025-12-31 and does at 2026-01-31; P05's report without a grade shows its date and no result. Fails if a later
|
||||
biopsy leaks into an earlier cut-off or a gradeless report is read as no biopsy."""
|
||||
nombres = hospital_de(base)
|
||||
en = lambda r: {nombres[i["pac_id"]]: i for i in r.get_json()["items"]}
|
||||
antes, despues = en(get(app, page_size=200)), en(get(app, corte="2026-01-31", page_size=200))
|
||||
assert (antes["P01"]["biopsia"], antes["P01"]["biopsia_fecha"]) == ("CARCINOMA_INVASOR", "2025-12-20")
|
||||
assert (antes["P02"]["biopsia"], antes["P02"]["biopsia_fecha"]) == (None, None)
|
||||
assert (despues["P02"]["biopsia"], despues["P02"]["biopsia_fecha"]) == ("CARCINOMA_IN_SITU", "2026-01-10")
|
||||
assert (antes["P05"]["biopsia"], antes["P05"]["biopsia_fecha"]) == (None, "2025-09-25")
|
||||
assert (antes["P06"]["biopsia"], antes["P06"]["biopsia_fecha"]) == ("CARCINOMA_IN_SITU", "2025-10-20")
|
||||
|
||||
|
||||
def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app):
|
||||
"""Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its
|
||||
date: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data
|
||||
doesn't support is added, or the hospital's identifier leaks."""
|
||||
respuesta = get(app, page_size=200)
|
||||
cuerpo = respuesta.get_json()
|
||||
assert cuerpo["simulado"] is True
|
||||
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha"} for i in cuerpo["items"])
|
||||
assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"])
|
||||
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia"]
|
||||
assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES)
|
||||
assert respuesta.headers["Cache-Control"] == "no-store"
|
||||
|
||||
|
||||
def test_age_groups_come_from_the_platform_parameter_at_the_cutoff(base, app):
|
||||
"""Pins down: groups are `cama.grupos_edad` (`<40`, `40-49`, `50-59`, `60-69`, `70+`); a patient born on 1976-01-01 is
|
||||
still 49 on 2025-12-31 and turns 50 the next day; a missing or later birth date is `SIN_DATO`. Fails if the age is
|
||||
counted in years of birth or the groups are written in the code."""
|
||||
nombres = hospital_de(base)
|
||||
edad = lambda c: {nombres[i["pac_id"]]: i["grupo_edad"] for i in get(app, corte=c, page_size=200).get_json()["items"]}
|
||||
assert edad(CORTE)["P04"] == "40-49" and edad(CORTE)["P01"] == "60-69" and edad(CORTE)["P06"] == "70+"
|
||||
assert edad("2026-01-31")["P04"] == "50-59"
|
||||
grupos = listing.grupos_de_edad(Session(base.motor))
|
||||
assert grupos == ["<40", "40-49", "50-59", "60-69", "70+"]
|
||||
assert cohort.grupo_de_edad(None, D(2025, 1, 1), []) == cohort.SIN_DATO
|
||||
assert cohort.grupo_de_edad(D(2026, 1, 1), D(2025, 1, 1), []) == cohort.SIN_DATO
|
||||
|
||||
|
||||
def test_filters_combine_with_and_and_the_window_follows_the_mammogram_date(base, app):
|
||||
"""Pins down: BI-RADS 5 selects six patients; adding the biopsy filter narrows with AND (a group of fewer than five
|
||||
is then refused); a one-month window keeps the mammograms of December. Fails if filters are ORed or the window
|
||||
reads another date."""
|
||||
# P01-P06 and, when it wins the tie of its two mammograms, P17.
|
||||
assert len(pacs(get(app, birads="BIRADS_5", page_size=200))) in (6, 7)
|
||||
assert len(pacs(get(app, birads="BIRADS_4A", page_size=200))) in (5, 6)
|
||||
assert get(app, birads="BIRADS_5", biopsia="BENIGNO").status_code == 403
|
||||
un_mes = get(app, meses=1, page_size=200)
|
||||
assert un_mes.status_code == 200
|
||||
assert {i["mastografia_fecha"][:7] for i in un_mes.get_json()["items"]} == {"2025-12"}
|
||||
assert un_mes.get_json()["ventana"] == {"meses": 1, "desde": "2025-12-01", "hasta": CORTE}
|
||||
|
||||
|
||||
def test_a_selection_of_fewer_than_five_is_never_served_by_any_route(base, app):
|
||||
"""Pins down: groups of 1 to 4 (BI-RADS 6, BI-RADS 4 without subcategory, a rare combination) and filtered
|
||||
selections of none get 403 with the reason `supresion`, on the list and on the file alike. Fails if a filter or a
|
||||
window combination isolates a small group, or the file skips the rule the list applies."""
|
||||
for ruta in ("/cama/seguimiento", "/cama/seguimiento/exportacion"):
|
||||
for filtros in ({"birads": "BIRADS_6"}, {"birads": "BIRADS_4"}, {"birads": "BIRADS_5", "biopsia": "SIN_DATO"},
|
||||
{"grupo_edad": "<40"}):
|
||||
respuesta = get(app, ruta, **filtros)
|
||||
assert respuesta.status_code == 403, (ruta, filtros)
|
||||
assert respuesta.get_json()["motivo"] == "supresion"
|
||||
assert get(app, meses=1, birads="BIRADS_5").status_code == 403 # a window is a filter too
|
||||
|
||||
|
||||
def test_the_whole_cohort_is_refused_when_it_has_one_to_four_patients_and_is_empty_when_it_has_none(base, app):
|
||||
"""Pins down: the only selection that may be empty is the whole cohort with no window and no filter; with two
|
||||
patients it is refused. Fails if a small whole cohort is published or an empty one is an error."""
|
||||
assert get(app, corte="2025-06-20").status_code == 403
|
||||
vacia = get(app, corte="2025-01-01")
|
||||
assert vacia.status_code == 200 and vacia.get_json()["items"] == []
|
||||
assert vacia.get_json()["paginacion"] == {"page": 1, "page_size": 50, "total_items": 0, "total_pages": 0}
|
||||
assert vacia.get_json()["ventana"]["desde"] == "2025-01-01"
|
||||
|
||||
|
||||
def test_pages_are_stable_and_a_page_past_the_last_is_a_404(base, app):
|
||||
"""Pins down: three pages of six give 15 rows in the same order as one big page, newest mammogram first and `pac_id`
|
||||
after; page 4 is 404. Fails if pages overlap or reorder, or a page beyond the end answers 200."""
|
||||
todo = pacs(get(app, page_size=200))
|
||||
paginas = [pacs(get(app, page_size=6, page=n)) for n in (1, 2, 3)]
|
||||
assert [p for pagina in paginas for p in pagina] == todo
|
||||
assert [len(p) for p in paginas] == [6, 6, 3]
|
||||
assert get(app, page_size=6, page=4).status_code == 404
|
||||
fechas = [i["mastografia_fecha"] for i in get(app, page_size=200).get_json()["items"]]
|
||||
assert fechas == sorted(fechas, reverse=True)
|
||||
|
||||
|
||||
def test_the_file_has_the_rows_of_the_pages_and_a_size_limit(base, app, monkeypatch):
|
||||
"""Pins down: `/seguimiento/exportacion` returns every row of the selection with the list's header; it is refused
|
||||
over `EXPORTACION_MAXIMA` (413). Fails if the file and the list disagree about who is selected."""
|
||||
archivo = get(app, "/cama/seguimiento/exportacion").get_json()
|
||||
assert [i["pac_id"] for i in archivo["items"]] == pacs(get(app, page_size=200)) and archivo["total_items"] == 15
|
||||
assert archivo["revision"] == get(app).get_json()["revision"]
|
||||
monkeypatch.setattr(listing, "EXPORTACION_MAXIMA", 3)
|
||||
assert get(app, "/cama/seguimiento/exportacion").status_code == 413
|
||||
|
||||
|
||||
def test_the_revision_names_cohort_version_data_and_cutoff(base, app):
|
||||
"""Pins down: quoting the revision read opens the same list; another cut-off, a new load of data and another
|
||||
cohort give another revision, and a stale one is a 409. Fails if the revision ignores a part, or a client can read a
|
||||
list under a revision that isn't the server's."""
|
||||
cuerpo = get(app).get_json()
|
||||
contexto = {k: cuerpo[k] for k in ("cohorte", "escenario", "revision")}
|
||||
assert re.fullmatch(r"[0-9a-f]{64}", cuerpo["revision"])
|
||||
assert get(app, **contexto).status_code == 200
|
||||
otro_corte = get(app, corte="2026-01-31").get_json()["revision"]
|
||||
assert otro_corte != cuerpo["revision"]
|
||||
assert get(app, **{**contexto, "revision": otro_corte}).status_code == 409
|
||||
assert get(app, **{**contexto, "cohorte": "otra"}).status_code == 409
|
||||
assert get(app, **{**contexto, "escenario": "otro"}).status_code == 409
|
||||
assert get(app, **{**contexto, "revision": ""}).status_code == 400
|
||||
assert get(app, cohorte=contexto["cohorte"]).status_code == 400 # the three go together
|
||||
|
||||
|
||||
def test_new_loaded_rows_change_the_revision_and_a_load_without_changes_does_not(base, app):
|
||||
"""Pins down: a load that added rows gives the cohort a new build and so a new revision; a load that added or changed
|
||||
none (a recalculation) leaves it. Fails if every cycle invalidates the clients' pages, or new data goes unnoticed."""
|
||||
from webapi.orchestration.tables.cama import TABLAS
|
||||
|
||||
antes = get(app).get_json()["revision"]
|
||||
with Session(base.motor) as sesion:
|
||||
sesion.add(TABLAS.Carga(fuente="mastografia", inicio=datetime(2026, 1, 1, tzinfo=timezone.utc), filas_nuevas=0, filas_cambiadas=0, filas_sin_cambio=9))
|
||||
sesion.commit()
|
||||
assert get(app).get_json()["revision"] == antes
|
||||
sesion.add(TABLAS.Carga(fuente="mastografia", inicio=datetime(2026, 1, 2, tzinfo=timezone.utc), filas_nuevas=1))
|
||||
sesion.commit()
|
||||
assert get(app).get_json()["revision"] != antes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("params", [
|
||||
{"corte": "31/12/2025"}, {"corte": "2025-02-30"}, {"corte": "2999-01-01"}, {"meses": 2}, {"meses": "x"},
|
||||
{"page": 0}, {"page_size": 201}, {"birads": "BIRADS_9"}, {"grupo_edad": "20-29"}, {"biopsia": "MALIGNO"},
|
||||
{"estatus": "ALTA"}, {"prioridad": "ALTA"}, {"birads": ""},
|
||||
])
|
||||
def test_a_badly_written_request_is_a_400_before_anything_is_counted(app, params):
|
||||
"""Pins down: a malformed date, a future one, a window or page out of range, an unknown parameter (the retired
|
||||
status and priority included) or filter value is a 400, never a small-group 403. Fails if validation moves after
|
||||
the selection."""
|
||||
assert get(app, **params).status_code == 400
|
||||
|
||||
|
||||
def test_a_repeated_parameter_is_a_400(app):
|
||||
"""Pins down: `birads` twice is refused, so a request can't hide a filter. Fails if the first or last one is taken."""
|
||||
assert app.get("/cama/seguimiento?corte=2025-12-31&meses=0&birads=BIRADS_5&birads=BIRADS_6").status_code == 400
|
||||
|
||||
|
||||
def test_the_defaults_are_today_and_a_three_month_window(app):
|
||||
"""Pins down: without `corte` the cut-off is today and without `meses` the window is three months; none of the
|
||||
invented 2025 mammograms is that recent, so the window selects nobody and is refused. Fails if the defaults change."""
|
||||
respuesta = app.get("/cama/seguimiento")
|
||||
assert respuesta.status_code == 403 and respuesta.get_json()["motivo"] == "supresion"
|
||||
assert json.loads(get(app).get_data())["ventana"]["meses"] == 0
|
||||
assert date.today() - timedelta(days=1) > D(2025, 12, 31)
|
||||
|
||||
|
||||
def test_without_the_cohort_view_the_answer_is_an_informative_503(tmp_path):
|
||||
"""Pins down: a database whose indicator cycle hasn't created the event views answers 503 with the reason `cohorte`
|
||||
on both routes, not a server error. Fails if a missing view surfaces as a 500 or an empty list."""
|
||||
sin_ciclo = base_de("cama", tmp_path, datos=insertar)
|
||||
try:
|
||||
flask = Flask(__name__)
|
||||
flask.register_blueprint(follow_up_blueprint(lambda: Session(sin_ciclo.motor)), url_prefix="/cama")
|
||||
cliente = flask.test_client()
|
||||
for ruta in ("/cama/seguimiento", "/cama/seguimiento/exportacion"):
|
||||
respuesta = cliente.get(ruta, query_string={"corte": CORTE, "meses": 0})
|
||||
assert respuesta.status_code == 503 and respuesta.get_json()["motivo"] == "cohorte"
|
||||
finally:
|
||||
sin_ciclo.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def con_vista_a_mano(tmp_path):
|
||||
"""A CaMa database with the platform's parameters and the cohort's candidates written by hand: the view is replaced by
|
||||
a table, so a test can hold the contradictory duplicates that staging can't produce."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
|
||||
base = base_de("cama", tmp_path, datos=lambda sesion: None)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
from sqlalchemy import text
|
||||
|
||||
def escribir(filas):
|
||||
with base.motor.begin() as c:
|
||||
c.execute(text("drop view cama_cohorte_birads"))
|
||||
c.execute(text("create table cama_cohorte_birads (pac_id integer, procedimiento_id integer, fuente_id text, fecha_toma date, "
|
||||
"reporte_id integer, fecha_reporte date, birads text, fecha_nacimiento date, biopsia_id integer, "
|
||||
"biopsia_fuente_id text, biopsia_fecha_reporte date, biopsia_grado text)"))
|
||||
for fila in filas:
|
||||
c.execute(text("insert into cama_cohorte_birads values (:pac_id, :procedimiento_id, :fuente_id, :fecha_toma, :reporte_id, "
|
||||
":fecha_reporte, :birads, :fecha_nacimiento, :biopsia_id, :biopsia_fuente_id, :biopsia_fecha_reporte, :biopsia_grado)"),
|
||||
{"biopsia_id": None, "biopsia_fuente_id": None, "biopsia_fecha_reporte": None, "biopsia_grado": None, **fila})
|
||||
yield base, escribir
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
MAMOGRAFIA = {"pac_id": 1, "procedimiento_id": 10, "fuente_id": "10", "fecha_toma": "2025-11-01", "reporte_id": 11,
|
||||
"fecha_reporte": "2025-11-08", "fecha_nacimiento": "1970-01-01"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("orden", [1, -1])
|
||||
def test_contradictory_duplicates_resolve_the_same_way_whatever_the_row_order(con_vista_a_mano, orden):
|
||||
"""Pins down: one report with two different BI-RADS (4A and 5) counts as the more severe, a biopsy report with two
|
||||
grades on the same date shows the more severe, identical rows repeated by a join count once, and the answer doesn't
|
||||
depend on the order the rows come in. Fails if the first row read wins, a patient appears twice, or the choice
|
||||
changes with the order."""
|
||||
base, escribir = con_vista_a_mano
|
||||
filas = [
|
||||
{**MAMOGRAFIA, "birads": "B4A", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "BENIGNO"},
|
||||
{**MAMOGRAFIA, "birads": "B5", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "CARCINOMA_INVASOR"},
|
||||
{**MAMOGRAFIA, "birads": "B5", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "CARCINOMA_INVASOR"},
|
||||
]
|
||||
escribir(filas[::orden])
|
||||
with Session(base.motor) as sesion:
|
||||
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
|
||||
assert len(cohorte_) == 1
|
||||
assert (cohorte_[0].birads, cohorte_[0].biopsia) == ("BIRADS_5", "CARCINOMA_INVASOR")
|
||||
|
||||
|
||||
def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_stay_two(con_vista_a_mano):
|
||||
"""Pins down: a mammogram with two reports counts through the later report; two patients stay two rows. Fails if both
|
||||
reports become two rows of one patient."""
|
||||
base, escribir = con_vista_a_mano
|
||||
escribir([
|
||||
{**MAMOGRAFIA, "birads": "B4A", "reporte_id": 11, "fecha_reporte": "2025-11-08"},
|
||||
{**MAMOGRAFIA, "birads": "B5", "reporte_id": 12, "fecha_reporte": "2025-11-15"},
|
||||
{**MAMOGRAFIA, "pac_id": 2, "procedimiento_id": 30, "fuente_id": "30", "reporte_id": 31, "birads": "B6"},
|
||||
])
|
||||
with Session(base.motor) as sesion:
|
||||
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
|
||||
assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")]
|
||||
@@ -0,0 +1,310 @@
|
||||
"""What this module covers: the three CaMa measures of L3, answered on request from dbt's semantic layer over the follow-up
|
||||
fixture's invented patients (plus three on a period boundary and the diagnosing notes of the cases below): the detection
|
||||
rate (`CAMA_TASA_DETECCION_HISTOPATOLOGICA`, C1), the time from the mammogram's result to the diagnosis
|
||||
(`CAMA_DIAS_RESULTADO_DIAGNOSTICO`, C3r) and the histopathological result by BI-RADS (`CAMA_HISTOPATOLOGIA_BIRADS`, C2
|
||||
stratified by BI-RADS). Every number here is worked out by hand from the cases, not read from the measure.
|
||||
|
||||
Fixtures: `base`, the CaMa database loaded from `insertar_l3` through the cycle up to `event_models` (dbt's views, the three
|
||||
new ones included); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it). Suppression is off (threshold 1).
|
||||
|
||||
Cases added to the follow-up fixture's (see `test_cama_follow_up.py`):
|
||||
- P18 / P19 / P20: biopsies reported on the last day of a semester (06-30), the first day of the next (07-01) and the last
|
||||
day of the year (12-31): which period each report counts in, and the inclusive event cut-off.
|
||||
- Notes (a diagnosing note is a CIE-10 of the list written by oncologic surgery): P01 12 days after her report, P07 the
|
||||
same day, P08 a note between her mammogram and her report (not counted) and one 37 days after it, P09 193 days after
|
||||
(beyond the horizon), P03 an earlier breast cancer note (leaves her out), P04 a note by a specialty that doesn't
|
||||
diagnose, P12 the same day, P20 39 days after.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, Paciente
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from conftest import base_de
|
||||
from test_cama_follow_up import UNTIL_MODELS, insertar
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.fhir.measures import measure_report
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
|
||||
D = date
|
||||
TASA = "cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA"
|
||||
DIAS = "cama/CAMA_DIAS_RESULTADO_DIAGNOSTICO"
|
||||
HISTO = "cama/CAMA_HISTOPATOLOGIA_BIRADS"
|
||||
BIRADS_PACIENTE = "cama/CAMA_BIRADS456_PACIENTE"
|
||||
DIAS_TOMA = "cama/CAMA_DIAS_TOMA_DIAGNOSTICO"
|
||||
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
|
||||
|
||||
NUEVOS = {
|
||||
"P18": (D(1970, 1, 1), [(D(2025, 6, 20), "B4A", D(2025, 6, 25))]),
|
||||
"P19": (D(1970, 1, 1), [(D(2025, 6, 25), "B5", D(2025, 6, 28))]),
|
||||
"P20": (D(1970, 1, 1), [(D(2025, 12, 20), "B5", D(2025, 12, 24))]),
|
||||
}
|
||||
# (patient, request date, report date, grade): the mammogram of each of them is its first
|
||||
BIOPSIAS_NUEVAS = (
|
||||
("P18", D(2025, 6, 26), D(2025, 6, 30), "BENIGNO"),
|
||||
("P19", D(2025, 6, 29), D(2025, 7, 1), "CARCINOMA_INVASOR"),
|
||||
("P20", D(2025, 12, 28), D(2025, 12, 31), "CARCINOMA_IN_SITU"),
|
||||
)
|
||||
# (patient, date, CIE-10, specialty)
|
||||
NOTAS = (
|
||||
("P01", D(2025, 12, 20), "R92", ONCOLOGIA),
|
||||
("P07", D(2025, 12, 17), "N60", ONCOLOGIA),
|
||||
("P08", D(2025, 12, 5), "R92", ONCOLOGIA),
|
||||
("P08", D(2026, 1, 15), "R92", ONCOLOGIA),
|
||||
("P09", D(2026, 5, 20), "R92", ONCOLOGIA),
|
||||
("P03", D(2025, 1, 10), "C50", FAMILIAR),
|
||||
("P03", D(2025, 12, 1), "R92", ONCOLOGIA),
|
||||
("P04", D(2025, 11, 10), "R92", FAMILIAR),
|
||||
("P12", D(2025, 12, 22), "Z123", ONCOLOGIA),
|
||||
("P20", D(2026, 2, 1), "R92", ONCOLOGIA),
|
||||
)
|
||||
CORTE = D(2025, 12, 31)
|
||||
|
||||
|
||||
def insertar_l3(sesion: Session) -> None:
|
||||
insertar(sesion)
|
||||
pacientes = {h: Paciente(pac_id_hospital=h, pac_sexo="Femenino", pac_fecha_nacimiento=n) for h, (n, _) in NUEVOS.items()}
|
||||
sesion.add_all(pacientes.values())
|
||||
sesion.flush()
|
||||
mastografias = {}
|
||||
for hospital, (_, tomas) in NUEVOS.items():
|
||||
toma, birads, reporte = tomas[0]
|
||||
mastografias[hospital] = Mastografia(pac_id=pacientes[hospital].pac_id, pac_id_hospital=hospital, mast_fecha_toma=toma,
|
||||
mast_calidad_imagen="SATISFACTORIO", mast_birads=birads, mast_fecha_reporte=reporte)
|
||||
sesion.add_all(mastografias.values())
|
||||
sesion.flush()
|
||||
for hospital, solicitud, reporte, grado in BIOPSIAS_NUEVAS:
|
||||
m = mastografias[hospital]
|
||||
sesion.add(BiopsiaMama(pac_id=m.pac_id, pac_id_hospital=hospital, mast_id=m.mast_id, bx_fecha_solicitud=solicitud,
|
||||
bx_fecha_reporte=reporte, bx_grado_histologico=grado))
|
||||
todos = {p.pac_id_hospital: p for p in sesion.exec(select(Paciente))}
|
||||
sesion.add_all(NotaMedica(pac_id=todos[h].pac_id, pac_id_hospital=h, nm_id_hospital=f"NM-{i:03d}", nm_fecha=fecha,
|
||||
nm_cie_codigo=cie, nm_especialidad=esp) for i, (h, fecha, cie, esp) in enumerate(NOTAS, start=1))
|
||||
sesion.commit()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory, manifest):
|
||||
carpeta = tmp_path_factory.mktemp("cama_l3")
|
||||
sin_supresion = carpeta / "parametros.toml"
|
||||
sin_supresion.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
|
||||
base = base_de("cama", carpeta, datos=insertar_l3)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, "history": d.history_repository,
|
||||
"queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def proporcion(base, manifest, periodo, corte=None):
|
||||
r = answer("cama", measure_definitions(manifest)[TASA], Question(TASA, periodo, corte), **repositories(base))
|
||||
return r.numerator, r.denominator
|
||||
|
||||
|
||||
def duracion(base, manifest, periodo, corte=None, url=DIAS):
|
||||
return answer_duration("cama", duration_definitions(manifest)[url], Question(url, periodo, corte), **repositories(base))
|
||||
|
||||
|
||||
def composicion(base, manifest, periodo, corte=None, conocimiento=None, url=HISTO):
|
||||
return answer_composition("cama", composition_definitions(manifest)[url], Question(url, periodo, corte, conocimiento),
|
||||
**repositories(base))
|
||||
|
||||
|
||||
def matriz(resultado) -> dict:
|
||||
return {(b, c): n for b, por in resultado.strata["birads"].items() for c, n in por.items()}
|
||||
|
||||
|
||||
# --- the detection rate -----------------------------------------------------------------------------------------------
|
||||
|
||||
def test_the_detection_rate_counts_biopsy_reports_with_a_known_result_by_the_day_of_the_report(base, manifest):
|
||||
"""Pins down: the rate's units are biopsy reports dated by the report, over those with a known grade. The semester 1 holds
|
||||
P18's benign report of 06-30 (the last day); the semester 2 holds P19's invasive of 07-01 (the first), P20's in situ of 12-31
|
||||
(the last), P01's invasive, P04's benign and P06's two (benign and in situ): 6 known and 4 malignant; P05's has no grade, so it
|
||||
is outside both parts. Fails if a boundary day falls in the wrong period, a report without grade enters the denominator, or
|
||||
each patient (P06 has two reports) counts once instead of each report."""
|
||||
assert proporcion(base, manifest, "2025-S1") == (0, 1)
|
||||
assert proporcion(base, manifest, "2025-S2") == (4, 6)
|
||||
|
||||
|
||||
def test_the_detection_rate_by_month_adds_up_to_the_semesters_and_the_cutoff_is_inclusive(base, manifest):
|
||||
"""Pins down: the months of a semester hold the same reports as the semester (every report is in exactly one month), and a
|
||||
cut-off on the day of a report counts it while the day before doesn't. Fails if the monthly and the semester counts drift
|
||||
or the event cut-off excludes its own day."""
|
||||
meses = ["2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"]
|
||||
por_mes = [proporcion(base, manifest, m) for m in meses]
|
||||
assert (sum(n for n, _ in por_mes), sum(d for _, d in por_mes)) == proporcion(base, manifest, "2025-S2")
|
||||
assert proporcion(base, manifest, "2025-12") == (2, 2)
|
||||
assert proporcion(base, manifest, "2025-12", D(2025, 12, 31)) == (2, 2)
|
||||
assert proporcion(base, manifest, "2025-12", D(2025, 12, 30)) == (1, 1)
|
||||
|
||||
|
||||
def test_the_detection_rate_is_a_proportion_among_biopsies_and_not_the_confirmation_of_suspicious_mammograms(base, manifest):
|
||||
"""Pins down: the rate and the confirmation proportion answer different questions over the same data. In the semester 2 the
|
||||
rate counts 6 biopsy reports with a result; the confirmation counts mammograms of suspicion with a biopsy (its denominator
|
||||
is mammograms, not reports). Fails if the two measures end up with the same counts."""
|
||||
confirmacion = "cama/CAMA_CONFIRMACION_BIRADS45"
|
||||
r = answer("cama", measure_definitions(manifest)[confirmacion], Question(confirmacion, "2025-S2"), **repositories(base))
|
||||
assert (r.numerator, r.denominator) != (4, 6)
|
||||
assert r.denominator >= 15, "its denominator is the mammograms of suspicion of the period"
|
||||
|
||||
|
||||
def test_the_detection_flags_of_the_view_follow_the_parameters(base):
|
||||
"""Pins down: the view's flags are the grade lists of dbt's vars, which a test keeps equal to the parameter table's: known
|
||||
result = the catalog's grades, malignant = `cama.biopsia_cancer`. Fails if the two copies drift apart."""
|
||||
import tomllib
|
||||
|
||||
reglas = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
|
||||
with base.motor.connect() as c:
|
||||
flags = {(g, k, m) for g, k, m in c.execute(text("select distinct grado, con_resultado, maligno from cama_deteccion_biopsia"))}
|
||||
cancer = set(reglas["cama"]["biopsia_cancer"]["valor"])
|
||||
catalogo = {x["clave"] for x in reglas["cama"]["catalogos"]["biopsia"]["valor"]}
|
||||
assert flags == {(g, int(g in catalogo), int(g in cancer)) for g in {f[0] for f in flags}}
|
||||
assert {None, "BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"} == {f[0] for f in flags}
|
||||
assert (None, 0, 0) in flags
|
||||
|
||||
|
||||
# --- the time from the result to the diagnosis -------------------------------------------------------------------------
|
||||
|
||||
def test_the_time_from_result_to_diagnosis_counts_from_the_report_to_the_first_note_on_or_after_it(base, manifest):
|
||||
"""Pins down, in the semester 2 (16 mammograms with a report, P03's left out by her earlier breast cancer note): five have a
|
||||
diagnosing note within the horizon: P01 12 days, P07 and P12 the same day (0), P08 37 (her 12-05 note is before her report
|
||||
and doesn't count) and P20 39; the other eleven are excluded and counted (P09's note is 193 days after, P04's is of a
|
||||
specialty that doesn't diagnose, the rest have none). Median 12. Fails if a note before the report is used, the horizon
|
||||
isn't applied, a non-diagnosing specialty counts or an excluded mammogram isn't counted."""
|
||||
r = duracion(base, manifest, "2025-S2")
|
||||
assert (r.initial, r.n, r.excluded, r.median) == (16, 5, 11, 12.0)
|
||||
|
||||
|
||||
def test_the_event_cutoff_leaves_out_the_notes_after_it_and_does_not_measure_what_is_still_inside_the_horizon(base, manifest):
|
||||
"""Pins down, at 2025-12-31: the notes of 2026 don't exist yet (P08's and P20's) and every mammogram of the semester is
|
||||
still inside its horizon (180 days from its report), so those without a note are neither measured nor excluded: three
|
||||
observations (0, 0 and 12 days, median 0) are the whole population. The same rule as the mammogram-to-result measure: a
|
||||
mammogram is excluded only once its horizon has passed without a note. Fails if a note after the cut-off is measured or if
|
||||
a mammogram that can still get its note is counted as excluded."""
|
||||
r = duracion(base, manifest, "2025-S2", CORTE)
|
||||
assert (r.initial, r.n, r.excluded, r.median) == (3, 3, 0, 0.0)
|
||||
# Once every horizon of the semester has passed (the last report is 2025-12-27) the unmeasured are excluded and counted.
|
||||
tarde = duracion(base, manifest, "2025-S2", D(2026, 7, 1))
|
||||
assert (tarde.initial, tarde.n, tarde.excluded) == (16, 5, 11)
|
||||
|
||||
|
||||
def test_the_result_to_diagnosis_days_are_the_mammogram_to_diagnosis_days_minus_the_days_to_the_report(base):
|
||||
"""Pins down: for a mammogram whose first note is on or after its report, the days from the report equal the days of the
|
||||
mammogram-to-diagnosis measure minus the days from the mammogram to its report (the same note, another origin): P01 19-7,
|
||||
P07 7-7, P12 7-7. P08 is the difference by design (that measure takes her 12-05 note, this one her 01-15 note). Fails if the
|
||||
two measures read different notes where they should read the same."""
|
||||
with base.motor.connect() as c:
|
||||
nuevo = {h: d for h, d in c.execute(text(
|
||||
"select p.pac_id_hospital, r.dias_reporte_diagnostico from cama_resultado_diagnostico r join paciente p on p.pac_id = r.pac_id"))}
|
||||
viejo = {h: (d, t) for h, d, t in c.execute(text(
|
||||
"select p.pac_id_hospital, m.dias_toma_diagnostico, m.dias_toma_reporte from cama_tomas_mastografia m "
|
||||
"join paciente p on p.pac_id = m.pac_id"))}
|
||||
for h in ("P01", "P07", "P12"):
|
||||
assert nuevo[h] == viejo[h][0] - viejo[h][1], h
|
||||
assert (nuevo["P08"], viejo["P08"][0]) == (37, 3)
|
||||
|
||||
|
||||
def test_a_mammogram_without_a_report_is_not_in_the_population_and_the_report_date_gives_the_period(base):
|
||||
"""Pins down: the model holds one row per mammogram with a report, dated by it: all 24 mammograms of the fixture have one,
|
||||
and P16's second (reported 2026-01-05) is dated 2026, outside the semester of its mammogram. Fails if the period is read from
|
||||
the date of the mammogram."""
|
||||
with base.motor.connect() as c:
|
||||
filas = c.execute(text("select p.pac_id_hospital, r.fecha_toma, r.fecha_reporte from cama_resultado_diagnostico r "
|
||||
"join paciente p on p.pac_id = r.pac_id where p.pac_id_hospital = 'P16' order by 2")).all()
|
||||
assert [tuple(map(str, f[1:])) for f in filas] == [("2025-05-01", "2025-05-08"), ("2025-12-20", "2026-01-05")]
|
||||
|
||||
|
||||
# --- the histopathological result by BI-RADS ---------------------------------------------------------------------------
|
||||
|
||||
def test_the_matrix_of_the_semester_2_at_the_cutoff(base, manifest):
|
||||
"""Pins down, at 2025-12-31, one patient through her most severe mammogram of the semester: BI-RADS 5 (P01 invasive, P02
|
||||
without biopsy because hers is reported in 2026, P03 and P17 without biopsy, P04 benign, P05 a biopsy without grade, P06 in
|
||||
situ from her two biopsies, P20 in situ reported that same day), 4A (P07-P11 without biopsy), 6 (P12) and 4 without subcategory
|
||||
(P14). P15's semester-2 mammogram is a 2 and P16's 5 is reported in 2026: neither enters. P19 (a semester-1 mammogram) is out.
|
||||
Fails if the chosen mammogram, the biopsy of it, the cut-off or the grouping change."""
|
||||
r = composicion(base, manifest, "2025-S2", CORTE)
|
||||
assert matriz(r) == {
|
||||
("B5", "CARCINOMA_INVASOR"): 1, ("B5", "CARCINOMA_IN_SITU"): 2, ("B5", "BENIGNO"): 1, ("B5", "SIN_DATO"): 1, ("B5", "SIN_BIOPSIA"): 3,
|
||||
("B4A", "SIN_BIOPSIA"): 5, ("B6", "SIN_BIOPSIA"): 1, ("B4", "SIN_BIOPSIA"): 1,
|
||||
}
|
||||
assert sum(r.categories.values()) == 15
|
||||
|
||||
|
||||
def test_without_a_cutoff_the_biopsy_reported_later_and_the_late_report_count(base, manifest):
|
||||
"""Pins down: with no event cut-off P02's biopsy (reported 2026-01-10, in situ) is hers and P16's BI-RADS 5 (reported
|
||||
2026-01-05) is her semester's: one more in situ, and one more without biopsy. Fails if a cut-off is applied by default."""
|
||||
r = composicion(base, manifest, "2025-S2")
|
||||
assert matriz(r)[("B5", "CARCINOMA_IN_SITU")] == 3 and matriz(r)[("B5", "SIN_BIOPSIA")] == 3
|
||||
assert sum(r.categories.values()) == 16
|
||||
|
||||
|
||||
def test_the_semester_1_matrix_holds_each_patient_once(base, manifest):
|
||||
"""Pins down: P13 (BI-RADS 6, no biopsy), P15 (BI-RADS 5 of June, no biopsy), P18 (4A with her benign report of 06-30) and P19
|
||||
(BI-RADS 5 with her invasive report of 07-01, in the next semester: the biopsy belongs to her mammogram, not to the period of
|
||||
its report); P16's BI-RADS 1 is not admitted. Fails if a biopsy reported in the next period is lost."""
|
||||
r = composicion(base, manifest, "2025-S1", CORTE)
|
||||
assert matriz(r) == {("B6", "SIN_BIOPSIA"): 1, ("B5", "SIN_BIOPSIA"): 1, ("B4A", "BENIGNO"): 1, ("B5", "CARCINOMA_INVASOR"): 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("periodo", ["2025-S1", "2025-S2", "2025-06", "2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"])
|
||||
def test_the_matrix_counts_the_same_patients_as_the_birads_measure_in_every_period(base, manifest, periodo):
|
||||
"""Pins down: each period's BI-RADS strata equal the patients per category of CAMA_BIRADS456_PACIENTE (same rule: her most
|
||||
severe mammogram of the period), so Resumen's two cards never count different patients. Fails if the two measures choose
|
||||
other mammograms."""
|
||||
histo = composicion(base, manifest, periodo, CORTE)
|
||||
birads = composicion(base, manifest, periodo, CORTE, url=BIRADS_PACIENTE)
|
||||
por_birads = {b: sum(cs.values()) for b, cs in histo.strata["birads"].items()}
|
||||
assert por_birads == {b: n for b, n in birads.categories.items() if n}
|
||||
assert sum(histo.categories.values()) == sum(birads.categories.values())
|
||||
|
||||
|
||||
def test_a_knowledge_cutoff_later_the_same_day_still_sees_the_biopsies(base, manifest):
|
||||
"""Pins down the datetime compare of the biopsy's knowledge date: with a knowledge cut-off one second after the last load (the
|
||||
same day as the loads) every biopsy is known, as with none; with one before the first load nothing is. Fails if the biopsy's
|
||||
date is compared as text against the cut-off (`...T...` against `... ...`), which hid every biopsy on the day of the load."""
|
||||
with base.motor.connect() as c:
|
||||
ultima = c.execute(text("select max(inicio) from carga")).scalar()
|
||||
primera = c.execute(text("select min(inicio) from carga")).scalar()
|
||||
ultima = datetime.fromisoformat(str(ultima)).replace(tzinfo=timezone.utc) if isinstance(ultima, str) else ultima.replace(tzinfo=timezone.utc)
|
||||
primera = datetime.fromisoformat(str(primera)).replace(tzinfo=timezone.utc) if isinstance(primera, str) else primera.replace(tzinfo=timezone.utc)
|
||||
sin = composicion(base, manifest, "2025-S2", CORTE)
|
||||
con = composicion(base, manifest, "2025-S2", CORTE, ultima + timedelta(seconds=1))
|
||||
assert matriz(con) == matriz(sin)
|
||||
antes = composicion(base, manifest, "2025-S2", CORTE, primera - timedelta(days=1))
|
||||
assert antes.categories == {}
|
||||
|
||||
|
||||
def test_the_report_publishes_the_cross_of_birads_and_result_as_two_components(base, manifest):
|
||||
"""Pins down the FHIR report of the matrix: a stratifier coded by BI-RADS and by the biopsy grade whose strata carry the two
|
||||
components and the patients of each cell; the categories stratifier keeps the totals. Fails if the cross is published as
|
||||
marginals (the page couldn't rebuild the matrix) or a cell's count is not the matrix's."""
|
||||
definicion = composition_definitions(manifest)[HISTO]
|
||||
periodo = base.dominio.dim_periodo_repository.get("2025-S2")
|
||||
resultado = composicion(base, manifest, "2025-S2", CORTE)
|
||||
informe = measure_report(definicion, Question(HISTO, "2025-S2", CORTE), resultado, periodo, datetime.now(timezone.utc))
|
||||
grupo = informe["group"][0]
|
||||
assert [[c["coding"][0]["code"] for c in s["code"]] for s in grupo["stratifier"]] == [["biopsia_grado"], ["birads", "biopsia_grado"]]
|
||||
celdas = {tuple(c["value"]["coding"][0]["code"] for c in s["component"]): s["population"][0]["count"]
|
||||
for s in grupo["stratifier"][1]["stratum"]}
|
||||
assert celdas == matriz(resultado)
|
||||
assert sum(celdas.values()) == grupo["population"][0]["count"] == 15
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Isolated compiled-SQL regressions: repeated reports and identities across sources."""
|
||||
import json
|
||||
import sqlite3
|
||||
from datetime import date, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from test_cama_l3_measures import manifest
|
||||
|
||||
|
||||
def sql(manifest, name):
|
||||
nodes = json.loads(manifest.read_text())["nodes"].values()
|
||||
return next(n["compiled_code"] for n in nodes if n["name"] == name)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("days,expected", [(179, 179), (180, None)])
|
||||
def test_one_mammogram_uses_first_report_and_exclusive_180_day_horizon(manifest, days, expected):
|
||||
db = sqlite3.connect(":memory:")
|
||||
db.executescript('''
|
||||
create table cama_mastografias(procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id, reporte_id);
|
||||
create table cama_linea_de_tiempo(pac_id, tipo, fecha, conocida_en);
|
||||
create table dim_fecha(fecha, dia_num);
|
||||
create table carga(carga_id, inicio);
|
||||
create table procedimiento(procedimiento_id, fuente_tabla, fuente_id, pac_id, fecha, carga_id, padre_id, estudio_id, clase);
|
||||
create table observacion_clinica(procedimiento_id, resultado_id, valor_id, valor_fuente, carga_id);
|
||||
insert into carga values(1, '2026-11-17 00:00:00');
|
||||
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-06-20',1,10);
|
||||
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-07-10',1,11);
|
||||
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-06-20',1,12);
|
||||
insert into cama_linea_de_tiempo values(1,'diagnostico','2025-06-19','2026-11-17');
|
||||
insert into procedimiento values(1,'source','1',1,'2025-06-01',1,null,'mastografia','toma');
|
||||
insert into procedimiento select reporte_id,'source',cast(reporte_id as text),pac_id,fecha_reporte,reporte_carga_id,procedimiento_id,'mastografia','reporte' from cama_mastografias;
|
||||
''')
|
||||
start = date(2025, 6, 20)
|
||||
end = start + timedelta(days=days)
|
||||
db.execute("insert into cama_linea_de_tiempo values(1,'diagnostico',?,'2026-11-17')", (end.isoformat(),))
|
||||
for i in range(-30, 210):
|
||||
db.execute("insert into dim_fecha values(?,?)", ((start + timedelta(days=i)).isoformat(), i))
|
||||
db.execute("create view cama_resultado_diagnostico as " + sql(manifest, "cama_resultado_diagnostico"))
|
||||
assert db.execute('select procedimiento_id, fecha_reporte, dias_reporte_diagnostico from cama_resultado_diagnostico').fetchall() == [(1, '2025-06-20', expected)]
|
||||
# A note between reports belongs to the selected first report, never yields a negative interval.
|
||||
db.execute("insert into cama_linea_de_tiempo values(1,'diagnostico','2025-06-25','2026-11-17')")
|
||||
assert db.execute('select dias_reporte_diagnostico from cama_resultado_diagnostico').fetchall() == [(5,)]
|
||||
|
||||
|
||||
def test_detection_uses_platform_report_identity_even_when_source_ids_collide(manifest):
|
||||
db = sqlite3.connect(":memory:")
|
||||
db.executescript('''
|
||||
create table cama_reportes_biopsia(procedimiento_id, fuente_id, pac_id, fecha_reporte, grado, reporte_conocido_en);
|
||||
insert into cama_reportes_biopsia values(1,'7',1,'2025-06-30','BENIGNO','2026-11-17');
|
||||
insert into cama_reportes_biopsia values(2,'7',2,'2025-07-01','CARCINOMA_INVASOR','2026-11-17');
|
||||
insert into cama_reportes_biopsia values(3,'7',3,'2025-07-01',null,'2026-11-17');
|
||||
''')
|
||||
db.execute('create view cama_deteccion_biopsia as ' + sql(manifest, 'cama_deteccion_biopsia'))
|
||||
assert db.execute('select sum(maligno), sum(con_resultado), count(distinct procedimiento_id) from cama_deteccion_biopsia').fetchone() == (1, 2, 3)
|
||||
from webapi.metrics import measure_definitions
|
||||
d = measure_definitions(manifest)['cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA']
|
||||
assert d.denominator.measure_expr == d.numerator.measure_expr == 'procedimiento_id'
|
||||
@@ -0,0 +1,94 @@
|
||||
"""What this module covers: the publication metadata of CaMa's FHIR `Measure`s (figures and category captions), read
|
||||
from dbt's manifest alone.
|
||||
|
||||
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's
|
||||
reference parameters, whose CaMa catalogs hold the captions and colours the dbt definitions repeat.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.fhir.measures import CATEGORY_LABEL, FIGURES, labels, measure_resource
|
||||
from webapi.kpis import definitions_of
|
||||
|
||||
REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def measures(manifest):
|
||||
"""Each CaMa measure as the API serves it, by its FHIR id."""
|
||||
titles = labels(manifest)
|
||||
return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, "")))
|
||||
for d in definitions_of("cama", manifest).values()}
|
||||
|
||||
|
||||
def figures(measure: dict) -> list[str]:
|
||||
return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES]
|
||||
|
||||
|
||||
def captions(measure: dict) -> dict[str, tuple[str, str]]:
|
||||
"""The measure's declared categories, in order: code -> (caption, colour)."""
|
||||
found = {}
|
||||
for e in measure["extension"]:
|
||||
if e["url"] == CATEGORY_LABEL:
|
||||
part = {p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
|
||||
found[part["codigo"]] = (part["etiqueta"], part["color"])
|
||||
return found
|
||||
|
||||
|
||||
def catalog(name: str) -> dict[str, tuple[str, str]]:
|
||||
with REFERENCE.open("rb") as f:
|
||||
entries = tomllib.load(f)["cama"]["catalogos"][name]["valor"]
|
||||
return {e["clave"]: (e["etiqueta"], e["color"]) for e in entries}
|
||||
|
||||
|
||||
def no_data() -> tuple[str, str]:
|
||||
with REFERENCE.open("rb") as f:
|
||||
v = tomllib.load(f)["cama"]["catalogos"]["sin_dato"]["valor"]
|
||||
return v["etiqueta"], v["color"]
|
||||
|
||||
|
||||
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
|
||||
"""Pins down: a distribution offers the donut and the bars, a duration its box plot, and the proportion and the
|
||||
analysis' measure none. Fails if a figure is declared that the page has no builder for, or one is dropped."""
|
||||
expected = {"CAMA-BIOPSIAS": ["fig_c2_donas", "fig_c2_barras"], "CAMA-BIRADS": ["fig_c2_donas", "fig_c2_barras"],
|
||||
"CAMA-BIRADS456-MASTOGRAFIA": ["fig_c2_donas", "fig_c2_barras"],
|
||||
"CAMA-BIRADS456-PACIENTE": ["fig_c2_donas", "fig_c2_barras"],
|
||||
"CAMA-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-EU38A": ["fig_c3r_caja"],
|
||||
"CAMA-CONFIRMACION-BIRADS45": [], "CAMA-BIRADS-CANCER-INVASOR": [],
|
||||
"CAMA-DIAS-RESULTADO-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-TASA-DETECCION-HISTOPATOLOGICA": [],
|
||||
"CAMA-HISTOPATOLOGIA-BIRADS": []}
|
||||
assert {i: figures(m) for i, m in measures.items()} == expected
|
||||
|
||||
|
||||
def test_the_category_captions_are_the_reference_catalogs(measures):
|
||||
"""Pins down: the captions, colours and order the dbt definitions publish equal `cama.catalogos.*` in the
|
||||
reference parameters (BI-RADS, BI-RADS 4 to 6, biopsy grade, plus «Sin dato» where a unit can lack the value).
|
||||
Fails if either side is edited without the other."""
|
||||
sin_dato = {"SIN_DATO": no_data()}
|
||||
assert captions(measures["CAMA-BIRADS"]) == {**catalog("birads"), **sin_dato}
|
||||
assert captions(measures["CAMA-BIRADS456-PACIENTE"]) == catalog("birads_4_a_6")
|
||||
assert captions(measures["CAMA-BIRADS456-MASTOGRAFIA"]) == catalog("birads_4_a_6")
|
||||
assert captions(measures["CAMA-BIOPSIAS"]) == {**catalog("biopsia"), **sin_dato}
|
||||
assert list(captions(measures["CAMA-BIRADS"])) == [*catalog("birads"), "SIN_DATO"]
|
||||
# The histopathological result by BI-RADS: the biopsy grades, then the patients without a biopsy and without a grade.
|
||||
assert captions(measures["CAMA-HISTOPATOLOGIA-BIRADS"]) == {**catalog("biopsia"), "SIN_BIOPSIA": ("Sin biopsia reportada", "#C9CDD2"), **sin_dato}
|
||||
|
||||
|
||||
def test_the_measures_without_categories_declare_none(measures):
|
||||
"""Pins down: proportions and durations carry no category captions. Fails if one is attached to a measure that
|
||||
has no categories."""
|
||||
for fhir_id in ("CAMA-CONFIRMACION-BIRADS45", "CAMA-DIAS-TOMA-DIAGNOSTICO", "CAMA-EU38A", "CAMA-DIAS-RESULTADO-DIAGNOSTICO",
|
||||
"CAMA-TASA-DETECCION-HISTOPATOLOGICA"):
|
||||
assert captions(measures[fhir_id]) == {}
|
||||
@@ -0,0 +1,87 @@
|
||||
"""What this module covers: CaMa's measures answered on request from dbt's semantic layer, against what the kit
|
||||
computed on the same fixture data: every measure, every period, its units and its numbers.
|
||||
|
||||
Fixtures: `base`, the CaMa fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's
|
||||
`manifest.json` (`DBT_MANIFEST`; skipped without it); `fixtures/kit_oracle_cama.json`, the kit's units and published
|
||||
numbers for each measure and period (counts only; suppression off).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import base_de
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
|
||||
ORACLE = json.loads((Path(__file__).parent / "fixtures" / "kit_oracle_cama.json").read_text(encoding="utf-8"))
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
||||
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def units(base, report_id: int) -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad "
|
||||
"where report_id = :r"), {"r": report_id}).all()))
|
||||
|
||||
|
||||
def published_rows(expected) -> list[dict]:
|
||||
return [dict(zip(expected["published_columns"], row)) for row in expected["published"]]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", sorted(ORACLE))
|
||||
def test_each_measure_is_the_kit_s_in_every_period(base, manifest, url):
|
||||
"""Pins down every CaMa measure in every period: the kit's units (with each one's category or days) and its
|
||||
numbers: a composition's count per category, a proportion's numerator and denominator, a duration's n, median,
|
||||
quartiles and excluded where the kit didn't suppress them. Fails if an event model, a semantic definition or the
|
||||
construct it uses drifts from what the kit meant."""
|
||||
for kind, of in (("proportion", measure_definitions), ("composition", composition_definitions),
|
||||
("duration", duration_definitions)):
|
||||
if url in of(manifest):
|
||||
definition = of(manifest)[url]
|
||||
break
|
||||
for period_id, expected in ORACLE[url]["periodos"].items():
|
||||
question = Question(url, period_id)
|
||||
rows = published_rows(expected)
|
||||
if kind == "composition":
|
||||
result = answer_composition("cama", definition, question, **repositories(base))
|
||||
assert {k: v for k, v in result.categories.items() if v} == {
|
||||
r["categoria"]: r["n"] for r in rows if r["estrato_id"] == "total" and r["n"]}, period_id
|
||||
elif kind == "proportion":
|
||||
result = answer("cama", definition, question, **repositories(base))
|
||||
(total,) = [r for r in rows if r["estrato_id"] == "total"] or [{"numerador": 0, "denominador": 0}]
|
||||
assert (result.numerator, result.denominator) == (total["numerador"] or 0, total["denominador"] or 0), period_id
|
||||
else:
|
||||
result = answer_duration("cama", definition, question, **repositories(base))
|
||||
(total,) = [r for r in rows if r["estrato_id"] == "total"]
|
||||
if not total["suprimido"]:
|
||||
assert (result.n, result.median, result.q1, result.q3, result.excluded) == (
|
||||
total["n"], total["mediana"], total["q1"], total["q3"], total["n_excluido"]), period_id
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Verify default persistent cohort setup with retained legacy configuration."""
|
||||
|
||||
from flask import Flask
|
||||
|
||||
from webapi.cama_runtime import configure_cama_cohort
|
||||
|
||||
|
||||
def test_default_reader_uses_shared_persistence(monkeypatch):
|
||||
"""The reader is registered without special cohort environment variables."""
|
||||
for key in ('CAMA_COHORT_SYNTHETIC', 'CAMA_COHORT_SECRET', 'CAMA_COHORT_ACCESS_TOKEN'):
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
app = Flask(__name__)
|
||||
configure_cama_cohort(app)
|
||||
assert callable(app.config['CAMA_COHORT_READER'])
|
||||
assert 'CAMA_COHORT_ACCESS' not in app.config
|
||||
|
||||
|
||||
def test_application_starts_with_retained_obsolete_configuration(monkeypatch):
|
||||
"""Retained synthetic settings cannot prevent the health endpoint starting."""
|
||||
monkeypatch.setenv('CAMA_COHORT_SYNTHETIC', '1')
|
||||
monkeypatch.delenv('CAMA_COHORT_SECRET', raising=False)
|
||||
monkeypatch.setenv('CAMA_COHORT_ACCESS_TOKEN', 'invalid')
|
||||
from webapi import create_app
|
||||
|
||||
assert create_app().test_client().get('/health').get_json() == {'status': 'ok'}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata.
|
||||
dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as
|
||||
timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the
|
||||
labels a timeline stratum's values carry into FHIR.
|
||||
|
||||
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database
|
||||
(`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on
|
||||
2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from conftest import base_de
|
||||
from sqlalchemy import text
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.fhir.measures import _label
|
||||
from webapi.metrics import Question
|
||||
|
||||
URL = "cama/CAMA_BIRADS_CANCER_INVASOR"
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.run(*UNTIL_MODELS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def answered(base, manifest, period: str, event_cutoff: date | None = None):
|
||||
d = base.dominio
|
||||
definition = composition_definitions(manifest)[URL]
|
||||
return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff),
|
||||
parameters=d.def_parametro_repository, periods=d.dim_periodo_repository,
|
||||
history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True)
|
||||
|
||||
|
||||
def stratifiers(base) -> set[str]:
|
||||
with base.motor.connect() as con:
|
||||
return set(con.execute(text("select tipo from cama_estratificadores")).scalars())
|
||||
|
||||
|
||||
def test_the_stratifiers_come_from_h003_s_reports(base):
|
||||
"""Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology
|
||||
report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in
|
||||
`vars.cama.estratos` or a timeline `tipo` it reads changes."""
|
||||
assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"}
|
||||
|
||||
|
||||
def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest):
|
||||
"""Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to
|
||||
it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the
|
||||
category or a stratum's values drift."""
|
||||
assert answered(base, manifest, "2025-S1").categories == {}
|
||||
result = answered(base, manifest, "2025-S2")
|
||||
assert result.categories == {"B4A": 1}
|
||||
assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}},
|
||||
"etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}},
|
||||
"tamano": {"T1": {"B4A": 1}}}
|
||||
|
||||
|
||||
def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest):
|
||||
"""Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype
|
||||
(report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's
|
||||
start (H-003 would have nothing) or ignores the cut-off (she'd have her stage)."""
|
||||
strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata
|
||||
assert strata["clasificacion"] == {"HER2": {"B4A": 1}}
|
||||
assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}}
|
||||
|
||||
|
||||
SUBTIPOS = [
|
||||
({"her2": "H3"}, "subtipo_her2"),
|
||||
({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"),
|
||||
({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"),
|
||||
({"her2": "H0", "ki67_pct": None}, None),
|
||||
({"her2": "H2"}, None),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS)
|
||||
def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo):
|
||||
"""Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both
|
||||
receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and
|
||||
progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's
|
||||
report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise.
|
||||
Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes."""
|
||||
valores = {"receptor_progesterona": "POSITIVO", **cambios}
|
||||
with base.motor.begin() as con:
|
||||
for nombre, valor in valores.items():
|
||||
columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id"
|
||||
con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"),
|
||||
{"v": valor, "r": f"biopsia.{nombre}"})
|
||||
assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set())
|
||||
|
||||
|
||||
def test_a_timeline_stratum_s_values_carry_their_labels():
|
||||
"""Pins down: FHIR labels a timeline stratum's value from its entry in `valores`, and its `resto` from
|
||||
`resto_etiqueta`. Fails if `_label` reads labels only from a map."""
|
||||
spec = {"valores": [{"valor": "II", "etiqueta": "Estadio II", "si": []}], "resto": "SIN_DATO",
|
||||
"resto_etiqueta": "Sin dato"}
|
||||
assert (_label(spec, "II"), _label(spec, "SIN_DATO"), _label(spec, "IV")) == ("Estadio II", "Sin dato", None)
|
||||
@@ -0,0 +1,117 @@
|
||||
"""`commit_discovered_fields`: writes captions no known field claims
|
||||
straight into `procedimiento`/`observacion`, tagged apart from every
|
||||
staging-derived row with `FUENTE_CATALOGO_ABIERTO`. Fails if a known
|
||||
patient's discovered fields stop landing there, or if an unmatched one
|
||||
stops growing the catalog instead of being silently dropped.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlmodel import select
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction import ExtractedRecord
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.services.catalog_commit_service import FUENTE_CATALOGO_ABIERTO, commit_discovered_fields
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _record(key: str, pairs: list[tuple[str, str]]) -> ExtractedRecord:
|
||||
return ExtractedRecord(
|
||||
values={}, sources=[], key=key, discovered=[DiscoveredField(c, v, EVIDENCE) for c, v in pairs]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu_catalog(tmp_path, monkeypatch):
|
||||
"""`add_resultado`/`sync` write real rows and a real file:
|
||||
kept off the checked-in `cacu.toml` and off any other domain's data."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text(
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.calidad_muestra]\netiqueta = "Calidad de la muestra"\ntipo_valor = "texto"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def known_patient(wire_domain):
|
||||
wire_domain("cacu")
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
paciente_repository.create(Paciente(pac_id_hospital="DOC-FB-1", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
return "DOC-FB-1"
|
||||
|
||||
|
||||
def test_a_matched_field_is_written_on_the_existing_resultado(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
[procedimiento] = sesion.exec(select(carga_repository.procedimiento)).all()
|
||||
assert procedimiento.fuente_tabla == FUENTE_CATALOGO_ABIERTO
|
||||
assert procedimiento.fuente_id == known_patient
|
||||
|
||||
|
||||
def test_an_unmatched_field_is_counted_and_the_catalog_left_untouched(cacu_catalog, known_patient):
|
||||
"""A caption the catalog doesn't know is counted, not written, and the
|
||||
catalog file isn't edited: it's versioned with the code. Fails if the
|
||||
import path mints catalog entries again."""
|
||||
before = cacu_catalog.read_text(encoding="utf-8")
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Tipo de fijador", "Formol")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.fields_minted, result.fields_unmatched) == (0, 0, 1)
|
||||
assert cacu_catalog.read_text(encoding="utf-8") == before
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
assert sesion.exec(select(carga_repository.observacion)).all() == []
|
||||
|
||||
|
||||
def test_a_patient_outside_persona_is_skipped_not_dropped_silently(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields(
|
||||
[_record("NOT-A-PATIENT", [("Calidad de muestra", "x")])], proyecto="cacu", estudio_id="citologia"
|
||||
)
|
||||
assert (result.records_written, result.records_without_patient) == (0, 1)
|
||||
|
||||
|
||||
def test_a_record_without_discovered_fields_is_ignored(cacu_catalog, known_patient):
|
||||
result = commit_discovered_fields([_record(known_patient, [])], proyecto="cacu", estudio_id="citologia")
|
||||
assert result.records_written == 0
|
||||
|
||||
|
||||
def test_a_repeated_caption_is_folded_not_written_twice(cacu_catalog, known_patient):
|
||||
"""A static label printed on several pages of the same document (a date,
|
||||
a signature line) discovers as one `DiscoveredField` per occurrence,
|
||||
on purpose (`discover_captions`'s docstring). Fails if this stops
|
||||
folding repeats before writing: `observacion` has one row per
|
||||
`(procedimiento, resultado_id)`, so a second occurrence of the same
|
||||
resultado_id raises `IntegrityError` and the whole record's fields —
|
||||
including the ones that weren't duplicated — are lost."""
|
||||
result = commit_discovered_fields(
|
||||
[_record(known_patient, [("Calidad de muestra", "Insatisfactoria"), ("Calidad de muestra", "Satisfactoria")])],
|
||||
proyecto="cacu",
|
||||
estudio_id="citologia",
|
||||
)
|
||||
assert (result.records_written, result.fields_matched, result.fields_minted) == (1, 1, 0)
|
||||
|
||||
from persistance.cacu import carga_repository
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[observacion] = sesion.exec(select(carga_repository.observacion)).all()
|
||||
assert observacion.resultado_id == "citologia.calidad_muestra"
|
||||
assert observacion.valor_texto == "Insatisfactoria"
|
||||
@@ -0,0 +1,90 @@
|
||||
"""`catalog_matching.match_or_mint`: fails if it stops reusing an existing
|
||||
catalog field for an OCR caption that's clearly the same thing worded
|
||||
differently, or if an unmatched caption stops being added to the catalog
|
||||
and silently drops its value instead.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from webapi.orchestration.reference.catalogs import Catalogo
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
from extraction.nlp import DiscoveredField, Evidence
|
||||
from webapi.imports.schemas.catalog_matching import match_or_mint
|
||||
|
||||
EVIDENCE = Evidence("fila.pdf", 1, "")
|
||||
|
||||
|
||||
def _field(caption: str, value: str) -> DiscoveredField:
|
||||
return DiscoveredField(caption, value, EVIDENCE)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo() -> Catalogo:
|
||||
tablas = tablas_de("cacu")
|
||||
return Catalogo(
|
||||
estudios=[tablas.CatEstudio(estudio_id="citologia", etiqueta="Citología cervical")],
|
||||
resultados=[
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.calidad_muestra", estudio_id="citologia",
|
||||
etiqueta="Calidad de la muestra", tipo_valor="codigo",
|
||||
),
|
||||
tablas.CatResultado(
|
||||
resultado_id="citologia.celulas_glandulares", estudio_id="citologia",
|
||||
etiqueta="Células glandulares", tipo_valor="texto",
|
||||
),
|
||||
],
|
||||
valores=[
|
||||
tablas.CatValor(
|
||||
resultado_id="citologia.calidad_muestra", valor_id="SATISFACTORIO",
|
||||
etiqueta="Satisfactoria", orden=1, estado="vigente",
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_toml(tmp_path, monkeypatch):
|
||||
"""`add_resultado` writes to disk; keep it off the real `cacu.toml`."""
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
(tmp_path / "cacu.toml").write_text("", encoding="utf-8")
|
||||
return tmp_path / "cacu.toml"
|
||||
|
||||
|
||||
def test_a_worded_differently_caption_reuses_the_existing_resultado(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Calidad de muestra", "SATISFACTORIO")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.resultado_id == "citologia.calidad_muestra" and not matched.is_new
|
||||
assert matched.observacion["valor_id"] == "SATISFACTORIO"
|
||||
assert catalogo_toml.read_text(encoding="utf-8") == "" # nothing minted
|
||||
|
||||
|
||||
def test_an_unmatched_caption_in_a_known_estudio_is_minted_there(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint(
|
||||
[_field("Tipo de fijador", "Formol")], proyecto="cacu", catalogo=catalogo, estudio_id="citologia"
|
||||
)
|
||||
assert matched.is_new and matched.resultado_id.startswith("citologia.")
|
||||
assert matched.observacion["valor_texto"] == "Formol"
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert matched.resultado_id in {r.resultado_id for r in sincronizado.resultados}
|
||||
|
||||
|
||||
def test_an_unmatched_caption_with_no_estudio_falls_back_to_documento_externo(catalogo, catalogo_toml):
|
||||
[matched] = match_or_mint([_field("Observación suelta", "algo")], proyecto="cacu", catalogo=catalogo)
|
||||
assert matched.resultado_id == "documento_externo." + matched.resultado_id.split(".", 1)[1]
|
||||
|
||||
sincronizado = catalogos.catalogo_desde_toml(catalogo_toml, tablas=tablas_de("cacu"))
|
||||
assert "documento_externo" in {e.estudio_id for e in sincronizado.estudios}
|
||||
|
||||
|
||||
def test_the_inferred_tipo_valor_follows_the_value_shape(catalogo, catalogo_toml):
|
||||
fecha, numero, texto = match_or_mint(
|
||||
[_field("Fecha de algo", "15/01/2024"), _field("Cuenta de algo", "12.5"), _field("Nota libre", "ninguna")],
|
||||
proyecto="cacu", catalogo=catalogo, estudio_id="citologia",
|
||||
)
|
||||
assert fecha.observacion["valor_fecha"] == date(2024, 1, 15)
|
||||
assert numero.observacion["valor_numerico"] == 12.5
|
||||
assert texto.observacion["valor_texto"] == "ninguna"
|
||||
@@ -0,0 +1,77 @@
|
||||
"""`add_resultado`: adds a new field to a project's catalog TOML file on
|
||||
disk, for a caller (`webapi.imports.schemas.catalog_matching`) that found a
|
||||
field no catalog entry matches closely enough. Each test pins down one
|
||||
rule of that append; fails if any of them regresses into losing data or
|
||||
duplicating an entry that's already there.
|
||||
"""
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_file(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
|
||||
def escribir(contenido: str) -> None:
|
||||
(tmp_path / "prueba.toml").write_text(contenido, encoding="utf-8")
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
def test_a_new_resultado_is_appended_under_its_existing_estudio(catalogo_file):
|
||||
catalogo_file('[citologia]\netiqueta = "Citología"\n')
|
||||
|
||||
resultado_id = catalogos.add_resultado(
|
||||
"prueba", estudio_id="citologia", nombre="nuevo_campo", etiqueta="Nuevo campo", tipo_valor="texto"
|
||||
)
|
||||
|
||||
assert resultado_id == "citologia.nuevo_campo"
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["citologia"]["etiqueta"] == "Citología" # what was already there survives
|
||||
assert leido["citologia"]["resultados"]["nuevo_campo"] == {"etiqueta": "Nuevo campo", "tipo_valor": "texto"}
|
||||
|
||||
|
||||
def test_a_resultado_of_an_unknown_estudio_also_creates_the_estudio(catalogo_file):
|
||||
catalogo_file("")
|
||||
|
||||
catalogos.add_resultado(
|
||||
"prueba",
|
||||
estudio_id="documento_externo",
|
||||
nombre="campo",
|
||||
etiqueta="Campo",
|
||||
tipo_valor="fecha",
|
||||
estudio_etiqueta="Documento externo",
|
||||
)
|
||||
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["documento_externo"]["etiqueta"] == "Documento externo"
|
||||
assert leido["documento_externo"]["resultados"]["campo"]["tipo_valor"] == "fecha"
|
||||
|
||||
|
||||
def test_adding_the_same_resultado_twice_does_not_touch_the_file(catalogo_file):
|
||||
"""Fails if re-discovering the same field on a later row duplicates it
|
||||
or rewrites what a human already edited in the file."""
|
||||
original = '[citologia]\netiqueta = "Citología"\n\n[citologia.resultados.campo]\netiqueta = "Campo"\ntipo_valor = "texto"\n'
|
||||
catalogo_file(original)
|
||||
|
||||
catalogos.add_resultado("prueba", estudio_id="citologia", nombre="campo", etiqueta="Otra cosa", tipo_valor="numero")
|
||||
|
||||
assert catalogos.ruta_de_catalogo("prueba").read_text(encoding="utf-8") == original
|
||||
|
||||
|
||||
def test_an_unknown_tipo_valor_is_rejected(catalogo_file):
|
||||
catalogo_file("")
|
||||
with pytest.raises(catalogos.CatalogoInvalido):
|
||||
catalogos.add_resultado("prueba", estudio_id="x", nombre="y", etiqueta="Y", tipo_valor="no_existe")
|
||||
|
||||
|
||||
def test_a_quote_in_a_label_does_not_break_the_file(catalogo_file):
|
||||
"""Fails if a caption or label read off a document (arbitrary text)
|
||||
produces TOML the next `catalogo_desde_toml` can't parse."""
|
||||
catalogo_file("")
|
||||
catalogos.add_resultado(
|
||||
"prueba", estudio_id="nota", nombre="campo", etiqueta='Dx: "sospechoso"', tipo_valor="texto"
|
||||
)
|
||||
leido = catalogos._leer(catalogos.ruta_de_catalogo("prueba"))
|
||||
assert leido["nota"]["resultados"]["campo"]["etiqueta"] == 'Dx: "sospechoso"'
|
||||
@@ -1,220 +0,0 @@
|
||||
"""An operator connects ISSSTELEON's test source through the API, the way the /conectar
|
||||
screens do: look into its tables, save the drawn pipeline, run it, read what came out, and
|
||||
settle what review shows. Real API and Dagster processes; nothing faked."""
|
||||
|
||||
import json
|
||||
import time
|
||||
|
||||
from sqlalchemy import create_engine, make_url, text
|
||||
|
||||
SQL = "dlt.sources.sql_database:sql_database"
|
||||
CYTOLOGY = {"entity": "cervical_cytology"}
|
||||
STUDIES = ("cervical_cytology", "cervical_biopsy", "mammography", "breast_biopsy",
|
||||
"breast_treatment", "breast_recurrence", "clinical_note") # fmt: skip
|
||||
|
||||
|
||||
def ok(response, status=200):
|
||||
assert response.status_code == status, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def wait_for(api, run_id: str, seconds: int = 900) -> None:
|
||||
deadline = time.monotonic() + seconds
|
||||
while (status := ok(api.get(f"/runs/{run_id}"))["status"]) not in ("SUCCESS", "FAILURE"):
|
||||
assert time.monotonic() < deadline, f"run {run_id} still {status}"
|
||||
time.sleep(2)
|
||||
assert status == "SUCCESS"
|
||||
|
||||
|
||||
def run(api, pipeline: str) -> None:
|
||||
wait_for(api, ok(api.post(f"/ingest/pipelines/{pipeline}/runs", json={}))["run_id"])
|
||||
|
||||
|
||||
def test_an_operator_connects_a_site_and_settles_its_review(api, platform, site, tmp_path):
|
||||
truth = site.truth
|
||||
database = {"credentials": site.url, "schema": "dbo"}
|
||||
|
||||
# What the site has, and what one of its tables holds (documents shown by size).
|
||||
found = ok(api.post("/ingest/sources/resources", json={"source": SQL, "args": database}))
|
||||
assert found == ["ResultadoSubrogado"]
|
||||
missing = {"credentials": "mssql+pymssql://sa:x@nowhere.invalid:1433/Pruebas"}
|
||||
unreachable = api.post("/ingest/sources/resources", json={"source": SQL, "args": missing})
|
||||
assert unreachable.status_code == 422, unreachable.text
|
||||
reports = {"id": "reports", "kind": "source", "source": SQL, "args": database}
|
||||
sample = ok(
|
||||
api.post(
|
||||
"/ingest/sources/preview?limit=3", json=reports | {"resource": "ResultadoSubrogado"}
|
||||
)
|
||||
)
|
||||
assert len(sample) == 3 and all(r["Archivo"].endswith(" bytes>") for r in sample)
|
||||
|
||||
# A file someone uploads (a report sent by mail) becomes a source like any other.
|
||||
engine = create_engine(site.url)
|
||||
with engine.connect() as con:
|
||||
pdf = con.execute(text("select Archivo from dbo.ResultadoSubrogado where Id = 1")).scalar()
|
||||
engine.dispose()
|
||||
uploaded = ok(api.post("/ingest/uploads", files={"files": ("informe.pdf", pdf)}))
|
||||
mailed = {
|
||||
"id": "mailed",
|
||||
"kind": "source",
|
||||
"source": "dlt.sources.filesystem:filesystem",
|
||||
"args": {"bucket_url": uploaded["bucket_url"]},
|
||||
"then": "persistance.readers:read_bytes",
|
||||
}
|
||||
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=mailed))) == 1
|
||||
|
||||
# The site's codes in platform terms: a ConceptMap, saved before the drawing that names
|
||||
# it. One that maps onto a code no field allows is refused, saying which.
|
||||
drawn = json.loads(site.drawn)
|
||||
missing = api.put("/ingest/pipelines/site", json=drawn)
|
||||
assert missing.status_code == 422 and "erick_site" in missing.text
|
||||
codes = json.loads(site.concept_map.read_text())
|
||||
wrong = json.loads(json.dumps(codes).replace('"code": "HSIL"', '"code": "BIRADS-7"'))
|
||||
refused = api.put("/ingest/concept-maps/erick_site", json=wrong)
|
||||
assert refused.status_code == 422 and "BIRADS-7 is not an allowed code" in refused.text
|
||||
assert ok(api.put("/ingest/concept-maps/erick_site", json=codes)) == {"version": 1}
|
||||
|
||||
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
||||
broken = {
|
||||
"nodes": [
|
||||
*drawn["nodes"],
|
||||
{"id": "loose", "kind": "read", "inputs": ["gone"], "column": "x"},
|
||||
]
|
||||
}
|
||||
assert "no node" in api.put("/ingest/pipelines/site", json=broken).text
|
||||
assert ok(api.put("/ingest/pipelines/site", json=drawn)) == {"version": 1}
|
||||
assert ok(api.get("/ingest/pipelines/site"))["version"] == 1
|
||||
|
||||
# A password is never shown, and survives the UI sending the masked drawing back.
|
||||
shown = ok(api.get("/ingest/pipelines/site"))["pipeline"]
|
||||
password = make_url(site.url).password
|
||||
assert password not in json.dumps(shown)
|
||||
assert ok(api.put("/ingest/pipelines/site", json=shown)) == {"version": 2}
|
||||
stored = platform.query(
|
||||
"select doc from config.pipelines where pipeline_id = 'site' and version = 2"
|
||||
)
|
||||
assert site.url in stored[0][0]
|
||||
|
||||
# Run it, and look at what any node produced.
|
||||
run(api, "site")
|
||||
record_of = {}
|
||||
assert ok(api.get("/ingest/pipelines/site/nodes/resultados/rows?limit=3"))
|
||||
held_by = platform.query("select id, _record from bronze.n__site__resultados")
|
||||
record_of |= {f"ResultadoSubrogado:{i}": r for i, r in held_by}
|
||||
assert len(record_of) == len(truth)
|
||||
# Papers no route recognises wait for a reviewer, and only they.
|
||||
unknown = ok(api.get("/review/unrecognised", params={"pipeline": "site"}))
|
||||
assert {f"ResultadoSubrogado:{r['id']}" for r in unknown} == {
|
||||
r["where"] for r in truth if r.get("document") == "unrecognised"} # fmt: skip
|
||||
assert all("VIGENCIA" in r["preview"] for r in unknown)
|
||||
forms = sum(1 for r in truth
|
||||
if r["entity"] == "cervical_cytology"
|
||||
and r.get("document") in (None, "cytology_with_hpv")) # fmt: skip
|
||||
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == forms
|
||||
|
||||
# Review: reports that contradict each other, rows held because their person is torn
|
||||
# (a pathology report that fits two women of one name), and persons that may be one.
|
||||
# (a disputed cytology shows all its records: both HPV copies and the form they share)
|
||||
disputed = {(r["person"], r["values"]["sample_date"]) for r in truth if r.get("conflict")}
|
||||
conflicting = {record_of[r["where"]] for r in truth if r["entity"] == "cervical_cytology"
|
||||
and (r["person"], r["values"]["sample_date"]) in disputed} # fmt: skip
|
||||
shown = {c["_record"] for c in ok(api.get("/review/conflicts", params=CYTOLOGY))}
|
||||
assert shown and shown <= conflicting
|
||||
persons = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"}))
|
||||
assert persons["to_settle"] and len(persons["torn"]) == 1
|
||||
|
||||
# The reviewer settles all of it, checking each case against the source documents.
|
||||
patient = site.patients(platform.query)
|
||||
whose, before = {}, {}
|
||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||
whose.setdefault(person, set()).add(patient[record])
|
||||
before[record] = person
|
||||
# A queued person or candidate is one of its records (decisions are kept by record).
|
||||
whose |= {record: whose[person] for record, person in before.items()}
|
||||
for r in truth:
|
||||
if r.get("flipped"):
|
||||
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
||||
ok(api.post("/review/rejections", json=decision), status=201)
|
||||
merges = 0
|
||||
for entry in persons["to_settle"]:
|
||||
for c in entry["candidates"]:
|
||||
same = whose[entry["person"]] == whose[c["candidate"]]
|
||||
merges += same
|
||||
decision = {"person": entry["person"], "candidate": c["candidate"], "same": same}
|
||||
ok(api.post("/review/persons", json=decision), status=201)
|
||||
# A person nothing names (a scan whose name wasn't read): the reviewer reads whose
|
||||
# document it is and joins it to her.
|
||||
for entry in persons["unnamed"]:
|
||||
scan = entry["records"][0]["_record"] # decisions are kept by record
|
||||
owner = next(r for r, person in before.items()
|
||||
if patient[r] == patient[scan] and person != entry["person"]) # fmt: skip
|
||||
decision = {"person": scan, "candidate": owner, "same": True}
|
||||
ok(api.post("/review/persons", json=decision), status=201)
|
||||
merges += 1
|
||||
# The torn person: each record without a birth date (pathology prints none; a scan's
|
||||
# may not be read) gets the one its woman's other documents show.
|
||||
at = {record_of[r["where"]]: r for r in truth}
|
||||
for record in persons["torn"][0]["records"]:
|
||||
r = at[record["_record"]]
|
||||
if record.get("birth_date") is None:
|
||||
fix = {"record": record["_record"], "field": "birth_date",
|
||||
"value": site.meta["birth_dates"][r["person"]]} # fmt: skip
|
||||
ok(api.post("/review/corrections", json=fix), status=201)
|
||||
# A row a rule held because a value came out wrong (a scan misread: "lA" for a stage)
|
||||
# gets the value the reviewer reads in the document; one with nothing to fix is
|
||||
# rejected, but for the torn person's rows, which wait for the correction above.
|
||||
misread = []
|
||||
for study in STUDIES:
|
||||
for h in ok(api.get("/review/held", params={"entity": study})):
|
||||
torn = any("disagree on birth date" in why for why in h["_held"])
|
||||
r = at[h["_record"]]
|
||||
truly = r.get("clinical_note") if study == "clinical_note" else r["values"]
|
||||
wrong = {f: v for f, v in truly.items()
|
||||
if v is not None and str(h["_raw"].get(f)) != str(v)} # fmt: skip
|
||||
for field, v in wrong.items():
|
||||
fix = {"entity": study, "record": h["_record"], "field": field, "value": str(v)}
|
||||
ok(api.post("/review/corrections", json=fix), status=201)
|
||||
if not wrong and not torn:
|
||||
decision = {"entity": study, "record": h["_record"], "reason": "misread"}
|
||||
ok(api.post("/review/rejections", json=decision), status=201)
|
||||
misread.append((h["_record"], study))
|
||||
stage = {"entity": "breast_biopsy", "record": "x", "field": "stage", "value": "VII"}
|
||||
assert api.post("/review/corrections", json=stage).status_code == 422
|
||||
bad = {"record": "x", "field": "birth_date", "value": "not a date"}
|
||||
assert api.post("/review/corrections", json=bad).status_code == 422
|
||||
|
||||
# The next run applies every decision: one person per patient, nothing left to review,
|
||||
# and silver holds every cytology but the wrong copies and the misreads.
|
||||
run(api, "site")
|
||||
assert ok(api.get("/review/conflicts", params=CYTOLOGY)) == []
|
||||
for study in STUDIES:
|
||||
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
||||
left = ok(api.get("/review/persons", params={"pipeline": "site", "node": "persons"}))
|
||||
assert left == {"to_settle": [], "torn": [], "unnamed": []}
|
||||
people = {r["person"] for r in truth}
|
||||
groups = {}
|
||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||
groups.setdefault(person, set()).add(patient[record])
|
||||
assert sorted(map(sorted, groups.values())) == sorted([p] for p in people)
|
||||
|
||||
# Person ids are stable: a person keeps an id her records had, and an id that went
|
||||
# away (merged by the review) resolves to the person that replaced it.
|
||||
after = dict(platform.query("select _record, person_id from bronze.n__site__persons"))
|
||||
gone = set(before.values()) - set(after.values())
|
||||
replaced = dict(platform.query("select person_id, replaced_by from silver.person_link"))
|
||||
assert merges and len(gone) == merges and set(replaced) == gone
|
||||
for old, new in replaced.items():
|
||||
assert new in set(after.values())
|
||||
assert any(before[r] == old and after[r] == new for r in before)
|
||||
# No person got a new id, but for the woman parted from the torn person (two namesakes
|
||||
# one pathology report had joined): her records all come from that person.
|
||||
new = set(after.values()) - set(before.values())
|
||||
torn_id = persons["torn"][0]["person"]
|
||||
assert len(new) <= 1
|
||||
assert all(before[r] == torn_id for r, p in after.items() if p in new)
|
||||
rejected = {r for r, study in misread if study == "cervical_cytology"}
|
||||
rejected |= {record_of[r["where"]] for r in truth if r.get("flipped")}
|
||||
cytologies = {(r["person"], r["values"]["sample_date"]) for r in truth
|
||||
if r["entity"] == "cervical_cytology"
|
||||
and record_of[r["where"]] not in rejected} # fmt: skip
|
||||
assert platform.count("silver.cervical_cytology") == len(cytologies)
|
||||
@@ -0,0 +1,127 @@
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from webapi.imports.connectors.csv_ import CsvConnector
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.excel import ExcelConnector
|
||||
from webapi.imports.connectors.json_ import JsonConnector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
|
||||
def test_csv_connector_reads_columns_and_rows():
|
||||
raw = b"nombre,edad\nAna,30\nLuis,40\n"
|
||||
connector = CsvConnector(raw)
|
||||
columns = {c.name: c.inferred_type for c in connector.preview().columns}
|
||||
assert columns == {"nombre": "string", "edad": "integer"}
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
assert len(preview.sample_rows) == 1
|
||||
# Cells stay text; typing is the import schema's job (see CsvConnector).
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
|
||||
assert rows == [{"pac_nombre": "Ana", "pac_edad": "30"}, {"pac_nombre": "Luis", "pac_edad": "40"}]
|
||||
|
||||
|
||||
def test_csv_connector_keeps_leading_zeros_and_blank_cells():
|
||||
raw = b"cp,exp\n01000,007\n,H-2\n"
|
||||
connector = CsvConnector(raw)
|
||||
assert {c.name: c.inferred_type for c in connector.preview().columns} == {"cp": "string", "exp": "string"}
|
||||
rows = list(connector.read_rows({"cp": "pac_codigo_postal", "exp": "pac_id_hospital"}))
|
||||
assert rows == [
|
||||
{"pac_codigo_postal": "01000", "pac_id_hospital": "007"},
|
||||
{"pac_codigo_postal": None, "pac_id_hospital": "H-2"},
|
||||
]
|
||||
|
||||
|
||||
def test_csv_connector_single_column_file():
|
||||
connector = CsvConnector(b"id\nH3\nH4\n")
|
||||
assert [c.name for c in connector.preview().columns] == ["id"]
|
||||
assert connector.metadata()["delimiter"] == ","
|
||||
|
||||
|
||||
def test_csv_connector_sniffs_semicolons_and_strips_excel_bom():
|
||||
raw = "\ufeffExpediente;Sexo\nH-1;F\n".encode("utf-8")
|
||||
connector = CsvConnector(raw)
|
||||
assert [c.name for c in connector.preview().columns] == ["Expediente", "Sexo"]
|
||||
assert connector.metadata() == {"delimiter": ";", "encoding": "utf-8-sig"}
|
||||
|
||||
|
||||
def test_csv_connector_falls_back_to_cp1252():
|
||||
raw = "nombre\nPeña\n".encode("cp1252")
|
||||
connector = CsvConnector(raw)
|
||||
assert list(connector.read_rows({"nombre": "n"})) == [{"n": "Peña"}]
|
||||
|
||||
|
||||
def test_csv_connector_bad_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
CsvConnector(b"\xff\xfe\x00\x01not valid utf-8 csv bytes")
|
||||
|
||||
|
||||
def test_json_connector_reads_list_of_records():
|
||||
raw = b'[{"nombre": "Ana", "edad": 30}, {"nombre": "Luis", "edad": 40}]'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
def test_json_connector_reads_wrapped_data_key():
|
||||
raw = b'{"data": [{"nombre": "Ana"}]}'
|
||||
connector = JsonConnector(raw)
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre"}
|
||||
|
||||
|
||||
def test_json_connector_bad_json_raises_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
JsonConnector(b"{not valid json")
|
||||
|
||||
|
||||
def test_excel_connector_reads_columns_and_rows():
|
||||
pd = pytest.importorskip("pandas")
|
||||
buffer = io.BytesIO()
|
||||
pd.DataFrame({"nombre": ["Ana", "Luis"], "edad": [30, 40]}).to_excel(buffer, index=False, engine="openpyxl")
|
||||
connector = ExcelConnector(buffer.getvalue())
|
||||
assert connector.list_sheets() == ["Sheet1"]
|
||||
assert {c.name for c in connector.preview().columns} == {"nombre", "edad"}
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre"}))
|
||||
assert rows == [{"pac_nombre": "Ana"}, {"pac_nombre": "Luis"}]
|
||||
|
||||
|
||||
def test_excel_connector_bad_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
ExcelConnector(b"not an excel file")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_source_url(tmp_path):
|
||||
db_path = tmp_path / "source.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE patients (nombre TEXT, edad INTEGER)"))
|
||||
conn.execute(text("INSERT INTO patients (nombre, edad) VALUES ('Ana', 30), ('Luis', 40)"))
|
||||
return url
|
||||
|
||||
|
||||
def test_sql_connector_introspection_and_rows(sqlite_source_url):
|
||||
connector = SqlConnector(sqlite_source_url)
|
||||
connector.test_connection()
|
||||
assert connector.get_dialect() == "sqlite"
|
||||
assert "patients" in connector.list_tables()
|
||||
columns = {c.name for c in connector.list_columns("patients")}
|
||||
assert columns == {"nombre", "edad"}
|
||||
|
||||
connector.select_table("patients")
|
||||
preview = connector.preview()
|
||||
assert preview.total_rows == 2
|
||||
rows = list(connector.read_rows({"nombre": "pac_nombre", "edad": "pac_edad"}))
|
||||
assert rows == [{"pac_nombre": "Ana", "pac_edad": 30}, {"pac_nombre": "Luis", "pac_edad": 40}]
|
||||
|
||||
|
||||
def test_sql_connector_bad_connection_string_raises_connector_error():
|
||||
# may fail either at construction (unknown dialect) or at connect time;
|
||||
# both must surface as ConnectorError rather than a raw sqlalchemy error
|
||||
with pytest.raises(ConnectorError):
|
||||
connector = SqlConnector("not-a-real://connection-string")
|
||||
connector.test_connection()
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Exercises `SqlConnector` against a real MySQL server, covering
|
||||
MySQL-specific reflection (native `ENUM` columns, `pymysql` quirks, DATE
|
||||
types) that the SQLite-based tests don't reach. Skipped unless
|
||||
`MYSQL_TEST_URL` is set.
|
||||
|
||||
To stand one up locally:
|
||||
docker run -d --name isssteleon-mysql-test \
|
||||
-e MYSQL_ROOT_PASSWORD=<root_pw> -e MYSQL_DATABASE=hospital_legacy \
|
||||
-e MYSQL_USER=<user> -e MYSQL_PASSWORD=<pw> -p 3307:3306 mysql:8.0
|
||||
export MYSQL_TEST_URL="mysql+pymysql://<user>:<pw>@127.0.0.1:3307/hospital_legacy"
|
||||
"""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
|
||||
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set — no real MySQL server to test against")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def legacy_table():
|
||||
"""A legacy table whose columns are unrelated to Core's naming, as in a
|
||||
third-party database we don't control."""
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
table_name = "test_connectors_mysql_fixture"
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"CREATE TABLE {table_name} ("
|
||||
" legacy_id VARCHAR(40) NOT NULL PRIMARY KEY,"
|
||||
" legacy_sexo ENUM('F','M'),"
|
||||
" legacy_nacimiento DATE"
|
||||
") ENGINE=InnoDB"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO {table_name} (legacy_id, legacy_sexo, legacy_nacimiento) VALUES "
|
||||
"('MYFIX-1', 'F', '1990-01-15'), ('MYFIX-2', 'M', '1985-06-20')"
|
||||
)
|
||||
)
|
||||
yield table_name
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_connects_and_reports_mysql_dialect():
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
connector.test_connection()
|
||||
assert connector.get_dialect() == "mysql"
|
||||
|
||||
|
||||
def test_introspects_real_mysql_schema(legacy_table):
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
assert legacy_table in connector.list_tables()
|
||||
columns = {c.name: c.inferred_type for c in connector.list_columns(legacy_table)}
|
||||
assert columns["legacy_id"] == "string"
|
||||
assert columns["legacy_nacimiento"] == "date"
|
||||
# A native MySQL ENUM column is reflected as a string-like type.
|
||||
assert columns["legacy_sexo"] == "string"
|
||||
|
||||
|
||||
def test_reads_rows_with_column_mapping_against_real_mysql(legacy_table):
|
||||
connector = SqlConnector(MYSQL_TEST_URL)
|
||||
connector.select_table(legacy_table)
|
||||
preview = connector.preview()
|
||||
assert preview.total_rows == 2
|
||||
|
||||
rows = list(
|
||||
connector.read_rows({"legacy_id": "pac_id_hospital", "legacy_sexo": "pac_sexo", "legacy_nacimiento": "pac_fecha_nacimiento"})
|
||||
)
|
||||
by_id = {r["pac_id_hospital"]: r for r in rows}
|
||||
assert by_id["MYFIX-1"]["pac_sexo"] == "F"
|
||||
# Rows come straight from the driver, so a MySQL DATE is a `date`.
|
||||
import datetime as _dt
|
||||
|
||||
assert by_id["MYFIX-1"]["pac_fecha_nacimiento"] == _dt.date(1990, 1, 15)
|
||||
|
||||
|
||||
def test_bad_mysql_credentials_raise_connector_error():
|
||||
bad_url = MYSQL_TEST_URL.rsplit("@", 1)[-1]
|
||||
connector = SqlConnector(f"mysql+pymysql://nobody:wrongpassword@{bad_url}")
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.test_connection()
|
||||
@@ -0,0 +1,327 @@
|
||||
"""Tests for `PdfConnector`. PDF fixtures are generated at test time with
|
||||
reportlab.
|
||||
|
||||
- `build_table_pdf()`: a ruled table with selectable text, for the table
|
||||
detection path.
|
||||
- `build_scanned_like_pdf()` / `build_three_column_pdf()`: text rendered into
|
||||
an image that fills the page, so there is no text layer and only the
|
||||
OCR/region path applies. The three-column variant uses known values per
|
||||
row so alignment can be checked.
|
||||
"""
|
||||
|
||||
import difflib
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
||||
|
||||
# The synthetic "scanned" pages are drawn onto an image this size, then
|
||||
# stretched to fill the whole (letter-size) PDF page, so a normalized
|
||||
# 0..1 bbox computed from these pixel coordinates lines up with the region
|
||||
# regardless of the DPI used to re-render the page for OCR.
|
||||
IMG_W, IMG_H = 900, 1200
|
||||
COL_X = {"name": 40, "age": 340, "city": 620}
|
||||
COL_WIDTH = 260
|
||||
ROW_YS = [120, 320, 520]
|
||||
ROW_HEIGHT = 100
|
||||
|
||||
|
||||
def _font(size: int = 34) -> ImageFont.ImageFont:
|
||||
for path in (
|
||||
"/System/Library/Fonts/Helvetica.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except Exception:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def build_table_pdf(rows: list[tuple[str, str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
||||
data = [["pac_id_hospital", "pac_sexo"], *[[a, b] for a, b in rows]]
|
||||
table = Table(data)
|
||||
table.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 12),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 8),
|
||||
]
|
||||
)
|
||||
)
|
||||
doc.build([table])
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _page_image(lines: list[str]) -> Image.Image:
|
||||
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
y = 40
|
||||
for line in lines:
|
||||
draw.text((40, y), line, fill="black", font=font)
|
||||
y += 60
|
||||
return img
|
||||
|
||||
|
||||
def build_scanned_like_pdf(pages_lines: list[list[str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
for lines in pages_lines:
|
||||
img = _page_image(lines)
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _three_column_page_image(rows: list[tuple[str, str, str]]) -> Image.Image:
|
||||
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
for y, (name, age, city) in zip(ROW_YS, rows):
|
||||
draw.text((COL_X["name"], y), name, fill="black", font=font)
|
||||
draw.text((COL_X["age"], y), age, fill="black", font=font)
|
||||
draw.text((COL_X["city"], y), city, fill="black", font=font)
|
||||
return img
|
||||
|
||||
|
||||
def build_three_column_pdf(pages_rows: list[list[tuple[str, str, str]]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
for rows in pages_rows:
|
||||
img = _three_column_page_image(rows)
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def _norm_bbox(field: str) -> tuple[float, float, float, float]:
|
||||
x0 = COL_X[field]
|
||||
x1 = x0 + COL_WIDTH
|
||||
y0 = ROW_YS[0] - 60
|
||||
y1 = ROW_YS[-1] + ROW_HEIGHT
|
||||
return (x0 / IMG_W, y0 / IMG_H, x1 / IMG_W, y1 / IMG_H)
|
||||
|
||||
|
||||
def _similar(a: str, b: str, threshold: float = 0.7) -> bool:
|
||||
return difflib.SequenceMatcher(None, a.strip().lower(), b.strip().lower()).ratio() >= threshold
|
||||
|
||||
|
||||
ROWS = [("Ana Garcia", "30", "Monterrey"), ("Luis Perez", "40", "Saltillo"), ("Marta Ruiz", "50", "Torreon")]
|
||||
ROWS_PAGE_2 = [("Elena Diaz", "60", "Chihuahua"), ("Jorge Nava", "22", "Durango"), ("Sofia Reyes", "35", "Culiacan")]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Classification
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_has_text_layer_true_for_table_pdf():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
||||
assert connector.has_text_layer() is True
|
||||
|
||||
|
||||
def test_has_text_layer_false_for_scanned_pdf():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
||||
assert connector.has_text_layer() is False
|
||||
|
||||
|
||||
def test_malformed_pdf_bytes_raise_connector_error():
|
||||
with pytest.raises(ConnectorError):
|
||||
PdfConnector(b"not a pdf at all")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Ruled table detection
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_detect_tables_finds_candidate_with_right_shape_on_table_pdf():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M"), ("H-TAB-3", "F")]))
|
||||
candidates = connector.detect_tables()
|
||||
assert len(candidates) == 1
|
||||
candidate = candidates[0]
|
||||
assert candidate.page_number == 1
|
||||
assert len(candidate.grid) == 4 # header + 3 data rows
|
||||
assert len(candidate.grid[0]) == 2
|
||||
assert candidate.grid[0] == ["pac_id_hospital", "pac_sexo"]
|
||||
assert candidate.grid[1][0] == "H-TAB-1"
|
||||
|
||||
|
||||
def test_detect_tables_empty_on_scanned_pdf():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
||||
assert connector.detect_tables() == []
|
||||
|
||||
|
||||
def test_select_table_then_connector_abc_roundtrip():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
||||
candidate = connector.detect_tables()[0]
|
||||
connector.select_table(candidate.page_number, candidate.bbox)
|
||||
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"pac_id_hospital", "pac_sexo"}
|
||||
|
||||
preview = connector.preview(limit=1)
|
||||
assert preview.total_rows == 2
|
||||
assert len(preview.sample_rows) == 1
|
||||
|
||||
rows = list(connector.read_rows({"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}))
|
||||
assert rows == [
|
||||
{"pac_id_hospital": "H-TAB-1", "pac_sexo": "F"},
|
||||
{"pac_id_hospital": "H-TAB-2", "pac_sexo": "M"},
|
||||
]
|
||||
|
||||
|
||||
def test_select_table_out_of_range_page_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.select_table(99, (0, 0, 100, 100))
|
||||
|
||||
|
||||
def test_read_rows_before_resolution_raises_connector_error():
|
||||
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.preview().columns
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Rendering
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_render_page_image_returns_valid_png_with_expected_aspect_ratio():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
||||
png_bytes = connector.render_page_image(1, dpi=150)
|
||||
image = Image.open(io.BytesIO(png_bytes))
|
||||
assert image.format == "PNG"
|
||||
page_w, page_h = letter
|
||||
expected_ratio = page_w / page_h
|
||||
actual_ratio = image.width / image.height
|
||||
assert abs(actual_ratio - expected_ratio) < 0.01
|
||||
|
||||
|
||||
def test_render_page_image_out_of_range_raises_connector_error():
|
||||
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.render_page_image(7)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR / region path
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_single_region_ocr_matches_known_column():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
region = RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name"))
|
||||
result = connector.extract_regions([region])
|
||||
assert len(result["name"]) == 3
|
||||
for actual, (expected, _, _) in zip(result["name"], ROWS):
|
||||
assert _similar(actual, expected), f"{actual!r} not close enough to {expected!r}"
|
||||
|
||||
|
||||
def test_multi_region_row_alignment_matches_ground_truth():
|
||||
"""Three columns OCR'd independently must recombine into the rows they
|
||||
came from."""
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
RegionSpec(target_field="city", page_numbers=[1], bbox=_norm_bbox("city")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
assert len(result["name"]) == len(result["age"]) == len(result["city"]) == 3
|
||||
for i, (expected_name, expected_age, expected_city) in enumerate(ROWS):
|
||||
assert _similar(result["name"][i], expected_name), f"row {i} name mismatch: {result['name'][i]!r}"
|
||||
assert _similar(result["age"][i], expected_age), f"row {i} age mismatch: {result['age'][i]!r}"
|
||||
assert _similar(result["city"][i], expected_city), f"row {i} city mismatch: {result['city'][i]!r}"
|
||||
|
||||
rows = list(
|
||||
connector.read_rows({"name": "name", "age": "age", "city": "city"})
|
||||
)
|
||||
assert len(rows) == 3
|
||||
assert _similar(rows[0]["name"], ROWS[0][0])
|
||||
|
||||
|
||||
def test_two_page_apply_to_every_page_regions():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1, 2], bbox=_norm_bbox("age")),
|
||||
RegionSpec(target_field="city", page_numbers=[1, 2], bbox=_norm_bbox("city")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
all_rows = ROWS + ROWS_PAGE_2
|
||||
assert len(result["name"]) == 6
|
||||
for i, (expected_name, expected_age, expected_city) in enumerate(all_rows):
|
||||
assert _similar(result["name"][i], expected_name), f"row {i}: {result['name']}"
|
||||
assert _similar(result["age"][i], expected_age)
|
||||
assert _similar(result["city"][i], expected_city)
|
||||
|
||||
# page 1's rows precede page 2's, not just correct as a set
|
||||
assert _similar(result["name"][0], ROWS[0][0])
|
||||
assert _similar(result["name"][3], ROWS_PAGE_2[0][0])
|
||||
|
||||
|
||||
def test_regions_on_different_pages_still_give_rectangular_rows():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
result = connector.extract_regions(regions)
|
||||
|
||||
assert len(result["name"]) == len(result["age"]) == 6
|
||||
assert result["age"][3:] == [None, None, None]
|
||||
assert len(list(connector.read_rows({"name": "name", "age": "age"}))) == 6
|
||||
|
||||
|
||||
def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
regions = [
|
||||
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
||||
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
||||
]
|
||||
connector.extract_regions(regions)
|
||||
columns = {c.name for c in connector.preview().columns}
|
||||
assert columns == {"name", "age"}
|
||||
|
||||
|
||||
def test_split_conflict_records_warning_without_dropping_data():
|
||||
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
||||
connector.warnings = []
|
||||
lines = [
|
||||
{"target_field": "a", "y": 100, "height": 20, "text": "A1"},
|
||||
{"target_field": "b", "y": 108, "height": 20, "text": "B1"},
|
||||
{"target_field": "a", "y": 116, "height": 20, "text": "A2"},
|
||||
]
|
||||
rows = connector._cluster_rows(lines, page_number=1)
|
||||
total_values = sum(len(row) for row in rows)
|
||||
assert total_values == 3 # nothing silently dropped
|
||||
assert len(connector.warnings) == 1
|
||||
assert connector.warnings[0].page_number == 1
|
||||
@@ -0,0 +1,53 @@
|
||||
"""The dbt target and environment derived from the deployment's database URLs (`webapi.dbt_manifest`).
|
||||
|
||||
No dbt runs here: only the mapping the entrypoint relies on to compile the manifest against the right engine.
|
||||
No fixtures."""
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.dbt_manifest import dbt_executable, environment, target_of
|
||||
|
||||
URLS_MSSQL = {
|
||||
"cacu": "mssql+pymssql://usuario:clave@servidor:1433/isss_cacu",
|
||||
"cama": "mssql+pymssql://usuario:clave@servidor:1433/isss_cama",
|
||||
"tea": "mssql+pymssql://usuario:clave@servidor:1433/isss_tea",
|
||||
}
|
||||
|
||||
|
||||
def test_sqlite_urls_keep_the_image_manifest():
|
||||
"""SQLite URLs give the `sqlite` target, which the entrypoint treats as "keep the image's manifest". Fails if
|
||||
`target_of` stops recognising SQLite or maps it elsewhere."""
|
||||
urls = {d: f"sqlite:////data/{d}.db" for d in ("cacu", "cama", "tea")}
|
||||
assert target_of(urls) == "sqlite"
|
||||
assert environment(urls, "sqlite")["TEA_DB_PATH"] == "/data/tea.db"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scheme, target", [("mssql+pymssql", "sqlserver"), ("postgresql+psycopg2", "postgres"),
|
||||
("mysql+pymysql", "mysql"), ("mariadb+pymysql", "mysql")])
|
||||
def test_each_engine_maps_to_its_dbt_target(scheme, target):
|
||||
"""Every engine the platform runs on has a dbt target. Fails if a backend name is dropped from `TARGETS`."""
|
||||
urls = {d: f"{scheme}://u:p@h:1/{d}" for d in ("cacu", "cama", "tea")}
|
||||
assert target_of(urls) == target
|
||||
|
||||
|
||||
def test_mixed_engines_are_refused():
|
||||
"""One manifest serves the three domains, so their databases must share an engine. Fails if `target_of`
|
||||
silently picks one of several engines."""
|
||||
urls = {**URLS_MSSQL, "tea": "sqlite:////data/tea.db"}
|
||||
with pytest.raises(ValueError, match="one engine"):
|
||||
target_of(urls)
|
||||
|
||||
|
||||
def test_environment_feeds_profiles_yml():
|
||||
"""The server, port, credentials and each domain's database name reach dbt through the variables
|
||||
`Transformation/profiles.yml` reads. Fails if a variable name changes on either side."""
|
||||
env = environment(URLS_MSSQL, "sqlserver")
|
||||
assert env == {"CACU_DBT_DATABASE": "isss_cacu", "CAMA_DBT_DATABASE": "isss_cama", "TEA_DBT_DATABASE": "isss_tea",
|
||||
"DBT_HOST": "servidor", "DBT_PORT": "1433", "DBT_USER": "usuario", "DBT_PASSWORD": "clave"}
|
||||
|
||||
|
||||
def test_mysql_has_its_own_environment(tmp_path):
|
||||
"""dbt-mysql pins an older dbt-core, so the image keeps it in `.venv-mysql`. Fails if the executable lookup
|
||||
stops distinguishing MySQL."""
|
||||
assert dbt_executable(tmp_path, "mysql") == tmp_path / ".venv-mysql" / "bin" / "dbt"
|
||||
assert dbt_executable(tmp_path, "sqlserver") == tmp_path / ".venv" / "bin" / "dbt"
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Options that let one document source cope with however its rows are
|
||||
stored: columns carried through as field values, a column grouping rows
|
||||
into records, filters that pick which documents feed a target, documents
|
||||
kept as hex or base64 text, unreadable rows, and queries that a derived
|
||||
table can't hold as written.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database) and
|
||||
`documents_table`, a SQLite table built per test whose rows carry two
|
||||
reports of one order, a third report of the same patient under another
|
||||
order, and an unrelated kind of report.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.document import document_bytes
|
||||
from webapi.imports.connectors.sql import SqlConnector, _without_trailing_order_by
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def documents_table(tmp_path):
|
||||
"""Rows 1 and 2 are two reports of order 10 of patient P-1, row 3 is
|
||||
a report of order 11 of the same patient, and row 4 is a report of a
|
||||
kind the CaCu cytology target doesn't take. No body prints the
|
||||
patient id the structured columns hold."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
rows = [
|
||||
(1, "P-1", 10, "Prueba de VPH\nVPH alto riesgo: POSITIVO"),
|
||||
(2, "P-1", 10, "Prueba de VPH\nGenotipo 18: DETECTADO"),
|
||||
(3, "P-1", 11, "Prueba de VPH\nVPH alto riesgo: NEGATIVO"),
|
||||
(4, "P-1", 12, "Informe de otra especialidad\nSin datos de VPH"),
|
||||
]
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, patient INTEGER, order_ref INTEGER, body TEXT)"))
|
||||
for row in rows:
|
||||
conn.execute(text("INSERT INTO docs VALUES (:a, :b, :c, :d)"), dict(zip("abcd", row)))
|
||||
return url
|
||||
|
||||
|
||||
def _payload(url: str, **sql) -> dict:
|
||||
base = {"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"}
|
||||
return {"sql": {**base, **sql}, "target": "cacu.CitologiaCervical"}
|
||||
|
||||
|
||||
def _extract(client, payload: dict) -> dict:
|
||||
response = client.post("/imports/sources/document/extract", json=payload)
|
||||
assert response.status_code == 200, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
def test_group_column_keeps_orders_apart_and_merges_within_one(client, documents_table):
|
||||
"""Rows sharing `group_column` become one record; the same patient's
|
||||
other order stays its own record. Fails if `group_column` stops
|
||||
reaching `record_keys`."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(
|
||||
documents_table,
|
||||
fields={"pac_id_hospital": "patient", "ord_numero_hospital": "order_ref"},
|
||||
group_column="order_ref",
|
||||
)
|
||||
| {"exclude_pattern": "otra especialidad"},
|
||||
)
|
||||
by_key = {record["key"]: record for record in body["records"]}
|
||||
assert set(by_key) == {"10", "11"}
|
||||
assert by_key["10"]["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert by_key["11"]["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert by_key["10"]["fields"]["pac_id_hospital"]["value"] == "P-1"
|
||||
|
||||
|
||||
def test_filters_leave_out_other_kinds_of_report_and_say_so(client, documents_table):
|
||||
"""`include_pattern` keeps only matching documents, matched without
|
||||
regard to case or accents, and the rest are listed as skipped. Fails
|
||||
if the filters stop applying or `skipped` stops reporting them."""
|
||||
body = _extract(
|
||||
client,
|
||||
_payload(documents_table, fields={"pac_id_hospital": "patient"}) | {"include_pattern": "prueba de vph"},
|
||||
)
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["4"]
|
||||
|
||||
|
||||
def test_a_filter_that_matches_nothing_is_an_error(client, documents_table):
|
||||
"""Filtering out every document is reported instead of returning an
|
||||
empty import. Fails if `_extract` stops refusing an empty selection."""
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json=_payload(documents_table) | {"include_pattern": "no aparece"}
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_an_invalid_filter_is_a_bad_request(client, documents_table):
|
||||
"""A filter that isn't a valid regular expression is rejected with a
|
||||
message naming it. Fails if `_compile_filter` lets `re.error` through."""
|
||||
response = client.post("/imports/sources/document/extract", json=_payload(documents_table) | {"exclude_pattern": "("})
|
||||
assert response.status_code == 400 and "exclude_pattern" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_documents_stored_as_hex_or_base64_text_are_decoded():
|
||||
"""A PDF kept in a text column as hex (with or without `0x`) or base64
|
||||
reaches the readers as the PDF itself, and ordinary text stays text.
|
||||
Fails if `document_bytes` stops recognizing either encoding."""
|
||||
pdf = text_pdf([["Expediente: X-1"]])
|
||||
assert document_bytes("0x" + pdf.hex()) == pdf
|
||||
assert document_bytes(pdf.hex().upper()) == pdf
|
||||
assert document_bytes(base64.b64encode(pdf).decode()) == pdf
|
||||
assert document_bytes("Expediente: X-1") == b"Expediente: X-1"
|
||||
|
||||
|
||||
def test_an_unreadable_row_is_skipped_not_fatal(client, tmp_path):
|
||||
"""One corrupt document among readable ones is listed as skipped while
|
||||
the rest are extracted. Fails if a single unreadable row aborts the
|
||||
whole source again."""
|
||||
url = f"sqlite:///{tmp_path / 'mixed.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body BLOB)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (1, :b)"), {"b": b"%PDF-1.4 truncated"})
|
||||
conn.execute(text("INSERT INTO docs VALUES (2, :b)"), {"b": text_pdf([["Expediente: X-2", "VPH alto riesgo: POSITIVO"]])})
|
||||
body = _extract(client, _payload(url))
|
||||
assert [record["key"] for record in body["records"]] == ["X-2"]
|
||||
assert [skipped["document"] for skipped in body["skipped"]] == ["1"]
|
||||
|
||||
|
||||
def test_repeated_key_column_values_still_name_rows_apart(tmp_path):
|
||||
"""Two rows with the same `key_column` value get distinct names, so
|
||||
neither one's fields or pages overwrite the other's. Fails if
|
||||
`_files_from_sql` stops suffixing repeated names."""
|
||||
from webapi.imports.connectors.document import _files_from_sql
|
||||
|
||||
url = f"sqlite:///{tmp_path / 'r.db'}"
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE docs (row_id INTEGER, body TEXT)"))
|
||||
conn.execute(text("INSERT INTO docs VALUES (7, 'uno'), (7, 'dos')"))
|
||||
documents = _files_from_sql({"connection_string": url, "table": "docs", "column": "body", "key_column": "row_id"})
|
||||
assert [name for name, _ in documents.files] == ["7", "7#2"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query,kept",
|
||||
[
|
||||
("SELECT a FROM t ORDER BY a", "SELECT a FROM t"),
|
||||
("SELECT TOP 5 a FROM t ORDER BY a", None),
|
||||
("SELECT a FROM t ORDER BY a OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY", None),
|
||||
("SELECT a, (SELECT TOP 1 b FROM u ORDER BY b) AS x FROM t", None),
|
||||
("SELECT 'ORDER BY' AS s FROM t ORDER BY s", "SELECT 'ORDER BY' AS s FROM t"),
|
||||
],
|
||||
)
|
||||
def test_an_unlimited_trailing_order_by_is_dropped_before_wrapping(query, kept):
|
||||
"""SQL Server refuses `ORDER BY` inside a derived table unless TOP or
|
||||
OFFSET goes with it, so one that only sorts is dropped; one that picks
|
||||
rows, or sits inside a subquery or a string, stays. Fails if
|
||||
`_without_trailing_order_by` drops an `ORDER BY` that chooses rows or
|
||||
keeps one that would make the wrapped query invalid."""
|
||||
assert _without_trailing_order_by(query, "mssql") == (kept or query)
|
||||
|
||||
|
||||
def test_a_named_instance_or_embedded_port_reaches_the_driver():
|
||||
"""`host\\instance` leaves the port unset for the server to resolve,
|
||||
and `host,port` or `host:port` fill it in. Fails if `server_url` stops
|
||||
parsing addresses or goes back to forcing the default port on a named
|
||||
instance."""
|
||||
named = SqlConnector.server_url({"engine": "mssql", "host": "db.example\\INST", "database": "d"})
|
||||
assert (named.host, named.port) == ("db.example\\INST", None)
|
||||
comma = SqlConnector.server_url({"engine": "mssql", "host": "db.example,1500", "database": "d"})
|
||||
assert (comma.host, comma.port) == ("db.example", 1500)
|
||||
colon = SqlConnector.server_url({"engine": "postgresql", "host": "db.example:6543", "database": "d"})
|
||||
assert (colon.host, colon.port) == ("db.example", 6543)
|
||||
@@ -0,0 +1,174 @@
|
||||
"""`DocumentConnector` reading its documents from a SQL source instead of
|
||||
uploaded files: one document per row, read from a column that may hold a
|
||||
PDF (a binary column) or already be plain text, both without a filesystem
|
||||
path in between. Fails if the bridge to `SqlConnector` breaks, or if a
|
||||
plain-text column stops reaching the same field extraction a PDF does.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
REPORT = text_pdf(
|
||||
[["Expediente: SQL-0001", "Fecha de nacimiento: 12/03/1981", "VPH alto riesgo: POSITIVO"]]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sqlite_studies_table(tmp_path):
|
||||
"""A source table with one row per study, its
|
||||
report in a binary column, plus a plain-text variant of the same
|
||||
report in another row, both alongside the row's own key column."""
|
||||
db_path = tmp_path / "estudios.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{"id": "ROW-1", "reporte": REPORT},
|
||||
)
|
||||
conn.execute(
|
||||
text("INSERT INTO estudios (estudio_id, reporte) VALUES (:id, :reporte)"),
|
||||
{
|
||||
"id": "ROW-2",
|
||||
"reporte": "Expediente: SQL-0002\nFecha de nacimiento: 01/01/1990\nVPH alto riesgo: NEGATIVO",
|
||||
},
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def _sql_payload(url: str, **overrides) -> dict:
|
||||
return {"connection_string": url, "table": "estudios", "column": "reporte", "key_column": "estudio_id", **overrides}
|
||||
|
||||
|
||||
def test_a_pdf_column_is_read_like_an_uploaded_pdf(client, sqlite_studies_table):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[first, second] = body["records"]
|
||||
assert first["key"] == "SQL-0001"
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["sources"] == [{"document": "ROW-1", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_a_plain_text_column_reaches_the_same_field_extraction(client, sqlite_studies_table):
|
||||
"""Fails if a source whose bundle is a plain string (not binary at
|
||||
all) stops producing fields, since a source's column may not always
|
||||
be a PDF (`extraction.readers.TextReader`)."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table), "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
[_, second] = body["records"]
|
||||
assert second["key"] == "SQL-0002"
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["sources"] == [{"document": "ROW-2", "page_numbers": [1]}]
|
||||
|
||||
|
||||
def test_sql_sourced_documents_commit_like_uploaded_ones(client, sqlite_studies_table):
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(sqlite_studies_table)},
|
||||
"label": "estudios",
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("SQL-")}
|
||||
assert rows["SQL-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["SQL-0002"].cit_vph_resultado == "NEGATIVO"
|
||||
|
||||
|
||||
def test_column_and_key_column_must_differ(client, sqlite_studies_table):
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"sql": _sql_payload(sqlite_studies_table, key_column="reporte"), "target": "cacu.CitologiaCervical"},
|
||||
)
|
||||
assert response.status_code == 400 and "key_column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_missing_column_is_a_bad_request(client, sqlite_studies_table):
|
||||
payload = _sql_payload(sqlite_studies_table)
|
||||
del payload["column"]
|
||||
response = client.post(
|
||||
"/imports/sources/document/extract", json={"sql": payload, "target": "cacu.CitologiaCervical"}
|
||||
)
|
||||
assert response.status_code == 400 and "column" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_a_caption_outside_the_target_schema_is_committed_through_the_catalog(client, tmp_path, monkeypatch):
|
||||
"""Mixing sources: a field the import schema doesn't name (`Tipo de
|
||||
fijador`) but the project's catalog does still reaches the silver
|
||||
layer through the open-catalog path, alongside the recognized fields
|
||||
`commit_sources` writes as before, when the source asks for it with
|
||||
`catalog_fallback`. Fails if `/imports/commit` stops wiring that second
|
||||
path in, or runs it for a source that didn't ask.
|
||||
Its own table and patient (`SQL-EXTRA-1`), so it doesn't collide with
|
||||
the module's other tests sharing this `client`'s database."""
|
||||
from datetime import date
|
||||
|
||||
from sqlalchemy import create_engine, text as sa_text
|
||||
from sqlmodel import select
|
||||
|
||||
from webapi.orchestration.reference import catalogs as catalogos
|
||||
from core.cacu.paciente.model import Paciente
|
||||
from persistance.cacu import carga_repository, paciente_repository
|
||||
|
||||
monkeypatch.setattr(catalogos, "RAIZ_CATALOGOS", tmp_path)
|
||||
catalog = (
|
||||
'[citologia]\netiqueta = "Citología cervical"\n\n'
|
||||
'[citologia.resultados.tipo_de_fijador]\netiqueta = "Tipo de fijador"\ntipo_valor = "texto"\n'
|
||||
)
|
||||
(tmp_path / "cacu.toml").write_text(catalog, encoding="utf-8")
|
||||
paciente_repository.create(Paciente(pac_id_hospital="SQL-EXTRA-1", pac_fecha_nacimiento=date(1981, 3, 12)))
|
||||
|
||||
db_url = f"sqlite:///{tmp_path / 'estudios_extra.db'}"
|
||||
report = text_pdf([["Expediente: SQL-EXTRA-1", "VPH alto riesgo: POSITIVO", "Tipo de fijador: Formol"]])
|
||||
with create_engine(db_url).begin() as conn:
|
||||
conn.execute(sa_text("CREATE TABLE estudios (estudio_id TEXT, reporte BLOB)"))
|
||||
conn.execute(sa_text("INSERT INTO estudios (estudio_id, reporte) VALUES ('ROW-1', :r)"), {"r": report})
|
||||
|
||||
source = {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"sql": _sql_payload(db_url), "estudio_id": "citologia"},
|
||||
"label": "estudios_extra",
|
||||
}
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1, body
|
||||
assert not [r for r in body.get("catalog_fallback", []) if r["label"] == "estudios_extra"]
|
||||
|
||||
body = client.post("/imports/commit", json={"sources": [{**source, "catalog_fallback": True}], "on_conflict": "upsert"}).get_json()
|
||||
[fallback] = [r for r in body["catalog_fallback"] if r["label"] == "estudios_extra"]
|
||||
assert (fallback["records_written"], fallback["fields_matched"], fallback["fields_minted"]) == (1, 1, 0)
|
||||
assert (tmp_path / "cacu.toml").read_text(encoding="utf-8") == catalog
|
||||
|
||||
with carga_repository.open_session() as sesion:
|
||||
[written] = list(
|
||||
sesion.exec(select(carga_repository.observacion).where(carga_repository.observacion.pac_id.in_(
|
||||
select(Paciente.pac_id).where(Paciente.pac_id_hospital == "SQL-EXTRA-1")
|
||||
)))
|
||||
)
|
||||
assert written.resultado_id == "citologia.tipo_de_fijador" and written.valor_texto == "Formol"
|
||||
@@ -0,0 +1,118 @@
|
||||
"""What this module covers: the cycle's `analyze_eeg` step (TEA's EEG analysis before the silver load) and how the
|
||||
cycle gets its analysis (`webapi.orchestration.eeg`).
|
||||
|
||||
Fixtures: `tea_base`, a migrated TEA database (`base_de`) holding one patient (`pac_id` 1, born 2024-01-01) and one
|
||||
EEG `e-1` with an EDF and no analysis; `fake_analysis`, an analysis that writes sleep and 21 channels on `e-1`, as
|
||||
the real one would, and notes whether a silver load existed when it ran.
|
||||
"""
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from models.eeg_analysis import Summary
|
||||
from webapi.orchestration import cycle, run, steps_of
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.eeg import CLUSTER_ENV, live_eeg_analysis
|
||||
|
||||
|
||||
def _rows(sesion):
|
||||
from core.tea.models import Eeg, Pacientes
|
||||
|
||||
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2024, 1, 1)))
|
||||
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_id_registro_laboratorio="LAB-1", eeg_fecha_estudio=date(2025, 6, 1),
|
||||
eeg_estudio=b"edf"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tea_base(tmp_path):
|
||||
"""Patient 1 and EEG `e-1` (an EDF, nothing analysed) in a migrated TEA database."""
|
||||
from conftest import base_de
|
||||
|
||||
base = base_de("tea", tmp_path, datos=_rows)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_analysis(tea_base):
|
||||
"""Writes `eeg_con_sueno` 1 and `eeg_canales` 21 on `e-1`; `calls` records the loads that existed at each call."""
|
||||
from core.tea.indicadores.models import Carga
|
||||
from core.tea.models import Eeg
|
||||
|
||||
calls = []
|
||||
|
||||
def analysis():
|
||||
with Session(tea_base.motor) as sesion:
|
||||
calls.append(len(sesion.exec(select(Carga)).all()))
|
||||
eeg = sesion.get(Eeg, "e-1")
|
||||
eeg.eeg_con_sueno, eeg.eeg_canales = 1, 21
|
||||
sesion.add(eeg)
|
||||
sesion.commit()
|
||||
return Summary(pending=1, valid=1, not_valid=0, failed=0)
|
||||
|
||||
analysis.calls = calls
|
||||
return analysis
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_the_eeg_analysis_runs_before_the_silver_load(proyecto):
|
||||
"""Pins down: `load` depends on `analyze_eeg`, which needs only the migrated schema.
|
||||
|
||||
Fails if `load` stops waiting for the analysis (the cycle would load an EEG's old analysis and pick the new one up
|
||||
only on the next cycle), or the analysis starts waiting for steps it doesn't need.
|
||||
"""
|
||||
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
|
||||
deps = {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
|
||||
assert "analyze_eeg" in deps["load"]
|
||||
assert deps["analyze_eeg"] == {"migrate"}
|
||||
order = steps_of(proyecto)
|
||||
assert order.index("analyze_eeg") < order.index("load")
|
||||
|
||||
|
||||
def test_without_an_analysis_the_step_does_nothing():
|
||||
"""Pins down: a context without `eeg_analysis` (CaCu, CaMa, the tests' cycles) makes the step a no-op.
|
||||
|
||||
Fails if the step starts running an analysis nobody configured.
|
||||
"""
|
||||
pasos = run(Context("cacu", 2025, 2025), only=["analyze_eeg"])
|
||||
assert [(p.name, p.summary) for p in pasos] == [("analyze_eeg", {})]
|
||||
|
||||
|
||||
def test_what_the_analysis_writes_is_loaded_by_the_same_cycle(tea_base, fake_analysis):
|
||||
"""Pins down: the cycle runs the analysis once, before any silver load, and `load` then carries what it wrote
|
||||
into the EEG's silver observations.
|
||||
|
||||
Fails if the analysis runs after `load` or more than once, or its summary stops being the step's.
|
||||
"""
|
||||
from core.tea.indicadores.models import Observacion, Procedimiento
|
||||
|
||||
pasos = tea_base.run("analyze_eeg", "catalogs", "load", eeg_analysis=fake_analysis)
|
||||
assert pasos["analyze_eeg"] == {"pending": 1, "valid": 1, "not_valid": 0, "failed": 0}
|
||||
assert fake_analysis.calls == [0]
|
||||
with Session(tea_base.motor) as sesion:
|
||||
toma = sesion.exec(select(Procedimiento).where(Procedimiento.estudio_id == "eeg",
|
||||
Procedimiento.clase == "toma")).one()
|
||||
valores = {o.resultado_id: o.valor_numerico for o in sesion.exec(
|
||||
select(Observacion).where(Observacion.procedimiento_id == toma.procedimiento_id))}
|
||||
assert valores["eeg.canales"] == 21
|
||||
|
||||
|
||||
def test_only_tea_has_an_analysis_and_it_can_be_turned_off(monkeypatch):
|
||||
"""Pins down: TEA's cycle gets the analysis, with the cluster `EEG_ANALYSIS_CLUSTER` names; the other domains
|
||||
get none, `off` leaves it out, and an unknown value is refused.
|
||||
|
||||
Fails if another domain starts analysing EEGs, `off` stops leaving the analysis out, or a mistyped cluster is
|
||||
silently taken as the default.
|
||||
"""
|
||||
monkeypatch.delenv(CLUSTER_ENV, raising=False)
|
||||
assert live_eeg_analysis("tea").keywords == {"cluster": "auto"}
|
||||
assert live_eeg_analysis("cacu") is None
|
||||
monkeypatch.setenv(CLUSTER_ENV, "sync")
|
||||
assert live_eeg_analysis("tea").keywords == {"cluster": "sync"}
|
||||
monkeypatch.setenv(CLUSTER_ENV, "off")
|
||||
assert live_eeg_analysis("tea") is None
|
||||
monkeypatch.setenv(CLUSTER_ENV, "everywhere")
|
||||
with pytest.raises(ValueError, match=CLUSTER_ENV):
|
||||
live_eeg_analysis("tea")
|
||||
@@ -0,0 +1,178 @@
|
||||
"""What this module covers: catalog results read from a staging row's text (`silver.extracted`). The catalog's
|
||||
`etiquetas_fuente` and `alias` checked when it's read; a report's text, a PDF's text layer and a note turned into
|
||||
codes, numbers and their sources; a spelling the catalog doesn't know kept as text and turned into a code by a
|
||||
catalog change alone; and CaMa's load putting them in silver and dbt's timeline.
|
||||
|
||||
Fixtures: `catalogo_en`, a copy of CaMa's catalog in `tmp_path` that the catalog functions read instead of Core's;
|
||||
`cargada`, the CaMa fixture database (`staging/cama.py`: H-003's texts and pathology PDF, H-101's unknown density)
|
||||
loaded, with dbt's views when `DBT_MANIFEST` is set.
|
||||
"""
|
||||
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from staging.cama import INFORME_DE_PATOLOGIA, pdf_de
|
||||
from webapi.orchestration.reference import catalogs
|
||||
from webapi.orchestration.reference.catalogs import CatalogoInvalido, catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.silver import cama
|
||||
from webapi.orchestration.silver.extracted import DesdeTexto
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
|
||||
DENSIDAD = """
|
||||
[mastografia]
|
||||
etiqueta = "Mastografía"
|
||||
|
||||
[mastografia.resultados.densidad]
|
||||
etiqueta = "Densidad"
|
||||
tipo_valor = "codigo"
|
||||
etiquetas_fuente = ["Densidad mamaria"]
|
||||
valores = [
|
||||
{ valor = "C", etiqueta = "Heterogéneamente densa", alias = ["Tipo C"] },
|
||||
{ valor = "D", etiqueta = "Extremadamente densa", alias = ["Tipo D"] },
|
||||
]
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def catalogo_en(tmp_path, monkeypatch):
|
||||
"""Writes a catalog for `cama` in `tmp_path` and points the catalog functions at it. Returns a writer."""
|
||||
ruta = tmp_path / "cama.toml"
|
||||
monkeypatch.setattr(catalogs, "ruta_de_catalogo", lambda proyecto: ruta)
|
||||
|
||||
def escribir(contenido: str):
|
||||
ruta.write_text(contenido, encoding="utf-8")
|
||||
return ruta
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proyecto():
|
||||
return "cama"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cargada(base):
|
||||
pasos = ("catalogs", "load", "event_models") if os.environ.get("DBT_MANIFEST") else ("catalogs", "load")
|
||||
base.run(*pasos)
|
||||
return base
|
||||
|
||||
|
||||
def observaciones(base, resultado_prefijo: str) -> dict[str, tuple]:
|
||||
"""`resultado_id` -> (valor_id, valor_numerico, valor_fuente) of the observations whose result starts so."""
|
||||
with base.motor.connect() as con:
|
||||
filas = con.execute(text(
|
||||
"SELECT resultado_id, valor_id, valor_numerico, valor_fuente FROM observacion_clinica "
|
||||
"WHERE resultado_id LIKE :p AND (valor_id IS NOT NULL OR valor_numerico IS NOT NULL OR valor_fuente IS NOT NULL)"
|
||||
), {"p": resultado_prefijo + "%"}).all()
|
||||
return {f.resultado_id: (f.valor_id, f.valor_numerico, f.valor_fuente) for f in filas}
|
||||
|
||||
|
||||
# --- the catalog ---
|
||||
|
||||
def test_the_catalog_lists_cama_s_extractable_results_as_provisional():
|
||||
"""Pins down: every CaMa result with captions is extractable and marked provisional, and the catalog still
|
||||
loads with them. Fails if `resultados_extraibles` drops a result or the new keys break `catalogo_desde_toml`."""
|
||||
extraibles = catalogs.resultados_extraibles("cama")
|
||||
assert set(extraibles) >= {"mastografia.densidad", "biopsia.her2", "nota_medica.estadio_clinico"}
|
||||
assert all(e.provisional for e in extraibles.values())
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo("cama"), tablas=tablas_de("cama"))
|
||||
assert {r.resultado_id for r in catalogo.resultados} >= set(extraibles)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("cambio, error", [
|
||||
(('alias = ["Tipo D"]', 'alias = ["Tipo C"]'), "se escribe igual"),
|
||||
(('etiquetas_fuente = ["Densidad mamaria"]', 'etiquetas_fuente = []'), "lista de textos"),
|
||||
(('etiquetas_fuente = ["Densidad mamaria"]\n', ''), "solo sirven con etiquetas_fuente"),
|
||||
])
|
||||
def test_an_ambiguous_or_incomplete_mapping_is_rejected(catalogo_en, cambio, error):
|
||||
"""Pins down: one spelling on two values, empty captions, or aliases without captions stop the catalog from
|
||||
loading. Fails if a check is dropped and an alias could turn into either of two codes."""
|
||||
ruta = catalogo_en(DENSIDAD.replace(*cambio))
|
||||
with pytest.raises(CatalogoInvalido, match=error):
|
||||
catalogo_desde_toml(ruta, tablas=tablas_de("cama"))
|
||||
|
||||
|
||||
# --- reading text ---
|
||||
|
||||
def test_a_report_s_text_gives_codes_with_their_spelling_and_numbers():
|
||||
"""Pins down: a caption followed by a known spelling gives its code and that spelling as source; a number
|
||||
after its caption gives the number. Fails if the catalog's aliases stop reaching Extraction's field specs."""
|
||||
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(
|
||||
mast_interpretacion="Densidad mamaria: heterogéneamente densas (C).\nTamaño de la lesión: 14 mm."))
|
||||
assert leido == {"mastografia.densidad": ("C", "heterogéneamente densas"), "mastografia.tamano_lesion_mm": (14.0, None)}
|
||||
|
||||
|
||||
def test_an_unknown_spelling_is_kept_as_its_source_without_a_code():
|
||||
"""Pins down: what follows a caption that matches no alias is kept as source text, with no code. Fails if it's
|
||||
dropped (it couldn't be found and mapped later) or forced into a code."""
|
||||
leido = cama.DE_LA_INTERPRETACION.leer(SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E"))
|
||||
assert leido["mastografia.densidad"] == (None, "tipo E")
|
||||
|
||||
|
||||
def test_a_stage_is_found_in_a_note_without_a_caption():
|
||||
"""Pins down: a result marked `buscar_en_texto` is found as a mention in narrative text. Fails if the flag
|
||||
stops reaching `scan_free_text`."""
|
||||
leido = cama.DE_LA_NOTA.leer(SimpleNamespace(
|
||||
nm_diagnostico_texto="Carcinoma de mama izquierda, estadio clínico IIA (T2N0M0)", nm_pronostico=None))
|
||||
assert leido["nota_medica.estadio_clinico"] == ("EIIA", "estadio clínico IIA")
|
||||
|
||||
|
||||
def test_a_pathology_pdf_s_text_layer_gives_its_results():
|
||||
"""Pins down: a PDF's text layer is read without OCR and every result on it comes out. Fails if bytes stop
|
||||
going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor."""
|
||||
leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1])))
|
||||
assert {r: v for r, (v, _) in leido.items()} == {
|
||||
"biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2",
|
||||
"biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0,
|
||||
"biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0,
|
||||
"biopsia.her2": "H3", "biopsia.ki67_pct": 25.0,
|
||||
}
|
||||
|
||||
|
||||
def test_no_text_gives_no_values():
|
||||
"""Pins down: a row without text (or a PDF that can't be read) gives every result empty. Fails if an empty
|
||||
text or broken bytes raise during a load."""
|
||||
assert set(cama.DE_LA_NOTA.leer(SimpleNamespace(nm_diagnostico_texto=None, nm_pronostico=None)).values()) == {(None, None)}
|
||||
assert set(cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=b"not a pdf")).values()) == {(None, None)}
|
||||
|
||||
|
||||
def test_adding_an_alias_maps_the_same_text_on_the_next_read(catalogo_en):
|
||||
"""Pins down: an unknown spelling becomes a code by adding it to the catalog, with nothing else changed. Fails
|
||||
if the mapping is cached across catalog reads or lives anywhere but the catalog."""
|
||||
fila = SimpleNamespace(mast_interpretacion="Densidad mamaria: tipo E")
|
||||
catalogo_en(DENSIDAD)
|
||||
antes = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
|
||||
catalogo_en(DENSIDAD.replace('alias = ["Tipo D"]', 'alias = ["Tipo D", "Tipo E"]'))
|
||||
despues = DesdeTexto("cama", ("mastografia.densidad",), texto=lambda f: f.mast_interpretacion).leer(fila)
|
||||
assert antes["mastografia.densidad"] == (None, "tipo E")
|
||||
assert despues["mastografia.densidad"] == ("D", "tipo E")
|
||||
|
||||
|
||||
# --- the load ---
|
||||
|
||||
def test_the_load_puts_the_extracted_results_in_silver(cargada):
|
||||
"""Pins down: CaMa's load writes the results read from the interpretation, the pathology PDF and the note, and
|
||||
an unknown spelling as an out-of-catalog source. Fails if `cama.DESDE_STAGING` stops wiring a `DesdeTexto`."""
|
||||
with cargada.motor.connect() as con:
|
||||
densidades = sorted(con.execute(text(
|
||||
"SELECT coalesce(valor_id, '?') || ':' || valor_fuente FROM observacion_clinica "
|
||||
"WHERE resultado_id = 'mastografia.densidad' AND valor_fuente IS NOT NULL")).scalars())
|
||||
assert densidades == ["?:tipo E", "C:heterogéneamente densas"]
|
||||
assert observaciones(cargada, "biopsia.her2") == {"biopsia.her2": ("H3", None, "3+")}
|
||||
assert observaciones(cargada, "biopsia.ki67_pct") == {"biopsia.ki67_pct": (None, 25.0, None)}
|
||||
assert observaciones(cargada, "nota_medica.estadio_clinico") == {
|
||||
"nota_medica.estadio_clinico": ("EIIA", None, "estadio clínico IIA")}
|
||||
|
||||
|
||||
def test_the_timeline_carries_the_extracted_results(cargada):
|
||||
"""Pins down: the timeline declares the new results, so H-003's stage, receptors and density are rows of it.
|
||||
Fails if a source line is missing from `cama_linea_de_tiempo.yml`."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
filas = cargada.ctx.repos.silver.timeline.read()
|
||||
valores = {(f["tipo"], f["valor_codigo"] or f["valor_numerico"]) for f in filas}
|
||||
assert {("estadio_clinico", "EIIA"), ("her2", "H3"), ("receptor_estrogeno_pct", 90.0),
|
||||
("densidad_mamaria", "C"), ("densidad_mamaria", "tipo E")} <= valores
|
||||
@@ -0,0 +1,109 @@
|
||||
"""What this module covers: `GET /cacu/fhir/RiskAssessment?subject=Patient/<pac_id>` (`webapi.fhir.cacu`): a patient's
|
||||
current risk as a FHIR R4 `RiskAssessment` in a `searchset` Bundle, as TEA's patient resources are served: the
|
||||
resource's shape (status, subject, method, one prediction per horizon from the risk's index date, the interval
|
||||
extension), the `simulado` tag, an empty Bundle without a confirmed batch, a 400 without `subject`, and the
|
||||
`CapabilityStatement` entry. The reads behind it are Persistance's, tested there.
|
||||
|
||||
Fixtures: `client`, the app in DEV (`DEV_REVISION`, so the patient routes exist) over the kit's CaCu demonstration
|
||||
database (`conftest.cliente_de`); needs `DBT_MANIFEST`. `seeded`: a surveillance build with two of its patients, one
|
||||
with a confirmed batch whose risks have the model's index date.
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
MODEL_INDEX = date(2026, 6, 1)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "pruebas")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def seeded(client):
|
||||
"""Two demo patients in a new surveillance build; the first has a confirmed batch with risks at 0 and 3 years, the
|
||||
3-year one with an interval. Returns (scored patient, member without risks)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
scored, unscored = [p.pac_id for p in cacu.persona_repository.list(limit=2)]
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="fhir-risk", marco_sha="m",
|
||||
n_miembros=2, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add_all([CohorteMiembro(armado_id=build.armado_id, pac_id=p, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(p))
|
||||
for p in (scored, unscored)])
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
batch, _ = cacu.cohort_repository.save_batch(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_pim", "modelo_version": "3", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_mas", [(scored, MODEL_INDEX, 3.0, 0.21, 0.15, 0.28), (scored, MODEL_INDEX, 0.0, 0.08, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.cohort_repository.change_state(batch, "final", "revisado")
|
||||
return scored, unscored, batch
|
||||
|
||||
|
||||
def test_a_scored_patient_gets_her_risk_assessment(client, seeded):
|
||||
"""Pins down the resource: a `searchset` of one `RiskAssessment`, `final`, about `Patient/<pac_id>`, evaluated
|
||||
when the batch was, by the registered model and version, with one prediction per horizon whose period starts at
|
||||
the risk's index date (the model's, not the member's) and ends a horizon later; the interval in its extension;
|
||||
tagged `simulado`. Fails if a field moves out of FHIR's shape or the period is anchored elsewhere."""
|
||||
scored, _, batch = seeded
|
||||
|
||||
response = client.get(f"/cacu/fhir/RiskAssessment?subject=Patient/{scored}")
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
|
||||
bundle = response.get_json()
|
||||
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 1)
|
||||
risk = bundle["entry"][0]["resource"]
|
||||
assert bundle["entry"][0]["fullUrl"].endswith(f"/cacu/fhir/RiskAssessment/{batch}-{scored}")
|
||||
assert (risk["resourceType"], risk["status"], risk["subject"]) == ("RiskAssessment", "final", {"reference": f"Patient/{scored}"})
|
||||
assert risk["occurrenceDateTime"] == "2026-10-01T00:00:00Z"
|
||||
assert risk["method"]["coding"][0]["code"] == "cacu-cin2_pim" and risk["method"]["coding"][0]["version"] == "3"
|
||||
assert [p["outcome"]["coding"][0]["code"] for p in risk["prediction"]] == ["cin2_mas", "cin2_mas"]
|
||||
assert [(p["probabilityDecimal"], p["whenPeriod"]) for p in risk["prediction"]] == [
|
||||
(0.08, {"start": "2026-06-01", "end": "2026-06-01"}), (0.21, {"start": "2026-06-01", "end": "2029-06-01"})]
|
||||
assert "extension" not in risk["prediction"][0]
|
||||
assert risk["prediction"][1]["extension"][0]["valueRange"] == {"low": {"value": 0.15}, "high": {"value": 0.28}}
|
||||
assert any(t["code"] == "simulado" for t in risk["meta"]["tag"])
|
||||
|
||||
|
||||
def test_without_a_confirmed_batch_the_bundle_is_empty(client, seeded):
|
||||
"""Pins down: a member with no confirmed risk, and an unknown patient, get an empty searchset, not an error.
|
||||
Fails if a missing risk becomes a 404 or a resource with no predictions."""
|
||||
_, unscored, _ = seeded
|
||||
|
||||
for subject in (f"Patient/{unscored}", "Patient/987654321"):
|
||||
bundle = client.get(f"/cacu/fhir/RiskAssessment?subject={subject}").get_json()
|
||||
assert (bundle["total"], bundle.get("entry", [])) == (0, []) # R4B drops an empty `entry`
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["", "?subject=Patient/abc", "?subject=Group/1"])
|
||||
def test_the_risk_is_searched_by_patient(client, query):
|
||||
"""Pins down: without `subject=Patient/<pac_id>` the answer is a 400 `OperationOutcome`. Fails if the route lists
|
||||
every patient's risk."""
|
||||
response = client.get(f"/cacu/fhir/RiskAssessment{query}")
|
||||
|
||||
assert response.status_code == 400 and response.get_json()["resourceType"] == "OperationOutcome"
|
||||
|
||||
|
||||
def test_the_capability_statement_declares_the_search(client):
|
||||
"""Pins down: CaCu's CapabilityStatement lists `RiskAssessment` with its `subject` search; TEA's patient
|
||||
resources stay TEA's. Fails if the route exists without being declared, or the other way round."""
|
||||
resources = client.get("/cacu/fhir/metadata").get_json()["rest"][0]["resource"]
|
||||
risk = [r for r in resources if r["type"] == "RiskAssessment"]
|
||||
|
||||
assert risk and risk[0]["searchParam"] == [{"name": "subject", "type": "reference"}]
|
||||
assert not [r for r in resources if r["type"] == "EpisodeOfCare"]
|
||||
@@ -1,152 +0,0 @@
|
||||
"""Phase 3.5 gate: one silver, two doors. What one platform serves as FHIR, another takes
|
||||
through its FHIR door, as a standard hospital would send it, and places the same silver: the
|
||||
same values of the same studies of the same patients, and so the same indicators. The
|
||||
receiving side is configuration only: a pipeline whose fhir nodes read the sender's inbox."""
|
||||
|
||||
import json
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
from fhir_checks import pages
|
||||
from test_conectar import ok, run, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||
PIPELINES = ROOT / "tests" / "fixtures" / "pipelines"
|
||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||
SILVER = """
|
||||
select i.value, o.study, o.instance, o.field,
|
||||
o.value_text, o.value_num, o.value_bool, o.value_date
|
||||
from silver.observation as o
|
||||
join silver.person_identifier as i on i.person_id = o.person_id
|
||||
where i.system not like '%curp' and i.system not like '%nss'
|
||||
"""
|
||||
|
||||
|
||||
def _served(api) -> list[dict]:
|
||||
"""Everything the CaCu FHIR base serves about every patient."""
|
||||
patients = [e["resource"] for b in pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
||||
for e in b.get("entry", [])] # fmt: skip
|
||||
found = list(patients)
|
||||
ids = [p["id"] for p in patients]
|
||||
for kind in ("DiagnosticReport", "Observation", "Encounter"):
|
||||
for i in range(0, len(ids), 50):
|
||||
subject = ",".join(f"Patient/{p}" for p in ids[i : i + 50])
|
||||
for b in pages(api, f"/cacu/fhir/{kind}", {"subject": subject, "_count": 200}):
|
||||
found += [e["resource"] for e in b.get("entry", [])]
|
||||
return found
|
||||
|
||||
|
||||
def _silver(platform) -> set[tuple]:
|
||||
"""Every value silver holds, by patient record number, as Python values (each engine
|
||||
returns booleans and dates its own way)."""
|
||||
|
||||
def plain(row) -> tuple:
|
||||
number, study, instance, field, text, num, flag, day = row
|
||||
num = None if num is None else float(num)
|
||||
flag = None if flag is None else bool(flag)
|
||||
return number, study, instance, field, text, num, flag, day and str(day)[:10]
|
||||
|
||||
return {plain(r) for r in platform.query(SILVER)}
|
||||
|
||||
|
||||
def test_what_one_platform_serves_another_places_through_the_fhir_door(
|
||||
api, platform, fresh_api, fresh_platform
|
||||
):
|
||||
# The sending side: the CaCu hospital, loaded through its drawn pipeline.
|
||||
put_concept_map(api, "hospital_cacu")
|
||||
drawn = (PIPELINES / "hospital_cacu.json").read_text().replace("{hospital}", str(HOSPITAL))
|
||||
ok(api.put("/ingest/pipelines/cacu", json=json.loads(drawn)))
|
||||
run(api, "cacu")
|
||||
sent = _served(api)
|
||||
bundle = {"resourceType": "Bundle", "type": "batch", "entry": [
|
||||
{"resource": r, "request": {"method": "PUT", "url": f"{r['resourceType']}/{r['id']}"}}
|
||||
for r in sent
|
||||
]} # fmt: skip
|
||||
|
||||
# The receiving side: what it sends goes nowhere without a pipeline to place it.
|
||||
door = "/cacu/fhir?sender=hospital"
|
||||
assert fresh_api.post(door, json=bundle).status_code == 404
|
||||
receiving = (PIPELINES / "fhir_door.json").read_text().replace("{sender}", "hospital")
|
||||
ok(fresh_api.put("/ingest/pipelines/hospital", json=json.loads(receiving)))
|
||||
assert (
|
||||
fresh_api.post(door, json={"resourceType": "Bundle", "type": "searchset"}).status_code
|
||||
== 422
|
||||
)
|
||||
answer = fresh_api.post(door, json=bundle)
|
||||
assert answer.status_code == 202, answer.text
|
||||
assert answer.headers["content-type"].startswith("application/fhir+json")
|
||||
assert len(answer.json()["entry"]) == len(sent)
|
||||
wait_for(fresh_api, answer.headers["location"].rsplit("/", 1)[1])
|
||||
|
||||
# One silver: every value of every study instance, by patient record number.
|
||||
placed = _silver(platform)
|
||||
assert len(placed) > 1000 and {r[1] for r in placed} >= {"cervical_cytology", "clinical_note"}
|
||||
assert _silver(fresh_platform) == placed
|
||||
assert fresh_platform.count("silver.person") == platform.count("silver.person")
|
||||
|
||||
# And so the same indicators, every measure, every semester.
|
||||
(measures,) = pages(api, "/cacu/fhir/Measure")
|
||||
for measure in [e["resource"]["id"] for e in measures["entry"]]:
|
||||
params = {"measure": measure, "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": "2026-11-25"} # fmt: skip
|
||||
ours, theirs = (
|
||||
[e["resource"]["group"] for b in pages(a, "/cacu/fhir/MeasureReport", params)
|
||||
for e in b["entry"]]
|
||||
for a in (api, fresh_api)
|
||||
) # fmt: skip
|
||||
assert ours == theirs, measure
|
||||
|
||||
|
||||
# The same laboratory, a year later: it renamed its result column and writes its results in
|
||||
# words. Nothing in code changes: the drawing names the new column, the ConceptMap gets the
|
||||
# new spellings.
|
||||
RENAMED = {"NORMAL": "Negativo para lesión", "LIEBG": "Lesión de bajo grado",
|
||||
"LIEAG": "Lesión de alto grado"} # fmt: skip
|
||||
|
||||
|
||||
def test_a_new_label_is_a_concept_map_row_not_code(api, platform, fresh_api, fresh_platform,
|
||||
tmp_path): # fmt: skip
|
||||
put_concept_map(api, "hospital_cacu")
|
||||
drawn = (PIPELINES / "hospital_cacu.json").read_text()
|
||||
ok(
|
||||
api.put(
|
||||
"/ingest/pipelines/cacu", json=json.loads(drawn.replace("{hospital}", str(HOSPITAL)))
|
||||
)
|
||||
)
|
||||
run(api, "cacu")
|
||||
|
||||
(tmp_path / "lab").mkdir()
|
||||
for name in ("hospital_cacu.db",):
|
||||
(tmp_path / "lab" / name).write_bytes((HOSPITAL / name).read_bytes())
|
||||
with sqlite3.connect(tmp_path / "lab" / "hospital_cacu.db") as con:
|
||||
con.execute(
|
||||
"alter table citologiacervical rename column cit_celulas_escamosas to PAP_RESULT"
|
||||
)
|
||||
for old, new in RENAMED.items():
|
||||
con.execute(
|
||||
"update citologiacervical set PAP_RESULT = ? where PAP_RESULT = ?", (new, old)
|
||||
)
|
||||
codes = json.loads(
|
||||
(ROOT / "tests" / "fixtures" / "concept_maps" / "hospital_cacu.json").read_text()
|
||||
)
|
||||
bethesda = next(g for g in codes["group"] if g["target"].endswith("/bethesda"))
|
||||
bethesda["element"] += [{"code": new, "target": [{"code": {"NORMAL": "NILM", "LIEBG": "LSIL",
|
||||
"LIEAG": "HSIL"}[old], "equivalence": "equivalent"}]}
|
||||
for old, new in RENAMED.items()] # fmt: skip
|
||||
ok(fresh_api.put("/ingest/concept-maps/hospital_cacu", json=codes))
|
||||
# The source names the database's column; the map names it as bronze holds it (the
|
||||
# canvas preview shows dlt's normalised names: PAP_RESULT is pap_result).
|
||||
renamed = drawn.replace(
|
||||
'"cit_celulas_escamosas", "cit_vph_resultado"', '"PAP_RESULT", "cit_vph_resultado"'
|
||||
)
|
||||
renamed = renamed.replace('"result": "cit_celulas_escamosas"', '"result": "pap_result"')
|
||||
renamed = renamed.replace("{hospital}", str(tmp_path / "lab"))
|
||||
ok(fresh_api.put("/ingest/pipelines/cacu", json=json.loads(renamed)))
|
||||
run(fresh_api, "cacu")
|
||||
|
||||
placed = _silver(platform)
|
||||
assert any(r[3] == "result" and r[4] == "NILM" for r in placed)
|
||||
assert _silver(fresh_platform) == placed
|
||||
@@ -0,0 +1,60 @@
|
||||
"""What this module covers: the FHIR R4 measure routes of `webapi.fhir` for CaCu and CaMa: every `Measure` of the
|
||||
domain and one `MeasureReport` of each, checked against FHIR's models (`fhir.resources`, R4B), and the patient routes
|
||||
absent outside TEA.
|
||||
|
||||
Fixtures: `domain_client`, a Flask app with only the domain's FHIR blueprint over its fixture database loaded through
|
||||
the cycle up to `event_models` (`conftest.base_de`); needs `DBT_MANIFEST`.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fhir.resources.R4B import get_fhir_model_class
|
||||
from flask import Flask
|
||||
|
||||
from conftest import base_de
|
||||
from webapi.fhir import fhir_blueprint
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama"])
|
||||
def domain_client(request, tmp_path_factory):
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
if not manifest:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base = base_de(request.param, tmp_path_factory.mktemp(request.param))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(fhir_blueprint(request.param, base.dominio, Path(manifest), with_patients=True),
|
||||
url_prefix=f"/{request.param}/fhir")
|
||||
yield request.param, app.test_client()
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def valid(resource: dict) -> dict:
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
for item in resource.get("entry", ()):
|
||||
get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"])
|
||||
return resource
|
||||
|
||||
|
||||
def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
|
||||
"""Pins down: each Measure of the domain, and its report for 2025-S1, validate as FHIR R4 resources, compositions
|
||||
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
|
||||
domain, client = domain_client
|
||||
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
|
||||
assert measures["total"] == {"cacu": 7, "cama": 11}[domain]
|
||||
for item in measures["entry"]:
|
||||
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1")
|
||||
assert response.status_code in (200, 409), response.get_json()
|
||||
valid(response.get_json())
|
||||
|
||||
|
||||
def test_the_patient_routes_are_tea_s_only(domain_client):
|
||||
"""Pins down: `EpisodeOfCare` exists only on TEA's endpoint; elsewhere it's an OperationOutcome 404. Fails if
|
||||
the patient routes register for another domain."""
|
||||
domain, client = domain_client
|
||||
response = client.get(f"/{domain}/fhir/EpisodeOfCare")
|
||||
assert response.status_code == 404 and valid(response.get_json())["resourceType"] == "OperationOutcome"
|
||||
@@ -0,0 +1,330 @@
|
||||
"""What this module covers: TEA's FHIR R4 endpoint (`/tea/fhir/`): the capability statement, the measures as
|
||||
`Measure` and their answers as `MeasureReport` (one period and several), the follow-up list as `EpisodeOfCare` with
|
||||
its filters, paging and includes, the EEG summary and the patient summary; and that the alterations stay hidden until
|
||||
validated. Every resource is checked against FHIR's models (`fhir.resources`, R4B, which keeps R4's shape for these
|
||||
resources).
|
||||
|
||||
Fixtures: `client`, a Flask app in DEV (`DEV_REVISION`, so the patient routes exist) over TEA's fixture database
|
||||
(`staging.tea`) loaded through the cycle up to `event_models`; needs `DBT_MANIFEST`. `validated`, the switch that
|
||||
shows the alterations (`TEA_ALTERACIONES_VALIDADAS`).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
from fhir.resources.R4B import get_fhir_model_class
|
||||
|
||||
from conftest import base_de
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
mp = pytest.MonkeyPatch()
|
||||
mp.setenv("DEV_REVISION", "pruebas")
|
||||
mp.delenv("TEA_ALTERACIONES_VALIDADAS", raising=False)
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea_fhir"))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
base.motor.dispose()
|
||||
mp.undo()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def validated(monkeypatch):
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
|
||||
|
||||
def valid(resource: dict) -> dict:
|
||||
"""The resource, after checking it and every resource in it against FHIR's model of its type."""
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
for item in resource.get("entry", ()):
|
||||
get_fhir_model_class(item["resource"]["resourceType"]).model_validate(item["resource"])
|
||||
return resource
|
||||
|
||||
|
||||
def get(client, url: str, status: int = 200) -> dict:
|
||||
response = client.get(url)
|
||||
assert response.status_code == status, response.get_json()
|
||||
assert response.mimetype == "application/fhir+json"
|
||||
return valid(response.get_json())
|
||||
|
||||
|
||||
def resources(bundle: dict, kind: str | None = None, mode: str | None = None) -> list[dict]:
|
||||
return [e["resource"] for e in bundle["entry"] if (kind is None or e["resource"]["resourceType"] == kind)
|
||||
and (mode is None or e.get("search", {}).get("mode") == mode)]
|
||||
|
||||
|
||||
def test_the_capability_statement_lists_the_measures_and_the_patient_routes(client):
|
||||
"""Pins down: `metadata` is a valid CapabilityStatement naming Measure with `evaluate-measure` and, in DEV,
|
||||
EpisodeOfCare with its search parameters. Fails if a route drops out of it."""
|
||||
body = get(client, "/tea/fhir/metadata")
|
||||
kinds = {r["type"]: r for r in body["rest"][0]["resource"]}
|
||||
assert {"Measure", "MeasureReport", "EpisodeOfCare", "Patient"} <= set(kinds)
|
||||
assert {p["name"] for p in kinds["EpisodeOfCare"]["searchParam"]} >= {"date", "etapa", "fecha-etapa", "alteracion"}
|
||||
|
||||
|
||||
def test_the_measures_hide_m30_until_the_alterations_are_validated(client, monkeypatch):
|
||||
"""Pins down: the Measure list has the nine measures without alterations; M30 shows only with the switch on.
|
||||
Fails if M30 leaks before the domain expert validates the references, or the switch stops showing it."""
|
||||
ids = {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))}
|
||||
assert len(ids) == 9 and "M30-resultado-eeg" not in ids
|
||||
assert get(client, "/tea/fhir/Measure/M30_resultado_eeg", 404)["resourceType"] == "OperationOutcome"
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert "M30-resultado-eeg" in {m["id"] for m in resources(get(client, "/tea/fhir/Measure"))}
|
||||
|
||||
|
||||
def test_the_routes_outside_fhir_hide_m30_too(client, monkeypatch):
|
||||
"""Pins down: `/tea/indicadores` neither lists nor answers M30 until the alterations are validated, and does both
|
||||
with the switch on. Fails if the measures answered outside `/tea/fhir/` stop waiting for the validation."""
|
||||
assert "M30_resultado_eeg" not in {m["id"] for m in client.get("/tea/indicadores").get_json()}
|
||||
assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 404
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert "M30_resultado_eeg" in {m["id"] for m in client.get("/tea/indicadores").get_json()}
|
||||
assert client.get("/tea/indicadores/M30_resultado_eeg?periodos=2025-S1").status_code == 200
|
||||
|
||||
|
||||
def test_a_measure_carries_what_the_page_needs(client):
|
||||
"""Pins down: a Measure has its absolute canonical, title, scoring (a C2 is a cohort), its strata and its category
|
||||
labels. Fails if the page's catalog fields stop reaching the Measure."""
|
||||
m28 = get(client, "/tea/fhir/Measure/M28_casos_por_estado")
|
||||
assert m28["url"] == "https://isssteleon.org/fhir/Measure/M28-casos-por-estado"
|
||||
assert m28["title"] == "Casos por estatus" and m28["scoring"]["coding"][0]["code"] == "cohort"
|
||||
assert {e["extension"][0]["valueCode"] for e in m28["extension"] if e["url"].endswith("/categoria")} == {
|
||||
"SOLO_MCHAT", "PSICOLOGIA", "NEUROPEDIATRIA", "EEG"}
|
||||
m24 = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico")
|
||||
assert m24["group"][0]["stratifier"][0]["code"]["coding"][0]["code"] == "grupo_edad"
|
||||
assert "denominator-exclusion" in {p["code"]["coding"][0]["code"] for p in m24["group"][0]["population"]}
|
||||
|
||||
|
||||
def test_evaluate_measure_answers_one_period_as_a_measure_report(client):
|
||||
"""Pins down: `$evaluate-measure` with periodStart and periodEnd answers that period of `dim_periodo`: M28's first
|
||||
semester of 2025 counts six children by stage, as a cohort whose stages are a stratifier. Fails if the period
|
||||
lookup, the canonical or the C2 shape changes."""
|
||||
report = get(client, "/tea/fhir/Measure/M28_casos_por_estado/$evaluate-measure"
|
||||
"?periodStart=2025-01-01&periodEnd=2025-06-30")
|
||||
assert report["measure"].startswith("https://isssteleon.org/fhir/Measure/M28-casos-por-estado|")
|
||||
(group,) = report["group"]
|
||||
assert group["population"][0]["count"] == 6
|
||||
stages = {s["value"]["coding"][0]["code"]: s["population"][0]["count"] for s in group["stratifier"][0]["stratum"]}
|
||||
assert stages == {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2}
|
||||
|
||||
|
||||
def test_a_proportion_reports_its_exclusion_and_its_strata_with_codings(client):
|
||||
"""Pins down: M24's report has the exclusion count (child 2's note without F84.0) and each age group as a coded
|
||||
stratum. Fails if `denominator-exclusion` or the stratum codings drop out."""
|
||||
report = get(client, "/tea/fhir/Measure/M24_confirmacion_diagnostico/$evaluate-measure?periodo=2025-04")
|
||||
counts = {p["code"]["coding"][0]["code"]: p["count"] for p in report["group"][0]["population"]}
|
||||
assert counts == {"denominator": 3, "numerator": 1, "denominator-exclusion": 1}
|
||||
values = {s["value"]["coding"][0]["code"] for s in report["group"][0]["stratifier"][0]["stratum"]}
|
||||
assert {"16_23", "30_36"} <= values
|
||||
|
||||
|
||||
def test_the_measure_report_search_answers_several_periods_with_paging(client):
|
||||
"""Pins down: `MeasureReport?measure=…&tipo-periodo=mes&period=ge…&period=le…` gives one report per month, and
|
||||
`_count` pages them with a `next` link. Fails if the search stops selecting `dim_periodo` by type and dates."""
|
||||
url = ("/tea/fhir/MeasureReport?measure=https://isssteleon.org/fhir/Measure/M26-dias-mchat-ados2"
|
||||
"&tipo-periodo=mes&period=ge2025-01-01&period=le2025-03-31")
|
||||
body = get(client, url)
|
||||
assert body["total"] == 3 and [r["period"]["start"] for r in resources(body)] == [
|
||||
"2025-01-01", "2025-02-01", "2025-03-01"]
|
||||
paged = get(client, url + "&_count=2")
|
||||
assert len(paged["entry"]) == 2 and any(link["relation"] == "next" for link in paged["link"])
|
||||
|
||||
|
||||
def test_the_follow_up_list_is_each_child_s_episode_at_the_cut_off(client):
|
||||
"""Pins down: `EpisodeOfCare?date=le…` gives each child who entered by the cut-off, at its stage then: at 31 May,
|
||||
children 1, 2, 3, 6 and 7 (child 5 enters in June), child 1 finished on its good EEG. A window from 1 June leaves
|
||||
child 1 out. Fails if the episode's status, stage or window drift from the measures' rules."""
|
||||
may = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-05-31"))
|
||||
assert len(may) == 5
|
||||
assert sorted(e["status"] for e in may) == ["active"] * 4 + ["finished"]
|
||||
assert all(e["meta"]["tag"][0]["code"] == "simulado" for e in may)
|
||||
june = resources(get(client, "/tea/fhir/EpisodeOfCare?date=ge2025-06-01&date=le2025-06-30"))
|
||||
assert len(june) == 5 and "finished" in {e["status"] for e in june}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("query", "n"), [
|
||||
("etapa=PSICOLOGIA", 1), ("grupo-edad=24_29", 2), ("mchat=ge12", 3), ("css=ge4", 3),
|
||||
("fecha-etapa=ge2025-06-01&fecha-etapa=le2025-06-30", 2), ("status=finished", 2), ("resultado-eeg=sin-eeg-valido", 3),
|
||||
])
|
||||
def test_the_follow_up_filters(client, query, n):
|
||||
"""Pins down each search parameter at the year's end, over the six children who entered by then: child 3 at
|
||||
psychology; children 2 and 6 in 24 to 29 months (finished episodes still list); M-CHAT of 12 or more for children
|
||||
1, 3 and 6; CSS of 4 or more for 1, 2 and 6; a stage dated in June for child 5 (its M-CHAT; its EEG doesn't count)
|
||||
and child 6 (EEG on 2 June); children 1 and 6 finished; children 2, 3 and 7 without a valid EEG. Fails if a filter
|
||||
stops reading its column."""
|
||||
assert get(client, f"/tea/fhir/EpisodeOfCare?date=le2025-12-31&{query}")["total"] == n
|
||||
|
||||
|
||||
def test_includes_bring_the_patient_its_steps_and_its_study_eeg(client):
|
||||
"""Pins down: `_include` adds each child's Patient (birth date to the month), CarePlan with its steps, M-CHAT,
|
||||
ADOS-2 (the list shows its CSS and module), confirmed diagnosis and study EEG as a DiagnosticReport with its quality
|
||||
observations, one per check of its analysis (clean windows, usable scalp, triage level, line noise) as the
|
||||
analysis's own report writes them; no metric observation while the alterations are hidden. Fails if an included
|
||||
resource drops out, a check stops reaching the report or changes shape, or the alterations leak."""
|
||||
body = get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&status=finished&_include=*")
|
||||
included = resources(body, mode="include")
|
||||
kinds = {r["resourceType"] for r in included}
|
||||
assert {"Patient", "CarePlan", "Observation", "Condition", "DiagnosticReport", "Procedure"} <= kinds
|
||||
assert all(len(p["birthDate"]) == 7 for p in included if p["resourceType"] == "Patient")
|
||||
reports = [r for r in included if r["resourceType"] == "DiagnosticReport"]
|
||||
assert {r["conclusionCode"][0]["coding"][0]["code"] for r in reports} == {"BUENO"}
|
||||
assert all(len(r["result"]) == 4 for r in reports)
|
||||
assert all(r["conclusionCode"][1]["coding"][0] == {"system": "urn:tea:validation", "code": "valid"} for r in reports)
|
||||
quality = [r for r in included if r["resourceType"] == "Observation" and r["id"].startswith("calidad-")]
|
||||
assert {r["code"]["coding"][0]["system"] for r in quality} == {"urn:tea:validation"}
|
||||
clean = next(r for r in quality if r["code"]["coding"][0]["code"] == "clean-windows")
|
||||
assert (clean["valueQuantity"]["value"], clean["referenceRange"][0]["low"]["value"]) == (95.0, 60.0)
|
||||
assert clean["interpretation"][0]["coding"][0]["code"] == "N"
|
||||
assert clean["component"] == [{"code": {"text": "decisive"}, "valueBoolean": True}]
|
||||
triage = next(r for r in quality if r["code"]["coding"][0]["code"] == "triage-level")
|
||||
assert triage["valueString"] == "completo"
|
||||
ados2 = [r for r in included if r["resourceType"] == "Observation" and r["code"]["coding"][0]["code"] == "ados2"]
|
||||
assert ados2 and all(any(c["code"]["coding"][0]["code"] == "ados2.css" for c in r["component"]) for r in ados2)
|
||||
|
||||
|
||||
def test_a_bad_eeg_reports_its_failed_check_and_its_bad_channel(client):
|
||||
"""Pins down, on a bad EEG's rows as dbt's views give them (too few clean windows, a dead channel at T3): the report
|
||||
says MALO and the analysis's not-valid with the triage level; the clean windows are abnormal and decisive; the
|
||||
dead channel is an abnormal observation with its electrode as a component; every resource conforms to FHIR.
|
||||
Fails if a failed check or a bad channel stops reaching FHIR, or loses its electrode or decisive flag."""
|
||||
from webapi.fhir import tea
|
||||
|
||||
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-04-02", "calidad": "MALO", "valido": 0, "nivel": "parcial",
|
||||
"duracion_min": 25.0, "canales": 19}
|
||||
checks = [
|
||||
{"procedimiento_id": 9, "criterio": "clean_windows", "electrodo": None, "valor": 40.0, "valor_texto": None,
|
||||
"bajo": 60.0, "alto": None, "anormal": 1, "decisivo": 1, "etiqueta": "Ventanas limpias", "unidad": "%"},
|
||||
{"procedimiento_id": 9, "criterio": "dead_channel", "electrodo": "T3", "valor": None,
|
||||
"valor_texto": "dead channel", "bajo": None, "alto": None, "anormal": 1, "decisivo": 0,
|
||||
"etiqueta": "Canal muerto", "unidad": None},
|
||||
]
|
||||
resources = tea.eeg_resources(eeg, "P-X", [], [], False, checks)
|
||||
report = next(r for r in resources if r["resourceType"] == "DiagnosticReport")
|
||||
assert [c["coding"][0]["code"] for c in report["conclusionCode"]] == ["MALO", "not-valid"]
|
||||
assert report["conclusion"].endswith("(nivel de triaje: parcial).")
|
||||
clean, dead = (r for r in resources if r["resourceType"] == "Observation")
|
||||
assert (clean["interpretation"][0]["coding"][0]["code"], clean["component"][-1]["valueBoolean"]) == ("A", True)
|
||||
assert dead["id"] == "calidad-dead-channel-T3-9" and dead["valueString"] == "dead channel"
|
||||
assert dead["component"] == [{"code": {"text": "electrode"}, "valueString": "T3"},
|
||||
{"code": {"text": "decisive"}, "valueBoolean": False}]
|
||||
for resource in resources:
|
||||
get_fhir_model_class(resource["resourceType"]).model_validate(resource)
|
||||
|
||||
|
||||
def test_the_alteration_filter_waits_for_the_validation(client, monkeypatch):
|
||||
"""Pins down: filtering by an alteration is refused while they're hidden, and works with the switch on (child 1's
|
||||
slow posterior rhythm). Fails if the filter leaks alterations before validation."""
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?alteracion=ritmo_posterior", 403)["resourceType"] == "OperationOutcome"
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&alteracion=ritmo_posterior")["total"] == 1
|
||||
|
||||
|
||||
def test_the_eeg_summary_counts_valid_eegs_and_alterations_only_when_validated(client, monkeypatch):
|
||||
"""Pins down `$resumen-eeg`: children 1, 5 and 6 with a valid EEG, 2, 3 and 7 without; with the alterations
|
||||
validated, child 1 abnormal (posterior rhythm), 5 and 6 normal. Fails if the summary counts bad EEGs as valid or
|
||||
shows the split before validation."""
|
||||
def counts(body):
|
||||
return {p["name"]: p.get("valueInteger") for p in body["parameter"] if "valueInteger" in p}
|
||||
|
||||
hidden = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31")
|
||||
assert counts(hidden) == {"con_eeg_valido": 3, "sin_eeg_valido": 3}
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
shown = get(client, "/tea/fhir/EpisodeOfCare/$resumen-eeg?date=le2025-12-31")
|
||||
assert counts(shown) == {"con_eeg_valido": 3, "sin_eeg_valido": 3, "normales": 2, "anormales": 1}
|
||||
|
||||
|
||||
def test_the_patient_summary_shows_the_first_ados2_and_the_study_eeg(client, monkeypatch):
|
||||
"""Pins down `$resumen-tea` for child 1: its Patient, its ADOS-2 (module, CSS, domain totals and items), its first
|
||||
good EEG (20 May, not the bad one of April nor the later one) with its quality; with the alterations validated,
|
||||
the metrics against their age baseline (p5 as the low end of the reference, the median as a component) and each
|
||||
electrode's z-score; and its episode, with the age group. Fails if the summary takes another EEG, shows the
|
||||
alterations before validation, maps the electrodes' raw values or loses the age group."""
|
||||
episodes = resources(get(client, "/tea/fhir/EpisodeOfCare?date=le2025-12-31&grupo-edad=16_23&status=finished"))
|
||||
(child_1,) = episodes
|
||||
path = f"/tea/fhir/Patient/{child_1['id']}/$resumen-tea"
|
||||
bundle = get(client, path)
|
||||
assert bundle["type"] == "collection"
|
||||
(report,) = resources(bundle, "DiagnosticReport")
|
||||
assert report["effectiveDateTime"] == "2025-05-20" and report["conclusionCode"][0]["coding"][0]["code"] == "BUENO"
|
||||
ados2 = next(o for o in resources(bundle, "Observation") if o["id"].startswith("ados2-"))
|
||||
codes = {c["code"]["coding"][0]["code"] for c in ados2["component"]}
|
||||
assert {"ados2.modulo", "ados2.css", "SA", "RRB", "ados2.sa_b1"} <= codes
|
||||
assert not any("tea-eeg-metrica" in o["code"]["coding"][0]["system"] for o in resources(bundle, "Observation"))
|
||||
monkeypatch.setenv("TEA_ALTERACIONES_VALIDADAS", "1")
|
||||
shown = get(client, path)
|
||||
metrics = [o for o in resources(shown, "Observation") if o["code"]["coding"][0]["system"].endswith("tea-eeg-metrica")]
|
||||
rhythm = next(o for o in metrics if o["id"].startswith("ritmo-posterior-"))
|
||||
assert rhythm["interpretation"][0]["coding"][0]["code"] == "L" and rhythm["referenceRange"][0]["low"]["value"] == 4.5
|
||||
assert {c["code"]["coding"][0]["code"]: c["valueQuantity"]["value"] for c in rhythm["component"]} == {
|
||||
"z": -4.08, "mediana": 5.75}
|
||||
(episode,) = resources(shown, "EpisodeOfCare")
|
||||
assert episode["extension"][0]["valueCoding"]["code"] == "16_23"
|
||||
electrodes = next(o for o in metrics if o["id"].startswith("electrodos-ritmo-posterior-"))
|
||||
assert [(c["code"]["coding"][0]["code"], c["valueQuantity"]["value"]) for c in electrodes["component"]] == [
|
||||
("O1", -2.8), ("O2", -2.4), ("Pz", -1.1)]
|
||||
|
||||
|
||||
def test_a_metric_the_baseline_couldnt_score_keeps_its_value():
|
||||
"""Pins down: a metric with a value but no z (no baseline in production, or an age it doesn't cover) keeps its
|
||||
value and has no interpretation nor reference; one without a value is `not-performed`. Fails if an unscored metric
|
||||
loses its value (the summary couldn't tell it from one never measured) or gets an interpretation it doesn't have."""
|
||||
from webapi.fhir import tea
|
||||
|
||||
eeg = {"procedimiento_id": 9, "fecha_eeg": "2025-05-20"}
|
||||
row = {"procedimiento_id": 9, "ref_min": None, "ref_mediana": None, "ref_max": None, "grupo_edad_eeg": "16_23",
|
||||
"estado": "no_evaluable", "valor_z": None}
|
||||
unscored, unmeasured = tea.metric_observations(eeg, [{**row, "metrica": "ritmo_posterior", "valor": 6.8},
|
||||
{**row, "metrica": "husos_sueno_n3", "valor": None}],
|
||||
[], "P-X", False)[::-1]
|
||||
assert unscored["valueQuantity"]["value"] == 6.8
|
||||
assert not {"interpretation", "referenceRange", "dataAbsentReason", "component"} & set(unscored)
|
||||
assert unmeasured["dataAbsentReason"]["coding"][0]["code"] == "not-performed" and "valueQuantity" not in unmeasured
|
||||
|
||||
|
||||
def test_the_quality_checks_are_a_code_system_of_the_analysis(client):
|
||||
"""Pins down: `CodeSystem/tea-eeg-criterio` is the EEG analysis's code system (`urn:tea:validation`) with every
|
||||
check code and the catalog's label, and each metric has a text for every state, normal included.
|
||||
|
||||
Fails if a check code the quality observations use has no concept, or a metric loses its normal effect.
|
||||
"""
|
||||
from core.tea.enums import CriterioEeg
|
||||
|
||||
checks = get(client, "/tea/fhir/CodeSystem/tea-eeg-criterio")
|
||||
assert checks["url"] == "urn:tea:validation"
|
||||
assert {c["code"] for c in checks["concept"]} == {c.value for c in CriterioEeg}
|
||||
assert next(c for c in checks["concept"] if c["code"] == "clean-windows")["display"] == "Ventanas limpias"
|
||||
metrics = get(client, "/tea/fhir/CodeSystem/tea-eeg-metrica")
|
||||
assert all(any(p["code"] == "efecto-normal" for p in c["property"]) for c in metrics["concept"])
|
||||
|
||||
|
||||
def test_an_answer_that_doesnt_conform_to_fhir_never_leaves(client):
|
||||
"""Pins down: `fhir()` validates every answer against R4B; one that doesn't conform is a 500 `OperationOutcome`.
|
||||
|
||||
Fails if a malformed resource reaches a client, or the check stops running.
|
||||
"""
|
||||
from webapi import create_app
|
||||
from webapi.fhir.common import fhir
|
||||
|
||||
with create_app().test_request_context():
|
||||
bad = fhir({"resourceType": "Observation", "id": "x"}) # no status, no code
|
||||
good = fhir({"resourceType": "Observation", "id": "x", "status": "final", "code": {"text": "t"}})
|
||||
assert (bad.status_code, json.loads(bad.data)["resourceType"]) == (500, "OperationOutcome")
|
||||
assert (good.status_code, json.loads(good.data)["status"]) == (200, "final")
|
||||
|
||||
|
||||
def test_an_unknown_patient_or_parameter_is_an_operation_outcome(client):
|
||||
"""Pins down: errors are OperationOutcomes with the HTTP status: an unknown pseudonym (404), an unknown search
|
||||
parameter (400). Fails if an error goes back to `{"error": …}`."""
|
||||
assert get(client, "/tea/fhir/Patient/P-NADIE/$resumen-tea", 404)["issue"][0]["code"] == "not-found"
|
||||
assert get(client, "/tea/fhir/EpisodeOfCare?color=azul", 400)["issue"][0]["code"] == "invalid"
|
||||
@@ -0,0 +1,450 @@
|
||||
"""Endpoint tests for `/governance/*`: model versions and their promotion, downloading what a version's run stored,
|
||||
notebooks run on a cohort build, and the OCR review queue.
|
||||
|
||||
Fixtures: `client`, the app over a CaCu and a governance database with one patient and a SQLite-backed MLflow in a
|
||||
temporary folder (module scope); `notebooks`, a cohort build's file under a `COHORTS_DIR`, the Jupyter renderer and
|
||||
notebooks run in the request instead of in the background. `_trained` registers a version the way training does: a run
|
||||
that records each routine and saves its model.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import date
|
||||
|
||||
import mlflow.pyfunc
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("governance")
|
||||
|
||||
# A local, SQLite-backed MLflow tracking store for this module — no
|
||||
# server, no network. `chdir` into the same temp dir: an experiment with
|
||||
# no explicit artifact_location falls back to `./mlruns` relative to the
|
||||
# CWD (production never sets one either; the real MLflow server picks it).
|
||||
import mlflow
|
||||
|
||||
tmp_dir = tempfile.mkdtemp()
|
||||
uri = f"sqlite:///{os.path.join(tmp_dir, 'mlflow.db')}"
|
||||
os.environ["MLFLOW_TRACKING_URI"] = uri
|
||||
mlflow.set_tracking_uri(uri)
|
||||
previous_cwd = os.getcwd()
|
||||
os.chdir(tmp_dir)
|
||||
|
||||
from core.cacu.models import Paciente
|
||||
from persistance import db as persistance_db
|
||||
|
||||
with __import__("sqlmodel").Session(persistance_db.get_cacu_engine()) as session:
|
||||
session.add(Paciente(pac_id_hospital="H-1", pac_sexo="Femenino", pac_fecha_nacimiento=date(1990, 1, 1)))
|
||||
session.commit()
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
os.chdir(previous_cwd)
|
||||
del os.environ["MLFLOW_TRACKING_URI"]
|
||||
|
||||
|
||||
def test_list_model_versions_empty(client):
|
||||
response = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "tamizaje-vacio"})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json() == {"model_versions": []}
|
||||
|
||||
|
||||
def _armado(tag: str) -> int:
|
||||
"""A CaCu cohort build with one attrition step; returns its `armado_id`."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
with get_cacu_session() as session:
|
||||
armado = CohorteArmado(
|
||||
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
|
||||
datos_as_of=date(2025, 12, 31), huella=f"huella-{tag}", marco_sha="m", n_miembros=5,
|
||||
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(armado)
|
||||
session.flush()
|
||||
session.add(CohorteExclusion(armado_id=armado.armado_id, orden=1, paso="candidatas", n=5))
|
||||
session.commit()
|
||||
return armado.armado_id
|
||||
|
||||
|
||||
def _register(client, tag: str, *, scenario: str = "tamizaje", **extra) -> dict:
|
||||
body = {
|
||||
"domain": "cacu", "scenario": scenario, "environment": "PROD",
|
||||
"cohorte_armado_id": _armado(tag), "metrics": {"auc": 0.8},
|
||||
"technical_validation_report_uri": "docs/tecnica.pdf",
|
||||
"clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html",
|
||||
**extra,
|
||||
}
|
||||
response = client.post("/governance/model-versions", json=body)
|
||||
assert response.status_code == 201, response.get_json()
|
||||
return response.get_json()
|
||||
|
||||
|
||||
class Echo(mlflow.pyfunc.PythonModel):
|
||||
def predict(self, context, model_input, params=None):
|
||||
return model_input
|
||||
|
||||
|
||||
def _trained(tag: str, scenario: str, **reports) -> str:
|
||||
"""A PROD version as training leaves it: every routine recorded and the model saved."""
|
||||
from models.io.registry import registry
|
||||
from models.io.tracking import ROUTINE_KINDS, TrainingRun
|
||||
|
||||
run = TrainingRun(domain="cacu", scenario=scenario, environment="PROD", cohorte_armado_id=_armado(tag))
|
||||
for kind in ROUTINE_KINDS:
|
||||
run.log_routine(kind, {"method": "prueba"})
|
||||
run.log_model(Echo())
|
||||
return registry.register_run(run.finish(metrics={"auc": 0.8}), **reports)
|
||||
|
||||
|
||||
REPORTS = {"technical_validation_report_uri": "docs/tecnica.pdf", "clinical_validation_report_uri": "docs/clinica.pdf",
|
||||
"interpretability_report_uri": "docs/interpretabilidad.html"}
|
||||
|
||||
|
||||
def test_model_version_lifecycle_over_http(client):
|
||||
"""A version registered over HTTP carries no routine records or model, so it can't be promoted; trained ones can,
|
||||
and promoting the second retires the first. Fails if the ML-01a/ML-01b checks start trusting what's declared
|
||||
over the API, or promotion stops retiring the previous version."""
|
||||
declared = _register(client, "v0", scenario="lifecycle")
|
||||
checks = client.get(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/checks").get_json()
|
||||
assert checks["ready"] is False
|
||||
assert [c["code"] for c in checks["checks"] if not c["passed"]] == ["ML-01a", "ML-01b"]
|
||||
blocked = client.post(f"/governance/model-versions/cacu/lifecycle/{declared['version']}/promote")
|
||||
assert blocked.status_code == 409 and any(not c["passed"] for c in blocked.get_json()["checks"])
|
||||
|
||||
first = _trained("v1", "lifecycle", **REPORTS)
|
||||
assert client.post(f"/governance/model-versions/cacu/lifecycle/{first}/promote").get_json()["status"] == "produccion"
|
||||
second = _trained("v2", "lifecycle", **REPORTS)
|
||||
client.post(f"/governance/model-versions/cacu/lifecycle/{second}/promote")
|
||||
listed = client.get("/governance/model-versions", query_string={"domain": "cacu", "scenario": "lifecycle"}).get_json()
|
||||
statuses = {v["version"]: v["status"] for v in listed["model_versions"]}
|
||||
assert statuses[first] == "retirada" and statuses[second] == "produccion"
|
||||
|
||||
lineage = client.get(f"/governance/model-versions/cacu/lifecycle/{second}/lineage").get_json()
|
||||
assert lineage["cohorte_armado"]["huella"] == "huella-v2"
|
||||
assert lineage["cohorte_armado"]["datos_as_of"] == "2025-12-31"
|
||||
assert lineage["cohorte_exclusiones"] == [{"orden": 1, "paso": "candidatas", "n": 5}]
|
||||
assert lineage["routines"]["MUESTREO"] == {"method": "prueba"}
|
||||
|
||||
retired = client.post(f"/governance/model-versions/cacu/lifecycle/{second}/retire").get_json()
|
||||
assert retired["status"] == "retirada"
|
||||
|
||||
|
||||
def test_a_versions_files_download(client):
|
||||
"""ML-01b: a routine record downloads as itself, the model folder as a zip, and a path the run doesn't hold is 404.
|
||||
Fails if the endpoint stops going through `registry.artifact`."""
|
||||
version = _trained("v-desc", "descargas")
|
||||
base = f"/governance/model-versions/cacu/descargas/{version}/artifacts"
|
||||
record = client.get(f"{base}/rutinas/MUESTREO.json")
|
||||
assert record.status_code == 200 and record.get_json(force=True) == {"method": "prueba"}
|
||||
assert "attachment" in record.headers["Content-Disposition"]
|
||||
model = client.get(f"{base}/model")
|
||||
assert model.status_code == 200 and 'model.zip' in model.headers["Content-Disposition"]
|
||||
assert client.get(f"{base}/../../mlflow.db").status_code == 404
|
||||
assert client.get(f"{base}/rutinas/OTRO.json").status_code == 404
|
||||
|
||||
|
||||
def test_reports_can_be_attached_later(client):
|
||||
version = _register(client, "v3", scenario="reportes", clinical_validation_report_uri=None)
|
||||
response = client.patch(
|
||||
f"/governance/model-versions/cacu/reportes/{version['version']}/reports",
|
||||
json={"clinical_validation_report_uri": "docs/clinica-v3.pdf"},
|
||||
)
|
||||
assert response.get_json()["tags"]["clinical_validation_report_uri"] == "docs/clinica-v3.pdf"
|
||||
assert client.patch(f"/governance/model-versions/cacu/reportes/{version['version']}/reports", json={"metrics": "{}"}).status_code == 400
|
||||
|
||||
|
||||
def test_bad_registrations_are_rejected(client):
|
||||
assert client.post("/governance/model-versions", json={"domain": "cacu"}).status_code == 400
|
||||
|
||||
|
||||
def test_model_version_not_found(client):
|
||||
assert client.get("/governance/model-versions/cacu/no-existe/999/checks").status_code == 404
|
||||
|
||||
|
||||
def test_training_needs_a_dbt_manifest(client, monkeypatch):
|
||||
"""Pins down: with no `DBT_MANIFEST`, `/train` refuses before running anything. Fails if it tries to train with
|
||||
no manifest configured instead of failing fast."""
|
||||
monkeypatch.delenv("DBT_MANIFEST", raising=False)
|
||||
|
||||
response = client.post("/governance/model-versions/cacu/cin2_logistic/train")
|
||||
|
||||
assert response.status_code == 503
|
||||
|
||||
|
||||
def test_training_runs_the_same_pipeline_entrenar_does(client, monkeypatch):
|
||||
"""Pins down: `/train` calls `models.__main__.main` with exactly the arguments the `entrenar` compose profile
|
||||
runs (export from dbt, PROD, train, promote), reading the manifest path from `DBT_MANIFEST`, and returns its
|
||||
captured output on success. Fails if the route drifts from that one-shot invocation, or stops using the
|
||||
deployment's own manifest."""
|
||||
monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json")
|
||||
calls = []
|
||||
|
||||
def fake_main(argv):
|
||||
calls.append(argv)
|
||||
print("trained: version 1, from dbt/1.parquet")
|
||||
print("in production: version 1")
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr("models.__main__.main", fake_main)
|
||||
|
||||
response = client.post("/governance/model-versions/cacu/cin2_logistic/train")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert calls == [["run", "cacu", "cin2_logistic", "--export", "--source", "dbt", "--manifest",
|
||||
"/data/dbt/manifest.json", "--environment", "prod", "--train", "--promote"]]
|
||||
assert "in production: version 1" in response.get_json()["output"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("stderr, expected_status", [
|
||||
("no such model: cacu/ninguno\n", 404),
|
||||
("not promoted, missing: MLD-01 (reporte de pruebas técnicas)\n", 409),
|
||||
("a query of cacu/cohorte_vigilancia failed (no such table: cohorte_armado)\n", 503),
|
||||
])
|
||||
def test_training_failures_map_to_their_status(client, monkeypatch, stderr, expected_status):
|
||||
"""Pins down: an unknown model is 404, a trained-but-unpromotable version is 409 (attach reports, then
|
||||
`/promote`), and anything else operational is 503. Fails if a failure that needs a human step (missing reports)
|
||||
reads the same as a hard, transient failure, or either is swallowed as success."""
|
||||
import sys
|
||||
|
||||
def fake_main(argv):
|
||||
sys.stderr.write(stderr)
|
||||
return 1
|
||||
|
||||
monkeypatch.setenv("DBT_MANIFEST", "/data/dbt/manifest.json")
|
||||
monkeypatch.setattr("models.__main__.main", fake_main)
|
||||
|
||||
response = client.post("/governance/model-versions/cacu/cin2_logistic/train")
|
||||
|
||||
assert response.status_code == expected_status
|
||||
assert response.get_json()["error"] == stderr.strip()
|
||||
|
||||
|
||||
def test_ocr_run_unknown_job_is_404(client):
|
||||
response = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "no_such_entity"})
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_ocr_run_extracts_results_and_flags_unreadable_reports(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from extraction.testing import text_pdf
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
report = text_pdf([["LABORATORIO DE BIOLOGIA MOLECULAR", "Expediente: H-OCR-1", "VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"]])
|
||||
good = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-1", cit_vph_pdf_blob=report))
|
||||
bad = citologia_cervical_repository.create(CitologiaCervical(pac_id_hospital="H-OCR-2", cit_vph_pdf_blob=b"%PDF-fake"))
|
||||
|
||||
body = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
|
||||
assert body["processed"] >= 1 and body["failed"] >= 1
|
||||
|
||||
good = citologia_cervical_repository.get(good.cit_id)
|
||||
assert (good.cit_vph_resultado, good.cit_vph_genotipo_16, good.cit_vph_genotipo_18) == ("POSITIVO", 0, 1)
|
||||
assert good.cit_vph_ocr_estatus == "REALIZADO" and good.cit_vph_ocr_requiere_revision is False
|
||||
assert good.cit_vph_ocr_metodo_principal == "pdf-texto" and good.cit_vph_ocr_confianza >= 0.8
|
||||
bad = citologia_cervical_repository.get(bad.cit_id)
|
||||
assert bad.cit_vph_ocr_estatus == "FALLIDO" and bad.cit_vph_ocr_requiere_revision is True
|
||||
assert extraction_run_repository.count(entity_pk=str(good.cit_id)) == 1
|
||||
|
||||
again = client.post("/governance/ocr/run", json={"domain": "cacu", "entity": "citologia_cervical"}).get_json()
|
||||
assert again["skipped_already_done"] >= 1
|
||||
|
||||
|
||||
def test_eeg_run_analyses_at_most_the_limit_with_the_configured_cluster(client, monkeypatch):
|
||||
"""Pins down: `POST /governance/eeg/run` runs the EEG analysis in the request with the body's `limit` (5 by
|
||||
default), `all` and the cluster `EEG_ANALYSIS_CLUSTER` names, and answers its summary.
|
||||
|
||||
Fails if the route stops bounding the batch (a request could then run for hours) or ignores the body.
|
||||
"""
|
||||
import models.eeg_analysis
|
||||
from models.eeg_analysis import Summary
|
||||
|
||||
calls = []
|
||||
monkeypatch.setattr(models.eeg_analysis, "analyze_pending",
|
||||
lambda **kwargs: calls.append(kwargs) or Summary(pending=2, valid=1, not_valid=1, failed=0))
|
||||
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "sync")
|
||||
body = client.post("/governance/eeg/run", json={}).get_json()
|
||||
assert body == {"pending": 2, "valid": 1, "not_valid": 1, "failed": 0}
|
||||
client.post("/governance/eeg/run", json={"limit": 1, "all": True, "cluster": "local"})
|
||||
assert calls == [{"everything": False, "limit": 5, "cluster": "sync"},
|
||||
{"everything": True, "limit": 1, "cluster": "local"}]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [{"limit": 0}, {"limit": "many"}, {"cluster": "everywhere"}])
|
||||
def test_eeg_run_refuses_a_bad_limit_or_cluster(client, body):
|
||||
"""Pins down: a limit that isn't a positive whole number, or an unknown cluster, is a 400 before anything runs.
|
||||
|
||||
Fails if the route starts an analysis on a body it can't honour.
|
||||
"""
|
||||
assert client.post("/governance/eeg/run", json=body).status_code == 400
|
||||
|
||||
|
||||
def test_list_ocr_jobs(client):
|
||||
body = client.get("/governance/ocr/jobs").get_json()
|
||||
keys = {(j["domain"], j["entity"]) for j in body["jobs"]}
|
||||
assert ("cacu", "citologia_cervical") in keys
|
||||
assert ("cacu", "biopsia_cervical") in keys
|
||||
assert ("cama", "biopsia_mama") in keys
|
||||
cacu_vph = next(j for j in body["jobs"] if (j["domain"], j["entity"]) == ("cacu", "citologia_cervical"))
|
||||
assert set(cacu_vph["result_fields"]) == {"cit_vph_resultado", "cit_vph_genotipo_16", "cit_vph_genotipo_18"}
|
||||
|
||||
|
||||
def test_ocr_rows_unknown_job_is_404(client):
|
||||
assert client.get("/governance/ocr/cacu/no_such_entity/rows").status_code == 404
|
||||
|
||||
|
||||
def test_ocr_review_queue_blob_and_manual_correction(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
row = citologia_cervical_repository.create(
|
||||
CitologiaCervical(
|
||||
pac_id_hospital="H-1",
|
||||
cit_vph_pdf_blob=b"%PDF-review-me",
|
||||
cit_vph_ocr_estatus="FALLIDO",
|
||||
cit_vph_ocr_requiere_revision=True,
|
||||
)
|
||||
)
|
||||
|
||||
review = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
|
||||
assert review.status_code == 200
|
||||
review_body = review.get_json()
|
||||
assert row.cit_id in {r["id"] for r in review_body["rows"]}
|
||||
|
||||
blob_response = client.get(f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/blob")
|
||||
assert blob_response.status_code == 200
|
||||
assert blob_response.data == b"%PDF-review-me"
|
||||
assert blob_response.content_type == "application/pdf"
|
||||
|
||||
correction = client.post(
|
||||
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
|
||||
json={"values": {"cit_vph_resultado": "POSITIVO"}, "confianza": 1.0},
|
||||
)
|
||||
assert correction.status_code == 200
|
||||
corrected = correction.get_json()
|
||||
assert corrected["cit_vph_resultado"] == "POSITIVO"
|
||||
assert corrected["cit_vph_ocr_estatus"] == "REALIZADO"
|
||||
assert corrected["cit_vph_ocr_requiere_revision"] is False
|
||||
assert corrected["cit_vph_ocr_metodo_principal"] == "manual"
|
||||
|
||||
done = client.get("/governance/ocr/cacu/citologia_cervical/rows", query_string={"status": "review"})
|
||||
assert row.cit_id not in {r["id"] for r in done.get_json()["rows"]}
|
||||
|
||||
from persistance.governance import extraction_run_repository
|
||||
|
||||
runs = extraction_run_repository.list(entity="citologia_cervical")
|
||||
assert any("manual" in (r.transform_description or "").lower() for r in runs)
|
||||
|
||||
|
||||
def test_ocr_correct_rejects_unknown_column(client):
|
||||
from core.cacu.models import CitologiaCervical
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
row = citologia_cervical_repository.create(
|
||||
CitologiaCervical(pac_id_hospital="H-2", cit_vph_pdf_blob=b"%PDF-2")
|
||||
)
|
||||
response = client.post(
|
||||
f"/governance/ocr/cacu/citologia_cervical/{row.cit_id}/correct",
|
||||
json={"values": {"pac_id_hospital": "HACKED"}},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_ocr_blob_not_found_for_unknown_row(client):
|
||||
assert client.get("/governance/ocr/cacu/citologia_cervical/999999/blob").status_code == 404
|
||||
|
||||
|
||||
def _notebook(*sources: str) -> bytes:
|
||||
cells = [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": s} for s in sources]
|
||||
return json.dumps({"cells": cells, "metadata": {}, "nbformat": 4, "nbformat_minor": 5}).encode()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def notebooks(tmp_path, monkeypatch):
|
||||
"""Build 4 of dbt's `cacu/cohorte_vigilancia` under `COHORTS_DIR`, the Jupyter renderer, and `submit` running the
|
||||
notebook before the request answers."""
|
||||
import pandas as pd
|
||||
import pyarrow as pa
|
||||
import pyarrow.parquet as pq
|
||||
from datetime import datetime, timezone
|
||||
from models.io.contracts import COHORT_SCHEMA
|
||||
from webapi.blueprints import governance
|
||||
|
||||
row = {"pac_id": 1, "fecha_indice": date(2025, 1, 1), "fecha": date(2025, 1, 1),
|
||||
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
|
||||
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||
"fuente_id": "S1"}
|
||||
table = pa.Table.from_pandas(pd.DataFrame([row], columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False)
|
||||
path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "4.parquet"
|
||||
path.parent.mkdir(parents=True)
|
||||
metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "4", "datos_as_of": "2025-12-31",
|
||||
"n_members": "1"}
|
||||
pq.write_table(table.replace_schema_metadata(metadata), path)
|
||||
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||
monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter")
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
monkeypatch.setattr(governance, "submit", lambda job, *args: job(*args))
|
||||
|
||||
|
||||
def _run(client, notebook: bytes, *, scenario="exploracion", **fields):
|
||||
form = {"file": (io.BytesIO(notebook), "analisis.ipynb"), "domain": "cacu", "scenario": scenario,
|
||||
"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "4", **fields}
|
||||
return client.post("/governance/experiments", data=form, content_type="multipart/form-data")
|
||||
|
||||
|
||||
def test_the_builds_a_notebook_can_run_on_are_listed(client, notebooks):
|
||||
"""Fails if `/cohort-files` stops listing exported builds from their files."""
|
||||
builds = client.get("/governance/cohort-files", query_string={"domain": "cacu"}).get_json()["builds"]
|
||||
assert builds == [{"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": 4, "datos_as_of": "2025-12-31",
|
||||
"n_members": "1"}]
|
||||
|
||||
|
||||
def test_an_uploaded_notebook_runs_on_the_build_and_its_page_is_sandboxed(client, notebooks):
|
||||
"""The upload answers 202 with the run; the notebook reads the build through `models.notebook`; its page is served
|
||||
with a sandbox policy and its files download. Fails if the endpoint stops handing the build to the run or serves
|
||||
the notebook's page as part of the app's origin."""
|
||||
started = _run(client, _notebook("from models.notebook import experiment\n"
|
||||
"print('miembros', experiment().cohort().pac_id.nunique())"))
|
||||
assert started.status_code == 202, started.get_json()
|
||||
run_id = started.get_json()["run_id"]
|
||||
run = client.get(f"/governance/experiments/{run_id}").get_json()
|
||||
assert run["status"] == "terminado" and run["cohort"]["build"] == "4" and run["notebook"] == "analisis"
|
||||
page = client.get(f"/governance/experiments/{run_id}/page")
|
||||
assert "miembros 1" in page.get_data(as_text=True) and "sandbox" in page.headers["Content-Security-Policy"]
|
||||
source = client.get(f"/governance/experiments/{run_id}/artifacts/notebook/analisis.ipynb")
|
||||
assert source.status_code == 200 and "attachment" in source.headers["Content-Disposition"]
|
||||
listed = client.get("/governance/experiments", query_string={"domain": "cacu", "scenario": "exploracion"}).get_json()
|
||||
assert run_id in [r["run_id"] for r in listed["experiments"]]
|
||||
|
||||
|
||||
def test_a_failing_notebook_reports_its_error(client, notebooks):
|
||||
"""Fails if a notebook whose cell raises is reported as finished or without its error."""
|
||||
run_id = _run(client, _notebook("raise ValueError('sin datos')")).get_json()["run_id"]
|
||||
run = client.get(f"/governance/experiments/{run_id}").get_json()
|
||||
assert run["status"] == "fallido" and "sin datos" in run["error"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fields, notebook", [
|
||||
({"build": "99"}, None),
|
||||
({"url": "tea/otra"}, None),
|
||||
({"build": "x"}, None),
|
||||
({"version": "999"}, None),
|
||||
({}, b"no es json"),
|
||||
({}, b'{"cells": [], "nbformat": 3}'),
|
||||
])
|
||||
def test_bad_notebook_runs_are_refused(client, notebooks, fields, notebook):
|
||||
"""A build that isn't exported, a cohort of another domain, an unknown version, or a file that isn't a notebook is
|
||||
refused before anything runs. Fails if `/experiments` stops checking any of them."""
|
||||
response = _run(client, notebook or _notebook("1"), **fields)
|
||||
assert response.status_code in (400, 404)
|
||||
@@ -0,0 +1,265 @@
|
||||
"""End-to-end tests (Flask test client, SQLite) of how a batch fills the
|
||||
database from several sources: strict catalogs, upserts that keep unmapped
|
||||
columns, defaults, atomic batches, itemized conflicts, and 400s for malformed
|
||||
requests."""
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def _csv(text: str, mapping: dict, *, target="cacu.Paciente", **extra) -> dict:
|
||||
return {"source_type": "csv", "target": target, "column_mapping": mapping, "payload": {"file_base64": _b64(text.encode())}, **extra}
|
||||
|
||||
|
||||
def _rows(client, target):
|
||||
return {r["pac_id_hospital"]: r for r in client.get(f"/data/{target}?limit=500").get_json()["rows"]}
|
||||
|
||||
|
||||
def test_catalog_values_are_enforced_and_aliases_resolved(client):
|
||||
source = _csv(
|
||||
"exp,sexo,dep,nac\nCAT-1,f,calles y caminos,1990-01-01\nCAT-2,GARBAGE,,1990-01-01\nCAT-3,Masculino,SECRETARIA DE SALUD,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "sexo": "pac_sexo", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
body = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert body["valid_count"] == 2
|
||||
assert [(e["row_index"], e["field"], e["category"], e["raw_value"]) for e in body["errors"]] == [
|
||||
(1, "pac_sexo", "out_of_catalog", "GARBAGE")
|
||||
]
|
||||
|
||||
client.post("/imports/commit", json={"sources": [source]})
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["CAT-1"]["pac_sexo"] == "Femenino"
|
||||
assert rows["CAT-1"]["pac_dependencia"] == "CALLES Y CAMINOS" # alias normalized
|
||||
# Dependencia is a tentative catalog in Core, so unknown values are kept.
|
||||
assert rows["CAT-3"]["pac_dependencia"] == "SECRETARIA DE SALUD"
|
||||
|
||||
|
||||
def test_postal_codes_keep_leading_zeros_and_are_validated(client):
|
||||
source = _csv(
|
||||
"exp,cp,nac\nCP-1,01000,1990-01-01\nCP-2,6400,1990-01-01\nCP-3,64000a,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
body = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["CP-1"]["pac_codigo_postal"] == "01000"
|
||||
assert "CP-2" not in rows and "CP-3" not in rows # 4 digits / non-digit
|
||||
|
||||
|
||||
def test_upsert_only_touches_mapped_columns(client):
|
||||
client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv("exp,sexo,nac\nUP-1,F,15/01/1990\n", {"exp": "pac_id_hospital", "sexo": "pac_sexo", "nac": "pac_fecha_nacimiento"})]},
|
||||
)
|
||||
# pac_fecha_nacimiento is required (IND-01), so every row, insert or
|
||||
# upsert, must carry it. pac_sexo is the field that must stay untouched
|
||||
# when a later source doesn't map it.
|
||||
body = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv(
|
||||
"exp,cp,nac\nUP-1,64000,15/01/1990\n",
|
||||
{"exp": "pac_id_hospital", "cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
],
|
||||
"on_conflict": "upsert",
|
||||
},
|
||||
).get_json()
|
||||
assert body["results"][0]["updated"] == 1
|
||||
row = _rows(client, "cacu.Paciente")["UP-1"]
|
||||
assert (row["pac_sexo"], row["pac_fecha_nacimiento"], row["pac_codigo_postal"]) == ("Femenino", "1990-01-15", "64000")
|
||||
|
||||
|
||||
def test_defaults_fill_unmapped_fields_and_blank_cells(client):
|
||||
source = _csv(
|
||||
"exp,dep,nac\nDEF-1,,1990-01-01\nDEF-2,GOBIERNO,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "dep": "pac_dependencia", "nac": "pac_fecha_nacimiento"},
|
||||
defaults={"pac_dependencia": "CALLES Y CAMINOS", "pac_parentesco": "afiliado"},
|
||||
)
|
||||
assert client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]["created"] == 2
|
||||
rows = _rows(client, "cacu.Paciente")
|
||||
assert rows["DEF-1"]["pac_dependencia"] == "CALLES Y CAMINOS"
|
||||
assert rows["DEF-2"]["pac_dependencia"] == "GOBIERNO"
|
||||
# Defaults go through the same validation/normalization as mapped cells.
|
||||
assert rows["DEF-1"]["pac_parentesco"] == rows["DEF-2"]["pac_parentesco"] == "Afiliado"
|
||||
|
||||
|
||||
def test_several_sources_compose_several_tables_in_one_batch(client):
|
||||
"""One Excel workbook feeds two tables (a source per sheet), a CSV adds
|
||||
more patients, and a JSON source feeds a third table, all in one batch
|
||||
and one transaction."""
|
||||
workbook = openpyxl.Workbook()
|
||||
pacientes = workbook.active
|
||||
pacientes.title = "Pacientes"
|
||||
pacientes.append(["Expediente", "Sexo", "Nacimiento"])
|
||||
pacientes.append(["MIX-1", "F", "1990-01-01"])
|
||||
ordenes = workbook.create_sheet("Ordenes")
|
||||
ordenes.append(["Folio", "Expediente", "Tipo"])
|
||||
ordenes.append([9001, "MIX-1", "Solicitud de Papanicolao en Base Liquida"])
|
||||
buffer = io.BytesIO()
|
||||
workbook.save(buffer)
|
||||
xlsx = _b64(buffer.getvalue())
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/file/preview",
|
||||
data={"file": (io.BytesIO(buffer.getvalue()), "libro.xlsx"), "source_kind": "excel", "target": "cacu.OrdenesEstudio", "options": json.dumps({"sheet_name": "Ordenes"})},
|
||||
content_type="multipart/form-data",
|
||||
).get_json()
|
||||
assert preview["source_metadata"] == {"sheets": ["Pacientes", "Ordenes"], "sheet_name": "Ordenes"}
|
||||
assert [c["name"] for c in preview["columns"]] == ["Folio", "Expediente", "Tipo"]
|
||||
|
||||
batch = [
|
||||
{"source_type": "excel", "label": "libro.xlsx › Pacientes", "target": "cacu.Paciente", "column_mapping": {"Expediente": "pac_id_hospital", "Sexo": "pac_sexo", "Nacimiento": "pac_fecha_nacimiento"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Pacientes"}}},
|
||||
_csv("id,genero,nac\nMIX-2,M,1990-01-01\n", {"id": "pac_id_hospital", "genero": "pac_sexo", "nac": "pac_fecha_nacimiento"}, label="extra.csv"),
|
||||
{"source_type": "excel", "target": "cacu.OrdenesEstudio", "column_mapping": {"Folio": "ord_numero_hospital", "Expediente": "pac_id_hospital", "Tipo": "ord_tipo_estudio"}, "payload": {"file_base64": xlsx, "options": {"sheet_name": "Ordenes"}}},
|
||||
{"source_type": "json", "target": "cacu.BiometriaHematica", "column_mapping": {"paciente.exp": "pac_id_hospital", "hb": "hemoglobina_g_dl"}, "payload": {"file_base64": _b64(json.dumps([{"paciente": {"exp": "MIX-1"}, "hb": 13.5}]).encode())}},
|
||||
]
|
||||
body = client.post("/imports/commit", json={"sources": batch}).get_json()
|
||||
assert body["ok"] is True
|
||||
assert [(r["label"], r["target"], r["created"]) for r in body["results"]] == [
|
||||
("libro.xlsx › Pacientes", "cacu.Paciente", 1),
|
||||
("extra.csv", "cacu.Paciente", 1),
|
||||
(None, "cacu.OrdenesEstudio", 1),
|
||||
(None, "cacu.BiometriaHematica", 1),
|
||||
]
|
||||
assert {"MIX-1", "MIX-2"} <= set(_rows(client, "cacu.Paciente"))
|
||||
orden = client.get("/data/cacu.OrdenesEstudio").get_json()["rows"][0]
|
||||
assert orden["ord_numero_hospital"] == 9001
|
||||
|
||||
|
||||
def test_conflicts_are_itemized_with_their_row(client):
|
||||
body = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv(
|
||||
"exp,nac\nDUP-1,1990-01-01\nDUP-1,1990-01-01\n",
|
||||
{"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"},
|
||||
)
|
||||
]
|
||||
},
|
||||
).get_json()
|
||||
result = body["results"][0]
|
||||
assert (result["created"], result["rejected"]) == (1, 1)
|
||||
assert result["errors"] == [
|
||||
{"row_index": 1, "field": "pac_id_hospital", "category": "conflict", "message": "conflict on ('pac_id_hospital',)", "raw_value": "DUP-1"}
|
||||
]
|
||||
|
||||
|
||||
def test_a_failing_source_rolls_back_the_whole_batch(client, monkeypatch):
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from persistance.repository import Repository
|
||||
|
||||
original = Repository.bulk_upsert
|
||||
calls = {"n": 0}
|
||||
|
||||
def flaky(self, objs, **kwargs):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
raise OperationalError("INSERT ...", {}, Exception("disk full"))
|
||||
return original(self, objs, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Repository, "bulk_upsert", flaky)
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
_csv("exp,nac\nATOM-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
_csv("exp,nac\nATOM-2,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
]
|
||||
},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "no se escribió nada" in response.get_json()["error"]
|
||||
assert not {"ATOM-1", "ATOM-2"} & set(_rows(client, "cacu.Paciente"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"sources": [{"source_type": "csv", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "%%%not-base64"}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "no_such_field"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": [{"source_type": "csv", "target": "cacu.Paciente", "column_mapping": {"a": "pac_sexo", "b": "pac_sexo"}, "payload": {"file_base64": "YQ=="}}]},
|
||||
{"sources": "nope"},
|
||||
{"sources": [{"source_type": "pdf", "target": "cacu.Paciente", "column_mapping": {"a": "pac_id_hospital"}, "payload": {"file_base64": "YQ==", "mode": "regions", "regions": [], "dpi": 5000}}]},
|
||||
],
|
||||
)
|
||||
def test_malformed_commits_are_400_not_500(client, payload):
|
||||
response = client.post("/imports/commit", json=payload)
|
||||
assert response.status_code == 400, response.get_json()
|
||||
assert response.get_json()["error"]
|
||||
|
||||
|
||||
def test_page_image_rejects_absurd_dpi(client):
|
||||
from reportlab.pdfgen import canvas
|
||||
|
||||
buffer = io.BytesIO()
|
||||
pdf = canvas.Canvas(buffer)
|
||||
pdf.drawString(72, 720, "hola")
|
||||
pdf.save()
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(buffer.getvalue()), "a.pdf"), "page_number": "1", "dpi": "5000"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "dpi" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_data_endpoint_pages_through_the_repository(client):
|
||||
body = client.get("/data/cacu.Paciente?limit=2").get_json()
|
||||
assert body["limit"] == 2 and len(body["rows"]) == 2 and body["total"] >= 2
|
||||
assert client.get("/data/cacu.Nope").status_code == 404
|
||||
|
||||
|
||||
def test_children_are_linked_to_parents_loaded_in_the_same_batch_whatever_the_order(client):
|
||||
"""Biopsies listed before their patients still get `pac_id` filled, since
|
||||
parents are written first within the batch's transaction. A child whose
|
||||
patient doesn't exist keeps a null FK."""
|
||||
from webapi.imports.services.link_resolver import dependency_rank, links_for
|
||||
|
||||
assert [link.fk_field for link in links_for("cacu.BiopsiaCervical")] == ["pac_id"]
|
||||
assert links_for("cacu.Paciente") == ()
|
||||
assert [link.fk_field for link in links_for("cama.Mastografia")] == ["pac_id", "ord_id"]
|
||||
assert dependency_rank("cama.Paciente") < dependency_rank("cama.OrdenesEstudio") < dependency_rank("cama.Mastografia")
|
||||
|
||||
batch = [
|
||||
_csv("exp,grado\nLINK-1,NORMAL\nNO-SUCH-PATIENT,NORMAL\n", {"exp": "pac_id_hospital", "grado": "bx_cin_grado"}, target="cacu.BiopsiaCervical"),
|
||||
_csv("exp,nac\nLINK-1,1990-01-01\n", {"exp": "pac_id_hospital", "nac": "pac_fecha_nacimiento"}),
|
||||
]
|
||||
body = client.post("/imports/commit", json={"sources": batch}).get_json()
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.BiopsiaCervical", "cacu.Paciente"]
|
||||
assert body["results"][0]["linked"] == {"pac_id": 1}
|
||||
|
||||
patient = _rows(client, "cacu.Paciente")["LINK-1"]
|
||||
biopsies = {r["pac_id_hospital"]: r for r in client.get("/data/cacu.BiopsiaCervical?limit=500").get_json()["rows"]}
|
||||
assert biopsies["LINK-1"]["pac_id"] == patient["pac_id"]
|
||||
assert biopsies["NO-SUCH-PATIENT"]["pac_id"] is None
|
||||
|
||||
|
||||
def test_data_endpoint_reports_columns_in_table_order(client):
|
||||
body = client.get("/data/cacu.Paciente?limit=1").get_json()
|
||||
assert body["columns"][:2] == ["pac_id", "pac_id_hospital"]
|
||||
@@ -0,0 +1,244 @@
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
_PACIENTE_MAPPING = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
}
|
||||
|
||||
|
||||
def _csv_source(csv_bytes: bytes, *, target: str, column_mapping: dict | None = None) -> dict:
|
||||
return {
|
||||
"source_type": "csv",
|
||||
"target": target,
|
||||
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
|
||||
}
|
||||
|
||||
|
||||
def _json_source(records: list[dict], *, target: str, column_mapping: dict | None = None) -> dict:
|
||||
raw = json.dumps(records).encode()
|
||||
return {
|
||||
"source_type": "json",
|
||||
"target": target,
|
||||
"column_mapping": column_mapping or _PACIENTE_MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(raw).decode()},
|
||||
}
|
||||
|
||||
|
||||
def test_get_targets_lists_registered_entities(client):
|
||||
response = client.get("/imports/targets")
|
||||
assert response.status_code == 200
|
||||
keys = {t["key"] for t in response.get_json()["targets"]}
|
||||
assert {"cacu.Paciente", "tea.Pacientes"} <= keys
|
||||
cacu_target = next(t for t in response.get_json()["targets"] if t["key"] == "cacu.Paciente")
|
||||
assert cacu_target["conflict_fields"] == ["pac_id_hospital"]
|
||||
assert any(f["name"] == "pac_id_hospital" and f["required"] for f in cacu_target["fields"])
|
||||
|
||||
|
||||
def test_file_preview_returns_columns_sample_rows_and_suggested_mapping(client):
|
||||
csv_bytes = b"pac_id_hospital,Sexo\nH-PREVIEW-1,F\n"
|
||||
data = {
|
||||
"file": (io.BytesIO(csv_bytes), "pacientes.csv"),
|
||||
"source_kind": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
}
|
||||
response = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert {c["name"] for c in body["columns"]} == {"pac_id_hospital", "Sexo"}
|
||||
assert body["total_rows"] == 1
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["pac_id_hospital"] == "pac_id_hospital"
|
||||
assert suggested["Sexo"] == "pac_sexo"
|
||||
|
||||
|
||||
def test_validate_reports_row_errors_without_writing(client):
|
||||
csv_bytes = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-VALIDATE-1,F,1990-01-01\n,M,1990-01-01\n"
|
||||
response = client.post("/imports/validate", json={"source": _csv_source(csv_bytes, target="cacu.Paciente")})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["total_rows"] == 2
|
||||
assert body["valid_count"] == 1
|
||||
assert body["error_count"] == 1
|
||||
assert body["errors"][0]["field"] == "pac_id_hospital"
|
||||
assert "H-VALIDATE-1" not in _patients(client)
|
||||
|
||||
|
||||
def test_commit_multi_source_batch_mixes_file_and_sql_within_one_domain(client, tmp_path):
|
||||
# A batch can mix file and SQL sources targeting the same domain: here a
|
||||
# CSV and a live SQL connection both land in cacu.Paciente in one commit.
|
||||
# Uses its own SQL fixture (distinct hospital id) because the row in
|
||||
# `sql_source_db` is also used by another test against this cacu.db.
|
||||
source_db_path = tmp_path / "batch_source.db"
|
||||
source_engine = create_engine(f"sqlite:///{source_db_path}")
|
||||
with source_engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-BATCH-1', 'M', '1990-01-01')"
|
||||
)
|
||||
)
|
||||
|
||||
cacu_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-BATCH-1,F,1990-01-01\n"
|
||||
csv_source = _csv_source(cacu_csv, target="cacu.Paciente")
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {"connection_string": f"sqlite:///{source_db_path}", "table": "hospital_patients"},
|
||||
}
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [csv_source, sql_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["ok"] is True
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.Paciente", "cacu.Paciente"]
|
||||
assert sum(r["created"] for r in body["results"]) == 2
|
||||
assert {"H-BATCH-1", "H-SQL-BATCH-1"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_rejects_a_batch_mixing_domains(client):
|
||||
cacu_source = _csv_source(b"pac_id_hospital,pac_sexo\nH-MIX-1,F\n", target="cacu.Paciente")
|
||||
tea_source = _json_source([{"pac_id_hospital": "T-MIX-1"}], target="tea.Pacientes",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"})
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [cacu_source, tea_source], "on_conflict": "reject"})
|
||||
assert response.status_code == 400
|
||||
assert "dominios" in response.get_json()["error"]
|
||||
|
||||
|
||||
def test_commit_on_conflict_reject_then_upsert(client):
|
||||
first_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,F,1990-01-01\n"
|
||||
first = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
||||
)
|
||||
assert first.get_json()["results"][0]["created"] == 1
|
||||
|
||||
reject_again = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(first_csv, target="cacu.Paciente")], "on_conflict": "reject"},
|
||||
)
|
||||
reject_body = reject_again.get_json()["results"][0]
|
||||
assert reject_body["created"] == 0
|
||||
assert reject_body["rejected"] == 1
|
||||
|
||||
upsert_csv = b"pac_id_hospital,pac_sexo,pac_fecha_nacimiento\nH-CONFLICT-1,M,1990-01-01\n"
|
||||
upsert = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [_csv_source(upsert_csv, target="cacu.Paciente")], "on_conflict": "upsert"},
|
||||
)
|
||||
upsert_body = upsert.get_json()["results"][0]
|
||||
assert upsert_body["created"] == 0
|
||||
assert upsert_body["updated"] == 1
|
||||
|
||||
|
||||
def test_commit_upsert_rejected_for_target_without_natural_key(client):
|
||||
source = _json_source(
|
||||
[{"pac_id_hospital": "H-NO-KEY"}], target="cacu.BiometriaHematica",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"},
|
||||
)
|
||||
response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_tea_patient_keeps_the_source_id_and_reimport_updates_it(client):
|
||||
mapping = {"pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento"}
|
||||
first = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-05-01"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [first], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
|
||||
again = _json_source([{"pac_id": 9001, "pac_id_hospital": "T-SRC-1", "pac_fecha_nacimiento": "2023-06-01"}],
|
||||
target="tea.Pacientes", column_mapping=mapping)
|
||||
body = client.post("/imports/commit", json={"sources": [again], "on_conflict": "upsert"}).get_json()
|
||||
assert body["results"][0]["created"] == 0
|
||||
assert body["results"][0]["updated"] == 1
|
||||
|
||||
[paciente] = client.get("/data/tea.Pacientes").get_json()["rows"]
|
||||
assert paciente["pac_id"] == 9001 and paciente["pac_id_hospital"] == "T-SRC-1"
|
||||
assert paciente["pac_fecha_nacimiento"] == "2023-06-01"
|
||||
|
||||
|
||||
def test_an_import_into_tea_queues_its_recomputation(client):
|
||||
"""Pins down: TEA's measures come from the cycle like CaCu's and CaMa's, so a TEA import saves its rows and
|
||||
asks for a recomputation of TEA.
|
||||
|
||||
Fails if TEA leaves the queue's domains (`DOMAINS` in `webapi.recomputation`).
|
||||
"""
|
||||
source = _json_source([{"pac_id_hospital": "T-RECALC"}], target="tea.Pacientes",
|
||||
column_mapping={"pac_id_hospital": "pac_id_hospital"})
|
||||
response = client.post("/imports/commit", json={"sources": [source]})
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["results"][0]["created"] == 1
|
||||
assert body["indicadores_en_recalculo"] is True
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sql_source_db(tmp_path):
|
||||
db_path = tmp_path / "external_source.db"
|
||||
url = f"sqlite:///{db_path}"
|
||||
engine = create_engine(url)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("CREATE TABLE hospital_patients (id_hospital TEXT, sexo TEXT, nacimiento TEXT)"))
|
||||
conn.execute(
|
||||
text("INSERT INTO hospital_patients (id_hospital, sexo, nacimiento) VALUES ('H-SQL-1', 'F', '1990-01-01')")
|
||||
)
|
||||
return url
|
||||
|
||||
|
||||
def test_sql_source_introspection_preview_and_commit(client, sql_source_db):
|
||||
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": sql_source_db})
|
||||
assert test_conn.status_code == 200
|
||||
assert test_conn.get_json()["dialect"] == "sqlite"
|
||||
|
||||
tables = client.post("/imports/sources/sql/tables", json={"connection_string": sql_source_db})
|
||||
assert "hospital_patients" in tables.get_json()["tables"]
|
||||
|
||||
columns = client.post(
|
||||
"/imports/sources/sql/columns", json={"connection_string": sql_source_db, "table": "hospital_patients"}
|
||||
)
|
||||
assert {c["name"] for c in columns.get_json()["columns"]} == {"id_hospital", "sexo", "nacimiento"}
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/sql/preview",
|
||||
json={"connection_string": sql_source_db, "table": "hospital_patients", "target": "cacu.Paciente"},
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
assert preview.get_json()["total_rows"] == 1
|
||||
|
||||
sql_import_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo", "nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {"connection_string": sql_source_db, "table": "hospital_patients"},
|
||||
}
|
||||
commit_response = client.post("/imports/commit", json={"sources": [sql_import_source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
assert commit_response.get_json()["results"][0]["created"] == 1
|
||||
@@ -0,0 +1,163 @@
|
||||
"""Fills `cacu.Paciente` from a MySQL legacy table, a CSV and a JSON file in
|
||||
one batch, through the HTTP endpoints with the `pymysql` driver.
|
||||
|
||||
Skipped unless `MYSQL_TEST_URL` is set; see `tests/test_connectors_mysql.py`
|
||||
for a local setup.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
MYSQL_TEST_URL = os.environ.get("MYSQL_TEST_URL")
|
||||
|
||||
pytestmark = pytest.mark.skipif(not MYSQL_TEST_URL, reason="MYSQL_TEST_URL not set")
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def mysql_legacy_source():
|
||||
"""A legacy MySQL table whose column names and types are unrelated to
|
||||
`Core`'s `Paciente`."""
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
table_name = "test_multisource_legacy_patients"
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"CREATE TABLE {table_name} ("
|
||||
" expediente VARCHAR(40) NOT NULL PRIMARY KEY,"
|
||||
" sexo_paciente ENUM('F','M')"
|
||||
") ENGINE=InnoDB"
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
sa.text(
|
||||
f"INSERT INTO {table_name} (expediente, sexo_paciente) VALUES "
|
||||
"('MYSQL-MULTI-1', 'F'), ('MYSQL-MULTI-2', 'M')"
|
||||
)
|
||||
)
|
||||
yield table_name
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text(f"DROP TABLE IF EXISTS {table_name}"))
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_sql_source_http_endpoints_browse_real_mysql_schema(client, mysql_legacy_source):
|
||||
"""The schema-browsing flow the WebApp SQL wizard drives (test-connection
|
||||
-> schemas -> tables -> columns -> preview) against MySQL."""
|
||||
test_conn = client.post("/imports/sources/sql/test-connection", json={"connection_string": MYSQL_TEST_URL})
|
||||
assert test_conn.status_code == 200
|
||||
assert test_conn.get_json()["dialect"] == "mysql"
|
||||
|
||||
schemas = client.post("/imports/sources/sql/schemas", json={"connection_string": MYSQL_TEST_URL})
|
||||
assert "hospital_legacy" in schemas.get_json()["schemas"]
|
||||
|
||||
tables = client.post(
|
||||
"/imports/sources/sql/tables", json={"connection_string": MYSQL_TEST_URL, "schema": "hospital_legacy"}
|
||||
)
|
||||
assert mysql_legacy_source in tables.get_json()["tables"]
|
||||
|
||||
columns = client.post(
|
||||
"/imports/sources/sql/columns",
|
||||
json={"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source, "schema": "hospital_legacy"},
|
||||
)
|
||||
assert {c["name"] for c in columns.get_json()["columns"]} == {"expediente", "sexo_paciente"}
|
||||
|
||||
preview = client.post(
|
||||
"/imports/sources/sql/preview",
|
||||
json={
|
||||
"connection_string": MYSQL_TEST_URL,
|
||||
"table": mysql_legacy_source,
|
||||
"schema": "hospital_legacy",
|
||||
"target": "cacu.Paciente",
|
||||
},
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
body = preview.get_json()
|
||||
assert body["total_rows"] == 2
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
# "expediente" is a column_matcher synonym for pac_id_hospital.
|
||||
assert suggested.get("expediente") == "pac_id_hospital"
|
||||
|
||||
|
||||
def test_commit_batch_mixes_mysql_json_and_csv_into_one_domain(client, mysql_legacy_source):
|
||||
csv_bytes = b"pac_id_hospital,pac_sexo\nCSV-MULTI-1,F\n"
|
||||
csv_source = {
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"},
|
||||
"payload": {"file_base64": base64.b64encode(csv_bytes).decode()},
|
||||
}
|
||||
|
||||
json_records = [{"id_hospital": "JSON-MULTI-1", "sexo": "M"}]
|
||||
json_source = {
|
||||
"source_type": "json",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"id_hospital": "pac_id_hospital", "sexo": "pac_sexo"},
|
||||
"payload": {"file_base64": base64.b64encode(json.dumps(json_records).encode()).decode()},
|
||||
}
|
||||
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={"sources": [csv_source, json_source, sql_source], "on_conflict": "reject"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["ok"] is True
|
||||
assert [r["target"] for r in body["results"]] == ["cacu.Paciente"] * 3
|
||||
# csv: 1 row, json: 1 row, mysql: 2 rows
|
||||
assert [r["created"] for r in body["results"]] == [1, 1, 2]
|
||||
|
||||
assert {"CSV-MULTI-1", "JSON-MULTI-1", "MYSQL-MULTI-1", "MYSQL-MULTI-2"} <= set(_patients(client))
|
||||
|
||||
|
||||
def test_commit_upsert_against_mysql_source_updates_existing_row(client, mysql_legacy_source):
|
||||
sql_source = {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo_paciente": "pac_sexo"},
|
||||
"payload": {"connection_string": MYSQL_TEST_URL, "table": mysql_legacy_source},
|
||||
}
|
||||
assert client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"}).status_code == 200
|
||||
|
||||
engine = sa.create_engine(MYSQL_TEST_URL)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(
|
||||
sa.text(f"UPDATE {mysql_legacy_source} SET sexo_paciente = 'M' WHERE expediente = 'MYSQL-MULTI-1'")
|
||||
)
|
||||
engine.dispose()
|
||||
|
||||
response = client.post("/imports/commit", json={"sources": [sql_source], "on_conflict": "upsert"})
|
||||
assert response.status_code == 200
|
||||
result = response.get_json()["results"][0]
|
||||
# Upsert reports "updated" for every row that already existed, changed or not.
|
||||
assert result["updated"] == 2
|
||||
assert result["created"] == 0
|
||||
# 'M' is coerced through SEXO_BIOLOGICO_ALIAS into the canonical value.
|
||||
assert _patients(client)["MYSQL-MULTI-1"]["pac_sexo"] == "Masculino"
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Endpoint tests for the PDF routes. One round trip per resolution path:
|
||||
- detect -> table/preview -> validate -> commit, for the ruled-table
|
||||
path, writing into `cacu.Paciente`.
|
||||
- detect -> page-image -> regions/extract -> validate -> commit, for the
|
||||
OCR/region path, writing into `cacu.Paciente` as well.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from reportlab.lib import colors
|
||||
from reportlab.lib.pagesizes import letter
|
||||
from reportlab.lib.utils import ImageReader
|
||||
from reportlab.pdfgen import canvas
|
||||
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
||||
|
||||
|
||||
def _patients(client) -> dict[str, dict]:
|
||||
rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"]
|
||||
return {row["pac_id_hospital"]: row for row in rows}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Fixture PDFs
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def _build_table_pdf(rows: list[tuple[str, str, str]]) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
||||
data = [["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"], *[list(row) for row in rows]]
|
||||
table = Table(data)
|
||||
table.setStyle(
|
||||
TableStyle(
|
||||
[
|
||||
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
||||
("FONTSIZE", (0, 0), (-1, -1), 12),
|
||||
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
||||
("TOPPADDING", (0, 0), (-1, -1), 8),
|
||||
]
|
||||
)
|
||||
)
|
||||
doc.build([table])
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
_IMG_W, _IMG_H = 900, 1200
|
||||
|
||||
|
||||
def _font(size: int = 34):
|
||||
for path in (
|
||||
"/System/Library/Fonts/Helvetica.ttc",
|
||||
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
||||
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
||||
):
|
||||
try:
|
||||
return ImageFont.truetype(path, size)
|
||||
except Exception:
|
||||
continue
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def _build_scanned_form_pdf(id_hospital: str, sexo: str, nacimiento: str = "1980-05-17") -> bytes:
|
||||
"""A scanned-like page with three text blocks on one line at known pixel
|
||||
positions and no text layer, so only the OCR/region path applies. The birth
|
||||
date is there because a patient row is not valid without it."""
|
||||
img = Image.new("RGB", (_IMG_W, _IMG_H), "white")
|
||||
draw = ImageDraw.Draw(img)
|
||||
font = _font()
|
||||
draw.text((40, 100), id_hospital, fill="black", font=font)
|
||||
draw.text((400, 100), sexo, fill="black", font=font)
|
||||
draw.text((560, 100), nacimiento, fill="black", font=font)
|
||||
|
||||
buffer = io.BytesIO()
|
||||
c = canvas.Canvas(buffer, pagesize=letter)
|
||||
page_w, page_h = letter
|
||||
reader_buf = io.BytesIO()
|
||||
img.save(reader_buf, format="PNG")
|
||||
reader_buf.seek(0)
|
||||
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
||||
c.showPage()
|
||||
c.save()
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
_ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H)
|
||||
_SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H)
|
||||
_NACIMIENTO_BBOX = (540 / _IMG_W, 60 / _IMG_H, 880 / _IMG_W, 180 / _IMG_H)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# Table path: detect -> table/preview -> validate -> commit (cacu.Paciente)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_table_round_trip_detect_preview_validate_commit(client):
|
||||
pdf_bytes = _build_table_pdf([("H-PDF-TAB-1", "F", "1990-01-01"), ("H-PDF-TAB-2", "M", "1985-06-15")])
|
||||
|
||||
detect_response = client.post(
|
||||
"/imports/sources/pdf/detect",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "table.pdf")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert detect_response.status_code == 200
|
||||
detect_body = detect_response.get_json()
|
||||
assert detect_body["page_count"] == 1
|
||||
assert detect_body["has_text_layer"] is True
|
||||
assert len(detect_body["table_candidates"]) == 1
|
||||
candidate = detect_body["table_candidates"][0]
|
||||
assert candidate["row_count"] == 2
|
||||
assert candidate["column_count"] == 3
|
||||
|
||||
preview_response = client.post(
|
||||
"/imports/sources/pdf/table/preview",
|
||||
data={
|
||||
"file": (io.BytesIO(pdf_bytes), "table.pdf"),
|
||||
"page_number": str(candidate["page_number"]),
|
||||
"bbox": json.dumps(candidate["bbox"]),
|
||||
"target": "cacu.Paciente",
|
||||
},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert preview_response.status_code == 200
|
||||
preview_body = preview_response.get_json()
|
||||
assert {c["name"] for c in preview_body["columns"]} == {"pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"}
|
||||
assert preview_body["total_rows"] == 2
|
||||
suggested = {m["source_column"]: m["target_field"] for m in preview_body["suggested_mapping"]}
|
||||
assert suggested["pac_id_hospital"] == "pac_id_hospital"
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "table",
|
||||
"page_number": candidate["page_number"],
|
||||
"bbox": candidate["bbox"],
|
||||
},
|
||||
}
|
||||
|
||||
validate_response = client.post("/imports/validate", json={"source": source})
|
||||
assert validate_response.status_code == 200
|
||||
validate_body = validate_response.get_json()
|
||||
assert validate_body["total_rows"] == 2
|
||||
assert validate_body["valid_count"] == 2
|
||||
assert validate_body["error_count"] == 0
|
||||
|
||||
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 2
|
||||
|
||||
assert "H-PDF-TAB-1" in _patients(client)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# page-image endpoint
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_page_image_returns_png(client):
|
||||
pdf_bytes = _build_scanned_form_pdf("H-IMG-1", "F")
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type == "image/png"
|
||||
image = Image.open(io.BytesIO(response.data))
|
||||
assert image.format == "PNG"
|
||||
|
||||
|
||||
def test_pdf_page_image_missing_file_returns_400(client):
|
||||
response = client.post(
|
||||
"/imports/sources/pdf/page-image", data={"page_number": "1"}, content_type="multipart/form-data"
|
||||
)
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------
|
||||
# OCR/region path: detect -> page-image -> regions/extract -> validate ->
|
||||
# commit (cacu.Paciente)
|
||||
# ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pdf_region_round_trip_detect_image_extract_validate_commit(client):
|
||||
pdf_bytes = _build_scanned_form_pdf("H-PDF-OCR-1", "F")
|
||||
|
||||
detect_response = client.post(
|
||||
"/imports/sources/pdf/detect",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf")},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert detect_response.status_code == 200
|
||||
detect_body = detect_response.get_json()
|
||||
assert detect_body["has_text_layer"] is False
|
||||
assert detect_body["table_candidates"] == []
|
||||
|
||||
image_response = client.post(
|
||||
"/imports/sources/pdf/page-image",
|
||||
data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"},
|
||||
content_type="multipart/form-data",
|
||||
)
|
||||
assert image_response.status_code == 200
|
||||
assert Image.open(io.BytesIO(image_response.data)).format == "PNG"
|
||||
|
||||
regions = [
|
||||
{"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)},
|
||||
{"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)},
|
||||
{"target_field": "pac_fecha_nacimiento", "page_numbers": [1], "bbox": list(_NACIMIENTO_BBOX)},
|
||||
]
|
||||
extract_response = client.post(
|
||||
"/imports/sources/pdf/regions/extract",
|
||||
json={"file_base64": base64.b64encode(pdf_bytes).decode(), "regions": regions},
|
||||
)
|
||||
assert extract_response.status_code == 200
|
||||
extract_body = extract_response.get_json()
|
||||
assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1980-05-17"}]
|
||||
assert extract_body["warnings"] == []
|
||||
|
||||
source = {
|
||||
"source_type": "pdf",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo", "pac_fecha_nacimiento": "pac_fecha_nacimiento"},
|
||||
"payload": {
|
||||
"file_base64": base64.b64encode(pdf_bytes).decode(),
|
||||
"mode": "regions",
|
||||
"regions": regions,
|
||||
},
|
||||
}
|
||||
|
||||
validate_response = client.post("/imports/validate", json={"source": source})
|
||||
assert validate_response.status_code == 200
|
||||
validate_body = validate_response.get_json()
|
||||
assert validate_body["total_rows"] == 1
|
||||
assert validate_body["valid_count"] == 1
|
||||
|
||||
commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"})
|
||||
assert commit_response.status_code == 200
|
||||
commit_body = commit_response.get_json()
|
||||
assert commit_body["ok"] is True
|
||||
result = commit_body["results"][0]
|
||||
assert result["target"] == "cacu.Paciente"
|
||||
assert result["created"] == 1
|
||||
|
||||
|
||||
def test_pdf_detect_missing_file_returns_400(client):
|
||||
response = client.post("/imports/sources/pdf/detect", data={}, content_type="multipart/form-data")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_pdf_regions_extract_missing_field_returns_400(client):
|
||||
response = client.post("/imports/sources/pdf/regions/extract", json={"regions": []})
|
||||
assert response.status_code == 400
|
||||
@@ -0,0 +1,135 @@
|
||||
"""What this module covers: `webapi.kpis`, the route that answers a measure's periods on request as a FHIR `Bundle`
|
||||
of `MeasureReport`s.
|
||||
|
||||
Fixtures: `base`, `manifest` and `kit` from `test_metrics_on_request` (the CaCu fixture database through the cycle,
|
||||
dbt's manifest, the kit's snapshot; skipped without `DBT_MANIFEST`); `client`, a Flask app with only this domain's KPI
|
||||
blueprint.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
|
||||
from test_metrics_on_request import EU7, EU13, IND1, base, kit, manifest, reports # noqa: F401
|
||||
from webapi.kpis import kpis_blueprint
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(base, manifest): # noqa: F811
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(kpis_blueprint("cacu", base.dominio, manifest), url_prefix="/cacu")
|
||||
return app.test_client()
|
||||
|
||||
|
||||
def counts(resource: dict) -> dict[str, int]:
|
||||
(group,) = resource["group"]
|
||||
return {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
||||
|
||||
|
||||
def history_entry(resource: dict) -> int:
|
||||
(entry,) = [e for e in resource["extension"] if e["url"].endswith("/reporte-id")]
|
||||
return entry["valueInteger"]
|
||||
|
||||
|
||||
def test_a_measure_s_periods_come_as_a_bundle_of_measure_reports(base, client, kit): # noqa: F811
|
||||
"""Pins down the contract: one `MeasureReport` per period asked, in order, with the kit's numbers. Fails if the
|
||||
route stops answering each period, changes the shape, or the counts drift from what the cycle published."""
|
||||
response = client.get("/cacu/indicadores/IND1?periodos=2025-S1,2025-S2")
|
||||
bundle = response.get_json(force=True)
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
|
||||
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 2)
|
||||
for entry, period_id in zip(bundle["entry"], ("2025-S1", "2025-S2")):
|
||||
report = entry["resource"]
|
||||
assert report["resourceType"] == "MeasureReport" and report["measure"] == "cacu/IND1|0.3.2"
|
||||
numerator, denominator = kit[IND1][period_id]["published"]["total|total"]
|
||||
assert counts(report) == {"initial-population": denominator, "denominator": denominator,
|
||||
"numerator": numerator}
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_ind1.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
def test_without_a_knowledge_cutoff_the_last_load_makes_the_answer_stable(base, client): # noqa: F811
|
||||
"""Pins down: by default the knowledge cut-off is the last load's start, so asking again before the next load
|
||||
reads the stored answer. Fails if the default becomes "now", which would store a new answer per request."""
|
||||
first = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
|
||||
before = reports(base)
|
||||
second = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
|
||||
|
||||
assert history_entry(second["entry"][0]["resource"]) == history_entry(first["entry"][0]["resource"])
|
||||
assert reports(base) == before
|
||||
|
||||
|
||||
def test_a_measure_with_strata_brings_its_stratifier(client):
|
||||
"""Pins down: EU13's reports carry its strata, by age and by follow-up status. Fails if the route drops one."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_EU13?periodos=2025-S1").get_json(force=True)
|
||||
stratifiers = bundle["entry"][0]["resource"]["group"][0]["stratifier"]
|
||||
|
||||
assert [s["code"][0]["text"] for s in stratifiers] == ["grupo_edad", "estatus_seguimiento"]
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu13.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
def test_the_list_names_what_is_answered_on_request(client):
|
||||
"""Pins down: `/indicadores` lists the measures the manifest defines for the domain. Fails if one is missing."""
|
||||
listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()}
|
||||
|
||||
assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE",
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_CONFIRMACION_CITOLOGIA",
|
||||
"CACU_RIESGO_BANDA"}
|
||||
|
||||
|
||||
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
|
||||
"""Pins down the route for durations: the samples measurable and measured as populations, the median as the
|
||||
score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day
|
||||
by default). 2025-S2's samples resolved in 40 and 161 days. Fails if a duration stops being served or its
|
||||
contract changes."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True)
|
||||
(entry,) = bundle["entry"]
|
||||
report = entry["resource"]
|
||||
(group,) = report["group"]
|
||||
assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3"
|
||||
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
||||
"initial-population": 4, "measure-observation": 2}
|
||||
assert group["measureScore"]["value"] == 100.5 and group["measureScore"]["unit"] == "d"
|
||||
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [70.25, 130.75]
|
||||
assert any(e["url"].endswith("corte-evento") for e in report["extension"])
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("path", "status"), [
|
||||
("/cacu/indicadores/NOPE?periodos=2025-S1", 404),
|
||||
("/cacu/indicadores/IND1", 400),
|
||||
("/cacu/indicadores/IND1?periodos=2025-S1&corte_evento=30-06-2025", 400),
|
||||
("/cacu/indicadores/IND1?periodos=2025-S1&corte_conocimiento=ayer", 400),
|
||||
("/cacu/indicadores/IND1?periodos=2031-S1", 404),
|
||||
])
|
||||
def test_a_bad_question_gets_a_clear_error(client, path, status):
|
||||
"""Pins down the errors: an unknown measure or period is 404, a missing or misspelled parameter 400. Fails if one
|
||||
of them becomes a 500."""
|
||||
response = client.get(path)
|
||||
|
||||
assert response.status_code == status and "error" in response.get_json()
|
||||
|
||||
|
||||
def test_a_composition_comes_with_its_categories(client, kit):
|
||||
"""Pins down: EU7's reports carry the categories as a `resultado` stratifier, with the kit's counts, under the
|
||||
route's default knowledge cut-off (the last load). Fails if the route stops telling compositions from
|
||||
proportions, or a result's knowledge date stops being compared as the type it's stored in."""
|
||||
bundle = client.get("/cacu/indicadores/CACU_EU7?periodos=2025-S1,2025-S2").get_json(force=True)
|
||||
stratifiers = [e["resource"]["group"][0]["stratifier"][0] for e in bundle["entry"]]
|
||||
|
||||
assert [s["code"] for s in stratifiers] == [[{"text": "resultado"}]] * 2
|
||||
for stratifier, period_id in zip(stratifiers, ("2025-S1", "2025-S2")):
|
||||
expected = {k.split("|")[2]: n for k, n in kit[EU7][period_id]["published"].items() if k.startswith("total|")}
|
||||
assert {s["value"]["text"]: s["population"][0]["count"] for s in stratifier["stratum"]} == expected
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu7.json").write_text(
|
||||
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
@@ -0,0 +1,58 @@
|
||||
"""The live estimators the recomputation worker hands the cycle (`webapi.orchestration.estimators`,
|
||||
`webapi.recomputation`).
|
||||
|
||||
Fixtures: `base` (conftest) gives a migrated CaCu database with the synthetic staging; the registry and the live
|
||||
estimators are stubbed so no MLflow store or model is needed. The stub estimator is the cycle tests' `EstimadorFijo`.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orchestration import estimators
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
from tests.test_orquestacion_riesgos import URL, EstimadorFijo
|
||||
|
||||
|
||||
def test_only_cacu_has_a_live_estimator():
|
||||
"""CaMa and TEA have no registered model, so their cycles estimate nothing. Fails if a domain without a model
|
||||
gets an estimator that would then fail resolving a version."""
|
||||
assert estimators.live_estimators("cama") == {}
|
||||
assert estimators.live_estimators("tea") == {}
|
||||
|
||||
|
||||
def test_without_a_production_version_cacu_estimates_nothing(monkeypatch):
|
||||
"""No version in production means no estimator: `estimate` then no-ops instead of failing the whole cycle.
|
||||
Fails if `live_estimators` stops catching the registry's `LookupError`."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: (_ for _ in ()).throw(LookupError("none")))
|
||||
assert estimators.live_estimators("cacu") == {}
|
||||
|
||||
|
||||
def test_with_a_production_version_the_surveillance_cohort_gets_its_estimator(monkeypatch):
|
||||
"""With a version in production, the CaCu surveillance cohort is scored by `Cin2LogisticEstimator`, which
|
||||
reports nothing until it has estimated. Fails if the cohort url or the estimator contract changes."""
|
||||
from models.io.registry import registry
|
||||
|
||||
monkeypatch.setattr(registry, "resolve", lambda *a, **k: object())
|
||||
live = estimators.live_estimators("cacu")
|
||||
assert list(live) == [URL]
|
||||
estimator = live[URL]
|
||||
assert estimator.desenlace == "cin2_mas" and callable(estimator.estimar)
|
||||
with pytest.raises(RuntimeError):
|
||||
estimator.procedencia()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_the_worker_runs_the_cycle_with_the_live_estimators(base, tmp_path, monkeypatch):
|
||||
"""After an import the worker's run leaves a preliminary risk batch for every cohort with a live estimator.
|
||||
Fails if `RecomputationQueue.run` stops passing `live_estimators` to the context, or the batch is written
|
||||
as anything but `preliminary`."""
|
||||
monkeypatch.setattr(estimators, "live_estimators", lambda domain: {URL: EstimadorFijo()})
|
||||
result = RecomputationQueue(tmp_path / "indicadores").run("cacu", desde=2025, hasta=2025)
|
||||
assert result["estado"] == "ok", result
|
||||
assert [p["paso"] for p in result["pasos"]][-2:] == ["cohorts", "estimate"]
|
||||
with base.motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo_lote")).scalar_one() == 1
|
||||
assert con.execute(text("SELECT MIN(estado) FROM evaluacion_riesgo")).scalar_one() == "preliminary"
|
||||
assert con.execute(text("SELECT COUNT(*) FROM evaluacion_riesgo")).scalar_one() > 0
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Derived fields and document columns inside an ordinary mapping: target
|
||||
fields computed from several source columns (joined, split, picked, read
|
||||
out of a longer text or translated), files kept in a column of a CSV or
|
||||
SQL source read for the fields the plain mapping left empty, and the
|
||||
captions nothing used, as the import report lists them.
|
||||
|
||||
Fixtures: `client` (the app wired to a fresh CaCu database). Sources are
|
||||
built inline: CSV text through `_csv`, SQLite tables under `tmp_path`.
|
||||
"""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
from extraction.testing import text_pdf
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.mapping.derived import build_derivation, parse_derived
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def _csv(content: str, **source) -> dict:
|
||||
return {"source_type": "csv", "target": "cacu.Paciente", "payload": {"file_base64": _b64(content.encode())}, **source}
|
||||
|
||||
|
||||
ROW = {"nombre": " ana maría ", "paterno": "Pérez", "materno": "", "completo": "Ana María Pérez López", "dir": "Calle 5, CP 64000"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rule,expected",
|
||||
[
|
||||
({"op": "concat", "columns": ["nombre", "paterno", "materno"]}, "ana maría Pérez"),
|
||||
({"op": "concat", "columns": ["paterno", "nombre"], "separator": ", ", "case": "upper"}, "PÉREZ, ANA MARÍA"),
|
||||
({"op": "template", "template": "{paterno} {materno} / {nombre}"}, "Pérez / ana maría"),
|
||||
({"op": "split", "column": "completo", "start": 0, "stop": -2}, "Ana María"),
|
||||
({"op": "split", "column": "completo", "start": -2, "stop": -1}, "Pérez"),
|
||||
({"op": "coalesce", "columns": ["materno", "paterno"]}, "Pérez"),
|
||||
({"op": "extract", "column": "dir", "pattern": r"CP\s*(\d{5})", "group": 1}, "64000"),
|
||||
({"op": "map", "column": "paterno", "values": {"pérez": "P"}}, "P"),
|
||||
({"op": "map", "column": "nombre", "values": {"x": "y"}, "keep_unmatched": False}, None),
|
||||
({"op": "column", "column": "paterno"}, "Pérez"),
|
||||
],
|
||||
)
|
||||
def test_each_operation_computes_its_value(rule, expected):
|
||||
"""Pins what every registered operation returns for one row, blanks
|
||||
skipped and spaces collapsed. Fails if an operation's semantics change
|
||||
(`start`/`stop` counting, separators, `case`, unmatched values)."""
|
||||
assert build_derivation(rule).apply(ROW) == expected
|
||||
|
||||
|
||||
def test_rules_are_checked_before_any_row_is_read():
|
||||
"""Unknown operations, missing parameters, bad patterns and fields the
|
||||
target lacks are refused up front. Fails if `parse_derived` lets a
|
||||
malformed rule through to fail row by row."""
|
||||
for bad in ({"op": "nope"}, {"op": "concat"}, {"op": "extract", "column": "a", "pattern": "("}, {"op": "split", "column": "a", "case": "x"}):
|
||||
with pytest.raises(ConnectorError):
|
||||
build_derivation(bad)
|
||||
with pytest.raises(ConnectorError):
|
||||
parse_derived({"no_such_field": "a"}, {"pac_sexo"})
|
||||
|
||||
|
||||
def test_short_forms_name_a_column_or_join_several():
|
||||
"""A rule given as a column name reads it; a list of columns joins them.
|
||||
Fails if `rule_from` stops accepting the short forms."""
|
||||
rules = parse_derived({"a": "paterno", "b": ["nombre", "paterno"]}, {"a", "b"})
|
||||
assert rules["a"].apply(ROW) == "Pérez" and rules["b"].apply(ROW) == "ana maría Pérez"
|
||||
|
||||
|
||||
def test_derived_fields_reach_validation_and_the_mapped_preview(client):
|
||||
"""A source whose id is split over two columns and whose sex comes
|
||||
coded validates cleanly once `derived` joins and translates them, and
|
||||
`/imports/mapped-preview` shows the rows as they would be written.
|
||||
Fails if `ImportSource.rows` stops applying `derived`."""
|
||||
source = _csv(
|
||||
"serie,numero,sx,cp,nac\nA,001,1,64000,1980-01-02\nB,002,2,64100,1975-03-04\n",
|
||||
column_mapping={"cp": "pac_codigo_postal", "nac": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_id_hospital": {"op": "concat", "columns": ["serie", "numero"], "separator": "-"},
|
||||
"pac_sexo": {"op": "map", "column": "sx", "values": {"1": "F", "2": "M"}},
|
||||
},
|
||||
)
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert [(r["pac_id_hospital"], r["pac_sexo"]) for r in rows] == [("A-001", "F"), ("B-002", "M")]
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def test_a_field_cannot_be_both_mapped_and_derived(client):
|
||||
"""Fails if a field fed twice (mapping and `derived`) stops being refused."""
|
||||
source = _csv("a\n1\n", column_mapping={"a": "pac_id_hospital"}, derived={"pac_id_hospital": "a"})
|
||||
assert client.post("/imports/validate", json={"source": source}).status_code == 400
|
||||
|
||||
|
||||
def test_the_operations_are_listed_for_clients(client):
|
||||
"""`/imports/derivations` lists every operation with its parameters, so
|
||||
the import screen builds its forms from the server. Fails if an
|
||||
operation is registered without being described."""
|
||||
body = client.get("/imports/derivations").get_json()
|
||||
ops = {d["op"]: d for d in body["derivations"]}
|
||||
assert {"column", "concat", "template", "split", "coalesce", "extract", "map"} <= set(ops)
|
||||
assert [p["name"] for p in ops["split"]["params"]] == ["column", "separator", "start", "stop"]
|
||||
assert body["cases"] == ["upper", "lower", "title"]
|
||||
|
||||
|
||||
def _documents_table(tmp_path) -> str:
|
||||
"""Two rows of one order of patient P-7, one with its report as a PDF
|
||||
and one as base64 text, and a third row with no document."""
|
||||
url = f"sqlite:///{tmp_path / 'docs.db'}"
|
||||
report = text_pdf([["VPH alto riesgo: POSITIVO"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, orden INTEGER, archivo BLOB, texto TEXT)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-7', 5, :f, NULL)"), {"f": report})
|
||||
conn.execute(
|
||||
text("INSERT INTO t VALUES ('P-7', 5, NULL, :t)"), {"t": _b64(text_pdf([["Genotipo 16: DETECTADO"]]))}
|
||||
)
|
||||
conn.execute(text("INSERT INTO t VALUES ('P-8', 6, NULL, NULL)"))
|
||||
return url
|
||||
|
||||
|
||||
def _sql_source(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"column_mapping": {"pid": "pac_id_hospital", "orden": "ord_numero_hospital"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_a_sql_preview_flags_the_columns_that_hold_documents(client, tmp_path):
|
||||
"""Binary files and files written as base64 text are both flagged;
|
||||
plain values aren't. Fails if `document_columns` stops reaching the
|
||||
preview."""
|
||||
url = _documents_table(tmp_path)
|
||||
body = client.post("/imports/sources/sql/preview", json={"connection_string": url, "table": "t"}).get_json()
|
||||
assert set(body["document_columns"]) == {"archivo", "texto"}
|
||||
|
||||
|
||||
def test_document_columns_fill_what_the_mapping_leaves_empty(client, tmp_path):
|
||||
"""The mapped id and order are kept; the documents of both rows of the
|
||||
order add the fields they print; a row without documents passes
|
||||
through mapped. Fails if `documents` stops reading cells of an
|
||||
ordinary mapping, or loses the rows that have none."""
|
||||
source = _sql_source(_documents_table(tmp_path), documents={"columns": ["archivo", "texto"], "group_by": "orden"})
|
||||
rows = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
by_patient = {row["pac_id_hospital"]: row for row in rows}
|
||||
assert by_patient["P-7"]["ord_numero_hospital"] == 5
|
||||
assert by_patient["P-7"]["cit_vph_resultado"] == "POSITIVO"
|
||||
assert by_patient["P-7"]["cit_vph_genotipo_16"] == 1
|
||||
assert by_patient["P-8"]["ord_numero_hospital"] == 6
|
||||
|
||||
|
||||
def test_documents_of_a_mapping_can_be_reviewed_and_committed(client, tmp_path):
|
||||
"""`/imports/sources/document/extract` with `{source}` reviews the same
|
||||
records the commit writes, with the record's pages in `file_field`.
|
||||
Fails if the review and the commit read document columns differently."""
|
||||
source = _sql_source(
|
||||
_documents_table(tmp_path),
|
||||
documents={"columns": "archivo", "group_by": "orden", "file_field": "cit_pdf_blob"},
|
||||
label="t",
|
||||
)
|
||||
report = client.post("/imports/sources/document/extract", json={"source": source}).get_json()
|
||||
[record] = report["records"]
|
||||
assert record["fields"]["pac_id_hospital"]["method"] == "columna_fuente"
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
stored = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100)}
|
||||
assert stored["P-7"].cit_vph_resultado == "POSITIVO"
|
||||
assert stored["P-7"].cit_pdf_blob.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_a_csv_column_of_base64_documents_is_read_like_a_sql_one(client):
|
||||
"""Document columns are not tied to SQL: a CSV whose column carries
|
||||
base64 PDFs feeds the same extraction. Fails if `documents` only works
|
||||
for one kind of source."""
|
||||
report = _b64(text_pdf([["VPH alto riesgo: NEGATIVO"]]))
|
||||
source = _csv(
|
||||
f"exp,doc\nC-1,{report}\n",
|
||||
target="cacu.CitologiaCervical",
|
||||
column_mapping={"exp": "pac_id_hospital"},
|
||||
documents={"columns": "doc"},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert row["pac_id_hospital"] == "C-1" and row["cit_vph_resultado"] == "NEGATIVO"
|
||||
|
||||
|
||||
def _id_and_file_table(tmp_path) -> str:
|
||||
"""Each row has only an id and a file; every other value is printed
|
||||
in the file under captions no target field knows."""
|
||||
url = f"sqlite:///{tmp_path / 'files.db'}"
|
||||
report = text_pdf([["Tipo de persona: Mujer", "Domicilio actual: Calle 5, C.P. 64000", "Nacida el: 02/01/1980"]])
|
||||
with create_engine(url).begin() as conn:
|
||||
conn.execute(text("CREATE TABLE t (pid TEXT, archivo BLOB)"))
|
||||
conn.execute(text("INSERT INTO t VALUES ('Q-1', :f)"), {"f": report})
|
||||
return url
|
||||
|
||||
|
||||
def _paciente_from_file(url: str, **extra) -> dict:
|
||||
return {
|
||||
"source_type": "sql",
|
||||
"target": "cacu.Paciente",
|
||||
"payload": {"connection_string": url, "table": "t"},
|
||||
"documents": {"columns": "archivo"},
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def test_captions_printed_in_documents_are_offered_as_columns(client, tmp_path):
|
||||
"""`/imports/sources/document/columns` lists the source's own columns
|
||||
and every caption its documents print, with their values. Fails if
|
||||
discovered captions stop becoming columns of the source."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/columns", json={"source": _paciente_from_file(_id_and_file_table(tmp_path))}
|
||||
).get_json()
|
||||
names = [column["name"] for column in body["columns"]]
|
||||
assert {"pid", "Tipo de persona", "Domicilio actual", "Nacida el"} <= set(names)
|
||||
[row] = body["sample_rows"]
|
||||
assert row["Tipo de persona"] == "Mujer"
|
||||
|
||||
|
||||
def test_mapping_and_rules_reach_what_the_documents_print(client, tmp_path):
|
||||
"""A caption maps onto a field like a column does, and derived rules
|
||||
translate or cut values read from the page. Fails if the mapping and
|
||||
`derived` stop running over the record's document values."""
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path),
|
||||
column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"},
|
||||
derived={
|
||||
"pac_sexo": {"op": "map", "column": "Tipo de persona", "values": {"mujer": "F", "hombre": "M"}},
|
||||
"pac_codigo_postal": {"op": "extract", "column": "Domicilio actual", "pattern": r"\d{5}"},
|
||||
},
|
||||
)
|
||||
[row] = client.post("/imports/mapped-preview", json={"source": source}).get_json()["rows"]
|
||||
assert (row["pac_id_hospital"], row["pac_sexo"], row["pac_codigo_postal"]) == ("Q-1", "F", "64000")
|
||||
assert row["pac_fecha_nacimiento"] == "02/01/1980"
|
||||
result = client.post("/imports/validate", json={"source": source}).get_json()
|
||||
assert result["error_count"] == 0, result["errors"]
|
||||
|
||||
|
||||
def _last_report() -> dict:
|
||||
from webapi.imports.audit import default_sink
|
||||
|
||||
return default_sink().read()[-1]
|
||||
|
||||
|
||||
def test_the_import_report_lists_unused_captions_never_their_values(client, tmp_path, monkeypatch):
|
||||
"""Captions the documents print that nothing in the import used are
|
||||
listed with how many records print them, and none of their values
|
||||
reaches the report. Below the minimum count they are only counted.
|
||||
Fails if `unused_captions` stops reaching the audit, lists a caption
|
||||
the mapping uses, or lets a value through."""
|
||||
import json
|
||||
|
||||
source = _paciente_from_file(
|
||||
_id_and_file_table(tmp_path), column_mapping={"pid": "pac_id_hospital", "Nacida el": "pac_fecha_nacimiento"}
|
||||
)
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "1")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {"Tipo de persona": 1, "Domicilio actual": 1}
|
||||
text = json.dumps(_last_report(), ensure_ascii=False)
|
||||
assert "Mujer" not in text and "64000" not in text and "02/01/1980" not in text
|
||||
|
||||
monkeypatch.setenv("WEBAPI_REPORT_MIN_COUNT", "2")
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
report = _last_report()["fuentes"][0]
|
||||
assert report["etiquetas_sin_usar"] == {} and report["etiquetas_sin_usar_poco_frecuentes"] == 2
|
||||
@@ -0,0 +1,100 @@
|
||||
"""What this module covers: compositions answered from dbt's semantic layer on the hand-written cases their rules were
|
||||
written with, one database per case: CACU_CONFIRMACION_CITOLOGIA (`fixtures/casos_confirmacion_citologia.toml`: the
|
||||
last valid sample decides, the most severe biopsy of that sample by the cut-off is the category, a biopsy of another
|
||||
sample doesn't count) and CACU_RIESGO_BANDA (`fixtures/casos_riesgo_banda.toml`: the current batch of estimates, the
|
||||
latest version of each, the bands by the rules' cut points).
|
||||
|
||||
Fixtures: each case's database, migrated, with only its rows: staging rows through the load (a patient for each
|
||||
`pac_id` named) and cohort builds and risk estimates as they are; its rule overrides in `def_parametro`; dbt's views
|
||||
created by the cycle (`catalogs` … `event_models`; needs `DBT_MANIFEST`).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import tomllib
|
||||
from dataclasses import replace
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from conftest import base_de
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, EvaluacionRiesgo, EvaluacionRiesgoLote
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical, Paciente
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.metrics import Question
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
FILES = ("casos_confirmacion_citologia.toml", "casos_riesgo_banda.toml")
|
||||
TABLES = {m.__tablename__: m for m in (CitologiaCervical, BiopsiaCervical, CohorteArmado, CohorteMiembro,
|
||||
EvaluacionRiesgoLote, EvaluacionRiesgo)}
|
||||
STAGING = ("citologiacervical", "biopsiacervical")
|
||||
# Rows go in by their parents first.
|
||||
ORDER = ("citologiacervical", "biopsiacervical", "cohorte_armado", "cohorte_miembro", "evaluacion_riesgo_lote",
|
||||
"evaluacion_riesgo")
|
||||
|
||||
|
||||
def cases():
|
||||
for name in FILES:
|
||||
document = tomllib.loads((FIXTURES / name).read_text(encoding="utf-8"))
|
||||
templates = document.get("plantillas", {})
|
||||
for case in document["caso"]:
|
||||
rows = [row for t in case.get("incluye", ()) for row in templates[t]] + case["filas"]
|
||||
yield pytest.param(document["measure"], {**case, "filas": rows}, id=case["nombre"])
|
||||
|
||||
|
||||
def rows_of(case: dict):
|
||||
"""What the case's rows insert: a patient for each `pac_id`, then every row by its parents first."""
|
||||
def insert(session):
|
||||
for pac_id in sorted({row["pac_id"] for row in case["filas"] if "pac_id" in row}):
|
||||
session.add(Paciente(pac_id=pac_id, pac_id_hospital=f"H-{pac_id:03d}", pac_sexo="Femenino",
|
||||
pac_fecha_nacimiento=date(1980, 1, 1)))
|
||||
session.flush()
|
||||
for row in sorted(case["filas"], key=lambda r: ORDER.index(r["tabla"])):
|
||||
data = {k: v for k, v in row.items() if k != "tabla"}
|
||||
if row["tabla"] in STAGING:
|
||||
data["pac_id_hospital"] = f"H-{row['pac_id']:03d}"
|
||||
session.add(TABLES[row["tabla"]](**data))
|
||||
session.flush()
|
||||
session.commit()
|
||||
return insert
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("url", "case"), list(cases()))
|
||||
def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case):
|
||||
"""Pins down each hand-written case: the count in each category it names (zero included), the patients in the
|
||||
categories it lists and their stratum values, at its cut-off and with its rules. Fails if the measure stops
|
||||
meaning what the case says; the case's name says which rule."""
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
if not manifest:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base = base_de("cacu", tmp_path, rows_of(case))
|
||||
base.run("catalogs", "load", "registry", "definitions", "event_models", parameters=sin_supresion,
|
||||
allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
for key, value in case.get("parametros", {}).items():
|
||||
connection.execute(text("update def_parametro set valor = :v where clave = :k"),
|
||||
{"v": json.dumps(value), "k": key})
|
||||
definition = composition_definitions(Path(manifest))[url]
|
||||
d = base.dominio
|
||||
for period_id in sorted({*case.get("espera", {}), *case.get("unidades", {}), *case.get("estratos", {})}):
|
||||
result = answer_composition(
|
||||
"cacu", definition, Question(url, period_id, case.get("corte")), parameters=d.def_parametro_repository,
|
||||
periods=d.dim_periodo_repository, history=d.history_repository, queries=d.dbt_query_repository,
|
||||
allow_undecided=True)
|
||||
for category, n in case.get("espera", {}).get(period_id, {}).items():
|
||||
assert result.categories.get(category.removeprefix("cat:"), 0) == n, (period_id, category)
|
||||
with base.motor.connect() as connection:
|
||||
units = connection.execute(text(
|
||||
"select valor_id, unidad_id from measure_report_unidad where report_id = :r"),
|
||||
{"r": result.report_id}).all()
|
||||
strata = connection.execute(text(
|
||||
"select estrato_id, unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r"),
|
||||
{"r": result.report_id}).all()
|
||||
for category, expected in case.get("unidades", {}).get(period_id, {}).items():
|
||||
assert sorted(u for v, u in units if v == category.removeprefix("cat:")) == sorted(map(str, expected)), (
|
||||
period_id, category)
|
||||
for stratum, expected in case.get("estratos", {}).get(period_id, {}).items():
|
||||
assert {u: v for s, u, v in strata if s == stratum} == expected, (period_id, stratum)
|
||||
base.motor.dispose()
|
||||
@@ -0,0 +1,474 @@
|
||||
"""What this module covers: `webapi.metrics` and `webapi.compositions`, CaCu's measures answered on request from
|
||||
dbt's semantic definitions, with the period and both cut-offs in the question, and `MeasureHistoryRepository`, which
|
||||
keeps each answer under its key.
|
||||
|
||||
Fixtures: `base`, the CaCu fixture database through the cycle up to `event_models` (which creates dbt's event models);
|
||||
`manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `kit`, what the kit computed for IND1, EU13
|
||||
and EU7 on the same fixture data (`fixtures/kit_cacu_snapshot.json`): the oracle these answers were proven against.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from conftest import base_de
|
||||
from core.cacu.models import BiopsiaCervical, CitologiaCervical
|
||||
from webapi.compositions import answer_composition, composition_definitions, composition_report
|
||||
from webapi.metrics import Question, answer, measure_definitions, measure_report
|
||||
from webapi.orchestration import run
|
||||
|
||||
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
|
||||
STATUS = "estatus_seguimiento"
|
||||
HASTA_MODELOS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
PERIODS = [f"2025-{m:02d}" for m in range(1, 13)] + ["2025-S1", "2025-S2"]
|
||||
SNAPSHOT = Path(__file__).parent / "fixtures" / "kit_cacu_snapshot.json"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cacu", tmp_path)
|
||||
base.run(*HASTA_MODELOS, parameters=sin_supresion, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parameters=sin_supresion, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit():
|
||||
return json.loads(SNAPSHOT.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def definition(manifest):
|
||||
return measure_definitions(manifest)[IND1]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def eu13(manifest):
|
||||
return measure_definitions(manifest)[EU13]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def eu7(manifest):
|
||||
return composition_definitions(manifest)[EU7]
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
||||
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def ask(base, definition, period_id, *, event_cutoff=None, knowledge_cutoff=None):
|
||||
question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff)
|
||||
if definition.url == EU7:
|
||||
return answer_composition("cacu", definition, question, **repositories(base))
|
||||
return answer("cacu", definition, question, **repositories(base))
|
||||
|
||||
|
||||
def units(base, report_id: int) -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select grupo, resultado_id, unidad_id, pac_id, valor_id from measure_report_unidad where report_id = :r"),
|
||||
{"r": report_id}).all()))
|
||||
|
||||
|
||||
def strata_rows(base, report_id: int, stratum: str = "grupo_edad") -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select unidad_id, estrato_valor from measure_report_unidad_estrato where report_id = :r "
|
||||
"and estrato_id = :e"), {"r": report_id, "e": stratum}).all()))
|
||||
|
||||
|
||||
def proportion_cells(result) -> dict:
|
||||
"""An answer as the snapshot keeps what `v_c1` published: `{"stratum|value": [numerator, denominator]}`."""
|
||||
cells = {"total|total": [result.numerator, result.denominator]}
|
||||
for stratum, values in result.strata.items():
|
||||
cells |= {f"{stratum}|{v}": [c.numerator, c.denominator] for v, c in values.items()}
|
||||
return cells
|
||||
|
||||
|
||||
def composition_cells(result) -> dict:
|
||||
"""An answer as the snapshot keeps what `v_c2` published: `{"stratum|value|category": n}`."""
|
||||
cells = {f"total|total|{c}": n for c, n in result.categories.items()}
|
||||
for stratum, values in result.strata.items():
|
||||
cells |= {f"{stratum}|{v}|{c}": n for v, cs in values.items() for c, n in cs.items()}
|
||||
return cells
|
||||
|
||||
|
||||
def without(cells: dict, stratum: str) -> dict:
|
||||
return {k: v for k, v in cells.items() if not k.startswith(f"{stratum}|")}
|
||||
|
||||
|
||||
def reports(base) -> int:
|
||||
with base.motor.connect() as connection:
|
||||
return connection.execute(text("select count(*) from measure_report")).scalar_one()
|
||||
|
||||
|
||||
def reload(base, change) -> None:
|
||||
"""Changes the staging as the ingestion would and runs `load`: a new load, known later than everything before."""
|
||||
time.sleep(0.01)
|
||||
with Session(base.motor) as session:
|
||||
change(session)
|
||||
session.commit()
|
||||
run(base.ctx, only=["load"])
|
||||
|
||||
|
||||
def test_ind1_answers_what_the_kit_computed(base, definition, kit):
|
||||
"""Pins down: with no cut-off, every period's IND1 has the kit's units and its numbers. Fails if the semantic
|
||||
definition (event model, metrics, filter) stops meaning what the kit's IND1 meant."""
|
||||
for period_id in PERIODS:
|
||||
result, expected = ask(base, definition, period_id), kit[IND1][period_id]
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
assert proportion_cells(result)["total|total"] == expected["published"].get("total|total", [0, 0]), period_id
|
||||
|
||||
|
||||
def test_eu13_with_its_age_strata_answers_what_the_kit_computed(base, eu13, kit):
|
||||
"""Pins down: EU13 gives the kit's units, each patient's age group at the period's start and the numbers by age
|
||||
in every period. Fails if the event model, the report date's condition or the age from `dim_fecha` drift."""
|
||||
for period_id in PERIODS:
|
||||
result, expected = ask(base, eu13, period_id), kit[EU13][period_id]
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
|
||||
assert without(proportion_cells(result), STATUS) == (expected["published"] or {"total|total": [0, 0]}), period_id
|
||||
|
||||
|
||||
def test_eu7_puts_each_patient_in_her_last_valid_result_as_the_kit_did(base, eu7, kit):
|
||||
"""Pins down EU7, a composition: each patient in the category of her last valid sample (with a result and a
|
||||
satisfactory specimen) or SIN_DATO, with her age group, and the kit's counts by category, total and by age.
|
||||
Fails if the ranking (validity, then the latest sample, then the source id) or the validity rule drifts."""
|
||||
for period_id in PERIODS:
|
||||
result, expected = ask(base, eu7, period_id), kit[EU7][period_id]
|
||||
assert units(base, result.report_id) == expected["units"], period_id
|
||||
assert strata_rows(base, result.report_id) == expected["grupo_edad"], period_id
|
||||
assert without(composition_cells(result), STATUS) == expected["published"], period_id
|
||||
|
||||
|
||||
def test_every_stratum_value_written_is_in_the_catalog(base, eu13, eu7):
|
||||
"""Pins down: the strata an answer writes satisfy their foreign key to `cat_estrato_valor`, which SQLite doesn't
|
||||
enforce unless asked and SQL Server always does. Fails if `MeasureHistoryRepository.record` stops adding the
|
||||
stratum values the catalog lacks."""
|
||||
for d in (eu13, eu7):
|
||||
ask(base, d, "2025-S1")
|
||||
with base.motor.connect() as connection:
|
||||
written = connection.execute(text("select count(*) from measure_report_unidad_estrato")).scalar()
|
||||
broken = connection.execute(text("pragma foreign_key_check('measure_report_unidad_estrato')")).all()
|
||||
assert written > 0
|
||||
assert broken == []
|
||||
|
||||
|
||||
def test_a_stored_answer_reads_back_the_same(base, definition, eu13, eu7):
|
||||
"""Pins down: asking again reads the stored answer from its units' counts, with no view, and it's the same
|
||||
answer, strata included. Fails if `MeasureHistoryRepository.counts` and the computation stop agreeing."""
|
||||
for d in (definition, eu13, eu7):
|
||||
first = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
|
||||
before = reports(base)
|
||||
again = ask(base, d, "2025-S1", event_cutoff=date(2025, 6, 30))
|
||||
assert (again.report_id, again.stored_before, reports(base)) == (first.report_id, True, before)
|
||||
if d is eu7:
|
||||
assert (again.categories, again.strata) == (first.categories, first.strata)
|
||||
else:
|
||||
assert proportion_cells(again) == proportion_cells(first)
|
||||
|
||||
|
||||
def test_the_event_cutoff_leaves_out_later_facts(base, definition, kit):
|
||||
"""Pins down: S1 cut at March 31 counts the patients of January to March: the union of the kit's monthly units.
|
||||
Fails if the cut-off stops filtering the event date."""
|
||||
result = ask(base, definition, "2025-S1", event_cutoff=date(2025, 3, 31))
|
||||
months = sorted({tuple(u) for m in (1, 2, 3) for u in kit[IND1][f"2025-{m:02d}"]["units"]})
|
||||
|
||||
assert units(base, result.report_id) == [list(u) for u in months]
|
||||
|
||||
|
||||
def test_a_late_fact_counts_only_under_a_later_knowledge_cutoff(base, definition):
|
||||
"""Pins down: a cytology of S1 loaded later doesn't change what was known before its load; asked with a later
|
||||
knowledge cut-off, it counts. Fails if `conocida_en` stops being a condition of the question."""
|
||||
known = datetime.now(timezone.utc)
|
||||
before = ask(base, definition, "2025-S1", knowledge_cutoff=known)
|
||||
|
||||
def late_cytology(session):
|
||||
h005 = session.exec(select(CitologiaCervical).where(CitologiaCervical.pac_id_hospital == "H-005")).first()
|
||||
session.add(CitologiaCervical(pac_id=h005.pac_id, pac_id_hospital="H-005", cit_fecha_toma=date(2025, 3, 10),
|
||||
cit_calidad_especimen="SATISFACTORIO", cit_fecha_reporte=date(2025, 3, 20),
|
||||
cit_celulas_escamosas="LIEAG"))
|
||||
reload(base, late_cytology)
|
||||
|
||||
again = ask(base, definition, "2025-S1", knowledge_cutoff=known)
|
||||
fresh_then = ask(base, definition, "2025-S1", knowledge_cutoff=known, event_cutoff=date(2025, 6, 30))
|
||||
now = ask(base, definition, "2025-S1", knowledge_cutoff=datetime.now(timezone.utc))
|
||||
|
||||
assert again.report_id == before.report_id
|
||||
assert (fresh_then.numerator, fresh_then.denominator) == (before.numerator, before.denominator)
|
||||
assert (now.numerator, now.denominator) == (before.numerator + 1, before.denominator + 1)
|
||||
|
||||
|
||||
def test_a_changed_fact_is_kept_by_the_history_not_by_the_knowledge_cutoff(base, definition):
|
||||
"""Pins down the limit of the knowledge cut-off: silver keeps one version of each row, so after H-004's LIEAG of
|
||||
July becomes NEGATIVO, recomputing S2 as known before the change can't give the old numerator; only the stored
|
||||
answer still does. Fails if silver starts keeping versions (`dbt snapshot`): then expect the old one."""
|
||||
known = datetime.now(timezone.utc)
|
||||
shown = ask(base, definition, "2025-S2", knowledge_cutoff=known)
|
||||
assert shown.numerator == 1
|
||||
|
||||
def corrected(session):
|
||||
row = session.exec(select(CitologiaCervical).where(
|
||||
CitologiaCervical.pac_id_hospital == "H-004", CitologiaCervical.cit_fecha_toma == date(2025, 7, 1))).one()
|
||||
row.cit_celulas_escamosas = "NEGATIVO"
|
||||
reload(base, corrected)
|
||||
|
||||
stored = ask(base, definition, "2025-S2", knowledge_cutoff=known)
|
||||
recomputed_then = ask(base, definition, "2025-S2", knowledge_cutoff=known, event_cutoff=date(2025, 12, 31))
|
||||
|
||||
assert (stored.report_id, stored.numerator) == (shown.report_id, 1)
|
||||
assert recomputed_then.numerator == 0 # the July result now counts as known after `known`: it's left out
|
||||
assert ask(base, definition, "2025-S2", knowledge_cutoff=datetime.now(timezone.utc)).numerator == 0
|
||||
|
||||
|
||||
def test_eu13_counts_a_qualifying_biopsy_by_its_sample_and_its_report_date(base, eu13):
|
||||
"""Pins down EU13's numerator, which the fixture leaves at 0: once H-004's biopsy of August 1 (from the July 1
|
||||
sample) is LIEAG she counts in 2025-07 and 2025-S2, and an event cut-off before the report leaves her out.
|
||||
Fails if the numerator stops following the sample's period, the grade rule, or the report's date."""
|
||||
def lieag(session):
|
||||
biopsy = session.exec(select(BiopsiaCervical).where(BiopsiaCervical.pac_id_hospital == "H-004")).one()
|
||||
biopsy.bx_cin_grado = "LIEAG"
|
||||
reload(base, lieag)
|
||||
|
||||
assert ask(base, eu13, "2025-07").numerator == 1
|
||||
assert ask(base, eu13, "2025-S2").numerator == 1
|
||||
assert ask(base, eu13, "2025-S2", event_cutoff=date(2025, 7, 31)).numerator == 0
|
||||
|
||||
|
||||
def test_the_answers_are_fhir_measure_reports(base, definition, eu13, eu7):
|
||||
"""Pins down the contract WebApi serves: a FHIR `MeasureReport` with the measure's url and version, FHIR's
|
||||
inclusive period end, each population's count, the score, strata as a `stratifier`, and a composition's
|
||||
categories as one more. Fails if a population, the score, a stratum or a category stops matching the answer."""
|
||||
period = base.dominio.dim_periodo_repository.get("2025-S1")
|
||||
at = datetime(2026, 1, 2, tzinfo=timezone.utc)
|
||||
|
||||
report = measure_report(definition, Question(IND1, "2025-S1"), ask(base, definition, "2025-S1"), period, at)
|
||||
(group,) = report["group"]
|
||||
assert report["measure"] == "cacu/IND1|0.3.2"
|
||||
assert report["period"] == {"start": "2025-01-01", "end": "2025-06-30"}
|
||||
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
||||
"initial-population": 4, "denominator": 4, "numerator": 1}
|
||||
assert group["measureScore"] == {"value": 0.25}
|
||||
assert report["improvementNotation"]["coding"][0]["code"] == "decrease"
|
||||
|
||||
stratifiers = measure_report(eu13, Question(EU13, "2025-S1"), ask(base, eu13, "2025-S1"), period,
|
||||
at)["group"][0]["stratifier"]
|
||||
assert [s["code"] for s in stratifiers] == [[{"text": "grupo_edad"}], [{"text": STATUS}]]
|
||||
|
||||
composition = composition_report(eu7, Question(EU7, "2025-S1"), ask(base, eu7, "2025-S1"), period, at)
|
||||
by_result = composition["group"][0]["stratifier"][0]
|
||||
assert by_result["code"] == [{"text": "resultado"}]
|
||||
assert {s["value"]["text"]: s["population"][0]["count"] for s in by_result["stratum"]} == {
|
||||
"LIEBG": 1, "NEGATIVO": 2, "SIN_DATO": 1}
|
||||
if os.environ.get("MEASURE_REPORT_OUT"):
|
||||
Path(os.environ["MEASURE_REPORT_OUT"]).write_text(json.dumps(composition, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
ORACLE = Path(__file__).parent / "fixtures" / "kit_oracle_cacu.json"
|
||||
TIEMPO_REPORTE = "cacu/CACU_EU_TIEMPO_REPORTE"
|
||||
DIAS_TOMA_DIAGNOSTICO = "cacu/CACU_DIAS_TOMA_DIAGNOSTICO"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", [TIEMPO_REPORTE, DIAS_TOMA_DIAGNOSTICO])
|
||||
def test_each_duration_is_the_kit_s_in_every_period(base, manifest, url):
|
||||
"""Pins down the duration construct, for the time to the result and the time to the first note that resolves
|
||||
the sample: each sample of the period is measurable unless it has no value and its horizon hasn't passed by the
|
||||
cut-off (and, to diagnosis, unless a cervical cancer note came before it); the measured ones carry their days
|
||||
(`dim_fecha.dia_num` differences); n, the median and the quartiles (inclusive, ANSI) and the excluded are the
|
||||
kit's where it didn't suppress them (suppression isn't part of the prototype). Fails if the horizon, the day
|
||||
arithmetic, the resolving note, the exclusion or the quartiles' interpolation drift."""
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
|
||||
expected = json.loads(ORACLE.read_text(encoding="utf-8"))[url]
|
||||
definition = duration_definitions(manifest)[url]
|
||||
for period_id, kit_report in expected["periodos"].items():
|
||||
result = answer_duration("cacu", definition, Question(url, period_id), **repositories(base))
|
||||
assert units_with_numbers(base, result.report_id) == kit_report["units"], period_id
|
||||
published = dict(zip(kit_report["published_columns"], next(
|
||||
row for row in kit_report["published"] if row[1] == "total")))
|
||||
if published["suprimido"]:
|
||||
continue
|
||||
assert (result.n, result.median, result.q1, result.q3, result.excluded) == (
|
||||
published["n"], published["mediana"], published["q1"], published["q3"], published["n_excluido"]), period_id
|
||||
|
||||
|
||||
def units_with_numbers(base, report_id: int) -> list[list]:
|
||||
with base.motor.connect() as connection:
|
||||
return sorted(map(list, connection.execute(text(
|
||||
"select grupo, resultado_id, unidad_id, pac_id, valor_id, numero from measure_report_unidad "
|
||||
"where report_id = :r"), {"r": report_id}).all()))
|
||||
|
||||
|
||||
def test_the_follow_up_status_is_the_kit_s_in_every_period(base, eu13, eu7):
|
||||
"""Pins down: EU13's and EU7's `estatus_seguimiento` gives each unit the kit's status at the period's start, and
|
||||
the kit's published numbers by status. Fails if the timeline stratum, the procedures it infers or the order of
|
||||
the values drift. The fixture's patients are all PRE_COLPOSCOPIA; the other statuses are pinned down by
|
||||
`test_the_follow_up_status_follows_the_timeline`."""
|
||||
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))
|
||||
for period_id in PERIODS:
|
||||
for definition in (eu13, eu7):
|
||||
result, expected = ask(base, definition, period_id), oracle[definition.url]["periodos"][period_id]
|
||||
assert strata_rows(base, result.report_id, STATUS) == sorted(
|
||||
[u, v] for u, s, v in expected["strata"] if s == STATUS), (definition.url, period_id)
|
||||
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
|
||||
if definition is eu13:
|
||||
published = {f"{STATUS}|{r['estrato_valor']}": [r["numerador"], r["denominador"]]
|
||||
for r in rows if r["estrato_id"] == STATUS}
|
||||
ours = {k: v for k, v in proportion_cells(result).items() if k.startswith(f"{STATUS}|")}
|
||||
else:
|
||||
published = {f"{STATUS}|{r['estrato_valor']}|{r['categoria']}": r["n"]
|
||||
for r in rows if r["estrato_id"] == STATUS and r["n"]}
|
||||
ours = {k: v for k, v in composition_cells(result).items() if k.startswith(f"{STATUS}|")}
|
||||
assert ours == published, (definition.url, period_id)
|
||||
|
||||
|
||||
def kit_status(base, reference: str) -> dict[str, str]:
|
||||
"""What the kit's `estatus_al` says each patient's status was before `reference`, with the kit's rules."""
|
||||
import tomllib
|
||||
|
||||
from webapi.follow_up.status import estatus_al, reglas_de
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
|
||||
from webapi.follow_up.listing import leer_estrato
|
||||
from sqlalchemy import bindparam
|
||||
|
||||
rules = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
|
||||
|
||||
def rule(key):
|
||||
node = rules
|
||||
for part in key.split("."):
|
||||
node = node[part]
|
||||
return node["valor"]
|
||||
|
||||
values = {name: rule(key) for name, key in leer_estrato("cacu", STATUS).parametros.items()}
|
||||
status = estatus_al(bindparam("referencia"), reglas_de(values))
|
||||
query = select(status.c.pac_id, status.c.estatus)
|
||||
named = set(query.compile().params)
|
||||
with base.motor.connect() as connection:
|
||||
rows = connection.execute(query, {n: v for n, v in {**values, "referencia": reference}.items() if n in named})
|
||||
return {str(pac_id): value for pac_id, value in rows}
|
||||
|
||||
|
||||
def follow_up(session) -> None:
|
||||
"""Notes and orders that move three of the fixture's patients along follow-up, in a load of their own.
|
||||
|
||||
Patient 1 (sampled 2025-02-10): a valuation visit, a colposcopy note by its reason (with an accent) and a biopsy
|
||||
order that day, then a treatment note: POST_TRATAMIENTO from then on. Patient 4 (sampled 2025-05-30): a
|
||||
valuation visit, then a colposcopy note whose ICD-10 came «S/C» but whose diagnosis text names HPV:
|
||||
POST_COLPOSCOPIA. Patient 3 (sampled 2025-01-20): a colposcopy note with no valuation before it, which doesn't
|
||||
count, and her first cytology ordered by a specialty outside surveillance: no status holds, INFO_INSUFICIENTE.
|
||||
"""
|
||||
from core.cacu.indicadores.models import Carga, Observacion, Procedimiento
|
||||
|
||||
load = Carga(fuente="seguimiento", inicio=datetime.now(timezone.utc))
|
||||
session.add(load)
|
||||
session.flush()
|
||||
|
||||
def procedure(pac_id, study, kind, when, key, **observed) -> Procedimiento:
|
||||
p = Procedimiento(fuente_tabla="seguimiento", fuente_id=key, carga_id=load.carga_id, pac_id=pac_id,
|
||||
estudio_id=study, clase=kind, fecha=date.fromisoformat(when))
|
||||
session.add(p)
|
||||
session.flush()
|
||||
for result, (column_name, value) in observed.items():
|
||||
session.add(Observacion(procedimiento_id=p.procedimiento_id, carga_id=load.carga_id, pac_id=pac_id,
|
||||
resultado_id=result.replace("__", "."), **{column_name: value}))
|
||||
return p
|
||||
|
||||
def note(pac_id, when, key, *, cie, specialty="CLINICA_MUJER_COLPOSCOPIA", reason=None, text_dx=None):
|
||||
observed = {"nota_medica__diagnostico": ("valor_texto", cie),
|
||||
"nota_medica__especialidad": ("valor_id", specialty)}
|
||||
if reason:
|
||||
observed["nota_medica__motivo"] = ("valor_texto", reason)
|
||||
if text_dx:
|
||||
observed["nota_medica__diagnostico_texto"] = ("valor_texto", text_dx)
|
||||
procedure(pac_id, "nota_medica", "encuentro", when, key, **observed)
|
||||
|
||||
note(1, "2025-02-20", "n1a", cie="R876")
|
||||
note(1, "2025-03-03", "n1b", cie="Z000", reason="Acude a colposcopía")
|
||||
procedure(1, "biopsia", "orden", "2025-03-03", "o1")
|
||||
note(1, "2025-04-01", "n1c", cie="D06", specialty="CIRUGIA_ONCOLOGICA")
|
||||
note(4, "2025-06-05", "n4a", cie="R876")
|
||||
note(4, "2025-06-10", "n4b", cie="S/C", text_dx="Virus del papiloma humano")
|
||||
note(3, "2025-01-25", "n3a", cie="Z000", reason="COLPOSCOPIA")
|
||||
order = procedure(3, "citologia", "orden", "2025-01-19", "c3",
|
||||
orden__especialidad=("valor_id", "CIRUGIA_ONCOLOGICA"))
|
||||
(sample,) = session.exec(select(Procedimiento).where(
|
||||
Procedimiento.pac_id == 3, Procedimiento.estudio_id == "citologia", Procedimiento.clase == "toma",
|
||||
Procedimiento.fecha == date(2025, 1, 20))).all()
|
||||
sample.padre_id = order.procedimiento_id
|
||||
|
||||
|
||||
def test_the_follow_up_status_follows_the_timeline(base, eu13, eu7):
|
||||
"""Pins down: with colposcopies and a treatment on the timeline, every unit of EU13 and EU7 in every period gets
|
||||
the status the kit's `estatus_al` gives her at the period's start, and all four statuses come out; asked with a
|
||||
knowledge cut-off before those facts arrived, they're PRE_COLPOSCOPIA again. Fails if an inferred procedure
|
||||
(the valuation requirement, the same-day order, the accent-blind reason, the diagnosis text), the timeline
|
||||
stratum or the values' order stops meaning what the kit's rules mean."""
|
||||
with base.motor.connect() as connection:
|
||||
before_load = connection.execute(text("select max(inicio) from carga")).scalar_one()
|
||||
with Session(base.motor) as session:
|
||||
follow_up(session)
|
||||
session.commit()
|
||||
|
||||
seen = set()
|
||||
for period_id in PERIODS:
|
||||
start = base.dominio.dim_periodo_repository.get(period_id).inicio.isoformat()
|
||||
expected = kit_status(base, start)
|
||||
for definition in (eu13, eu7):
|
||||
ours = dict(strata_rows(base, ask(base, definition, period_id).report_id, STATUS))
|
||||
assert ours == {unit: expected[unit] for unit in ours}, (definition.url, period_id)
|
||||
seen |= set(ours.values())
|
||||
assert seen == {"PRE_COLPOSCOPIA", "POST_COLPOSCOPIA", "POST_TRATAMIENTO", "INFO_INSUFICIENTE"}
|
||||
|
||||
known_then = datetime.fromisoformat(before_load)
|
||||
earlier = ask(base, eu13, "2025-10", knowledge_cutoff=known_then)
|
||||
assert set(dict(strata_rows(base, earlier.report_id, STATUS)).values()) == {"PRE_COLPOSCOPIA"}
|
||||
|
||||
|
||||
def test_a_sample_waiting_for_its_diagnosis_within_the_horizon_is_not_measured_yet(base, manifest):
|
||||
"""Pins down the cut-off of the time to diagnosis: in 2025-S2 cut at September 30, the July sample resolved in
|
||||
August is measured (40 days); the August sample, resolved only in January, and the September one, with no note,
|
||||
are still within 180 days, so they aren't measured yet; the October sample is after the cut. Fails if a note
|
||||
after the cut-off counts, or a pending sample enters the initial population."""
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
|
||||
definition = duration_definitions(manifest)[DIAS_TOMA_DIAGNOSTICO]
|
||||
result = answer_duration("cacu", definition, Question(DIAS_TOMA_DIAGNOSTICO, "2025-S2", date(2025, 9, 30)),
|
||||
**repositories(base))
|
||||
assert (result.initial, result.n, result.median, result.excluded) == (1, 1, 40.0, 0)
|
||||
|
||||
|
||||
CONFIRMACION = "cacu/CACU_CONFIRMACION_CITOLOGIA"
|
||||
|
||||
|
||||
def test_the_confirmation_by_biopsy_is_the_kit_s_in_every_period(base, manifest):
|
||||
"""Pins down the composition that follows the chosen fact: each patient whose last valid sample of the period is
|
||||
high grade, in the grade of the most severe biopsy that sample led to by the cut-off (SIN_BIOPSIA without one),
|
||||
by that sample's result; units, strata and counts are the kit's in every period. Fails if the two-level ranking,
|
||||
the admission on the chosen sample, the severity order or the chosen-row stratum drift."""
|
||||
oracle = json.loads(ORACLE.read_text(encoding="utf-8"))[CONFIRMACION]
|
||||
definition = composition_definitions(manifest)[CONFIRMACION]
|
||||
for period_id, expected in oracle["periodos"].items():
|
||||
result = answer_composition("cacu", definition, Question(CONFIRMACION, period_id), **repositories(base))
|
||||
assert units(base, result.report_id) == [u[:5] for u in expected["units"]], period_id
|
||||
assert strata_rows(base, result.report_id, "citologia_alto_grado") == sorted(
|
||||
[u, v] for u, s, v in expected["strata"] if s == "citologia_alto_grado"), period_id
|
||||
rows = [dict(zip(expected["published_columns"], r)) for r in expected["published"]]
|
||||
published = {f"{r['estrato_id']}|{r['estrato_valor']}|{r['categoria']}": r["n"] for r in rows if r["n"]}
|
||||
assert {k: v for k, v in composition_cells(result).items() if v} == published, period_id
|
||||
@@ -0,0 +1,50 @@
|
||||
"""WebApi and `models` talk to each other through the database, both ways,
|
||||
over the same Repository objects: rows imported over HTTP are what a
|
||||
model trains on, and rows a model writes are what the API serves."""
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cama")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_imported_rows_are_what_models_reads_and_model_writes_are_what_the_api_serves(client):
|
||||
"""Rows imported over HTTP are read back through `models`' repository, and a row written there is served by
|
||||
the API. Fails if `resolve_repository` stops returning the objects WebApi writes with."""
|
||||
from core.cama.models import Mastografia
|
||||
from models.io.storage import resolve_repository
|
||||
|
||||
csv = b"Expediente,BIRADS\nRT-1,BI-RADS 4\nRT-2,2\n"
|
||||
response = client.post(
|
||||
"/imports/commit",
|
||||
json={
|
||||
"sources": [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cama.Mastografia",
|
||||
"column_mapping": {"Expediente": "pac_id_hospital", "BIRADS": "mast_birads"},
|
||||
"payload": {"file_base64": base64.b64encode(csv).decode()},
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
assert response.get_json()["results"][0]["created"] == 2
|
||||
|
||||
repository = resolve_repository("cama", "mastografia")
|
||||
seen = {row.pac_id_hospital: row.mast_birads for row in repository.iter_all()}
|
||||
assert seen == {"RT-1": "B4", "RT-2": "B2"}
|
||||
|
||||
repository.create(Mastografia(pac_id_hospital="RT-FROM-MODEL", mast_birads="B1"))
|
||||
served = client.get("/data/cama.Mastografia").get_json()
|
||||
assert served["total"] == 3
|
||||
assert "RT-FROM-MODEL" in {row["pac_id_hospital"] for row in served["rows"]}
|
||||
@@ -0,0 +1,388 @@
|
||||
"""Connector catalog, SQL Server, EEG files and clinical documents, end to end."""
|
||||
import base64
|
||||
import io
|
||||
from datetime import date
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import mssql
|
||||
|
||||
from extraction.testing import edf_file, scanned_pdf, text_pdf
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("cama")
|
||||
wire_domain("tea")
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def b64(raw: bytes) -> str:
|
||||
return base64.b64encode(raw).decode()
|
||||
|
||||
|
||||
def eeg(seconds: int = 8, rate: int = 128, **kwargs) -> bytes:
|
||||
t = np.arange(rate * seconds) / rate
|
||||
alpha = 40 * np.sin(2 * np.pi * 10 * t)
|
||||
return edf_file(signals={"EEG O1-REF": alpha, "EEG O2-REF": alpha, "EEG Fp1-REF": 20 * np.sin(2 * np.pi * 20 * t)}, sample_rate=rate, **kwargs)
|
||||
|
||||
|
||||
# -- catalog ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_catalog_lists_every_connector(client):
|
||||
connectors = {c["kind"]: c for c in client.get("/imports/connectors").get_json()["connectors"]}
|
||||
assert {"csv", "excel", "json", "pdf", "document", "edf", "sql"} <= set(connectors)
|
||||
assert connectors["edf"]["extensions"] == ["edf"]
|
||||
assert "pdf" in connectors["document"]["extensions"] and "tif" in connectors["document"]["extensions"]
|
||||
assert {s["id"] for s in connectors["document"]["segmentations"]} == {"auto", "document", "pages", "key"}
|
||||
engines = {e["id"]: e for e in connectors["sql"]["engines"]}
|
||||
assert engines["mssql"]["label"] == "SQL Server" and engines["mssql"]["default_port"] == 1433
|
||||
assert engines["mssql"]["available"] is True
|
||||
|
||||
|
||||
# -- SQL Server ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_sql_server_url_is_built_from_form_fields():
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
|
||||
url = SqlConnector.server_url({"engine": "mssql", "host": "his.local", "database": "HIS", "user": "lector", "password": "p@ss:/w"})
|
||||
assert url.drivername == "mssql+pymssql"
|
||||
assert url.port == 1433
|
||||
assert url.password == "p@ss:/w"
|
||||
|
||||
|
||||
def test_sql_server_preview_compiles_to_top(monkeypatch):
|
||||
from webapi.imports.connectors.sql import _text_subquery
|
||||
|
||||
statement = sa.select(_text_subquery("SELECT * FROM pacientes")).limit(5)
|
||||
compiled = str(statement.compile(dialect=mssql.dialect(), compile_kwargs={"literal_binds": True}))
|
||||
assert "TOP 5" in compiled and "LIMIT" not in compiled
|
||||
|
||||
|
||||
def test_unknown_engine_and_missing_host_are_rejected(client):
|
||||
assert client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "db2", "host": "x", "database": "y"}}).status_code == 400
|
||||
response = client.post("/imports/sources/sql/test-connection", json={"server": {"engine": "mssql", "database": "y"}})
|
||||
assert response.status_code == 400 and "host" in response.get_json()["error"]
|
||||
|
||||
|
||||
# -- EEG -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_edf_preview_maps_onto_eeg(client):
|
||||
"""Pins down: an EDF previews as one row with the study id, patient, date, channels and duration read from the
|
||||
file, and its columns suggest the `eeg` fields. Fails if the connector stops reading the header or the column
|
||||
matcher stops pairing them."""
|
||||
data = {"file": (io.BytesIO(eeg()), "estudio_007.edf"), "target": "tea.Eeg"}
|
||||
body = client.post("/imports/sources/file/preview", data=data, content_type="multipart/form-data").get_json()
|
||||
[row] = body["sample_rows"]
|
||||
assert row["id_registro_laboratorio"] == "LAB-778"
|
||||
assert row["paciente"] == "EXP-0042"
|
||||
assert row["fecha_estudio"] == "2024-01-15"
|
||||
assert row["canales"] == 3
|
||||
assert row["duracion_min"] == pytest.approx(8 / 60, abs=0.05)
|
||||
suggested = {m["source_column"]: m["target_field"] for m in body["suggested_mapping"]}
|
||||
assert suggested["estudio"] == "eeg_estudio"
|
||||
assert suggested["fecha_estudio"] == "eeg_fecha_estudio"
|
||||
assert suggested["canales"] == "eeg_canales"
|
||||
|
||||
|
||||
def test_several_edf_files_load_into_eeg_with_the_file(client):
|
||||
"""Pins down: several EDF files commit as one `eeg` row each, keyed by the lab's study id (or the file name),
|
||||
with the file stored. Fails if the commit drops the file or the key."""
|
||||
source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.Eeg",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"canales": "eeg_canales",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "a.edf", "file_base64": b64(eeg())}, {"name": "b.edf", "file_base64": b64(eeg(recording="sin datos"))}]},
|
||||
}
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
stored = {row.eeg_id_registro_laboratorio: row for row in eeg_repository.list()}
|
||||
assert set(stored) == {"LAB-778", "b"}
|
||||
assert stored["LAB-778"].eeg_canales == 3
|
||||
assert stored["LAB-778"].eeg_estudio[:8].strip() == b"0"
|
||||
assert stored["LAB-778"].eeg_fecha_estudio == date(2024, 1, 15)
|
||||
|
||||
|
||||
def test_eeg_rejects_a_file_mne_cannot_read():
|
||||
"""Pins down: `eeg_estudio` only takes a file MNE can open. Fails if the schema stops validating the EDF."""
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
from webapi.imports.schemas.tea.eeg import EegImportSchema
|
||||
|
||||
result = validate_rows(EegImportSchema, [{"eeg_estudio": b"definitely not an EDF file" * 20}])
|
||||
[row] = result.rejected
|
||||
assert row.errors[0].field == "eeg_estudio"
|
||||
|
||||
|
||||
# -- clinical documents -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _document_source(files: list[tuple[str, bytes]], target: str, mapping: dict, **options) -> dict:
|
||||
return {
|
||||
"source_type": "document",
|
||||
"target": target,
|
||||
"column_mapping": mapping,
|
||||
"payload": {"files": [{"name": n, "file_base64": b64(r)} for n, r in files], **options},
|
||||
"label": "documentos",
|
||||
}
|
||||
|
||||
|
||||
REPORTS = text_pdf(
|
||||
[
|
||||
["HOSPITAL REGIONAL - LABORATORIO DE PATOLOGIA", "Expediente: DOC-0001 Sexo: Femenino", "Fecha de nacimiento: 12/03/1981",
|
||||
"VPH alto riesgo: POSITIVO", "Genotipo 16: NO DETECTADO", "Genotipo 18: DETECTADO"],
|
||||
["Observaciones: muestra adecuada,", "con escaso moco cervical."],
|
||||
["Expediente: DOC-0002 Sexo: F", "Fecha de nacimiento: 1 de mayo de 1975",
|
||||
"Se identifica ADN de virus del papiloma humano de alto riesgo: NEGATIVO"],
|
||||
],
|
||||
image_on_page=2,
|
||||
)
|
||||
|
||||
|
||||
def test_document_extract_reports_records_evidence_and_images(client):
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "lote.pdf", "file_base64": b64(REPORTS)}], "target": "cacu.CitologiaCervical"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "pac_id_hospital"
|
||||
first, second = body["records"]
|
||||
assert first["key"] == "DOC-0001" and first["sources"] == [{"document": "lote.pdf", "page_numbers": [1, 2]}]
|
||||
assert first["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert first["fields"]["cit_vph_genotipo_16"]["value"] == 0
|
||||
assert first["fields"]["cit_vph_genotipo_18"]["value"] == 1
|
||||
assert first["fields"]["cit_observaciones"]["value"] == "muestra adecuada, con escaso moco cervical."
|
||||
assert first["fields"]["cit_vph_resultado"]["page_number"] == 1
|
||||
assert [image["page_number"] for image in first["images"]] == [2]
|
||||
assert second["fields"]["cit_vph_resultado"]["value"] == "NEGATIVO"
|
||||
assert second["fields"]["cit_vph_resultado"]["method"] == "texto_libre"
|
||||
|
||||
|
||||
def test_document_page_and_image_render(client):
|
||||
data = {"file": (io.BytesIO(REPORTS), "lote.pdf"), "page_number": "2", "bbox": "[0.4, 0.4, 0.8, 0.7]"}
|
||||
response = client.post("/imports/sources/document/page-image", data=data, content_type="multipart/form-data")
|
||||
assert response.status_code == 200 and response.mimetype == "image/png"
|
||||
|
||||
|
||||
def test_documents_commit_with_overrides_and_the_record_pdf(client):
|
||||
mapping = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"cit_vph_resultado": "cit_vph_resultado",
|
||||
"cit_vph_genotipo_18": "cit_vph_genotipo_18",
|
||||
"documento": "cit_vph_pdf_blob",
|
||||
}
|
||||
source = _document_source([("lote.pdf", REPORTS)], "cacu.CitologiaCervical", mapping, overrides={"1": {"cit_vph_resultado": "INDETERMINADO"}})
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 2, result
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
rows = {r.pac_id_hospital: r for r in citologia_cervical_repository.list(limit=100) if r.pac_id_hospital.startswith("DOC-")}
|
||||
assert rows["DOC-0001"].cit_vph_resultado == "POSITIVO"
|
||||
assert rows["DOC-0002"].cit_vph_resultado == "INDETERMINADO"
|
||||
assert rows["DOC-0001"].cit_vph_pdf_blob.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_patient_scattered_across_csv_and_scanned_forms_is_merged(client):
|
||||
csv = b"expediente,sexo,codigo_postal\nMIX-0001,F,64000\nMIX-0002,M,01000\n"
|
||||
scan = scanned_pdf([["FICHA DE IDENTIFICACION", "Expediente: MIX-0001", "Fecha de nacimiento: 15/08/1979", "Sexo: Masculino"]])
|
||||
sources = [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"label": "padron.csv",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "sexo": "pac_sexo", "codigo_postal": "pac_codigo_postal"},
|
||||
"payload": {"file_base64": b64(csv)},
|
||||
},
|
||||
_document_source(
|
||||
[("ficha.pdf", scan)],
|
||||
"cacu.Paciente",
|
||||
{"pac_id_hospital": "pac_id_hospital", "pac_fecha_nacimiento": "pac_fecha_nacimiento", "pac_sexo": "pac_sexo"},
|
||||
),
|
||||
]
|
||||
# On its own the CSV lacks the required birth date.
|
||||
assert client.post("/imports/validate", json={"source": sources[0]}).get_json()["error_count"] == 2
|
||||
|
||||
padron, ficha = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
|
||||
assert (padron["created"], padron["rejected"]) == (1, 1) # MIX-0002 has no birth date anywhere
|
||||
assert (ficha["merged"], ficha["created"]) == (1, 0)
|
||||
assert [(w["field"], w["raw_value"]) for w in ficha["warnings"]] == [("pac_sexo", "Masculino")]
|
||||
|
||||
from persistance.cacu import paciente_repository
|
||||
|
||||
[patient] = paciente_repository.list(pac_id_hospital="MIX-0001")
|
||||
assert patient.pac_fecha_nacimiento == date(1979, 8, 15)
|
||||
assert patient.pac_codigo_postal == "64000"
|
||||
|
||||
|
||||
EEG_REPORT = text_pdf(
|
||||
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-778", "Fecha de estudio: 15/01/2024"]],
|
||||
)
|
||||
|
||||
# A second study id, distinct from LAB-778 (already used by an earlier test
|
||||
# against this module-scoped client/database), for the merge test below.
|
||||
EEG_REPORT_2 = text_pdf(
|
||||
[["LABORATORIO DE NEUROFISIOLOGIA", "No. de estudio: LAB-900", "Fecha de estudio: 20/02/2024"]],
|
||||
)
|
||||
|
||||
|
||||
def test_an_eeg_report_gives_its_study_id_and_date(client):
|
||||
"""Pins down: a report read with NLP lands on `eeg` by the lab's own study id, with the study date. Fails if
|
||||
the extractor stops keying EEG records by `eeg_id_registro_laboratorio` or stops reading the date."""
|
||||
body = client.post(
|
||||
"/imports/sources/document/extract",
|
||||
json={"files": [{"name": "reporte.pdf", "file_base64": b64(EEG_REPORT)}], "target": "tea.Eeg"},
|
||||
).get_json()
|
||||
assert body["key_field"] == "eeg_id_registro_laboratorio"
|
||||
[record] = body["records"]
|
||||
assert record["key"] == "LAB-778"
|
||||
assert record["fields"]["eeg_fecha_estudio"]["value"] == "2024-01-15"
|
||||
|
||||
|
||||
def test_eeg_file_and_its_scanned_report_merge_into_one_eeg_row(client):
|
||||
"""Pins down: the EDF and its report, two sources of the same study, land on one `eeg` row through the lab's
|
||||
study id (read from the EDF header by one and from the report text by the other). Fails if
|
||||
`merge_duplicates` stops matching them on `eeg_id_registro_laboratorio`."""
|
||||
edf_source = {
|
||||
"source_type": "edf",
|
||||
"target": "tea.Eeg",
|
||||
"label": "estudio.edf",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"estudio": "eeg_estudio",
|
||||
},
|
||||
"payload": {"files": [{"name": "estudio.edf", "file_base64": b64(eeg(recording="Startdate 20-FEB-2024 LAB-900 Tec_Ruiz Nihon_Kohden"))}]},
|
||||
}
|
||||
document_source = _document_source(
|
||||
[("reporte.pdf", EEG_REPORT_2)],
|
||||
"tea.Eeg",
|
||||
{"eeg_id_registro_laboratorio": "eeg_id_registro_laboratorio", "eeg_fecha_estudio": "eeg_fecha_estudio"},
|
||||
)
|
||||
body = client.post(
|
||||
"/imports/commit", json={"sources": [edf_source, document_source], "merge_duplicates": True}
|
||||
).get_json()
|
||||
edf_result, doc_result = body["results"]
|
||||
assert edf_result["created"] == 1, body
|
||||
assert doc_result["merged"] == 1, body # absorbed into the EDF source's row, not inserted again
|
||||
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
[row] = eeg_repository.list(eeg_id_registro_laboratorio="LAB-900")
|
||||
# From the EDF file itself:
|
||||
assert row.eeg_duracion_min is not None
|
||||
assert row.eeg_estudio[:8].strip() == b"0"
|
||||
# From the report, on the very same row:
|
||||
assert row.eeg_fecha_estudio == date(2024, 2, 20)
|
||||
|
||||
|
||||
def test_citologia_table_and_scanned_report_merge_on_the_order_number(client):
|
||||
"""The order/date come from a structured table (a CSV export of the lab's
|
||||
own HIS); the VPH result comes from NLP over the scanned report PDF.
|
||||
`(pac_id_hospital, ord_numero_hospital)` is what lets them land on one
|
||||
`citologiacervical` row instead of two half-populated ones."""
|
||||
csv = b"expediente,orden,fecha_toma\nMRG-0001,5001,2024-03-01\n"
|
||||
report = text_pdf([["LABORATORIO DE CITOLOGIA", "Expediente: MRG-0001", "No. de orden: 5001", "VPH alto riesgo: POSITIVO"]])
|
||||
sources = [
|
||||
{
|
||||
"source_type": "csv",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"label": "padron.csv",
|
||||
"column_mapping": {"expediente": "pac_id_hospital", "orden": "ord_numero_hospital", "fecha_toma": "cit_fecha_toma"},
|
||||
"payload": {"file_base64": b64(csv)},
|
||||
},
|
||||
_document_source(
|
||||
[("reporte.pdf", report)],
|
||||
"cacu.CitologiaCervical",
|
||||
{"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital", "cit_vph_resultado": "cit_vph_resultado"},
|
||||
),
|
||||
]
|
||||
tabla, documento = client.post("/imports/commit", json={"sources": sources, "merge_duplicates": True}).get_json()["results"]
|
||||
assert tabla["created"] == 1, tabla
|
||||
assert documento["merged"] == 1, documento # absorbed into the table row, not inserted again
|
||||
|
||||
from persistance.cacu import citologia_cervical_repository
|
||||
|
||||
[row] = citologia_cervical_repository.list(pac_id_hospital="MRG-0001")
|
||||
# From the structured table:
|
||||
assert row.ord_numero_hospital == 5001
|
||||
assert row.cit_fecha_toma == date(2024, 3, 1)
|
||||
# From the scanned report, on the very same row:
|
||||
assert row.cit_vph_resultado == "POSITIVO"
|
||||
|
||||
|
||||
def test_embedded_image_in_the_report_maps_onto_the_target_dicom_column(client):
|
||||
"""The report has a picture of the mammogram alongside its narrative
|
||||
text; `imagen` (like `documento`, the combined PDF) is mappable onto any
|
||||
target column, so it lands in `mast_dicom_blob` next to the fields read
|
||||
from the surrounding text."""
|
||||
report = text_pdf(
|
||||
[["LABORATORIO DE IMAGENOLOGIA", "Expediente: IMG-0001", "Interpretación: nódulo circunscrito en cuadrante superior externo."]],
|
||||
image_on_page=1,
|
||||
)
|
||||
mapping = {"pac_id_hospital": "pac_id_hospital", "mast_interpretacion": "mast_interpretacion", "imagen": "mast_dicom_blob"}
|
||||
source = _document_source([("reporte.pdf", report)], "cama.Mastografia", mapping)
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()["results"][0]
|
||||
assert result["created"] == 1, result
|
||||
|
||||
from persistance.cama import mastografia_repository
|
||||
|
||||
[row] = mastografia_repository.list(pac_id_hospital="IMG-0001")
|
||||
assert "nódulo circunscrito" in row.mast_interpretacion
|
||||
assert row.mast_dicom_blob.startswith(b"\x89PNG")
|
||||
|
||||
|
||||
def test_a_tea_order_keeps_the_pdf_its_sql_source_carries(client, tmp_path):
|
||||
"""Pins down: `ord_pdf_blob` travels with the order from a SQL source into `ordenes_estudio`, byte for
|
||||
byte, and an order without a file stays without one. The source is a SQLite file in `tmp_path` holding a
|
||||
two-row `ordenes_estudio`. Fails if the import schema drops the field or the commit rewrites the bytes."""
|
||||
report = text_pdf([["EVALUACION PSICOLOGICA", "ADOS-2 Modulo 2"]])
|
||||
url = f"sqlite:///{tmp_path / 'hospital.db'}"
|
||||
table = sa.Table(
|
||||
"ordenes_estudio", sa.MetaData(),
|
||||
sa.Column("ord_id", sa.String(36), primary_key=True),
|
||||
sa.Column("ord_id_hospital", sa.String(64)),
|
||||
sa.Column("ord_tipo_estudio", sa.Text),
|
||||
sa.Column("ord_pdf_blob", sa.LargeBinary),
|
||||
)
|
||||
engine = sa.create_engine(url)
|
||||
table.create(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.insert(table), [
|
||||
{"ord_id": "ord-pdf-1", "ord_id_hospital": "ORD-PDF-1", "ord_tipo_estudio": "ADOS2", "ord_pdf_blob": report},
|
||||
{"ord_id": "ord-pdf-2", "ord_id_hospital": "ORD-PDF-2", "ord_tipo_estudio": "EEG", "ord_pdf_blob": None},
|
||||
])
|
||||
engine.dispose()
|
||||
source = {
|
||||
"source_type": "sql",
|
||||
"target": "tea.OrdenesEstudio",
|
||||
"column_mapping": {column.name: column.name for column in table.columns},
|
||||
"payload": {"connection_string": url, "table": "ordenes_estudio"},
|
||||
}
|
||||
|
||||
result = client.post("/imports/commit", json={"sources": [source], "on_conflict": "upsert"}).get_json()["results"][0]
|
||||
|
||||
assert (result["created"], result["rejected"]) == (2, 0), result
|
||||
|
||||
from persistance.tea import ordenes_estudio_repository
|
||||
|
||||
assert ordenes_estudio_repository.get("ord-pdf-1").ord_pdf_blob == report
|
||||
assert ordenes_estudio_repository.get("ord-pdf-2").ord_pdf_blob is None
|
||||
@@ -0,0 +1,89 @@
|
||||
"""What this module covers: the whole cycle on the CaCu fixture database, in order, once and again.
|
||||
|
||||
Fixtures: `bases`, one database loaded by the cycle from the kit's synthetic staging, with dbt's manifest
|
||||
(`DBT_MANIFEST`) for the definitions and the event models. The cycle computes no measure: they're answered on request
|
||||
(`test_metrics_on_request`), so running it again adds no report.
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orchestration import Context, run
|
||||
from webapi.orchestration.project import cohort_urls
|
||||
from webapi.orchestration.connection import point_to
|
||||
|
||||
ANIO = 2025
|
||||
# Lo que guarda cada reporte (T-19e): sus unidades de §6f. El número publicado sale de ellas (las vistas).
|
||||
CONSULTA = text("""
|
||||
SELECT r.measure_url, r.measure_version, r.periodo_id, r.fecha_corte, r.huella,
|
||||
u.grupo, u.unidad_id, u.resultado_id, u.valor_id, ROUND(u.numero, 12)
|
||||
FROM measure_report_unidad u JOIN measure_report r USING (report_id)""")
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", params=["cacu", "cama", "tea"])
|
||||
def bases(request, tmp_path_factory):
|
||||
proyecto = request.param
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
url = f"sqlite:///{carpeta / 'orquestada.db'}"
|
||||
point_to(proyecto, url)
|
||||
# `observe` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de
|
||||
# dev-data. Ningún cálculo la usa: la base de demostración calcula sin permitirlo y da lo mismo.
|
||||
ctx = Context(proyecto, ANIO, ANIO, allow_undecided=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"]))
|
||||
run(ctx, only=["migrate"])
|
||||
motor = create_engine(url)
|
||||
with Session(motor) as sesion:
|
||||
import_module(f"staging.{proyecto}").insertar(sesion)
|
||||
sesion.commit()
|
||||
pasos = run(ctx)
|
||||
return proyecto, ctx, motor, None, pasos
|
||||
|
||||
|
||||
def test_corre_todos_los_pasos_en_orden(bases):
|
||||
proyecto, _, _, _, pasos = bases
|
||||
nombres = [p.name for p in pasos]
|
||||
# `migrate` otra vez: con la base al día no hace nada. Los catálogos, antes de cargar (decisión 6 de §9).
|
||||
assert nombres[0] == "migrate" and nombres.index("catalogs") < nombres.index("load")
|
||||
assert nombres.index("load") < nombres.index("event_models") and "calcular" not in nombres
|
||||
|
||||
|
||||
|
||||
|
||||
def test_volver_a_correr_no_agrega_reportes(bases):
|
||||
"""Pins down: the cycle computes no measure (they're answered on request): running it adds no report."""
|
||||
_, ctx, motor, _, _ = bases
|
||||
with motor.connect() as con:
|
||||
antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one()
|
||||
run(ctx)
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
|
||||
|
||||
|
||||
def test_en_cacu_arma_cada_cohorte_de_dbt_una_vez(bases):
|
||||
"""Pins down: the cycle builds every cohort of the project in dbt's manifest, once each, and each build stores
|
||||
as many members as it counts. TEA and CaMa have no dbt cohorts, so no cohort step. Fails if a cohort comes from
|
||||
anywhere else than dbt, or a build's count and members disagree."""
|
||||
proyecto, ctx, motor, _, pasos = bases
|
||||
if proyecto != "cacu":
|
||||
assert "cohorts" not in [p.name for p in pasos]
|
||||
return
|
||||
armados = [p.summary for p in pasos if p.name == "cohorts"][0]
|
||||
assert set(armados) == set(cohort_urls(proyecto, ctx.dbt_manifest)) and "cacu/cohorte_vigilancia" in armados
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == len(armados)
|
||||
for armado_id, _ in armados.values():
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado WHERE armado_id = :a"),
|
||||
{"a": armado_id}).scalar_one() == con.execute(
|
||||
text("SELECT COUNT(*) FROM cohorte_miembro WHERE armado_id = :a"), {"a": armado_id}).scalar_one()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Los pasos de oro sobre la base del dominio: el registro y las definiciones (el catálogo, del manifiesto de dbt).
|
||||
|
||||
Vienen del kit (`test_pasos` y `test_produccion`, MD-16). El reporte se lee por los
|
||||
repositorios de Persistance, como lo leería `WebApi`.
|
||||
"""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.silver.loads import tablas_de_staging
|
||||
from webapi.orchestration.reference.age_groups import grupos_de_cortes
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, valores_del_archivo
|
||||
from webapi.orchestration.reference.periods import periodos_de_tipos
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from webapi.orchestration.project import period_types
|
||||
|
||||
from conftest import ANIO
|
||||
|
||||
# El indicador de ejemplo, su grupo total y lo que da: {periodo: (denominador, numerador)}.
|
||||
def cargas(proyecto) -> tuple[str, ...]:
|
||||
"""El paso que lleva el staging a la plata (staging directo, T-20c)."""
|
||||
return ("load",)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base):
|
||||
base.run("registry")
|
||||
base.run("registry", year_from=ANIO - 1)
|
||||
|
||||
tablas = tablas_de(base.proyecto)
|
||||
esperados = periodos_de_tipos(period_types(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas)
|
||||
assert base.dominio.dim_periodo_repository.count() == len(esperados)
|
||||
assert base.dominio.measure_report_repository.count() == 0
|
||||
|
||||
|
||||
def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base):
|
||||
"""I-MD27 (T-24f): de `comun.dim_fecha.desde` al fin del último año, y los grupos de `<proyecto>.grupos_edad`."""
|
||||
base.run("registry")
|
||||
base.run("registry", year_to=ANIO + 1) # repetir deja la tabla igual, con el año nuevo
|
||||
|
||||
valores = valores_del_archivo(RUTA_PARAMETROS)
|
||||
desde = date.fromisoformat(valores["comun.dim_fecha.desde"])
|
||||
fechas = base.dominio.dim_fecha_repository
|
||||
hasta = date(max(ANIO + 1, date.today().year), 12, 31) # o el año del corte (hoy), si es mayor
|
||||
assert fechas.count() == (hasta - desde).days + 1
|
||||
grupos = [g.etiqueta for g in base.dominio.dim_grupo_edad_repository.list(limit=100)]
|
||||
cortes = valores.get(f"{base.proyecto}.grupos_edad")
|
||||
esperados = [] if cortes is None else [g.etiqueta for g in grupos_de_cortes(cortes, tablas=tablas_de(base.proyecto))]
|
||||
assert sorted(grupos) == sorted(esperados) # TEA no tiene cortes: vacía
|
||||
|
||||
|
||||
|
||||
|
||||
def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path):
|
||||
base.run("registry")
|
||||
periodos = base.dominio.dim_periodo_repository.count()
|
||||
malo = tmp_path / "malo.toml"
|
||||
malo.write_text('[comun.x]\nvalor = 1\nestado = "provisional"\n', encoding="utf-8")
|
||||
|
||||
with pytest.raises(ValueError, match="fuente"):
|
||||
base.run("registry", year_from=ANIO - 1, year_to=ANIO + 1, parameters=malo)
|
||||
|
||||
assert base.dominio.def_parametro_repository.get("comun.x") is None
|
||||
assert base.dominio.def_parametro_repository.get("comun.umbral_supresion") is not None
|
||||
assert base.dominio.dim_periodo_repository.count() == periodos
|
||||
|
||||
|
||||
def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
|
||||
"""Pins down: `definitions` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a
|
||||
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
|
||||
resumen = base.run("definitions")["definitions"]
|
||||
|
||||
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
|
||||
# TEA: the age group and its ten measures.
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto]
|
||||
# Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado.
|
||||
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto]
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Las dependencias entre los pasos de cada proyecto, como las lee Hamilton de los parámetros."""
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
from webapi.orchestration import cycle, steps_of
|
||||
|
||||
|
||||
def dependencias(proyecto: str) -> dict[str, set[str]]:
|
||||
dr = driver.Builder().with_modules(cycle).with_config({"with_cohorts": proyecto == "cacu"}).build()
|
||||
return {n.name: {d.name for d in n.dependencies} - {"ctx"} for n in dr.graph.get_nodes() if n.name != "ctx"}
|
||||
|
||||
|
||||
def antes(deps: dict[str, set[str]], paso: str) -> set[str]:
|
||||
"""Todos los pasos que corren antes de `paso`."""
|
||||
previos = set()
|
||||
pending = list(deps[paso])
|
||||
while pending:
|
||||
anterior = pending.pop()
|
||||
if anterior not in previos:
|
||||
previos.add(anterior)
|
||||
pending.extend(deps[anterior])
|
||||
return previos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
deps = dependencias(proyecto)
|
||||
assert deps["migrate"] == set()
|
||||
assert {"migrate", "catalogs"} <= antes(deps, "load") # decisión 6 de §9
|
||||
assert {"load"} <= antes(deps, "event_models")
|
||||
assert {"registry"} <= antes(deps, "observe")
|
||||
assert {"load", "catalogs"} <= antes(deps, "check_silver")
|
||||
|
||||
|
||||
def test_las_cohortes_son_las_del_manifiesto_de_dbt(tmp_path, monkeypatch):
|
||||
"""Pins down: a project builds cohorts and estimates only if dbt's manifest has a cohort of it (`meta.cohort` of
|
||||
a population query), today only CaCu's; without a manifest no project does. Fails if the cycle reads cohort
|
||||
definitions from anywhere else than dbt."""
|
||||
manifest = tmp_path / "manifest.json"
|
||||
nodo = {"config": {"meta": {"cohort": "cacu/cohorte_vigilancia", "kind": "population"}}}
|
||||
manifest.write_text(json.dumps({"nodes": {"model.p.cacu_surveillance_all_patients": nodo}}))
|
||||
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu", manifest))
|
||||
for proyecto in ("cama", "tea"):
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto, manifest))
|
||||
monkeypatch.delenv("DBT_MANIFEST", raising=False)
|
||||
assert not {"cohorts", "estimate"} & set(steps_of("cacu"))
|
||||
@@ -0,0 +1,254 @@
|
||||
"""Los pasos de plata sobre la base del dominio: los catálogos, cargar (staging directo, T-20c), las vistas y observar.
|
||||
|
||||
Vienen del kit (`test_pasos`, `test_produccion` y `test_observacion`, MD-16): el kit
|
||||
ya no tiene pasos, y lo que se prueba aquí es cómo los pasos componen sus
|
||||
funciones con los repositorios de Persistance.
|
||||
"""
|
||||
|
||||
import json
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from conftest import base_de
|
||||
from webapi.orchestration.silver.loads import tablas_de_staging
|
||||
from webapi.orchestration.silver.observation_periods import (
|
||||
TIPO_EXTRACCION,
|
||||
ObservacionSinCorte,
|
||||
clave_de_inicio,
|
||||
)
|
||||
from webapi.orchestration.reference.catalogs import catalogo_desde_toml, ruta_de_catalogo
|
||||
from webapi.orchestration.reference.rules import RUTA_PARAMETROS, ParametroSinDefinir
|
||||
from webapi.orchestration.tables import tablas_de
|
||||
from sqlalchemy import inspect, text
|
||||
from sqlmodel import select
|
||||
|
||||
# Un cambio en staging y la fila de la plata que toca: (tabla de staging, columna, valor nuevo).
|
||||
CAMBIO = {
|
||||
"cacu": ("citologiacervical", "cit_calidad_especimen", "INSATISFACTORIO"),
|
||||
"cama": ("mastografia", "mast_calidad_imagen", "OTRA CALIDAD"),
|
||||
"tea": ("mchat", "mch_puntaje", 19),
|
||||
}
|
||||
CORTE = date(2025, 12, 31)
|
||||
|
||||
|
||||
def ultima_carga(base):
|
||||
return max(base.ctx.repos.silver.loads.list(limit=100), key=lambda c: c.carga_id)
|
||||
|
||||
|
||||
def contar(base, sql: str) -> int:
|
||||
with base.motor.connect() as con:
|
||||
return con.execute(text(sql)).scalar_one()
|
||||
|
||||
|
||||
def plata_de(base) -> tuple[int, int]:
|
||||
return contar(base, "SELECT COUNT(*) FROM procedimiento"), contar(base, "SELECT COUNT(*) FROM observacion_clinica")
|
||||
|
||||
|
||||
def cambiar_staging(base) -> str:
|
||||
"""Aplica `CAMBIO` a la primera fila de su tabla de staging. Devuelve su llave."""
|
||||
tabla, columna, nuevo = CAMBIO[base.proyecto]
|
||||
(modelo,) = [m for m in tablas_de_staging(base.proyecto) if m.__tablename__ == tabla]
|
||||
(llave,) = modelo.__table__.primary_key.columns
|
||||
with base.staging() as sesion:
|
||||
fila = sesion.exec(select(modelo).order_by(llave)).first()
|
||||
setattr(fila, columna, nuevo)
|
||||
sesion.commit()
|
||||
return str(getattr(fila, llave.name))
|
||||
|
||||
|
||||
# --- catalogos ---
|
||||
|
||||
|
||||
def filas_del_catalogo(base) -> dict[str, int]:
|
||||
"""Cuántas filas tiene cada tabla de catálogo en la base."""
|
||||
plata = base.ctx.repos.silver.catalogs
|
||||
with base.staging() as sesion:
|
||||
return {
|
||||
"estudios": len(sesion.exec(select(plata.model)).all()),
|
||||
"resultados": len(sesion.exec(select(plata.resultado)).all()),
|
||||
"valores": len(sesion.exec(select(plata.valor)).all()),
|
||||
}
|
||||
|
||||
|
||||
def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo(base.proyecto), tablas=tablas_de(base.proyecto))
|
||||
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
|
||||
"valores": len(catalogo.valores)}
|
||||
|
||||
conteos = base.run("catalogs")["catalogs"]
|
||||
assert conteos.pop("mapeos_nuevos") > 0
|
||||
assert conteos == {**del_toml, "retirados": 0}
|
||||
assert filas_del_catalogo(base) == del_toml
|
||||
|
||||
|
||||
def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
base.run("catalogs")
|
||||
antes = filas_del_catalogo(base)
|
||||
|
||||
conteos = base.run("catalogs")["catalogs"]
|
||||
assert (conteos["retirados"], conteos["mapeos_nuevos"]) == (0, 0)
|
||||
assert filas_del_catalogo(base) == antes
|
||||
|
||||
|
||||
# --- cargar (staging directo) ---
|
||||
|
||||
|
||||
def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
|
||||
base.run("catalogs")
|
||||
carga = base.run("load")["load"]
|
||||
|
||||
procedimientos, observaciones = plata_de(base)
|
||||
assert procedimientos and observaciones
|
||||
assert carga.fin is not None and (carga.filas_nuevas, carga.filas_cambiadas, carga.filas_sin_cambio) == (
|
||||
procedimientos, 0, 0)
|
||||
assert contar(base, "SELECT COUNT(*) FROM persona") == len(base.ctx.repos.bronze.staging.read(
|
||||
{"p": tablas_de_staging(base.proyecto)[0]})["p"])
|
||||
# Ningún reporte ni parte sin su toma (salvo los huérfanos, que no se escriben).
|
||||
assert contar(base, "SELECT COUNT(*) FROM procedimiento WHERE clase IN ('reporte', 'parte') AND padre_id IS NULL") == 0
|
||||
# Desde F6 (ADR-MD-009) no hay tablas por tipo: la base solo tiene las del kit, staging y lo restringido.
|
||||
assert contar(base, "SELECT COUNT(*) FROM sqlite_master WHERE name = 'orden_estudio_servicio'") == 0
|
||||
|
||||
|
||||
|
||||
|
||||
def test_volver_a_cargar_sin_cambios_no_toca_nada(base):
|
||||
base.run("catalogs", "load")
|
||||
antes = plata_de(base)
|
||||
|
||||
segunda = base.run("load")["load"]
|
||||
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 0, antes[0])
|
||||
assert plata_de(base) == antes
|
||||
for tabla in ("procedimiento", "observacion_clinica"):
|
||||
assert contar(base, f"SELECT COUNT(*) FROM {tabla} WHERE carga_id = {segunda.carga_id}") == 0
|
||||
|
||||
|
||||
def test_un_cambio_en_staging_toca_un_procedimiento(base):
|
||||
base.run("catalogs", "load")
|
||||
antes = plata_de(base)
|
||||
cambiar_staging(base)
|
||||
|
||||
segunda = base.run("load")["load"]
|
||||
assert (segunda.filas_nuevas, segunda.filas_cambiadas, segunda.filas_sin_cambio) == (0, 1, antes[0] - 1)
|
||||
assert plata_de(base) == antes
|
||||
|
||||
|
||||
|
||||
|
||||
# --- vistas ---
|
||||
|
||||
|
||||
def test_las_vistas_se_construyen_y_se_pueden_repetir(base):
|
||||
primera = base.run("views")["views"]
|
||||
|
||||
assert base.run("views")["views"] == primera
|
||||
# Only `v_persona`: the published numbers are answered on request, so the publication views aren't built.
|
||||
assert sorted(inspect(base.motor).get_view_names()) == ["v_persona"]
|
||||
|
||||
|
||||
# --- observar ---
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def con_regla(tmp_path, proyecto):
|
||||
"""Una copia de `parametros.toml` con el inicio de los datos del proyecto en ese valor y estado."""
|
||||
|
||||
def escribir(valor="2023-01-01", estado="provisional"):
|
||||
texto = RUTA_PARAMETROS.read_text(encoding="utf-8")
|
||||
cabecera = f"[{clave_de_inicio(proyecto)}]"
|
||||
antes, despues = texto.split(cabecera)
|
||||
despues = despues.replace('valor = "2023-01-01"', f'valor = "{valor}"', 1).replace(
|
||||
'estado = "sin_definir"', f'estado = "{estado}"', 1)
|
||||
ruta = tmp_path / "con_regla.toml"
|
||||
ruta.write_text(antes + cabecera + despues, encoding="utf-8")
|
||||
return ruta
|
||||
|
||||
return escribir
|
||||
|
||||
|
||||
observables = pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
|
||||
|
||||
@observables
|
||||
def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
|
||||
cuantos = base.run("observe", cutoff=CORTE)["observe"]
|
||||
|
||||
periodos = base.dominio.periodo_observacion_repository.list()
|
||||
assert cuantos == len(periodos) == base.dominio.persona_repository.count()
|
||||
assert {(p.fecha_inicio, p.fecha_fin, p.tipo_periodo) for p in periodos} == {
|
||||
(date(2024, 6, 1), CORTE, TIPO_EXTRACCION)}
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla())
|
||||
|
||||
base.run("observe")
|
||||
|
||||
carga = ultima_carga(base)
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {
|
||||
(carga.fin or carga.inicio).date()}
|
||||
|
||||
|
||||
@observables
|
||||
def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla())
|
||||
|
||||
primera = base.run("observe", cutoff=date(2025, 6, 30))["observe"]
|
||||
segunda = base.run("observe", cutoff=CORTE)["observe"]
|
||||
|
||||
assert primera == segunda == base.dominio.periodo_observacion_repository.count()
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {CORTE}
|
||||
|
||||
|
||||
@observables
|
||||
def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base):
|
||||
base.run("load", "registry")
|
||||
|
||||
with pytest.raises(ParametroSinDefinir, match="inicio_datos"):
|
||||
base.run("observe", cutoff=CORTE)
|
||||
assert base.run("observe", cutoff=CORTE, allow_undecided=True)["observe"] == (
|
||||
base.dominio.persona_repository.count())
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_el_registro_observar_dice_que_falta(base):
|
||||
base.run("load")
|
||||
|
||||
with pytest.raises(KeyError, match="preparar_registro|registro"):
|
||||
base.run("observe", cutoff=CORTE)
|
||||
|
||||
|
||||
@observables
|
||||
def test_un_corte_anterior_al_inicio_de_los_datos_se_rechaza(base, con_regla):
|
||||
base.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
|
||||
with pytest.raises(ValueError, match="anterior al inicio"):
|
||||
base.run("observe", cutoff=date(2024, 5, 31))
|
||||
assert base.dominio.periodo_observacion_repository.count() == 0
|
||||
|
||||
|
||||
@observables
|
||||
def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla):
|
||||
base.run("registry", parameters=con_regla())
|
||||
|
||||
with pytest.raises(ObservacionSinCorte):
|
||||
base.run("observe")
|
||||
|
||||
|
||||
# --- La carga doble (F5, ADR-MD-007): CaCu, CaMa y TEA ---
|
||||
|
||||
# --- verificar_plata (calidad de la plata de dos tablas) ---
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_verificar_plata_en_cacu_cuenta_los_valores_fuera_de_catalogo_del_fixture(base):
|
||||
conteos = base.run("catalogs", "load", "check_silver")["check_silver"]
|
||||
|
||||
# I-MD16 (textos del fixture fuera del catálogo) e I-MD18 (especialidades que el alias no reconoce): en la
|
||||
# plata, una observación de código sin `valor_id` y con su `valor_fuente`.
|
||||
i_md16 = contar(base, "SELECT COUNT(*) FROM observacion_clinica WHERE valor_fuente IN ('NEGATIVO', 'CIN1', 'CIN2')")
|
||||
fuera = contar(base, "SELECT COUNT(*) FROM observacion_clinica WHERE valor_id IS NULL AND valor_fuente IS NOT NULL")
|
||||
assert i_md16 > 0
|
||||
assert (conteos["reporte_sin_padre"], conteos["de_otro_estudio"]) == (0, 0)
|
||||
assert conteos["fuera_de_catalogo"] == fuera
|
||||
@@ -0,0 +1,30 @@
|
||||
"""La regla de §6: ningún paso abre una sesión; todo va por `ctx.repos`.
|
||||
|
||||
Las subclases viven en `persistance/edges/` y Persistance las instancia con su
|
||||
fábrica de sesión (ADR-MD-005). Solo `connection.py` nombra a `persistance.db`: cambia a
|
||||
qué base apunta Persistance (`<PROYECTO>_DATABASE_URL` en memoria); no es un paso.
|
||||
"""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
PAQUETE = Path(__file__).parents[1] / "webapi" / "orchestration"
|
||||
EXENTOS = {"connection.py"}
|
||||
PROHIBIDO = re.compile(r"fabrica_por_defecto|get_(cacu|cama|tea)_session|get_\{|Session\(|persistance\.db")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("modulo", sorted(str(p.relative_to(PAQUETE)) for p in PAQUETE.rglob("*.py") if p.name not in EXENTOS and ".ipynb_checkpoints" not in p.parts))
|
||||
def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo):
|
||||
texto = (PAQUETE / modulo).read_text(encoding="utf-8")
|
||||
assert not PROHIBIDO.findall(texto), f"{modulo} abre su propia sesión: debe usar ctx.repos"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True), ("tea", True)])
|
||||
def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes):
|
||||
repos = repositories_of(proyecto)
|
||||
assert (repos.gold.cohorts is not None) == con_cohortes
|
||||
assert repos.gold.calculation.model.__tablename__ == "measure_report"
|
||||
@@ -0,0 +1,97 @@
|
||||
"""El paso `estimate` y la orden `confirm-risks` (ADR-MD-008), con un estimador de prueba.
|
||||
|
||||
El estimador se inyecta en el contexto; aquí se usa uno que cumple el contrato `EstimadorDeRiesgo` sin MLflow.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orchestration.__main__ import confirm_risks, main
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Procedencia:
|
||||
modelo_nombre: str = "prueba"
|
||||
modelo_version: str = "1"
|
||||
mlflow_run_id: str = "sin-mlflow"
|
||||
modelo_sha: str = "sha-de-prueba"
|
||||
|
||||
def como_dict(self):
|
||||
return dict(self.__dict__)
|
||||
|
||||
|
||||
class EstimadorFijo:
|
||||
"""Cumple el contrato: un riesgo por miembro, `probabilidad` (0.1) al `horizonte` (0)."""
|
||||
|
||||
desenlace = "cin2_mas"
|
||||
|
||||
def __init__(self, cohorte_url=URL, horizonte=0.0, probabilidad=0.1):
|
||||
self.cohorte_url, self.horizonte, self.probabilidad = cohorte_url, horizonte, probabilidad
|
||||
self.columnas = None
|
||||
|
||||
def procedencia(self):
|
||||
return Procedencia()
|
||||
|
||||
def estimar(self, columnas, filas):
|
||||
self.columnas = columnas
|
||||
return [(fila[0], fila[1], self.horizonte, self.probabilidad, None, None) for fila in filas]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def cacu(base):
|
||||
base.run("catalogs", "load", "event_models", "cohorts", allow_undecided=True)
|
||||
return base
|
||||
|
||||
|
||||
def cuenta(base, sql):
|
||||
with base.motor.connect() as con:
|
||||
return con.execute(text(sql)).scalar_one()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
estimador = EstimadorFijo()
|
||||
|
||||
(lote_id, nuevo) = cacu.run("estimate", estimators={URL: estimador})["estimate"][URL]
|
||||
|
||||
miembros = cuenta(cacu, "SELECT n_miembros FROM cohorte_armado ORDER BY armado_id DESC LIMIT 1")
|
||||
assert nuevo and miembros > 0
|
||||
assert estimador.columnas[:2] == ["pac_id", "fecha_indice"] # el marco ancho de `leer_marco`
|
||||
assert cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}") == miembros
|
||||
assert cuenta(cacu, "SELECT COUNT(DISTINCT estado) FROM evaluacion_riesgo") == 1
|
||||
assert cuenta(cacu, "SELECT MIN(estado) FROM evaluacion_riesgo") == "preliminary"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
|
||||
assert cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL] == (primero, False)
|
||||
assert cacu.run("estimate")["estimate"] == {}
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo_lote") == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_confirmar_y_anular_un_lote_agregan_una_version(cacu, capsys):
|
||||
(lote_id, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
miembros = cuenta(cacu, f"SELECT COUNT(*) FROM evaluacion_riesgo WHERE lote_id = {lote_id}")
|
||||
|
||||
main(["confirm-risks", "cacu", str(lote_id), "--reason", "revisado"])
|
||||
assert f"{miembros} evaluaciones confirmadas" in capsys.readouterr().out
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'final' AND version = 2") == miembros
|
||||
|
||||
assert confirm_risks("cacu", lote_id, "error de captura", void=True) == miembros
|
||||
assert cuenta(cacu, "SELECT COUNT(*) FROM evaluacion_riesgo WHERE estado = 'entered-in-error'") == miembros
|
||||
|
||||
|
||||
# Por proyecto: la cohorte, el horizonte de sus bandas y su resumen por banda. Desde T-21h solo CaCu arma
|
||||
# su cohorte; las de TEA y CaMa son propuestas y su punta a punta está en `models` y en el kit.
|
||||
DE_PUNTA_A_PUNTA = {
|
||||
"cacu": (URL, 0.0, "cacu/CACU_RIESGO_BANDA"),
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""What this module covers: the timeline `repositories_of` wires into `ctx.repos.silver` is dbt's view
|
||||
`cacu_linea_de_tiempo`, the one the models' pipelines, the cohort builds and the measures' strata read: silver's
|
||||
facts as the indicator kit's own timeline gave them, plus the procedures dbt infers from them.
|
||||
|
||||
Fixtures: `base` (from `conftest.py`), the CaCu fixture database, loaded and with dbt's views created
|
||||
(`catalogs`, `load`, `event_models`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on
|
||||
that data (`fixtures/kit_cacu_timeline.json`, without `conocida_en`, which is each run's load time).
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
CORTE = date(2025, 12, 31)
|
||||
INFERRED = {"colposcopia", "tratamiento", "citologia_de_vigilancia", "diagnostico", "antecedente"}
|
||||
KIT_ROWS = Path(__file__).parent / "fixtures" / "kit_cacu_timeline.json"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def proyecto():
|
||||
return "cacu"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def loaded(base):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base.run("catalogs", "load", "event_models")
|
||||
return base
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def kit_rows():
|
||||
return json.loads(KIT_ROWS.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def as_kit(rows) -> list[dict]:
|
||||
"""Rows as the snapshot keeps them: text values, no load time, without the inferred procedures."""
|
||||
return [{k: None if v is None else str(v) for k, v in row.items() if k != "conocida_en"}
|
||||
for row in rows if row["tipo"] not in INFERRED]
|
||||
|
||||
|
||||
def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_rows):
|
||||
"""Pins down: the wired repository reads dbt's view, which holds every row the kit's timeline held, in its
|
||||
order and with a date as `fecha`, plus inferred procedures. Fails if the orchestration binds another query, or
|
||||
the view stops giving one of the kit's rows."""
|
||||
rows = loaded.ctx.repos.silver.timeline.read(until=CORTE)
|
||||
assert as_kit(rows) == kit_rows
|
||||
assert {row["tipo"] for row in rows} & INFERRED
|
||||
assert all(isinstance(row["fecha"], date) for row in rows)
|
||||
|
||||
|
||||
def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows):
|
||||
"""Pins down: `patients` keeps those patients' rows, all of them. Fails if the filter is dropped or misapplied."""
|
||||
patients = sorted({int(row["pac_id"]) for row in kit_rows})[:2]
|
||||
rows = loaded.ctx.repos.silver.timeline.read(patients=patients, until=CORTE)
|
||||
assert {row["pac_id"] for row in rows} == set(patients)
|
||||
assert as_kit(rows) == [row for row in kit_rows if int(row["pac_id"]) in patients]
|
||||
|
||||
|
||||
def test_known_until_cuts_at_what_was_loaded(loaded):
|
||||
"""Pins down: `known_until` compares with the load's time as a datetime: before the load nothing is known,
|
||||
after it everything is. Fails if the cut is ignored, applied to the clinical date, or compared as text."""
|
||||
timeline = loaded.ctx.repos.silver.timeline
|
||||
everything = timeline.read(until=CORTE)
|
||||
known = {row["conocida_en"] for row in everything}
|
||||
assert all(isinstance(at, datetime) and at.tzinfo is not None for at in known)
|
||||
assert timeline.read(until=CORTE, known_until=min(known) - timedelta(seconds=1)) == []
|
||||
assert timeline.read(until=CORTE, known_until=datetime.now(timezone.utc) + timedelta(days=1)) == everything
|
||||
@@ -0,0 +1,140 @@
|
||||
"""The aggregate import log and the live indicator recomputation."""
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
MAPPING = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
"pac_codigo_postal": "pac_codigo_postal",
|
||||
}
|
||||
|
||||
|
||||
def _csv(rows: list[str]) -> dict:
|
||||
body = "\n".join(["pac_id_hospital,pac_sexo,pac_fecha_nacimiento,pac_codigo_postal", *rows]).encode()
|
||||
return {
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(body).decode(), "options": {"file_name": "Garcia_Lopez.csv"}},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain, tmp_path_factory):
|
||||
wire_domain("cacu")
|
||||
import os
|
||||
|
||||
os.environ["WEBAPI_REPORT_DIR"] = str(tmp_path_factory.mktemp("reportes"))
|
||||
os.environ["INDICADORES_DIR"] = str(tmp_path_factory.mktemp("indicadores"))
|
||||
os.environ["INDICADORES_DESDE"] = "2025"
|
||||
os.environ["INDICADORES_HASTA"] = "2025"
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _log():
|
||||
from webapi.imports.audit import default_sink
|
||||
|
||||
return default_sink().read()
|
||||
|
||||
|
||||
def test_commit_is_logged_as_aggregates_only(client):
|
||||
rows = [f"RPT-{i},F,1980-01-0{i % 9 + 1},64000" for i in range(4)]
|
||||
rows += [f"RPT-BAD-{i},POSITIVO,15/13/1980,64000" for i in range(6)]
|
||||
rows += ["RPT-RARE,QWERTY,1980-01-01,"]
|
||||
response = client.post("/imports/commit", json={"sources": [_csv(rows)], "on_conflict": "reject"})
|
||||
body = response.get_json()
|
||||
assert response.status_code == 200
|
||||
assert body["results"][0]["created"] == 4
|
||||
assert body["indicadores_en_recalculo"] is True
|
||||
|
||||
record = _log()[-1]
|
||||
assert record["id"] == body["audit_id"]
|
||||
assert (record["operacion"], record["dominio"], record["resultado"]) == ("carga", "cacu", "completada")
|
||||
source = record["fuentes"][0]
|
||||
assert source["origen"] == {"tipo": "csv", "extensiones": [".csv"]}
|
||||
assert source["filas"]["leidas"] == 11
|
||||
assert source["filas"]["insertadas"] == 4
|
||||
assert source["filas"]["rechazadas_en_validacion"] == 7
|
||||
sexo = source["campos"]["pac_sexo"]
|
||||
assert sexo["valores_fuera_de_catalogo"] == {"POSITIVO": 6}
|
||||
assert sexo["valores_fuera_de_catalogo_poco_frecuentes"] == 1
|
||||
assert source["campos"]["pac_fecha_nacimiento"]["formatos_rechazados"] == {"99/99/9999": 6}
|
||||
assert source["campos"]["pac_codigo_postal"]["vacios"] == 1
|
||||
|
||||
raw = json.dumps(record)
|
||||
for secret in ("RPT-", "Garcia", "QWERTY", "15/13/1980"):
|
||||
assert secret not in raw
|
||||
|
||||
|
||||
def test_failed_request_and_validation_are_logged(client):
|
||||
bad = _csv(["RPT-X,F,1980-01-01,64000"])
|
||||
bad["target"] = "cacu.NoExiste"
|
||||
assert client.post("/imports/commit", json={"sources": [bad]}).status_code == 400
|
||||
assert _log()[-1]["resultado"] == "solicitud_invalida"
|
||||
|
||||
assert client.post("/imports/validate", json={"source": _csv(["RPT-V,F,1980-01-01,64000"])}).status_code == 200
|
||||
last = _log()[-1]
|
||||
assert (last["operacion"], last["resultado"]) == ("validacion", "completada")
|
||||
assert last["fuentes"][0]["filas"]["validas"] == 1
|
||||
|
||||
|
||||
def test_report_endpoints(client):
|
||||
body = client.get("/reportes/importaciones").get_json()
|
||||
paciente = body["resumen"]["destinos"]["cacu.Paciente"]
|
||||
assert paciente["cargas_completadas"] == 1
|
||||
assert paciente["filas_en_cargas_completadas"]["insertadas"] == 4
|
||||
assert body["intentos"][0]["operacion"] == "validacion"
|
||||
download = client.get("/reportes/importaciones/descarga")
|
||||
assert len(download.get_data(as_text=True).strip().splitlines()) == len(_log())
|
||||
|
||||
|
||||
def test_indicators_recompute_from_imported_rows(client):
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
|
||||
cola = RecomputationQueue()
|
||||
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
||||
assert cola.serve() == ["cacu"]
|
||||
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
||||
assert estado["estado"] == "ok", estado
|
||||
assert estado["pendiente"] is False
|
||||
assert {p["paso"] for p in estado["pasos"]} >= {"load", "event_models"}
|
||||
assert {m["id"] for m in client.get("/cacu/indicadores").get_json()} == {
|
||||
"IND1", "CACU_EU13", "CACU_EU7", "CACU_CONFIRMACION_CITOLOGIA", "CACU_EU_TIEMPO_REPORTE",
|
||||
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_RIESGO_BANDA"}
|
||||
|
||||
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
|
||||
|
||||
|
||||
def test_headerless_file_does_not_leak_its_first_record():
|
||||
"""Without a header row the first record becomes the column names."""
|
||||
from webapi.imports.audit import column_label
|
||||
|
||||
for header in ("pac_id_hospital", "fecha_nacimiento", "cit_vph_genotipo_16", "Sexo", "Código postal"):
|
||||
assert column_label(header) == header
|
||||
for value, shape in (("N-0001", "A-9999"), ("1980-01-01", "9999-99-99"), ("64000", "99999"),
|
||||
("H123", "A999"), ("ana@x.mx", "AAA@A.AA")):
|
||||
assert column_label(value) == shape
|
||||
note = "Paciente refiere dolor pélvico desde hace tres semanas"
|
||||
assert note not in column_label(note)
|
||||
|
||||
|
||||
def test_headerless_csv_logs_shapes(client):
|
||||
body = "N-0001,F,1980-01-01\nN-0002,F,1981-02-02\n".encode()
|
||||
source = {
|
||||
"source_type": "csv", "target": "cacu.Paciente",
|
||||
"column_mapping": {"N-0001": "pac_id_hospital", "F": "pac_sexo", "1980-01-01": "pac_fecha_nacimiento"},
|
||||
"payload": {"file_base64": base64.b64encode(body).decode()},
|
||||
}
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
raw = json.dumps(_log()[-1])
|
||||
assert "N-0001" not in raw and "1980-01-01" not in raw
|
||||
assert "A-9999" in raw
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Extraction's ranker in WebApi: the document review reports each field's
|
||||
alternatives, whether the record is about the target and which extraction
|
||||
version read it; an import whose records a person corrected teaches the
|
||||
domain's ranker once it is written (`webapi.imports.services.
|
||||
review_learning`); and `python -m webapi.nlp` scores and trains against an
|
||||
answer key.
|
||||
|
||||
Fixtures: `client` (the app over fresh CaCu, CaMa and TEA databases),
|
||||
`registry` (a SQLite MLflow per test with its files in `tmp_path`, the
|
||||
ranker and learning switched on, and learning run synchronously). Documents are made up inline with
|
||||
`text_pdf`.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
from concurrent.futures import Future
|
||||
|
||||
import pytest
|
||||
from extraction.testing import text_pdf
|
||||
|
||||
from webapi import nlp
|
||||
from webapi.imports.services import review_learning
|
||||
|
||||
REPORT = text_pdf([["LABORATORIO DE CITOLOGÍA", "Expediente: RV-0001", "No. de orden: 9001", "Prueba de VPH por PCR: POSITIVO",
|
||||
"Observaciones: se sugiere colposcopía; en caso de VPH negativo repetir en un año."]])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cacu")
|
||||
wire_domain("cama")
|
||||
wire_domain("tea")
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
class _Now:
|
||||
"""An executor that runs each task as it is submitted."""
|
||||
|
||||
def submit(self, fn, *args):
|
||||
future = Future()
|
||||
future.set_result(fn(*args))
|
||||
return future
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def registry(tmp_path, monkeypatch):
|
||||
import mlflow
|
||||
|
||||
from models.io import extraction_ranker
|
||||
|
||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
||||
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
|
||||
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
|
||||
mlflow.set_tracking_uri(uri)
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("EXTRACTION_RANKER", "auto")
|
||||
monkeypatch.setenv("EXTRACTION_LEARNING", "1")
|
||||
monkeypatch.setattr(extraction_ranker, "_cache", {})
|
||||
monkeypatch.setattr(review_learning, "_executor", _Now())
|
||||
from models.io.registry import registry as models_registry
|
||||
|
||||
yield models_registry
|
||||
|
||||
|
||||
def _source(**options) -> dict:
|
||||
return {
|
||||
"source_type": "document",
|
||||
"target": "cacu.CitologiaCervical",
|
||||
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital",
|
||||
"cit_vph_resultado": "cit_vph_resultado"},
|
||||
"payload": {"files": [{"name": "r.pdf", "file_base64": base64.b64encode(REPORT).decode()}], **options},
|
||||
"label": "documentos",
|
||||
}
|
||||
|
||||
|
||||
def test_the_review_reports_alternatives_topic_and_version(client):
|
||||
"""Fails if the review loses the other readings a person can pick, the
|
||||
subject check, or the extraction version that will be stored."""
|
||||
body = client.post("/imports/sources/document/extract", json={"files": _source()["payload"]["files"], "target": "cacu.CitologiaCervical"}).get_json()
|
||||
[record] = body["records"]
|
||||
assert record["on_topic"] is True
|
||||
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
|
||||
assert record["fields"]["cit_vph_resultado"]["assertion"] == "afirmado"
|
||||
assert body["nlp_version"].startswith("extraction ")
|
||||
assert all(isinstance(options, list) for options in record["alternatives"].values())
|
||||
|
||||
|
||||
def test_a_corrected_import_teaches_the_ranker(client, registry):
|
||||
"""Committing a document source with a correction registers a new DEV
|
||||
version of the domain's ranker, learned from that record. Fails if
|
||||
`commit_sources` stops calling `learn_from_reviews` or the examples are
|
||||
lost on the way."""
|
||||
source = _source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})
|
||||
result = client.post("/imports/commit", json={"sources": [source]}).get_json()
|
||||
assert result["ok"], result
|
||||
[version] = registry.versions("cacu", "extraccion")
|
||||
assert version["status"] == "desarrollo"
|
||||
from models.io.extraction_ranker import current
|
||||
|
||||
assert current("cacu").examples > 0
|
||||
|
||||
|
||||
def test_imports_without_corrections_or_with_learning_off_teach_nothing(client, registry, monkeypatch):
|
||||
"""Fails if an untouched import, or one made with
|
||||
`EXTRACTION_LEARNING=0`, creates ranker versions."""
|
||||
client.post("/imports/commit", json={"sources": [_source()]})
|
||||
monkeypatch.setenv("EXTRACTION_LEARNING", "0")
|
||||
client.post("/imports/commit", json={"sources": [_source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})]})
|
||||
assert registry.versions("cacu", "extraccion") == []
|
||||
|
||||
|
||||
def test_the_command_scores_and_trains_against_an_answer_key(tmp_path, registry):
|
||||
"""`evaluate` scores per field and overall without printing values
|
||||
unless asked; `train` estimates on held-out documents, then registers
|
||||
a version. Fails if the command's key format or outputs change."""
|
||||
folder = tmp_path / "documentos"
|
||||
folder.mkdir()
|
||||
(folder / "a.pdf").write_bytes(REPORT)
|
||||
(folder / "b.pdf").write_bytes(text_pdf([["Biopsia cervical dirigida", "Diagnóstico:", "NIC I"]]))
|
||||
key = {
|
||||
"a.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": "POSITIVO", "pac_id_hospital": "RV-0001"}},
|
||||
"b.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": None}, "cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG"}},
|
||||
}
|
||||
(tmp_path / "clave.json").write_text(json.dumps(key))
|
||||
paths = {"documents": str(folder), "key": str(tmp_path / "clave.json")}
|
||||
evaluated = nlp.command_evaluate(argparse.Namespace(**paths, with_values=False, no_ranker=True))
|
||||
assert evaluated["global"]["f1"] == 1.0
|
||||
assert evaluated["errores"] == []
|
||||
trained = nlp.command_train(argparse.Namespace(**paths))
|
||||
assert set(trained) == {"sin_ranker", "estimacion_dejando_uno_fuera", "versiones"}
|
||||
assert trained["versiones"] == {"cacu": "1"}
|
||||
@@ -0,0 +1,102 @@
|
||||
"""What this module covers: `GET /cacu/riesgos/lotes` and the confirm/void routes (`webapi.risk_batches`): which
|
||||
batches are listed, that confirming or voiding moves a batch off the list and that the route rejects a missing
|
||||
reason or an unknown batch. The reads and writes behind it are Persistance's, tested there.
|
||||
|
||||
Fixtures: `client`, the app over the kit's CaCu demonstration database (`conftest.cliente_de`); `batches`, two
|
||||
batches over a fresh surveillance build, both still preliminary.
|
||||
"""
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def batches(client):
|
||||
"""Three preliminary batches over one patient of the demo data: `older` and `newer` are confirmed/voided by
|
||||
the tests that exercise those routes; `untouched` stays preliminary for the tests that must not change a
|
||||
batch's state (an unknown id, a missing reason)."""
|
||||
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro
|
||||
from persistance import cacu
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
pac_id = cacu.persona_repository.list(limit=1)[0].pac_id
|
||||
with get_cacu_session() as session:
|
||||
build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.3.0", definicion_sha="d", reglas_sha="r",
|
||||
parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-batches", marco_sha="m",
|
||||
n_miembros=1, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc))
|
||||
session.add(build)
|
||||
session.flush()
|
||||
session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=pac_id, fecha_indice=date(2025, 3, 1),
|
||||
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id)))
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
provenance = {"modelo_nombre": "cacu-cin2_logistic", "modelo_sha": "s", "mlflow_run_id": "r"}
|
||||
|
||||
def batch(version, risk, ahora):
|
||||
lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version},
|
||||
"cin2_12m", [(pac_id, date(2025, 1, 1), 1.0, risk, None, None)], ahora=ahora)
|
||||
return lote_id
|
||||
|
||||
older = batch("1", 0.1, datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
newer = batch("2", 0.2, datetime(2026, 10, 2, tzinfo=timezone.utc))
|
||||
untouched = batch("3", 0.3, datetime(2026, 10, 3, tzinfo=timezone.utc))
|
||||
return older, newer, untouched
|
||||
|
||||
|
||||
def test_pending_batches_are_listed_newest_first(client, batches):
|
||||
"""Pins down: every preliminary batch is listed, newest first, with the fields the WebApp reads. Fails if the
|
||||
order is reversed or a field is renamed."""
|
||||
older, newer, untouched = batches
|
||||
|
||||
body = client.get("/cacu/riesgos/lotes").get_json()
|
||||
|
||||
assert [b["lote_id"] for b in body if b["lote_id"] in batches] == [untouched, newer, older]
|
||||
listed = next(b for b in body if b["lote_id"] == untouched)
|
||||
assert set(listed) == {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "n_evaluaciones"}
|
||||
assert (listed["modelo_nombre"], listed["modelo_version"], listed["n_evaluaciones"]) == ("cacu-cin2_logistic", "3", 1)
|
||||
|
||||
|
||||
def test_confirming_drops_a_batch_off_the_pending_list(client, batches):
|
||||
"""Pins down: confirming a batch moves its evaluations to `final` and it stops being listed as pending. Fails if
|
||||
it stays listed, or the evaluations aren't actually changed."""
|
||||
older, _, _ = batches
|
||||
|
||||
response = client.post(f"/cacu/riesgos/lotes/{older}/confirmar", json={"reason": "revisado por clínica"})
|
||||
|
||||
assert response.status_code == 200 and response.get_json() == {"lote_id": older, "evaluaciones_cambiadas": 1}
|
||||
assert older not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()]
|
||||
|
||||
|
||||
def test_voiding_also_drops_a_batch_off_the_pending_list(client, batches):
|
||||
"""Pins down: voiding is the other way out of the pending list, distinct from confirming. Fails if it confirms
|
||||
instead of voiding, or leaves the batch pending."""
|
||||
_, newer, _ = batches
|
||||
|
||||
response = client.post(f"/cacu/riesgos/lotes/{newer}/anular", json={"reason": "modelo equivocado"})
|
||||
|
||||
assert response.status_code == 200 and response.get_json()["evaluaciones_cambiadas"] == 1
|
||||
assert newer not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()]
|
||||
|
||||
|
||||
def test_a_decision_needs_a_reason(client, batches):
|
||||
"""Pins down: confirming or voiding with no reason is refused and changes nothing. Fails if the batch moves
|
||||
anyway, which would leave a decision with no recorded motive (ADR-MD-008)."""
|
||||
_, _, untouched = batches
|
||||
|
||||
response = client.post(f"/cacu/riesgos/lotes/{untouched}/confirmar", json={"reason": " "})
|
||||
|
||||
assert response.status_code == 400
|
||||
assert untouched in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()]
|
||||
|
||||
|
||||
def test_an_unknown_batch_is_404(client):
|
||||
"""Pins down: a `lote_id` with no evaluations is 404, not a silent no-op. Fails if it answers 200 having changed
|
||||
nothing."""
|
||||
assert client.post("/cacu/riesgos/lotes/987654321/confirmar", json={"reason": "revisado"}).status_code == 404
|
||||
@@ -0,0 +1,248 @@
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.mapping.column_matcher import suggest_mapping
|
||||
from webapi.imports.schemas.cacu.paciente import PacienteImportSchema
|
||||
from webapi.imports.schemas.classify import ErrorCategory, classify_error
|
||||
from webapi.imports.schemas.service import validate_rows
|
||||
from webapi.imports.schemas.tea.pacientes import PacientesImportSchema
|
||||
|
||||
|
||||
def test_paciente_schema_required_field_missing():
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
PacienteImportSchema(pac_sexo="F")
|
||||
errors = excinfo.value.errors()
|
||||
assert any(e["loc"] == ("pac_id_hospital",) for e in errors)
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_sexo_alias():
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="f", pac_fecha_nacimiento="1990-01-15")
|
||||
assert schema.pac_sexo == "Femenino"
|
||||
|
||||
schema2 = PacienteImportSchema(pac_id_hospital="H-2", pac_sexo="MASCULINO", pac_fecha_nacimiento="1990-01-15")
|
||||
assert schema2.pac_sexo == "Masculino"
|
||||
|
||||
|
||||
def test_paciente_schema_rejects_unknown_sexo():
|
||||
with pytest.raises(ValidationError):
|
||||
# pac_sexo has no enum constraint on the storage model, but this is
|
||||
# still a plain string field; feed something structurally invalid
|
||||
# (a date field) to prove type validation happens
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_date_from_iso_string():
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="2020-01-15")
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_paciente_schema_coerces_date_from_datetime_object():
|
||||
from datetime import datetime
|
||||
|
||||
schema = PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento=datetime(2020, 1, 15, 10, 30))
|
||||
assert schema.pac_fecha_nacimiento.isoformat() == "2020-01-15"
|
||||
|
||||
|
||||
def test_tea_pacientes_schema_is_fully_optional():
|
||||
schema = PacientesImportSchema()
|
||||
assert schema.pac_id_hospital is None
|
||||
|
||||
|
||||
def test_tea_neuropediatrics_note_takes_icd10_with_or_without_the_dot():
|
||||
"""Pins down: the note's ICD-10 is upper-cased and accepted with or without its dot; anything else is
|
||||
rejected. Fails if the pattern of `neu_cie_codigo` changes."""
|
||||
from webapi.imports.schemas.tea.evaluacion_neuropediatrica import EvaluacionNeuropediatricaImportSchema as Nota
|
||||
|
||||
assert Nota(neu_cie_codigo=" f84.0 ").neu_cie_codigo == "F84.0"
|
||||
assert Nota(neu_cie_codigo="F840").neu_cie_codigo == "F840"
|
||||
with pytest.raises(ValidationError):
|
||||
Nota(neu_cie_codigo="autismo")
|
||||
|
||||
|
||||
def test_classify_error_missing():
|
||||
try:
|
||||
PacienteImportSchema(pac_sexo="F")
|
||||
except ValidationError as exc:
|
||||
classified = [classify_error(e) for e in exc.errors()]
|
||||
assert any(c.category == ErrorCategory.MISSING and c.field == "pac_id_hospital" for c in classified)
|
||||
|
||||
|
||||
def test_classify_error_type_invalid():
|
||||
try:
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_fecha_nacimiento="not-a-date")
|
||||
except ValidationError as exc:
|
||||
classified = [classify_error(e) for e in exc.errors()]
|
||||
assert any(c.category == ErrorCategory.TYPE_INVALID for c in classified)
|
||||
|
||||
|
||||
def test_validate_rows_never_aborts_on_a_bad_row():
|
||||
rows = [
|
||||
{"pac_id_hospital": "H-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1990-01-15"},
|
||||
{"pac_sexo": "M"}, # missing required fields
|
||||
{"pac_id_hospital": "H-3", "pac_fecha_nacimiento": "1990-01-15"},
|
||||
]
|
||||
result = validate_rows(PacienteImportSchema, rows)
|
||||
assert result.total_rows == 3
|
||||
assert result.valid_count == 2
|
||||
assert result.error_count == 1
|
||||
assert result.rejected[0].row_index == 1
|
||||
|
||||
|
||||
def test_column_matcher_exact_normalized_synonym_fuzzy_none():
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"]
|
||||
|
||||
suggestions = suggest_mapping(
|
||||
["pac_id_hospital", "Sexo", "fecha_nacimiento", "columna_sin_relacion_xyz"], targets
|
||||
)
|
||||
by_source = {s.source_column: s for s in suggestions}
|
||||
|
||||
assert by_source["pac_id_hospital"].reason == "exact"
|
||||
assert by_source["pac_id_hospital"].target_field == "pac_id_hospital"
|
||||
|
||||
assert by_source["Sexo"].reason == "synonym"
|
||||
assert by_source["Sexo"].target_field == "pac_sexo"
|
||||
|
||||
assert by_source["fecha_nacimiento"].reason in ("synonym", "fuzzy")
|
||||
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
||||
|
||||
assert by_source["columna_sin_relacion_xyz"].target_field is None
|
||||
assert by_source["columna_sin_relacion_xyz"].reason == "none"
|
||||
|
||||
|
||||
def test_column_matcher_enforces_one_to_one():
|
||||
# two source columns that would both match "pac_sexo" exactly-ish
|
||||
suggestions = suggest_mapping(["pac_sexo", "sexo"], ["pac_sexo"])
|
||||
matched_targets = [s.target_field for s in suggestions if s.target_field]
|
||||
assert matched_targets == ["pac_sexo"] # only the first claims it
|
||||
|
||||
|
||||
def test_coerce_date_accepts_iso_day_first_and_timestamps_but_not_impossible_dates():
|
||||
from datetime import date, datetime
|
||||
|
||||
from webapi.imports.schemas.coercion import coerce_date
|
||||
|
||||
assert coerce_date("1990-01-15") == date(1990, 1, 15)
|
||||
assert coerce_date("15/01/1990") == date(1990, 1, 15)
|
||||
assert coerce_date("15-01-1990") == date(1990, 1, 15)
|
||||
assert coerce_date("1990-01-15 00:00:00") == date(1990, 1, 15)
|
||||
assert coerce_date(datetime(1990, 1, 15, 8, 30)) == date(1990, 1, 15)
|
||||
assert coerce_date(" ") is None
|
||||
with pytest.raises(ValueError, match="no es una fecha válida"):
|
||||
coerce_date("31/02/1990")
|
||||
|
||||
|
||||
def test_catalog_is_case_insensitive_accepts_member_names_and_rejects_unknowns():
|
||||
from core.cacu.enums import SEXO_BIOLOGICO_ALIAS, SexoBiologico
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
assert catalog.coerce(" femenino ") == "Femenino"
|
||||
assert catalog.coerce("m") == "Masculino"
|
||||
assert catalog.coerce("") is None
|
||||
with pytest.raises(ValueError, match="no está en el catálogo"):
|
||||
catalog.coerce("X")
|
||||
|
||||
|
||||
|
||||
|
||||
def test_postal_code_restores_leading_zero_from_numeric_sources():
|
||||
from webapi.imports.schemas.coercion import coerce_postal_code
|
||||
|
||||
assert coerce_postal_code(1000) == "01000"
|
||||
assert coerce_postal_code(64000.0) == "64000"
|
||||
assert coerce_postal_code(" 01000 ") == "01000"
|
||||
assert coerce_postal_code("") is None
|
||||
|
||||
def test_birads_subcategories_from_reports_are_not_rejected_as_out_of_catalog():
|
||||
"""`extraction.nlp.vocabulary.CLINICAL_TERMS` extracts BI-RADS 4A/4B/4C
|
||||
from narrative text (a standard ACR BI-RADS subcategory), but the schema
|
||||
only models the base B0-B6 categories; without an alias for them, every
|
||||
such report was silently unimportable."""
|
||||
from core.cama.mastografia.enums import BIRADS, BIRADS_ALIAS
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
for value in ("4A", "BI-RADS 4B", "bi-rads 4c"):
|
||||
assert catalog.coerce(value) == "B4"
|
||||
|
||||
def test_column_matcher_handles_accents_prefixes_and_global_one_to_one():
|
||||
targets = ["pac_id_hospital", "pac_sexo", "pac_codigo_postal", "pac_fecha_nacimiento"]
|
||||
by_source = {
|
||||
s.source_column: s
|
||||
for s in suggest_mapping(["Fech nacim", "Género", "C.P.", "Expediente", "fecha_nacimiento"], targets)
|
||||
}
|
||||
assert by_source["Género"].target_field == "pac_sexo"
|
||||
assert by_source["C.P."].target_field == "pac_codigo_postal"
|
||||
assert by_source["Expediente"].target_field == "pac_id_hospital"
|
||||
# The synonym "fecha_nacimiento" wins pac_fecha_nacimiento even
|
||||
# though the weaker fuzzy "Fech nacim" comes first in the file.
|
||||
assert by_source["fecha_nacimiento"].target_field == "pac_fecha_nacimiento"
|
||||
assert by_source["Fech nacim"].target_field is None
|
||||
|
||||
|
||||
def test_column_matcher_matches_names_without_the_table_prefix():
|
||||
suggestion = suggest_mapping(["hemoglobina_g_dl", "birads"], ["hemoglobina_g_dl", "mast_birads"])
|
||||
assert [(s.target_field, s.reason) for s in suggestion] == [("hemoglobina_g_dl", "exact"), ("mast_birads", "unprefixed")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"target, source, expected",
|
||||
[
|
||||
# Match on shared meaning, not shared suffixes ("solicitaDO" vs "solicitaNTE").
|
||||
("cacu.OrdenesEstudio", "Estudio solicitado", "ord_tipo_estudio"),
|
||||
("cacu.OrdenesEstudio", "Paciente", "pac_id_hospital"),
|
||||
("cacu.NotaMedica", "Servicio", "nm_especialidad"),
|
||||
("cacu.NotaMedica", "Fecha consulta", "nm_fecha"),
|
||||
("cacu.NotaMedica", "Peso (kg)", "nm_masa_corporal"),
|
||||
# Flattened JSON paths match by their last segment; unprefixed fields by their words.
|
||||
("cacu.BiometriaHematica", "paciente.expediente", "pac_id_hospital"),
|
||||
("cacu.BiometriaHematica", "resultados.hemoglobina", "hemoglobina_g_dl"),
|
||||
("cacu.BiopsiaCervical", "Fecha de reporte", "bx_fecha_reporte"),
|
||||
],
|
||||
)
|
||||
def test_column_matcher_real_world_headers(target, source, expected):
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY[target].schema.model_fields)
|
||||
assert suggest_mapping([source], fields)[0].target_field == expected
|
||||
|
||||
|
||||
def test_column_matcher_does_not_guess_from_shared_letters_alone():
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
fields = list(ENTITY_REGISTRY["cacu.NotaMedica"].schema.model_fields)
|
||||
assert suggest_mapping(["Observaciones del servicio xyz", "Clave única"], fields)[1].target_field is None
|
||||
|
||||
|
||||
def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
from webapi.imports.schemas.coercion import Catalog
|
||||
|
||||
catalog = PacienteImportSchema.catalog_for("pac_sexo")
|
||||
assert isinstance(catalog, Catalog)
|
||||
assert catalog.choices["F"] == "Femenino"
|
||||
assert PacienteImportSchema.catalog_for("pac_codigo_postal") is None
|
||||
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
PacienteImportSchema(pac_id_hospital="H-1", pac_sexo="X", pac_fecha_nacimiento="1990-01-15")
|
||||
(error,) = excinfo.value.errors()
|
||||
classified = classify_error(error)
|
||||
assert classified.field == "pac_sexo"
|
||||
assert classified.category == ErrorCategory.OUT_OF_CATALOG
|
||||
assert "no está en el catálogo" in classified.message
|
||||
|
||||
|
||||
def test_catalog_aliases_for_values_the_indicator_kit_uses():
|
||||
"""Hospital spellings the indicator kit's own synthetic sources use must
|
||||
not be rejected at import."""
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenes
|
||||
from webapi.imports.schemas.tea.ordenes_estudio import OrdenesEstudioImportSchema as TeaOrdenes
|
||||
|
||||
assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="CIN1").bx_cin_grado == "LIEBG"
|
||||
assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="nic 3").bx_cin_grado == "LIEAG"
|
||||
cito = CitologiaCervicalImportSchema(pac_id_hospital="H", cit_celulas_escamosas="NEGATIVO")
|
||||
assert cito.cit_celulas_escamosas == "NORMAL"
|
||||
assert CamaOrdenes(pac_id_hospital="H", ord_numero_hospital=1, ord_tipo_estudio="MASTOGRAFIA").ord_tipo_estudio == "MASTOGRAFIA"
|
||||
assert TeaOrdenes(ord_tipo_estudio="electroencefalograma").ord_tipo_estudio == "EEG"
|
||||
assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "ADOS2"
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Smoke-tests that every `ENTITY_REGISTRY` import schema is importable and
|
||||
constructible, plus spot checks of enum-alias coercion."""
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.ados2 import Ados2ImportSchema
|
||||
from webapi.imports.schemas.tea.mchat import MchatImportSchema
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema
|
||||
|
||||
|
||||
# Domains whose Core layer is fully permissive (every field Optional);
|
||||
# see `tea/pacientes.py`'s docstring. CaCu/CaMa entities all carry at least
|
||||
# one business-required field (`pac_id_hospital` and friends).
|
||||
_FULLY_OPTIONAL_PREFIXES = ("tea.",)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("entity_key", list(ENTITY_REGISTRY.keys()))
|
||||
def test_every_registered_schema_is_constructible(entity_key):
|
||||
spec = ENTITY_REGISTRY[entity_key]
|
||||
schema_cls = spec.schema
|
||||
|
||||
if entity_key.startswith(_FULLY_OPTIONAL_PREFIXES):
|
||||
# Fully permissive: an empty row must construct cleanly.
|
||||
instance = schema_cls()
|
||||
assert instance is not None
|
||||
else:
|
||||
# Has at least one required field: an empty row must be rejected.
|
||||
with pytest.raises(ValidationError):
|
||||
schema_cls()
|
||||
|
||||
|
||||
# --- Spot checks -----------------------------------------------------------
|
||||
# CaMa entity with a required, unique integer ord_numero_hospital and an
|
||||
# *_ALIAS-backed enum field.
|
||||
|
||||
|
||||
def test_cama_ordenes_estudio_requires_numero_hospital_and_coerces_tipo_estudio():
|
||||
with pytest.raises(ValidationError) as excinfo:
|
||||
CamaOrdenesEstudioImportSchema(pac_id_hospital="H-1")
|
||||
errors = excinfo.value.errors()
|
||||
assert any(e["loc"] == ("ord_numero_hospital",) for e in errors)
|
||||
|
||||
schema = CamaOrdenesEstudioImportSchema(
|
||||
pac_id_hospital="H-1", ord_numero_hospital=12345, ord_tipo_estudio="biopsia chica"
|
||||
)
|
||||
assert schema.ord_tipo_estudio == "BIOPSIA_CHICA"
|
||||
|
||||
|
||||
def test_tea_ados2_coerces_module_and_classification_aliases():
|
||||
"""Pins down: the ADOS-2's module comes from the bare enum and its classification takes the old spelling
|
||||
`NO_TEA`. Fails if either catalog stops normalizing case or aliases."""
|
||||
schema = Ados2ImportSchema(ado_modulo="modulo_1", ado_clasificacion="no_tea")
|
||||
assert (schema.ado_modulo, schema.ado_clasificacion) == ("MODULO_1", "NO_ESPECTRO")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("schema", "field", "value"), [
|
||||
(MchatImportSchema, "mch_puntaje", 21), (Ados2ImportSchema, "ado_css", 0), (Ados2ImportSchema, "ado_sa_b1", 4),
|
||||
])
|
||||
def test_tea_scores_out_of_their_range_are_rejected(schema, field, value):
|
||||
"""Pins down: an M-CHAT score above 20, a CSS below 1 and an ADOS-2 item above 3 are validation errors. Fails if
|
||||
a bound of `Bounded` is dropped from the schemas."""
|
||||
with pytest.raises(ValidationError):
|
||||
schema(**{field: value})
|
||||
|
||||
|
||||
# CaCu entity with a real *_ALIAS-backed field (GRADO_CIN_ALIAS).
|
||||
def test_cacu_biopsia_cervical_coerces_cin_grado_alias():
|
||||
schema = BiopsiaCervicalImportSchema(
|
||||
pac_id_hospital="H-1",
|
||||
bx_cin_grado="LESION INTRAEPITELIAL ESCAMOSA DE BAJO GRADO",
|
||||
)
|
||||
assert schema.bx_cin_grado == "LIEBG"
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
BiopsiaCervicalImportSchema(bx_cin_grado="LIEBG") # pac_id_hospital missing
|
||||
|
||||
|
||||
# CaCu EpisodioClinico: requires pac_id_hospital and coerces tipo_episodio/
|
||||
# especialidad_medica through their respective *_ALIAS catalogs.
|
||||
def test_cacu_episodio_clinico_requires_pac_id_hospital_and_coerces_catalogs():
|
||||
with pytest.raises(ValidationError):
|
||||
EpisodioClinicoImportSchema(tipo_episodio="SCREENING") # pac_id_hospital missing
|
||||
|
||||
schema = EpisodioClinicoImportSchema(
|
||||
pac_id_hospital="H-1", tipo_episodio="SCREENING", especialidad_medica="MEDICINA FAMILIAR",
|
||||
)
|
||||
assert schema.tipo_episodio == "TAMIZAJE"
|
||||
assert schema.especialidad_medica == "MEDICINA_FAMILIAR"
|
||||
@@ -0,0 +1,70 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, siempre simulada.
|
||||
|
||||
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: que existe sin `DEV_REVISION`, la forma y los códigos
|
||||
de error. Fixtures: `client`, la app sin `DEV_REVISION` sobre la base de demostración de CaCu.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"pac_id", "id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""La app sobre la base de demostración de CaCu, sin `DEV_REVISION` en el entorno."""
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
"""Fija: sin `DEV_REVISION` la ruta existe, con la forma del contrato y `simulado: true`. Falla si la ruta
|
||||
vuelve a depender de una variable de entorno o cambia un campo."""
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31")
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/json"
|
||||
cuerpo = response.get_json()
|
||||
assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True
|
||||
assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"])
|
||||
assert all(i["prioridad"] is None for i in cuerpo["items"])
|
||||
# The patient key is the platform's `pac_id`, the one the risk route takes; the hospital's id never leaves.
|
||||
assert all(i["pac_id"].isdigit() and i["id_seudonimo"] == i["pac_id"] for i in cuerpo["items"])
|
||||
assert "pac_id_hospital" not in response.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_el_pedido_se_respeta(client):
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=6&page=1&page_size=2&estatus=PRE_COLPOSCOPIA").get_json()
|
||||
|
||||
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
||||
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500"],
|
||||
)
|
||||
def test_un_pedido_mal_escrito_o_fuera_de_rango_da_400(client, query):
|
||||
response = client.get(f"/cacu/seguimiento{query}")
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_una_pagina_de_mas_da_404(client):
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31&page=9999")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_in_dev_esta_obsoleta():
|
||||
"""Fija: `in_dev()` avisa que está obsoleta. Falla si alguien vuelve a usarla como compuerta sin el aviso."""
|
||||
from webapi.follow_up.routes import in_dev
|
||||
|
||||
with pytest.warns(DeprecationWarning):
|
||||
in_dev()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Exercise regular and cohort follow-up with an authorized synthetic reader."""
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from flask import Flask
|
||||
|
||||
from webapi.cama_analysis import analysis, revision_of
|
||||
from webapi.seguimiento_cama import blueprint_seguimiento_cama
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
"""A fixed six-person cohort and a server-controlled access callback."""
|
||||
rows = [dict(pac_id=str(n + 1), mastografia_fecha='2026-10-15',
|
||||
birads='BIRADS_5', grupo_edad='50-59', biopsia=None,
|
||||
biopsia_fecha=None) for n in range(6)]
|
||||
app = Flask(__name__)
|
||||
app.register_blueprint(analysis, url_prefix='/cama')
|
||||
app.register_blueprint(blueprint_seguimiento_cama(), url_prefix='/cama')
|
||||
app.config.update(CAMA_COHORT_SYNTHETIC=True, CAMA_COHORT_READER=lambda cutoff: rows,
|
||||
CAMA_COHORT_ACCESS=lambda request: request.headers.get('X-Test') == 'yes')
|
||||
return app.test_client()
|
||||
|
||||
|
||||
def test_regular_list_detail_and_export_use_the_same_selection(client):
|
||||
"""Pagination, detail and export resolve the same filtered persistent cohort."""
|
||||
headers = {'X-Test': 'yes'}
|
||||
query = '?corte=2026-10-20&meses=3&birads=BIRADS_5'
|
||||
page = client.get('/cama/seguimiento' + query + '&page_size=2', headers=headers).get_json()
|
||||
assert page['paginacion']['total_items'] == 6
|
||||
assert page['cohorte'] == 'cama_birads_v1'
|
||||
context = '&cohorte=' + page['cohorte'] + '&escenario=' + page['escenario'] + '&revision=' + page['revision']
|
||||
rows = []
|
||||
for number in (1, 2, 3):
|
||||
rows.extend(client.get('/cama/seguimiento' + query + context + f'&page_size=2&page={number}', headers=headers).get_json()['items'])
|
||||
exported = client.get('/cama/seguimiento/exportacion' + query + context, headers=headers).get_json()
|
||||
assert exported['items'] == rows
|
||||
assert client.get('/cama/pacientes/' + rows[0]['pac_id'] + query + context, headers=headers).get_json()['item'] == rows[0]
|
||||
assert client.get('/cama/seguimiento' + query, headers=headers).headers['Cache-Control'] == 'no-store'
|
||||
|
||||
|
||||
def test_regular_followup_checks_access_and_suppression(client):
|
||||
"""The ordinary route cannot bypass authorization or suppression."""
|
||||
assert client.get('/cama/seguimiento').status_code == 403
|
||||
headers = {'X-Test': 'yes'}
|
||||
assert client.get('/cama/seguimiento?corte=2026-10-20&birads=BIRADS_4', headers=headers).status_code == 403
|
||||
assert client.get('/cama/seguimiento?corte=2026-10-20&estatus=BENIGNO', headers=headers).status_code == 400
|
||||
assert client.get('/cama/seguimiento?revision=' + '0' * 64, headers=headers).status_code == 400
|
||||
client.application.config['CAMA_COHORT_ACCESS'] = 'invalid'
|
||||
assert client.get('/cama/seguimiento', headers=headers).status_code == 403
|
||||
|
||||
|
||||
def test_disabled_provider_and_empty_window(client):
|
||||
"""Unavailable sources fail closed and an empty unfiltered window stays empty."""
|
||||
headers = {'X-Test': 'yes'}
|
||||
body = client.get('/cama/seguimiento?corte=2025-01-01&meses=3', headers=headers).get_json()
|
||||
assert body['items'] == [] and body['paginacion']['total_items'] == 0
|
||||
client.application.config['CAMA_COHORT_READER'] = None
|
||||
assert client.get('/cama/seguimiento', headers=headers).status_code == 503
|
||||
|
||||
|
||||
def test_provider_failure_does_not_break_other_routes(client):
|
||||
"""A failing cohort source returns unavailable while the app can serve other requests."""
|
||||
def fail(_cutoff):
|
||||
raise RuntimeError('provider unavailable')
|
||||
|
||||
client.application.add_url_rule('/health', 'health', lambda: {'status': 'ok'})
|
||||
client.application.config['CAMA_COHORT_READER'] = fail
|
||||
assert client.get('/cama/analisis/indicadores?corte=2026-10-20').status_code == 503
|
||||
assert client.get('/cama/seguimiento?corte=2026-10-20', headers={'X-Test': 'yes'}).status_code == 503
|
||||
assert client.get('/health').get_json() == {'status': 'ok'}
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Rows that reference a parent by the source's own id (a biopsy's `mast_id`,
|
||||
a hospital table's `pac_id`) must land on the right parent, whatever order or
|
||||
numbering the parents arrive in."""
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _json(records, target, mapping=None):
|
||||
mapping = mapping or {k: k for k in records[0]}
|
||||
return {"source_type": "json", "target": target, "column_mapping": mapping,
|
||||
"payload": {"file_base64": base64.b64encode(json.dumps(records).encode()).decode()}}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cama")
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_biopsy_keeps_pointing_at_its_mammogram(client):
|
||||
pacientes = [{"pac_id": 70, "pac_id_hospital": "SRC-A", "pac_fecha_nacimiento": "1970-01-01"},
|
||||
{"pac_id": 50, "pac_id_hospital": "SRC-B", "pac_fecha_nacimiento": "1971-01-01"}]
|
||||
# Hospital ids out of insertion order: an auto-numbered table would swap them.
|
||||
mastografias = [{"mast_id": 902, "pac_id": 50, "pac_id_hospital": "SRC-B", "mast_birads": "B4"},
|
||||
{"mast_id": 901, "pac_id": 70, "pac_id_hospital": "SRC-A", "mast_birads": "B1"}]
|
||||
biopsias = [{"bx_id": 1, "mast_id": 902, "pac_id": 50, "pac_id_hospital": "SRC-B"}]
|
||||
sources = [_json(pacientes, "cama.Paciente"), _json(mastografias, "cama.Mastografia"),
|
||||
_json(biopsias, "cama.BiopsiaMama", {"mast_id": "mast_id", "pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital"})]
|
||||
body = client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.cama import biopsia_mama_repository, mastografia_repository, paciente_repository
|
||||
|
||||
pacientes = {p.pac_id_hospital: p.pac_id for p in paciente_repository.list()}
|
||||
assert pacientes == {"SRC-A": 70, "SRC-B": 50}
|
||||
biopsia = biopsia_mama_repository.list()[0]
|
||||
mamografia = mastografia_repository.get(biopsia.mast_id)
|
||||
assert mamografia.pac_id == biopsia.pac_id == 50
|
||||
|
||||
|
||||
def test_natural_key_wins_over_a_foreign_internal_id(client):
|
||||
"""The patient came from a CSV without ids; the hospital table sends its own pac_id."""
|
||||
pacientes = [{"pac_id_hospital": "CSV-1", "pac_fecha_nacimiento": "1980-01-01"}]
|
||||
client.post("/imports/commit", json={"sources": [_json(pacientes, "cama.Paciente")]})
|
||||
notas = [{"pac_id": 999, "pac_id_hospital": "CSV-1", "nm_id_hospital": "N-1"}]
|
||||
result = client.post("/imports/commit", json={"sources": [_json(notas, "cama.NotaMedica")]}).get_json()["results"][0]
|
||||
assert result["created"] == 1, result
|
||||
assert result["linked"] == {"pac_id": 1}
|
||||
|
||||
from persistance.cama import nota_medica_repository, paciente_repository
|
||||
|
||||
paciente = next(p for p in paciente_repository.list() if p.pac_id_hospital == "CSV-1")
|
||||
nota = next(n for n in nota_medica_repository.list() if n.nm_id_hospital == "N-1")
|
||||
assert nota.pac_id == paciente.pac_id != 999
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def tea_client(wire_domain):
|
||||
wire_domain("tea")
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_tea_children_keep_pointing_at_their_parents_source_ids(tea_client):
|
||||
sources = [
|
||||
_json([{"pac_id": 1, "pac_id_hospital": "T-1"}], "tea.Pacientes"),
|
||||
_json([{"ord_id": "ord-1", "ord_pac_id": 1, "ord_id_hospital": "O-1"}], "tea.OrdenesEstudio"),
|
||||
_json([{"ado_id": "ado-1", "ado_ord_id": "ord-1", "ado_pac_id": 1}], "tea.Ados2"),
|
||||
_json([{"eeg_id": "eeg-1", "eeg_ord_id": "ord-1", "eeg_id_registro_laboratorio": "L-1"}], "tea.Eeg"),
|
||||
_json([{"neu_id": "neu-1", "neu_ord_id": "ord-1", "neu_pac_id": 1}], "tea.EvaluacionNeuropediatrica"),
|
||||
]
|
||||
body = tea_client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.tea import ados2_repository, eeg_repository, evaluacion_neuropediatrica_repository
|
||||
|
||||
assert eeg_repository.get("eeg-1").eeg_ord_id == "ord-1"
|
||||
assert eeg_repository.get("eeg-1").eeg_id_registro_laboratorio == "L-1"
|
||||
assert ados2_repository.get("ado-1").ado_ord_id == "ord-1"
|
||||
assert evaluacion_neuropediatrica_repository.get("neu-1").neu_ord_id == "ord-1"
|
||||
|
||||
|
||||
def test_tea_rows_without_a_source_id_get_one(tea_client):
|
||||
eeg = _json([{"eeg_id_registro_laboratorio": "L-SIN-ID"}], "tea.Eeg")
|
||||
assert tea_client.post("/imports/commit", json={"sources": [eeg]}).get_json()["results"][0]["created"] == 1
|
||||
|
||||
from persistance.tea import eeg_repository
|
||||
|
||||
[fila] = [e for e in eeg_repository.list() if e.eeg_id_registro_laboratorio == "L-SIN-ID"]
|
||||
assert len(fila.eeg_id) == 36
|
||||
@@ -0,0 +1,116 @@
|
||||
"""What this module covers: source forms as a function into the catalog's codes (`reference.source_mapping`):
|
||||
many forms to one code, no code for an unknown form, the same form read per source system and per date, and two
|
||||
codes for one form rejected when they're in force together; every catalog's TOML passing that check; and, in each
|
||||
domain's database, the catalog step seeding `cat_mapeo` without touching a stored row and `register` refusing a
|
||||
mapping that breaks the function.
|
||||
|
||||
Fixtures: `base` (conftest), each domain's migrated fixture database; the other tests build their rows.
|
||||
"""
|
||||
|
||||
import tomllib
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from webapi.orchestration.reference.catalogs import ruta_de_catalogo
|
||||
from webapi.orchestration.reference.source_mapping import (
|
||||
CATALOG, SourceForm, ambiguities, check_function, from_result, normalize, register, resolve,
|
||||
)
|
||||
|
||||
HER2 = "biopsia.her2"
|
||||
LAB_A = [SourceForm("lab_a", HER2, "3+", "H3", None, date(2026, 12, 31)),
|
||||
SourceForm("lab_a", HER2, "Positivo", "H3", None, date(2026, 12, 31))]
|
||||
LAB_B = [SourceForm("lab_b", HER2, "Positivo (score 3)", "H3", date(2027, 1, 1)),
|
||||
SourceForm("lab_b", HER2, "Positivo", "H2", date(2027, 1, 1))]
|
||||
|
||||
|
||||
def test_many_forms_give_one_code_and_an_unknown_form_none():
|
||||
"""Pins down: the mapping isn't injective and is partial: several spellings, compared without case, accents or
|
||||
extra spaces, give the same code; a spelling with no mapping gives None. Fails if `normalize` stops folding or
|
||||
`resolve` invents a code."""
|
||||
assert {resolve(LAB_A, "lab_a", HER2, f) for f in ("3+", " positivo ", "POSITIVO")} == {"H3"}
|
||||
assert resolve(LAB_A, "lab_a", HER2, "Equívoco") is None
|
||||
assert normalize(" Positívo (score 3) ") == "POSITIVO (SCORE 3)"
|
||||
|
||||
|
||||
def test_a_form_is_read_per_source_system_and_per_date():
|
||||
"""Pins down: "Positivo" is H3 at lab A and H2 at lab B, and a mapping applies only to documents dated within its
|
||||
validity. Fails if `resolve` ignores the system or the dates, letting one lab's spelling leak into another's."""
|
||||
rows = LAB_A + LAB_B
|
||||
assert resolve(rows, "lab_a", HER2, "Positivo", date(2026, 6, 1)) == "H3"
|
||||
assert resolve(rows, "lab_b", HER2, "Positivo", date(2027, 2, 1)) == "H2"
|
||||
assert resolve(rows, "lab_b", HER2, "Positivo", date(2026, 6, 1)) is None
|
||||
assert ambiguities(rows) == []
|
||||
|
||||
|
||||
def test_two_codes_for_one_form_in_force_together_are_rejected():
|
||||
"""Pins down: a form mapped to two codes with overlapping validity breaks the function: `check_function` names
|
||||
it and `resolve` gives None rather than either code. Two codes in validities that don't overlap, or the same
|
||||
code twice, are fine. Fails if the overlap test or the code comparison is dropped."""
|
||||
clash = SourceForm("lab_b", HER2, "positivo", "H3", date(2027, 6, 1))
|
||||
with pytest.raises(ValueError, match="se escribe igual para 'H2' y 'H3'"):
|
||||
check_function(LAB_B + [clash])
|
||||
assert resolve(LAB_B + [clash], "lab_b", HER2, "Positivo", date(2027, 7, 1)) is None
|
||||
corrected = [LAB_B[1]._replace(valid_to=date(2027, 5, 31)), clash]
|
||||
check_function(corrected)
|
||||
assert resolve(corrected, "lab_b", HER2, "Positivo", date(2027, 7, 1)) == "H3"
|
||||
check_function(LAB_B + [LAB_B[0]._replace(form="POSITIVO (SCORE 3)")])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama", "tea"])
|
||||
def test_every_catalog_s_spellings_are_a_function(proyecto):
|
||||
"""Pins down: in each domain's TOML, every result's codes, labels and aliases map to one value each. Fails when
|
||||
an edit to a catalog gives one spelling two values."""
|
||||
estudios = tomllib.loads(ruta_de_catalogo(proyecto).read_text(encoding="utf-8"))
|
||||
rows = [row for estudio_id, estudio in estudios.items()
|
||||
for nombre, resultado in estudio.get("resultados", {}).items()
|
||||
for row in from_result(f"{estudio_id}.{nombre}", resultado)]
|
||||
check_function(rows)
|
||||
|
||||
|
||||
# --- the stored mappings, in each domain ---
|
||||
|
||||
|
||||
def a_coded_result(base) -> tuple[str, str, str]:
|
||||
"""A coded result of the domain's catalog with two values: (resultado_id, first valor_id, second valor_id)."""
|
||||
estudios = tomllib.loads(ruta_de_catalogo(base.proyecto).read_text(encoding="utf-8"))
|
||||
for estudio_id, estudio in estudios.items():
|
||||
for nombre, resultado in estudio.get("resultados", {}).items():
|
||||
valores = resultado.get("valores", ())
|
||||
if len(valores) >= 2:
|
||||
return f"{estudio_id}.{nombre}", valores[0]["valor"], valores[1]["valor"]
|
||||
raise AssertionError("el catálogo no tiene un resultado codificado con dos valores")
|
||||
|
||||
|
||||
def test_the_catalog_step_seeds_the_mappings_and_keeps_what_a_person_changed(base):
|
||||
"""Pins down: the catalog step adds the catalog's own mappings (each value's code among them) and, run again,
|
||||
adds nothing and leaves a person's row for a new form as it is. Fails if the step stops seeding or a deploy
|
||||
replaces stored rows."""
|
||||
base.run("catalogs")
|
||||
mappings = base.ctx.repos.silver.mappings
|
||||
resultado, primero, segundo = a_coded_result(base)
|
||||
sembradas = mappings.forms(sistema_fuente_id=CATALOG, resultado_id=resultado, clase="valor")
|
||||
assert {(m.forma, m.valor_id) for m in sembradas} >= {(primero, primero), (segundo, segundo)}
|
||||
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=" forma del curador ", registrado_por="curador",
|
||||
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
assert base.run("catalogs")["catalogs"]["mapeos_nuevos"] == 0
|
||||
[mia] = mappings.forms(forma_normalizada="FORMA DEL CURADOR")
|
||||
assert (mia.forma, mia.valor_id, mia.registrado_por) == ("forma del curador", segundo, "curador")
|
||||
|
||||
|
||||
def test_register_refuses_a_second_code_for_a_form_in_force(base):
|
||||
"""Pins down: `register` checks the new row against the stored ones: the catalog's own code of one value can't
|
||||
be mapped to another value, and a lab's form can, once the first row's validity ends before the second's starts.
|
||||
Fails if the write path stops running `check_function`."""
|
||||
base.run("catalogs")
|
||||
mappings = base.ctx.repos.silver.mappings
|
||||
resultado, primero, segundo = a_coded_result(base)
|
||||
with pytest.raises(ValueError, match="se escribe igual"):
|
||||
register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma=primero, registrado_por="curador",
|
||||
vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
viejo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="Código de laboratorio",
|
||||
registrado_por="curador", vigente_desde=date(2026, 1, 1), resultado_id=resultado, valor_id=primero)
|
||||
mappings.close(viejo.mapeo_id, date(2026, 12, 31))
|
||||
nuevo = register(mappings, sistema_fuente_id=CATALOG, clase="valor", forma="codigo de LABORATORIO",
|
||||
registrado_por="curador", vigente_desde=date(2027, 1, 1), resultado_id=resultado, valor_id=segundo)
|
||||
filas = mappings.forms(forma_normalizada=normalize("Código de laboratorio"))
|
||||
assert [f.mapeo_id for f in filas] == [viejo.mapeo_id, nuevo.mapeo_id]
|
||||
@@ -1,165 +0,0 @@
|
||||
"""The Conectar dialog's API: an operator who knows nothing of dlt picks a kind of source,
|
||||
answers its questions, and "Probar conexión" says in plain words what it found."""
|
||||
|
||||
import os
|
||||
import sqlite3
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import make_url
|
||||
|
||||
from webapi import sources
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("SOURCE_ROOTS", str(own_platform / "shared"))
|
||||
(own_platform / "shared" / "reportes" / "2026").mkdir(parents=True)
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def probe(client, kind, **answers):
|
||||
response = client.post("/ingest/sources/test", json={"type": kind, "answers": answers})
|
||||
assert response.status_code == 200, response.text
|
||||
return response.json()
|
||||
|
||||
|
||||
def test_the_dialog_lists_every_kind_with_its_questions(client):
|
||||
found = client.get("/ingest/sources/types").json()
|
||||
assert {"database", "files", "cloud", "web"} <= set(found["groups"])
|
||||
assert found["types"]["sqlserver"]["fields"]["password"]["type"] == "password"
|
||||
|
||||
|
||||
def test_erick_sql_server_through_the_dialog(client, site):
|
||||
url = make_url(site.url)
|
||||
answers = {"host": url.host, "port": url.port, "database": url.database,
|
||||
"user": url.username, "password": url.password} # fmt: skip
|
||||
found = probe(client, "sqlserver", **answers)
|
||||
assert found["ok"] and found["tables"] == ["ResultadoSubrogado"]
|
||||
rows = probe(client, "sqlserver", **answers, table="ResultadoSubrogado")["rows"]
|
||||
assert rows and all(r["Archivo"].endswith(" bytes>") for r in rows)
|
||||
wrong = probe(client, "sqlserver", **answers | {"password": "not-it"})
|
||||
assert not wrong["ok"] and "contraseña" in wrong["message"] and wrong["detail"]
|
||||
|
||||
|
||||
def test_an_unknown_server_and_a_missing_answer_say_so_plainly(client):
|
||||
gone = probe(client, "sqlserver", host="nowhere.invalid", database="P", user="u",
|
||||
password="p") # fmt: skip
|
||||
assert not gone["ok"] and gone["message"].startswith(("No se encontró", "El servidor no"))
|
||||
assert probe(client, "postgresql", host="h")["message"].startswith("falta «Base de datos»")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not os.environ.get("POSTGRES_TEST_URL"), reason="needs PostgreSQL")
|
||||
def test_postgresql_through_the_dialog(client):
|
||||
url = make_url(os.environ["POSTGRES_TEST_URL"])
|
||||
found = probe(client, "postgresql", host=url.host, port=url.port or 5432,
|
||||
database=url.database, user=url.username, password=url.password) # fmt: skip
|
||||
assert found["ok"], found
|
||||
|
||||
|
||||
def test_a_sqlite_file_lists_its_tables_then_shows_rows(client, own_platform):
|
||||
path = own_platform / "shared" / "hospital.db"
|
||||
with sqlite3.connect(path) as con:
|
||||
con.execute("create table pacientes (id int, nombre text)")
|
||||
con.execute("insert into pacientes values (1, 'Ana')")
|
||||
assert probe(client, "sqlite", path=str(path))["tables"] == ["pacientes"]
|
||||
rows = probe(client, "sqlite", path=str(path), table="pacientes")["rows"]
|
||||
assert rows == [{"id": 1, "nombre": "Ana"}]
|
||||
|
||||
|
||||
def test_server_folders_are_browsed_only_under_the_mounted_roots(client, own_platform):
|
||||
roots = client.get("/ingest/sources/browse").json()["entries"]
|
||||
assert [e["name"] for e in roots] == ["shared"]
|
||||
inside = client.get("/ingest/sources/browse", params={"path": roots[0]["path"]}).json()
|
||||
assert [e["name"] for e in inside["entries"]] == ["reportes"]
|
||||
assert client.get("/ingest/sources/browse", params={"path": "/etc"}).status_code == 404
|
||||
escape = str(own_platform / "shared" / ".." / "data")
|
||||
assert client.get("/ingest/sources/browse", params={"path": escape}).status_code == 404
|
||||
|
||||
|
||||
def test_a_folder_uploaded_from_a_computer_is_read_as_spreadsheets_or_documents(client):
|
||||
sent = [("files", ("informes/enero/a.csv", b"folio,resultado\n1,NEGATIVO\n")),
|
||||
("files", ("informes/b.pdf", b"%PDF-1.4 ..."))] # fmt: skip
|
||||
uploaded = client.post("/ingest/uploads", files=sent).json()
|
||||
assert sorted(uploaded["files"]) == ["informes/b.pdf", "informes/enero/a.csv"]
|
||||
more = client.post("/ingest/uploads", files=[("files", ("../../fuera.csv", b"x\n"))],
|
||||
data={"folder": uploaded["bucket_url"]}).json() # fmt: skip
|
||||
assert more["files"] == ["fuera.csv"] and more["bucket_url"] == uploaded["bucket_url"]
|
||||
other = client.post("/ingest/uploads", files=[("files", ("x", b"x"))], data={"folder": "/"})
|
||||
assert other.status_code == 422
|
||||
rows = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.csv",
|
||||
read_as="dlt.sources.filesystem:read_csv")["rows"] # fmt: skip
|
||||
assert rows == [{"folio": 1, "resultado": "NEGATIVO"}]
|
||||
files = probe(client, "upload", folder=uploaded["bucket_url"], pattern="**/*.pdf")["rows"]
|
||||
assert [f["file_name"] for f in files] == ["b.pdf"]
|
||||
|
||||
|
||||
def test_an_empty_folder_says_what_to_check(client, own_platform):
|
||||
found = probe(client, "server_folder", folder=str(own_platform / "shared" / "reportes"))
|
||||
assert found["ok"] and "Revise la ruta" in found["message"]
|
||||
|
||||
|
||||
def test_a_sign_in_button_without_an_app_registration_says_who_must_register_one(client):
|
||||
found = client.get("/ingest/sources/oauth/google/start", params={"origin": "http://x"})
|
||||
assert found.status_code == 503 and "GOOGLE_CLIENT_ID" in found.json()["detail"]
|
||||
|
||||
|
||||
def test_signing_in_hands_the_account_to_the_dialog(client, monkeypatch, tmp_path):
|
||||
from authlib.integrations.httpx_client import OAuth2Client, oauth2_client
|
||||
|
||||
httpx = oauth2_client.httpx2 # the HTTP library this authlib is built on
|
||||
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_ID", "app")
|
||||
monkeypatch.setenv("MICROSOFT_CLIENT_SECRET", "app-secret")
|
||||
exchanged = {}
|
||||
|
||||
def provider(request: httpx.Request) -> httpx.Response: # the token endpoint
|
||||
exchanged["body"] = request.content.decode()
|
||||
return httpx.Response(200, json={"access_token": "at", "refresh_token": "rt",
|
||||
"token_type": "Bearer", "expires_in": 3600}) # fmt: skip
|
||||
|
||||
def client_for(found, env, redirect_uri):
|
||||
return OAuth2Client(env["client_id"], env["client_secret"], scope=found.scope,
|
||||
redirect_uri=redirect_uri, code_challenge_method="S256",
|
||||
transport=httpx.MockTransport(provider)) # fmt: skip
|
||||
|
||||
monkeypatch.setattr(sources, "_client", client_for)
|
||||
monkeypatch.setattr(sources, "PENDING", tmp_path / "pending") # any worker's callback
|
||||
monkeypatch.setattr(sources, "account", lambda p, token, env: {
|
||||
"user": "ana@hospital.mx", "drive_id": "d1",
|
||||
"oauth2_client_params": {"client_id": env["client_id"], "token": token}}) # fmt: skip
|
||||
start = client.get("/ingest/sources/oauth/microsoft/start",
|
||||
params={"origin": "http://10.0.10.41:5710"}).json() # fmt: skip
|
||||
assert start["url"].startswith("https://login.microsoftonline.com/organizations/")
|
||||
assert "code_challenge=" in start["url"] and "client_id=app" in start["url"]
|
||||
back = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert back.status_code == 200
|
||||
assert '"user": "ana@hospital.mx"' in back.text and '"http://10.0.10.41:5710"' in back.text
|
||||
assert "code_verifier=" in exchanged["body"] and "code=c0de" in exchanged["body"]
|
||||
again = client.get("/ingest/sources/oauth/microsoft/callback",
|
||||
params={"state": start["state"], "code": "c0de"}) # fmt: skip
|
||||
assert again.status_code == 400 # a sign-in is used once
|
||||
|
||||
|
||||
def test_a_saved_account_shows_who_but_never_its_tokens():
|
||||
from core.pipeline import MASK, Pipeline, redacted, restored
|
||||
|
||||
params = {"client_id": "app", "client_secret": "app-secret-xyz",
|
||||
"token": {"refresh_token": "refresh-xyz"}} # fmt: skip
|
||||
account = {"user": "ana@hospital.mx", "drive_id": "d1", "oauth2_client_params": params}
|
||||
saved = Pipeline(nodes=[{"id": "s", "kind": "source", "guided": {
|
||||
"type": "onedrive", "answers": {"account": account, "folder": "Reportes"}}}]) # fmt: skip
|
||||
shown = redacted(saved)
|
||||
answer = shown.nodes[0].guided.answers["account"]
|
||||
assert answer["user"] == "ana@hospital.mx"
|
||||
dumped = shown.model_dump_json()
|
||||
assert "refresh-xyz" not in dumped and "app-secret-xyz" not in dumped
|
||||
assert answer["oauth2_client_params"]["client_secret"] == MASK
|
||||
back = restored(Pipeline.model_validate(shown.model_dump()), saved).nodes[0]
|
||||
assert (
|
||||
back.args["storage_options"]["oauth2_client_params"]["token"]["refresh_token"]
|
||||
== "refresh-xyz"
|
||||
)
|
||||
@@ -0,0 +1,139 @@
|
||||
"""The SQL connector is the one import path where the client chooses what
|
||||
the server connects to; these tests pin its guard rails (see
|
||||
webapi.imports.connectors.sql_policy)."""
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
|
||||
from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.sql_policy import SqlSourcePolicy
|
||||
|
||||
PRODUCTION_POLICY = SqlSourcePolicy(
|
||||
allowed_dialects=frozenset({"mysql", "mariadb", "postgresql", "mssql"}), allowed_hosts=None
|
||||
)
|
||||
|
||||
|
||||
def test_sqlite_is_refused_by_default_policy(tmp_path):
|
||||
with pytest.raises(ConnectorError, match="'sqlite' no está permitido"):
|
||||
SqlConnector(f"sqlite:///{tmp_path / 'x.db'}", policy=PRODUCTION_POLICY)
|
||||
|
||||
|
||||
def test_host_allowlist_is_enforced():
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=frozenset({"10.0.10.50"}))
|
||||
with pytest.raises(ConnectorError, match="no está entre los permitidos"):
|
||||
policy.check_url("mysql+pymysql://u:p@evil.example.com/db")
|
||||
assert policy.check_url("mysql+pymysql://u:p@10.0.10.50/db").host == "10.0.10.50"
|
||||
|
||||
|
||||
def test_refuses_the_applications_own_database(monkeypatch, tmp_path):
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
own = tmp_path / "cacu.db"
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", f"sqlite:///{own}")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"sqlite"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url(f"sqlite:///{own}")
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cama_database_url", "mysql+pymysql://app:pw@db.internal:3306/isss_cama")
|
||||
mysql_policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
mysql_policy.check_url("mysql+pymysql://someone_else:pw@DB.internal:3306/isss_cama")
|
||||
mysql_policy.check_url("mysql+pymysql://app:pw@db.internal:3306/hospital_legacy")
|
||||
|
||||
|
||||
def test_an_explicit_default_port_does_not_bypass_the_own_database_check(monkeypatch):
|
||||
from persistance import settings as persistance_settings
|
||||
|
||||
monkeypatch.setattr(persistance_settings.settings, "cacu_database_url", "mysql+pymysql://app:pw@db/isss_cacu")
|
||||
policy = SqlSourcePolicy(allowed_dialects=frozenset({"mysql"}), allowed_hosts=None)
|
||||
with pytest.raises(ConnectorError, match="propia aplicación"):
|
||||
policy.check_url("mysql+pymysql://app:pw@db:3306/isss_cacu")
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"DELETE FROM paciente",
|
||||
"select 1; drop table paciente",
|
||||
"UPDATE t SET a = 1",
|
||||
"-- harmless\nDROP TABLE t",
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_only_single_select_queries_pass(query):
|
||||
with pytest.raises(ConnectorError):
|
||||
SqlSourcePolicy.check_query(query)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["SELECT * FROM t;", " with x as (select 1 as a) select a from x", "/* c */ SELECT 1", "SELECT 'a;b' AS literal"],
|
||||
)
|
||||
def test_select_queries_pass(query):
|
||||
assert SqlSourcePolicy.check_query(query)
|
||||
|
||||
|
||||
def test_a_writable_cte_is_rejected_by_parsing_the_query_not_matching_keywords():
|
||||
"""`WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d` is a syntactic
|
||||
SELECT at the top level, so a check that only looks at the first keyword
|
||||
lets it through; parsing the query and inspecting the tree catches the
|
||||
write hiding inside the CTE."""
|
||||
with pytest.raises(ConnectorError, match="no puede escribir"):
|
||||
SqlSourcePolicy.check_query("WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d")
|
||||
|
||||
|
||||
def test_select_into_a_new_table_is_rejected():
|
||||
"""SQL Server's `SELECT ... INTO` creates a table — a write a keyword
|
||||
check would miss entirely, since the statement still starts with SELECT."""
|
||||
with pytest.raises(ConnectorError, match="no puede escribir"):
|
||||
SqlSourcePolicy.check_query("SELECT * INTO nueva_tabla FROM t", dialect="mssql")
|
||||
|
||||
|
||||
def test_mysql_select_into_outfile_is_rejected():
|
||||
"""MySQL's `SELECT ... INTO OUTFILE` writes a file to the server's own
|
||||
filesystem. sqlglot's MySQL grammar doesn't model this clause at all, so
|
||||
it fails to parse — rejected as invalid SQL, which is the safe default
|
||||
for anything that can't be positively confirmed to be a plain read."""
|
||||
with pytest.raises(ConnectorError):
|
||||
SqlSourcePolicy.check_query("SELECT * FROM t INTO OUTFILE '/tmp/x.csv'", dialect="mysql")
|
||||
|
||||
|
||||
def test_connection_is_read_only_even_for_a_write_the_query_parser_could_miss(tmp_path):
|
||||
"""Defense in depth: even if a future sqlglot version or an edge-case
|
||||
dialect quirk let a write-shaped query past `check_query`, the
|
||||
connection itself is read-only and the transaction is always rolled
|
||||
back, so the underlying database still refuses to execute it."""
|
||||
db = tmp_path / "src.db"
|
||||
engine = sa.create_engine(f"sqlite:///{db}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text("CREATE TABLE t (a INTEGER)"))
|
||||
conn.execute(sa.text("INSERT INTO t VALUES (1), (2)"))
|
||||
|
||||
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None))
|
||||
# Bypass check_query directly to isolate the read-only connection itself,
|
||||
# rather than testing the parser twice.
|
||||
connector._query, connector._table = "WITH d AS (DELETE FROM t RETURNING a) SELECT a FROM d", None
|
||||
with pytest.raises(ConnectorError):
|
||||
connector.preview()
|
||||
with engine.connect() as conn:
|
||||
assert conn.execute(sa.text("SELECT COUNT(*) FROM t")).scalar_one() == 2
|
||||
|
||||
|
||||
def test_preview_only_fetches_the_limit_but_counts_everything(tmp_path):
|
||||
db = tmp_path / "big.db"
|
||||
engine = sa.create_engine(f"sqlite:///{db}")
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text("CREATE TABLE t (id INTEGER, cp TEXT)"))
|
||||
conn.execute(sa.text("INSERT INTO t VALUES " + ",".join(f"({i}, '0{i:04d}')" for i in range(500))))
|
||||
|
||||
connector = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_table("t")
|
||||
preview = connector.preview(limit=5)
|
||||
assert len(preview.sample_rows) == 5
|
||||
assert preview.total_rows == 500
|
||||
assert {c.name: c.inferred_type for c in preview.columns} == {"id": "integer", "cp": "string"}
|
||||
|
||||
custom = SqlConnector(f"sqlite:///{db}", policy=SqlSourcePolicy(frozenset({"sqlite"}), None)).select_query(
|
||||
"SELECT id AS expediente FROM t WHERE id < 10"
|
||||
)
|
||||
assert custom.preview(limit=3).total_rows == 10
|
||||
assert list(custom.read_rows({"expediente": "pac_id_hospital"}))[:2] == [{"pac_id_hospital": 0}, {"pac_id_hospital": 1}]
|
||||
@@ -1,63 +0,0 @@
|
||||
"""Phase 3.5 gate: Synthea through the FHIR door. A seeded synthetic population (Synthea,
|
||||
with the platform's cervical-screening module) arrives as a standard hospital would send it,
|
||||
and every report it holds reaches silver: nothing held, one person per patient."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from fhir_checks import pages
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
||||
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
||||
DOOR = ROOT / "tests" / "fixtures" / "pipelines" / "fhir_door.json"
|
||||
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
||||
|
||||
|
||||
def _population(out: Path, people: int = 20) -> list[dict]:
|
||||
"""Synthea's FHIR R4 transaction Bundles, one per patient (fixed seeds)."""
|
||||
subprocess.run(
|
||||
["java", "-jar", SYNTHEA, "-p", str(people), "-s", "7", "-cs", "7", "-g", "F",
|
||||
"-a", "25-64", "-d", str(MODULES), "-m", "cervical_screening",
|
||||
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
||||
"--exporter.hospital.fhir.export", "false",
|
||||
"--exporter.practitioner.fhir.export", "false"],
|
||||
check=True, capture_output=True, cwd=out.parent,
|
||||
) # fmt: skip
|
||||
return [json.loads(p.read_text()) for p in sorted((out / "fhir").glob("*.json"))]
|
||||
|
||||
|
||||
def _reports(bundles: list[dict], study: str) -> int:
|
||||
return sum(
|
||||
1 for b in bundles for e in b["entry"]
|
||||
if e["resource"]["resourceType"] == "DiagnosticReport"
|
||||
and any(c.get("system") == STUDY and c.get("code") == study
|
||||
for c in e["resource"].get("code", {}).get("coding", []))
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def test_a_synthea_population_comes_in_through_the_fhir_door(api, platform, tmp_path):
|
||||
bundles = _population(tmp_path / "synthea")
|
||||
patients = sum(1 for b in bundles for e in b["entry"]
|
||||
if e["resource"]["resourceType"] == "Patient") # fmt: skip
|
||||
# Synthea counts the living: the women who died come on top of the twenty.
|
||||
assert patients >= 20 and _reports(bundles, "cervical_cytology") > 40
|
||||
|
||||
receiving = DOOR.read_text().replace("{sender}", "synthea")
|
||||
ok(api.put("/ingest/pipelines/synthea", json=json.loads(receiving)))
|
||||
batch = {"resourceType": "Bundle", "type": "batch",
|
||||
"entry": [e for b in bundles for e in b["entry"]]} # fmt: skip
|
||||
answer = api.post("/cacu/fhir?sender=synthea", json=batch)
|
||||
assert answer.status_code == 202, answer.text[:500]
|
||||
wait_for(api, answer.headers["location"].rsplit("/", 1)[1])
|
||||
|
||||
# Nothing held, every report placed, one person per patient.
|
||||
for study in ("cervical_cytology", "cervical_biopsy"):
|
||||
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
||||
assert platform.count(f"silver.{study}") == _reports(bundles, study), study
|
||||
assert platform.count("silver.person") == patients
|
||||
(served,) = pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
||||
assert served["total"] == patients
|
||||
@@ -1,110 +0,0 @@
|
||||
"""Phase 4.5: a CaMa population from Synthea (tests/fixtures/synthea/modules/
|
||||
breast_screening.json) comes in through the FHIR door, by the API: every mammogram, biopsy
|
||||
and first-course treatment lands in silver, each biopsy's results (sent as several reports of
|
||||
the same day) as one biopsy, and gold's CaMa timeline carries the stage and the treatments the
|
||||
survival model reads."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
from conftest import ROOT
|
||||
|
||||
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
||||
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
||||
DOOR = ROOT / "tests" / "fixtures" / "pipelines" / "fhir_door_cama.json"
|
||||
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
||||
FIELD = "https://isssteleon.org/fhir/CodeSystem/catalog-field"
|
||||
WOMEN = 300
|
||||
|
||||
|
||||
def population(out: Path, women: int = WOMEN, seed: int = 7) -> list[dict]:
|
||||
"""Synthea's FHIR R4 Bundles for `women` women of 40 to 89 (fixed seeds), with only the
|
||||
resources the door reads."""
|
||||
subprocess.run(
|
||||
["java", "-jar", SYNTHEA, "-p", str(women), "-s", str(seed), "-cs", str(seed),
|
||||
"-g", "F", "-a", "40-89", "-d", str(MODULES), "-m", "breast_screening",
|
||||
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
||||
"--exporter.hospital.fhir.export", "false",
|
||||
"--exporter.practitioner.fhir.export", "false", "--exporter.years_of_history", "8",
|
||||
"--exporter.fhir.included_resources", "Patient,Encounter,DiagnosticReport,Observation"],
|
||||
check=True, capture_output=True, cwd=out.parent,
|
||||
) # fmt: skip
|
||||
return [json.loads(p.read_text()) for p in sorted((out / "fhir").glob("*.json"))]
|
||||
|
||||
|
||||
def _sent(bundles: list[dict]) -> Counter:
|
||||
"""What the bundles hold: mammograms, biopsies (one per patient and day), treatments, and
|
||||
the treatments of patients with a mammogram or a biopsy (CaMa's timeline is theirs: the
|
||||
export window can cut a study off and keep the treatment after it)."""
|
||||
found: Counter = Counter()
|
||||
biopsies = set()
|
||||
for b in bundles:
|
||||
studied = False
|
||||
treated = recurred = 0
|
||||
for e in b["entry"]:
|
||||
r = e["resource"]
|
||||
codes = [c for c in (r.get("code") or {}).get("coding", []) if c["system"] == STUDY]
|
||||
codes += [c for t in r.get("type", []) for c in t.get("coding", [])
|
||||
if c["system"] == STUDY] # fmt: skip
|
||||
for c in codes:
|
||||
if c["code"] == "breast_biopsy":
|
||||
biopsies.add((r["subject"]["reference"], r["effectiveDateTime"][:10]))
|
||||
else:
|
||||
found[c["code"]] += 1
|
||||
studied |= c["code"] in ("mammography", "breast_biopsy")
|
||||
treated += c["code"] == "breast_treatment"
|
||||
recurred += c["code"] == "breast_recurrence"
|
||||
if r["resourceType"] == "Patient" and r.get("deceasedDateTime"):
|
||||
found["death"] += 1
|
||||
found["timeline_treatment"] += treated if studied else 0
|
||||
found["timeline_recurrence"] += recurred if studied else 0
|
||||
found["breast_biopsy"] = len(biopsies)
|
||||
return found
|
||||
|
||||
|
||||
def test_a_synthea_cama_population_comes_in_through_the_fhir_door(api, platform, tmp_path):
|
||||
bundles = population(tmp_path / "synthea")
|
||||
sent = _sent(bundles)
|
||||
assert sent["breast_biopsy"] > 50 and sent["breast_treatment"] > 20 and sent["death"] > 0
|
||||
assert sent["breast_recurrence"] > 0
|
||||
|
||||
receiving = DOOR.read_text().replace("{sender}", "synthea")
|
||||
ok(api.put("/ingest/pipelines/synthea", json=json.loads(receiving)))
|
||||
batch = {"resourceType": "Bundle", "type": "batch",
|
||||
"entry": [e for b in bundles for e in b["entry"]]} # fmt: skip
|
||||
answer = api.post("/cama/fhir?sender=synthea", json=batch)
|
||||
assert answer.status_code == 202, answer.text[:500]
|
||||
wait_for(api, answer.headers["location"].rsplit("/", 1)[1], 1800)
|
||||
|
||||
for study in ("mammography", "breast_biopsy", "breast_treatment", "breast_recurrence"):
|
||||
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
||||
assert platform.count(f"silver.{study}") == sent[study], study
|
||||
q = platform.query
|
||||
# Each invasive biopsy holds all of its results; gold's timeline has them and the course.
|
||||
assert q("select count(*) from silver.breast_biopsy where histology = 'invasive' and "
|
||||
"(stage is null or her2 is null or grade is null or positive_nodes is null)"
|
||||
)[0][0] == 0 # fmt: skip
|
||||
kinds = dict(q("select type, count(*) from gold.cama_events where type in "
|
||||
"('stage', 'her2', 'positive_nodes', 'treatment', 'recurrence', 'death') "
|
||||
"group by type")) # fmt: skip
|
||||
assert kinds.get("stage", 0) > 0 and kinds.get("treatment", 0) == sent["timeline_treatment"]
|
||||
assert (
|
||||
kinds.get("positive_nodes", 0) > 0
|
||||
and kinds.get("recurrence", 0) == sent["timeline_recurrence"]
|
||||
)
|
||||
|
||||
# Recurrence, a roundtrip: trained through the API on these patients, its cohort is gold's
|
||||
# recurrence cohort and its recurrences are the ones Synthea wrote (slow: minutes).
|
||||
if not os.environ.get("RECURRENCE_SLOW"):
|
||||
return
|
||||
wait_for(api, ok(api.post("/models/cama/train", json={"models": ["recurrence"]}))["run_id"],
|
||||
3600) # fmt: skip
|
||||
report = ok(api.get("/models/cama/recurrence/versions/1/reports/technical_validation"))
|
||||
assert report["cohort"] == "site"
|
||||
members = q("select count(*) from gold.cama_cohort_recurrence where excluded_by is null")[0][0]
|
||||
assert report["rutinas"] and members > 0
|
||||
@@ -1,277 +0,0 @@
|
||||
"""Phase 4 gate, TEA: the synthetic hospital (EEG signals and ADOS-2 reports as BLOBs), loaded
|
||||
through one drawn pipeline, gives what the current platform gives on the same hospital (the
|
||||
reference fixtures, captured at the last load): the ADOS-2 results read from the reports and
|
||||
their scores, the EEG analysis, its indicators and its pages. Real API, Dagster and MLflow.
|
||||
|
||||
The hospital (205 MB) is kept outside git; its path is TEA_HOSPITAL (default
|
||||
~/isssteleon-data), and its hash is the manifest's.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
from collections import defaultdict
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fhir_checks import pages
|
||||
from sqlalchemy import inspect
|
||||
from test_conectar import ok, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
from core.tea import ados2
|
||||
from models.tea import association, jobs
|
||||
from models.tea.eeg import curves
|
||||
from models.tea.eeg import reference as eeg_reference
|
||||
from persistance import destination
|
||||
from persistance import eeg as eeg_store
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = Path(os.environ.get("TEA_HOSPITAL", Path.home() / "isssteleon-data"))
|
||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "tea"
|
||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_tea.json"
|
||||
MANIFEST = ROOT / "tests" / "fixtures" / "hospital" / "manifest.json"
|
||||
# The current platform's item columns, by module, for each item's meaning.
|
||||
ITEMS = {
|
||||
"vocalization_directed": {"module_1": "sa_a2"},
|
||||
"pointing": {"module_1": "sa_a7", "module_2": "sa_a6"},
|
||||
"gestures": {"module_1": "sa_a8", "module_2": "sa_a7"},
|
||||
"unusual_eye_contact": {"module_1": "sa_b1", "module_2": "sa_b1"},
|
||||
"facial_expressions": {"module_1": "sa_b3", "module_2": "sa_b2"},
|
||||
"gaze_integration": {"module_1": "sa_b4"},
|
||||
"shared_enjoyment": {"module_1": "sa_b5", "module_2": "sa_b3"},
|
||||
"showing": {"module_1": "sa_b9", "module_2": "sa_b5"},
|
||||
"joint_attention_initiation": {"module_1": "sa_b10", "module_2": "sa_b6"},
|
||||
"joint_attention_response": {"module_1": "sa_b11"},
|
||||
"social_overtures_quality": {"module_1": "sa_b12", "module_2": "sa_b8"},
|
||||
"reciprocal_communication": {"module_2": "sa_b11"},
|
||||
"rapport_quality": {"module_2": "sa_b12"},
|
||||
"intonation": {"module_1": "rrb_a3"},
|
||||
"stereotyped_language": {"module_1": "rrb_a5", "module_2": "rrb_a4"},
|
||||
"unusual_sensory_interest": {"module_1": "rrb_d1", "module_2": "rrb_d1"},
|
||||
"hand_finger_mannerisms": {"module_1": "rrb_d2", "module_2": "rrb_d2"},
|
||||
"repetitive_interests": {"module_1": "rrb_d4", "module_2": "rrb_d4"},
|
||||
} # fmt: skip
|
||||
MODULES = {"MODULO_1": "module_1", "MODULO_2": "module_2"}
|
||||
CLASSIFICATION = {"NO_ESPECTRO": "non_spectrum", "ESPECTRO_AUTISTA": "autism_spectrum",
|
||||
"AUTISMO": "autism"} # fmt: skip
|
||||
METRICS = {"RITMO_POSTERIOR": "posterior_rhythm", "HUSOS_SUENO_N2": "spindles_n2",
|
||||
"HUSOS_SUENO_N3": "spindles_n3", "PICOS_PAROXISTICOS": "paroxysmal_spikes",
|
||||
"GRADIENTE_ANTEROPOSTERIOR": "anteroposterior_gradient"} # fmt: skip
|
||||
LEVELS = {"completo": "complete", "no_analizable": "not_analyzable", "parcial": "partial",
|
||||
"sin_referencia_auricular": "no_ear_reference"} # fmt: skip
|
||||
CAPTURED_ON = "2026-11-26" # the day of the capture's load: durations counted to it
|
||||
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||
CODES = { # the current platform's code -> the platform's
|
||||
"CONFIRMADO": "confirmed", "EN_PROCESO": "in_process", "SIN_TEA": "not_confirmed",
|
||||
"SOLO_MCHAT": "mchat_only", "PSICOLOGIA": "psychology", "NEUROPEDIATRIA": "neuropediatrics",
|
||||
"EEG": "eeg", "BUENO": "good", "MALO": "bad", "SIN_ANALIZAR": "not_analyzed",
|
||||
"16_23": "16-23", "24_29": "24-29", "30_36": "30-36", "sin_dato": "no_data",
|
||||
} # fmt: skip
|
||||
STRATA = {"estado": "category", "paso": "category", "calidad": "category",
|
||||
"grupo_edad": "age_group"} # fmt: skip
|
||||
|
||||
|
||||
def _report(entry: dict, ours: bool) -> tuple:
|
||||
"""Counts, score and its extensions, and strata of one report, in the platform's codes.
|
||||
The current platform's proportions report no initial population."""
|
||||
group = entry["resource"]["group"][0]
|
||||
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
||||
if ours and "denominator" in populations:
|
||||
populations.pop("initial-population")
|
||||
score = group.get("measureScore", {})
|
||||
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
|
||||
strata = {}
|
||||
for s in group.get("stratifier", []):
|
||||
if len(s["code"]) > 1: # crossed with the category: not in the reference
|
||||
continue
|
||||
code = s["code"][0]
|
||||
name = code["coding"][0]["code"] if "coding" in code else STRATA[code["text"]]
|
||||
cells: dict = defaultdict(dict)
|
||||
for x in s.get("stratum", []):
|
||||
for p in x["population"]:
|
||||
kind = p["code"]["coding"][0]["code"]
|
||||
if not (ours and kind == "initial-population" and "denominator" in populations):
|
||||
cells[CODES.get(x["value"]["text"], x["value"]["text"])][kind] = p["count"]
|
||||
strata[name] = dict(cells)
|
||||
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
|
||||
|
||||
|
||||
def indicators(api) -> None:
|
||||
"""Every measure, every semester, as the current platform answers them."""
|
||||
reference = {k.upper(): v for k, v in
|
||||
json.loads((REFERENCE / "indicators.json").read_text()).items()} # fmt: skip
|
||||
(measures,) = pages(api, "/tea/fhir/Measure")
|
||||
assert {m["resource"]["name"] for m in measures["entry"]} == set(reference)
|
||||
for measure in [e["resource"] for e in measures["entry"]]:
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
found = [e for b in pages(api, "/tea/fhir/MeasureReport", params) for e in b["entry"]]
|
||||
cohort = measure["scoring"]["coding"][0]["code"] == "cohort"
|
||||
name = measure["name"]
|
||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
||||
a, b = _report(ours, True), _report(theirs, False)
|
||||
where = (name, ours["resource"]["period"]["start"])
|
||||
assert a[0] == b[0] and a[3] == b[3], (where, a, b)
|
||||
if cohort:
|
||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
||||
continue
|
||||
assert (a[1] is None) == (b[1] is None), where
|
||||
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
|
||||
assert a[2] == pytest.approx(b[2]), where
|
||||
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
not (HOSPITAL / "hospital_tea.db").exists(), reason="the TEA hospital is outside git"
|
||||
)
|
||||
|
||||
|
||||
def platform_eeg(platform):
|
||||
"""persistance.eeg reading this test's platform (never the deployed data folder)."""
|
||||
os.environ["PLATFORM_DATABASE_URL"] = platform.env["PLATFORM_DATABASE_URL"]
|
||||
destination.DATA_DIR = Path(platform.env["ISSSTELEON_DATA"])
|
||||
destination.engine.cache_clear()
|
||||
return eeg_store
|
||||
|
||||
|
||||
def _day(value) -> date:
|
||||
return value if isinstance(value, date) else date.fromisoformat(str(value)[:10])
|
||||
|
||||
|
||||
def test_tea_from_the_hospital_to_indicators(api, platform, tmp_path):
|
||||
db = HOSPITAL / "hospital_tea.db"
|
||||
expected = json.loads(MANIFEST.read_text())["files"]["hospital_tea.db"]["sha256"]
|
||||
assert hashlib.sha256(db.read_bytes()).hexdigest() == expected
|
||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
||||
put_concept_map(api, "hospital_tea")
|
||||
ok(api.put("/ingest/pipelines/tea", json=pipeline))
|
||||
wait_for(api, ok(api.post("/ingest/pipelines/tea/runs", json={}))["run_id"], 1800)
|
||||
q = platform.query
|
||||
|
||||
# Silver holds every study of the hospital; each file (EEG signal, ADOS-2 report) is
|
||||
# kept once, by its hash.
|
||||
counts = {s: q(f"select count(*) from silver.{s}")[0][0] for s in ("mchat", "ados2", "eeg")}
|
||||
assert counts == {"mchat": 216, "ados2": 113, "eeg": 84}
|
||||
assert q("select count(*) from silver.clinical_note where specialty = 'pediatric_neurology'"
|
||||
)[0][0] == 83 # fmt: skip
|
||||
assert q("select count(*) from silver.eeg where edf is not null")[0][0] == 78
|
||||
kept = "select count(*) from bronze.files where key in (select edf from silver.eeg)"
|
||||
assert q(kept)[0][0] == 78
|
||||
|
||||
# ADOS-2: the results read from the 50 reports are the current platform's.
|
||||
reference = {(r["ado_fecha"], r["ado_pac_id"]): r for r in
|
||||
json.loads((REFERENCE / "tables" / "ados2.json").read_text())
|
||||
if r["ado_modulo"]} # fmt: skip
|
||||
numbers = dict(q("select distinct person_id, record_number from bronze.staged__identity"))
|
||||
names = ["person_id", "evaluation_date", "module", *ITEMS]
|
||||
sql = f"select {', '.join(names)} from silver.ados2 where module is not null"
|
||||
found = [dict(zip(names, r, strict=True)) for r in q(sql)]
|
||||
assert len(found) == len(reference) == 50
|
||||
for row in found:
|
||||
theirs = reference[(str(row["evaluation_date"])[:10],
|
||||
int(numbers[row["person_id"]].removeprefix("N")))] # fmt: skip
|
||||
module = MODULES[theirs["ado_modulo"]]
|
||||
assert row["module"] == module
|
||||
for item, by_module in ITEMS.items():
|
||||
value = theirs["ado_" + by_module[module]] if module in by_module else None
|
||||
assert row[item] == (None if value is None else pytest.approx(value)), item
|
||||
# and their scores: the calibrated severity and the classification.
|
||||
birth = q(f"select birth_date from silver.person where person_id = '{row['person_id']}'")
|
||||
css, label = ados2.score({**row, "evaluation_date": _day(row["evaluation_date"])},
|
||||
_day(birth[0][0])) # fmt: skip
|
||||
assert (css, label) == (theirs["ado_css"], CLASSIFICATION[theirs["ado_clasificacion"]])
|
||||
|
||||
# The EEG analysis: every signal's verdict, level and metrics are the current platform's.
|
||||
wait_for(api, ok(api.post("/models/tea/analyze"))["run_id"], 1800)
|
||||
with sqlite3.connect(db) as con:
|
||||
signals = con.execute("select eeg_id, eeg_estudio from eeg where eeg_estudio is not null")
|
||||
hashes = {i: hashlib.sha256(b).hexdigest() for i, b in signals}
|
||||
tables = REFERENCE / "tables"
|
||||
reference = {hashes[r["eeg_id"]]: r for r in json.loads((tables / "eeg.json").read_text())
|
||||
if r["eeg_id"] in hashes} # fmt: skip
|
||||
found = {e: (v, lvl) for e, v, lvl in q("select edf, valid, level from bronze.eeg_analysis")}
|
||||
assert set(found) == set(reference)
|
||||
for edf, theirs in reference.items():
|
||||
assert found[edf] == (bool(theirs["eeg_valido"]), LEVELS[theirs["eeg_nivel"]]), edf
|
||||
by_id = {r["eeg_id"]: hashes.get(r["eeg_id"]) for r in reference.values()}
|
||||
metrics = {(by_id.get(r["met_eeg_id"]), METRICS[r["met_codigo"]]): r
|
||||
for r in json.loads((tables / "eeg_metrica.json").read_text())} # fmt: skip
|
||||
ours = {(e, c): v for e, c, v in q("select edf, code, value from bronze.eeg_metrics")}
|
||||
for key, theirs in metrics.items():
|
||||
value = theirs["met_valor"]
|
||||
assert ours.get(key) == (None if value is None else pytest.approx(value, rel=1e-12)), key
|
||||
|
||||
# Indicators, from the platform's own EEG verdicts.
|
||||
indicators(api)
|
||||
|
||||
# The age curves, a roundtrip: one training run gives a version of each, learned from the
|
||||
# site's own reference group (the valid EEGs of the children whose diagnosis ruled TEA
|
||||
# out); each is what the curves' math (proved on HK1K by models/tests/test_eeg.py) gives
|
||||
# on those EEGs, and once promoted it scores every analysed EEG with that curve.
|
||||
group = platform_eeg(platform).ruled_out(date.today())
|
||||
assert len(group) >= 5, "the hospital needs children with TEA ruled out and a good EEG"
|
||||
wait_for(api, ok(api.post("/models/tea/train", json={}))["run_id"], 3600)
|
||||
names = [m["name"] for m in ok(api.get("/models/tea"))]
|
||||
assert set(names) >= set(curves.SCENARIOS)
|
||||
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
|
||||
for name in curves.SCENARIOS:
|
||||
report = ok(api.get(f"/models/tea/{name}/versions/1/reports/technical_validation"))
|
||||
assert report["cohort"] == "site: children with TEA ruled out"
|
||||
assert report["studies"] == len(group)
|
||||
ok(api.post(f"/models/tea/{name}/versions/1/reports/clinical_validation", files=files))
|
||||
ok(api.post(f"/models/tea/{name}/versions/1/promote"))
|
||||
wait_for(api, ok(api.post("/models/tea/score"))["run_id"], 1800)
|
||||
trained = {name: curves.train(table, name)
|
||||
for name, table in eeg_reference.tables(group).items()} # fmt: skip
|
||||
analysed = {a["edf"]: a for a in platform_eeg(platform).analysed()}
|
||||
scored = {(e, c): r for e, c, *r in q(
|
||||
"select edf, code, z, outside, p5, median, p95 from gold.tea_eeg_metrics")} # fmt: skip
|
||||
assert scored
|
||||
for name, scenario in curves.SCENARIOS.items():
|
||||
if "value" not in trained[name]: # too few children for its whole-head curve
|
||||
continue
|
||||
for (edf, code), found in scored.items():
|
||||
if code != scenario.metric or edf not in analysed:
|
||||
continue
|
||||
one = analysed[edf]
|
||||
metric = next(m for m in one["metrics"] if m["code"] == code)
|
||||
features = one["features"].get(name, {})
|
||||
exposure = features.get(curves.EXPOSURE) if scenario.counts else None
|
||||
expected = curves.score(trained[name]["value"], metric["value"], one["age_months"],
|
||||
exposure) # fmt: skip
|
||||
want = [expected[k] for k in ("z", "outside", "p5", "median", "p95")]
|
||||
assert found == [None if v is None else pytest.approx(v, rel=1e-9)
|
||||
for v in want], (name, edf) # fmt: skip
|
||||
|
||||
# The EEG–ADOS-2 association, a roundtrip: trained on the promoted curves' z of the
|
||||
# site's children, it is what the association's math (proved against the old platform by
|
||||
# tests/test_tea_association.py) gives on that cohort; promoted, it scores every EEG.
|
||||
wait_for(api, ok(api.post("/models/tea/train", json={"models": [jobs.ASSOCIATION]}))["run_id"],
|
||||
1800) # fmt: skip
|
||||
platform_eeg(platform)
|
||||
fit, scored_eegs = jobs.association_cohort()
|
||||
expected = association.fit(fit)
|
||||
report = ok(api.get(f"/models/tea/{jobs.ASSOCIATION}/versions/1/reports/interpretability"))
|
||||
assert (report["level"], report["children"]) == (expected["level"], expected["n"])
|
||||
assert report["rows"] == json.loads(json.dumps(association.associations(expected)))
|
||||
ok(api.post(f"/models/tea/{jobs.ASSOCIATION}/versions/1/reports/clinical_validation",
|
||||
files=files)) # fmt: skip
|
||||
ok(api.post(f"/models/tea/{jobs.ASSOCIATION}/versions/1/promote"))
|
||||
wait_for(api, ok(api.post("/models/tea/score"))["run_id"], 1800) # curves, then it
|
||||
with destination.engine().connect() as con: # no table when no pair was estimated
|
||||
written = inspect(con).has_table("ados2_association_scores", schema="bronze")
|
||||
stored = q("select count(*) from bronze.ados2_association_scores")[0][0] if written else 0
|
||||
assert stored == len(association.score(expected, scored_eegs))
|
||||
|
||||
# The EEG pages: every study with its verdict, and a valid one's metrics with their scores.
|
||||
listed = ok(api.get("/tea/eegs"))
|
||||
summary = json.loads((REFERENCE / "pages.json").read_text())["/governance/tea/eeg/summary"]
|
||||
expected = summary["body"]
|
||||
assert (len(listed), sum(e["analysed"] for e in listed), sum(bool(e["valid"]) for e in listed)
|
||||
) == (expected["eegs"], expected["analysed"], expected["valid"]) # fmt: skip
|
||||
one = next(e for e in listed if e["valid"])
|
||||
shown = ok(api.get(f"/tea/eegs/{one['id']}"))
|
||||
assert shown["valid"] and shown["metrics"] and all(m["value"] is not None
|
||||
for m in shown["metrics"]) # fmt: skip
|
||||
@@ -0,0 +1,143 @@
|
||||
"""What this module covers: what the EEG analysis writes to TEA's bronze, carried into silver
|
||||
(`webapi.orchestration.silver.tea`) and into dbt's views of the EEG's quality checks, metrics and electrodes
|
||||
(`tea_paciente_eeg_criterios`, `tea_paciente_eeg_metricas`, `tea_paciente_eeg_electrodos`).
|
||||
|
||||
Fixtures: `loaded`, a TEA database (`base_de`) loaded up to the event models, with one patient and one analysed EEG
|
||||
`e-1`: valid, triage `completo`; three checks (95 % clean windows against a low limit of 60, the triage level as text,
|
||||
and a dead channel at T3); its posterior rhythm 6.8 Hz with z 1.2, -1/0/+1 0 and p5/median/p95 5/6/7, and its N2
|
||||
spindles' value 2.5 with z -0.4 at Fz.
|
||||
"""
|
||||
import os
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import Session, select
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
def _rows(sesion):
|
||||
from core.tea.models import Eeg, EegCriterio, EegMetrica, EegMetricaElectrodo, Mchat, Pacientes
|
||||
|
||||
sesion.add(Pacientes(pac_id=1, pac_id_hospital="H-1", pac_fecha_nacimiento=date(2023, 6, 1)))
|
||||
sesion.add(Mchat(mch_id="m-1", mch_pac_id=1, mch_fecha=date(2025, 1, 10), mch_puntaje=12))
|
||||
sesion.add(Eeg(eeg_id="e-1", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_valido=1, eeg_nivel="completo",
|
||||
eeg_fraccion_limpia=0.95, eeg_canales_malos=1, eeg_edad_meses=23.6, eeg_con_sueno=1))
|
||||
sesion.add_all([
|
||||
EegCriterio(cri_id="c-1", cri_eeg_id="e-1", cri_codigo="clean-windows", cri_valor=95.0, cri_unidad="%",
|
||||
cri_bajo=60.0, cri_decisivo=1, cri_anormal=0),
|
||||
EegCriterio(cri_id="c-2", cri_eeg_id="e-1", cri_codigo="triage-level", cri_valor_texto="completo",
|
||||
cri_decisivo=1, cri_anormal=0),
|
||||
EegCriterio(cri_id="c-3", cri_eeg_id="e-1", cri_codigo="dead-channel", cri_electrodo="T3",
|
||||
cri_valor_texto="dead channel", cri_decisivo=0, cri_anormal=1),
|
||||
])
|
||||
sesion.add_all([
|
||||
EegMetrica(met_id="r", met_eeg_id="e-1", met_codigo="RITMO_POSTERIOR", met_valor=6.8, met_z=1.2, met_fuera=0,
|
||||
met_p5=5.0, met_mediana=6.0, met_p95=7.0),
|
||||
EegMetrica(met_id="n2", met_eeg_id="e-1", met_codigo="HUSOS_SUENO_N2", met_valor=2.5),
|
||||
EegMetricaElectrodo(mel_id="n2-fz", mel_met_id="n2", mel_electrodo="Fz", mel_valor=1.4, mel_z=-0.4),
|
||||
])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def loaded(tmp_path_factory):
|
||||
"""The database after the cycle's load and event models, with dbt's views created."""
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("needs dbt's compiled manifest (DBT_MANIFEST)")
|
||||
from conftest import base_de
|
||||
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea_eeg"), datos=_rows)
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield base
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def _observations(base, clase: str) -> dict:
|
||||
from core.tea.indicadores.models import Observacion, Procedimiento
|
||||
|
||||
with Session(base.motor) as sesion:
|
||||
rows = sesion.exec(select(Procedimiento.codigo_fuente, Observacion).join(
|
||||
Observacion, Observacion.procedimiento_id == Procedimiento.procedimiento_id).where(
|
||||
Procedimiento.estudio_id == "eeg", Procedimiento.clase == clase)).all()
|
||||
return {(fuente, o.resultado_id): o.valor_numerico if o.valor_texto is None else o.valor_texto
|
||||
for fuente, o in rows}
|
||||
|
||||
|
||||
def test_the_verdict_and_study_checks_are_results_of_the_recording(loaded):
|
||||
"""Pins down: the EEG's verdict, triage level and each study-wide check (value, limit, out of range or not) are
|
||||
observations of its recording, under `eeg.calidad_<check>` in snake case; a check without a limit of that side
|
||||
gives none.
|
||||
|
||||
Fails if the silver mapping drops the verdict, stops turning check codes into catalog results, or the catalog
|
||||
loses one of them (the load skips a result the catalog doesn't have).
|
||||
"""
|
||||
toma = _observations(loaded, "toma")
|
||||
assert toma[None, "eeg.valido"] == 1 and toma[None, "eeg.nivel"] == "completo"
|
||||
assert (toma[None, "eeg.calidad_clean_windows"], toma[None, "eeg.calidad_clean_windows_bajo"],
|
||||
toma[None, "eeg.calidad_clean_windows_anormal"]) == (95.0, 60.0, 0)
|
||||
assert toma[None, "eeg.calidad_triage_level"] == "completo"
|
||||
assert (None, "eeg.calidad_clean_windows_alto") not in toma
|
||||
|
||||
|
||||
def test_a_bad_channel_and_an_electrode_value_are_parts_of_the_eeg(loaded):
|
||||
"""Pins down: a bad channel is a part of its EEG at its electrode with the analysis's reason; a metric's value at
|
||||
an electrode is a part with the value and its z.
|
||||
|
||||
Fails if the channel checks stop being parts, or the electrode z stops reaching silver.
|
||||
"""
|
||||
partes = _observations(loaded, "parte")
|
||||
assert partes["T3", "eeg.calidad_dead_channel"] == "dead channel"
|
||||
assert (partes["Fz", "eeg.husos_sueno_n2"], partes["Fz", "eeg.husos_sueno_n2_z"]) == (1.4, -0.4)
|
||||
|
||||
|
||||
def test_a_metric_carries_its_deviation_from_the_baseline(loaded):
|
||||
"""Pins down: a metric's z, -1/0/+1 and the baseline's p5/median/p95 at the age are results of the recording.
|
||||
|
||||
Fails if the silver mapping or the catalog drops one of the deviation's results.
|
||||
"""
|
||||
toma = _observations(loaded, "toma")
|
||||
assert [toma[None, f"eeg.ritmo_posterior{s}"] for s in ("", "_z", "_fuera", "_p5", "_mediana", "_p95")] == \
|
||||
[6.8, 1.2, 0, 5.0, 6.0, 7.0]
|
||||
|
||||
|
||||
def test_the_quality_view_lists_each_check_with_its_label(loaded):
|
||||
"""Pins down: `tea_paciente_eeg_criterios` has one row per check of the EEG, study-wide ones without an electrode
|
||||
and with their limit and decisive flag, the bad channel at its electrode as out of range and not decisive, each with the catalog's label; and the
|
||||
electrodes view keeps only metric values, not channel checks.
|
||||
|
||||
Fails if the view stops pivoting a check's observations, misses the channel parts, or the electrodes view starts
|
||||
reading the checks' parts as metrics.
|
||||
"""
|
||||
with loaded.motor.connect() as connection:
|
||||
rows = connection.execute(text(
|
||||
"select criterio, electrodo, valor, valor_texto, bajo, anormal, decisivo, etiqueta "
|
||||
"from tea_paciente_eeg_criterios "
|
||||
"order by criterio")).all()
|
||||
electrodes = connection.execute(text("select metrica, electrodo from tea_paciente_eeg_electrodos")).all()
|
||||
by_check = {r.criterio: r for r in rows}
|
||||
assert set(by_check) == {"clean_windows", "triage_level", "dead_channel"}
|
||||
assert (by_check["clean_windows"].valor, by_check["clean_windows"].bajo, by_check["clean_windows"].anormal,
|
||||
by_check["clean_windows"].decisivo) == (95.0, 60.0, 0, 1)
|
||||
assert (by_check["dead_channel"].electrodo, by_check["dead_channel"].anormal, by_check["dead_channel"].decisivo) == \
|
||||
("T3", 1, 0)
|
||||
assert by_check["clean_windows"].etiqueta == "Ventanas limpias"
|
||||
assert [tuple(e) for e in electrodes] == [("husos_sueno_n2", "Fz")]
|
||||
|
||||
|
||||
def test_a_metric_is_scored_by_the_analysis_s_deviation(loaded):
|
||||
"""Pins down: `tea_paciente_eeg_metricas` takes the analysis's z, its -1/0/+1 as the state and the baseline's
|
||||
p5/median/p95 as the reference; a metric without a z (no baseline in production) can't be evaluated. And the
|
||||
electrodes view carries each electrode's z next to its value.
|
||||
|
||||
Fails if dbt goes back to scoring metrics against fixed ranges of its own, or drops the electrode z.
|
||||
"""
|
||||
with loaded.motor.connect() as connection:
|
||||
metrics = {r.metrica: r for r in connection.execute(text(
|
||||
"select metrica, valor, ref_min, ref_mediana, ref_max, valor_z, estado from tea_paciente_eeg_metricas"))}
|
||||
(electrode,) = connection.execute(text("select valor, valor_z from tea_paciente_eeg_electrodos")).all()
|
||||
rhythm = metrics["ritmo_posterior"]
|
||||
assert (rhythm.valor, rhythm.ref_min, rhythm.ref_mediana, rhythm.ref_max, rhythm.valor_z, rhythm.estado) == \
|
||||
(6.8, 5.0, 6.0, 7.0, 1.2, "normal")
|
||||
assert (metrics["husos_sueno_n2"].valor_z, metrics["husos_sueno_n2"].estado) == (None, "no_evaluable")
|
||||
assert tuple(electrode) == (1.4, -0.4)
|
||||
@@ -0,0 +1,272 @@
|
||||
"""What this module covers: TEA's ten measures answered on request from dbt's semantic layer, on hand-written
|
||||
expectations for the synthetic children of `staging.tea`, period by period: who each period counts (the children in
|
||||
the screening during it, at their stage at its end, leaving after the period of their good EEG), the day counts, the
|
||||
EEGs by quality and the alterations of each child's first good EEG.
|
||||
|
||||
Fixtures: `base`, TEA's fixture database through the cycle up to `event_models` (dbt's views); `manifest`, dbt's
|
||||
`manifest.json` (`DBT_MANIFEST`; skipped without it). The expectations are worked out by hand from the children's
|
||||
dates in `staging/tea.py`; each test says which child makes each number.
|
||||
"""
|
||||
|
||||
import os
|
||||
from dataclasses import replace
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
from sqlmodel import select
|
||||
|
||||
import staging.tea as fixture
|
||||
from conftest import base_de
|
||||
from core.tea.models import Ados2, Eeg, EegCriterio, EegMetrica, Mchat
|
||||
from webapi.compositions import answer_composition, composition_definitions
|
||||
from webapi.durations import answer_duration, duration_definitions
|
||||
from webapi.metrics import Question, answer, measure_definitions
|
||||
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def manifest():
|
||||
path = os.environ.get("DBT_MANIFEST")
|
||||
if not path:
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
return Path(path)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def base(tmp_path_factory, manifest):
|
||||
"""The seven children of `staging.tea`, loaded once, with dbt's TEA views created."""
|
||||
base = base_de("tea", tmp_path_factory.mktemp("tea"))
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
yield replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def repositories(base) -> dict:
|
||||
d = base.dominio
|
||||
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository,
|
||||
"history": d.history_repository, "queries": d.dbt_query_repository, "allow_undecided": True}
|
||||
|
||||
|
||||
def composition(base, manifest, measure_id, period, **question):
|
||||
url = f"tea/{measure_id}"
|
||||
result = answer_composition("tea", composition_definitions(manifest)[url], Question(url, period, **question),
|
||||
**repositories(base))
|
||||
return {k: v for k, v in result.categories.items() if v}
|
||||
|
||||
|
||||
def proportion(base, manifest, measure_id, period, **question):
|
||||
url = f"tea/{measure_id}"
|
||||
return answer("tea", measure_definitions(manifest)[url], Question(url, period, **question), **repositories(base))
|
||||
|
||||
|
||||
def duration(base, manifest, measure_id, period):
|
||||
url = f"tea/{measure_id}"
|
||||
return answer_duration("tea", duration_definitions(manifest)[url], Question(url, period), **repositories(base))
|
||||
|
||||
|
||||
STAGES = {
|
||||
"2025-01": {"SOLO_MCHAT": 2},
|
||||
"2025-02": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2},
|
||||
"2025-03": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 1},
|
||||
"2025-04": {"PSICOLOGIA": 2, "NEUROPEDIATRIA": 2},
|
||||
"2025-05": {"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 1, "EEG": 1},
|
||||
"2025-06": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 1},
|
||||
"2025-07": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
"2025-12": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
"2025-S1": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1, "EEG": 2},
|
||||
"2025-S2": {"SOLO_MCHAT": 2, "PSICOLOGIA": 1, "NEUROPEDIATRIA": 1},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("period", sorted(STAGES))
|
||||
def test_m28_counts_every_child_in_the_screening_at_its_stage_at_the_period_s_end(base, manifest, period):
|
||||
"""Pins down M28: a period counts every cohort child who entered by its end and hadn't finished before its start,
|
||||
at the furthest step reached by its end, whether or not anything of theirs happened in it. Child 1 is at
|
||||
psychology in February and March's stage moves with its note; it reaches EEG in May and is gone from June. Child 2
|
||||
stays at neuropediatrics all year; child 5 stays at M-CHAT (no ADOS-2); child 6 reaches EEG on its note's day,
|
||||
2 June; child 4 (39 months) never counts; child 7 (no birth date) counts from May.
|
||||
|
||||
Fails if the population goes back to the children with a fact in the period, if a child stops leaving after the
|
||||
period of its good EEG, or if a step stops needing the previous one."""
|
||||
assert composition(base, manifest, "M28_casos_por_estado", period) == STAGES[period]
|
||||
|
||||
|
||||
def test_m28_an_event_cut_off_leaves_out_what_came_after_it(base, manifest):
|
||||
"""Pins down: facts dated after the event cut-off don't count. With a cut-off of 10 May, child 1's good EEG of
|
||||
20 May isn't there, so May counts it at neuropediatrics. Fails if the status rows stop applying the cut-off."""
|
||||
assert composition(base, manifest, "M28_casos_por_estado", "2025-05", event_cutoff=date(2025, 5, 10)) == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
|
||||
|
||||
RESULTS = {
|
||||
"2025-01": {"EN_PROCESO": 2},
|
||||
"2025-03": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
||||
"2025-04": {"CONFIRMADO": 1, "EN_PROCESO": 2},
|
||||
"2025-06": {"CONFIRMADO": 1, "EN_PROCESO": 3},
|
||||
"2025-07": {"EN_PROCESO": 3},
|
||||
"2025-S1": {"CONFIRMADO": 2, "EN_PROCESO": 3},
|
||||
"2025-S2": {"EN_PROCESO": 3},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("period", sorted(RESULTS))
|
||||
def test_m23_counts_the_confirmed_and_in_process_but_not_a_note_without_f84_0(base, manifest, period):
|
||||
"""Pins down M23: the confirmed (a F84.0 note by the period's end) and those in process (no note yet). Child 2's
|
||||
note says F84 without the subcode: from April it's out of M23, though still in the screening. Child 5's F84.0 note
|
||||
of July doesn't confirm it without the ADOS-2: it stays in process. Fails if F84 counts as a confirmation, if a
|
||||
note without F84.0 counts as in process, or if a note counts before the psychology step."""
|
||||
assert composition(base, manifest, "M23_pacientes_evaluados", period) == RESULTS[period]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "numerator", "denominator", "excluded"), [
|
||||
("2025-03", 1, 3, 0), ("2025-04", 1, 3, 1), ("2025-06", 1, 4, 1), ("2025-07", 0, 3, 1), ("2025-S1", 2, 5, 1),
|
||||
])
|
||||
def test_m24_is_the_confirmed_out_of_the_confirmed_and_in_process(base, manifest, period, numerator, denominator,
|
||||
excluded):
|
||||
"""Pins down M24: confirmed over confirmed plus in process, with child 2 (a note without F84.0) as its exclusion
|
||||
from April. In July child 5's F84.0 note, without the ADOS-2, leaves it in process. Fails if the denominator takes
|
||||
the children without TEA, the exclusion stops being counted, or a note confirms without the psychology step."""
|
||||
result = proportion(base, manifest, "M24_confirmacion_diagnostico", period)
|
||||
assert (result.numerator, result.denominator, result.excluded) == (numerator, denominator, excluded)
|
||||
|
||||
|
||||
def test_m24_is_stratified_by_the_age_group_at_the_first_m_chat(base, manifest):
|
||||
"""Pins down: the age group is the child's at its first M-CHAT, one per child, the page's windows. In March, child
|
||||
1 (19 months) is confirmed, child 2 (26) and child 3 (35) are in process. Fails if the stratum goes back to the age
|
||||
at the period's start or loses a window."""
|
||||
result = proportion(base, manifest, "M24_confirmacion_diagnostico", "2025-03")
|
||||
strata = {v: (c.numerator, c.denominator) for v, c in result.strata["grupo_edad"].items()}
|
||||
assert strata == {"16_23": (1, 1), "24_29": (0, 1), "30_36": (0, 1)}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "with_eeg", "without_eeg", "confirmed"), [
|
||||
("2025-03", 0, 1, 1), ("2025-05", 1, 0, 1), ("2025-06", 1, 0, 1), ("2025-07", 0, 0, 0),
|
||||
("2025-S1", 2, 0, 2), ("2025-S2", 0, 0, 0),
|
||||
])
|
||||
def test_m21_and_m22_split_the_confirmed_by_a_good_eeg_by_the_period_s_end(base, manifest, period, with_eeg,
|
||||
without_eeg, confirmed):
|
||||
"""Pins down M21 and its complement M22: of the confirmed at the period's end, those whose chain reached a good EEG
|
||||
by then. Child 1 is confirmed in March without its EEG (20 May), and with it in May; child 5 has a F84.0 note and
|
||||
a good EEG in July but no ADOS-2, so it isn't confirmed and July has nobody. Fails if the EEG is read beyond the
|
||||
period's end, or the note or the EEG count outside the chain."""
|
||||
m21 = proportion(base, manifest, "M21_diagnosticados_con_eeg", period)
|
||||
m22 = proportion(base, manifest, "M22_diagnosticados_sin_eeg", period)
|
||||
assert (m21.numerator, m21.denominator) == (with_eeg, confirmed)
|
||||
assert (m22.numerator, m22.denominator) == (without_eeg, confirmed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("measure_id", "period", "initial", "n", "median"), [
|
||||
("M26_dias_mchat_ados2", "2025-01", 2, 0, None),
|
||||
("M26_dias_mchat_ados2", "2025-02", 3, 2, 20.0),
|
||||
("M26_dias_mchat_ados2", "2025-03", 3, 3, 26.0),
|
||||
("M26_dias_mchat_ados2", "2025-S1", 6, 4, 20.5),
|
||||
("M27_dias_ados2_diagnostico", "2025-S1", 6, 3, 40.0),
|
||||
("M25_dias_mchat_diagnostico", "2025-S1", 6, 2, 59.5),
|
||||
("M25_dias_mchat_diagnostico", "2025-S2", 4, 0, None),
|
||||
])
|
||||
def test_the_day_counts_take_the_period_s_children_whose_interval_ended_by_its_end(base, manifest, measure_id, period,
|
||||
initial, n, median):
|
||||
"""Pins down M26, M27 and M25: every child the period counts is in the initial population; those whose interval
|
||||
ended by the period's end have days (repeated in each period that counts them), the rest count as without event.
|
||||
In February, child 1 (26 days) and child 3 (14) have their ADOS-2 and child 2 doesn't yet. Child 5's F84.0 note of
|
||||
1 July gives no days without the ADOS-2. Fails if the value is read beyond the period's end or the
|
||||
population goes back to the facts in the period."""
|
||||
result = duration(base, manifest, measure_id, period)
|
||||
assert (result.initial, result.n, result.median) == (initial, n, median)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "expected"), [
|
||||
("2025-04", {"MALO": 1}), ("2025-05", {"BUENO": 1}), ("2025-09", {"BUENO": 1}),
|
||||
("2025-S1", {"BUENO": 2, "MALO": 1}), ("2025-S2", {"BUENO": 2}),
|
||||
])
|
||||
def test_m29_counts_the_period_s_eegs_good_or_bad(base, manifest, period, expected):
|
||||
"""Pins down M29: the EEGs of the cohort's children dated in the period, by exam, good or bad. Child 1's bad EEG of
|
||||
April and its second good one of September count; so does child 5's, though its chain never reaches it. Fails if
|
||||
M29 stops counting exams, or a bad EEG stops showing."""
|
||||
assert composition(base, manifest, "M29_calidad_eeg", period) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("period", "total", "ritmo_posterior"), [
|
||||
("2025-05", (1, 1), (1, 1)), ("2025-06", (0, 1), (0, 1)), ("2025-S1", (1, 2), (1, 2)), ("2025-S2", (0, 1), (0, 1)),
|
||||
])
|
||||
def test_m30_reads_the_alterations_of_each_child_s_first_good_eeg(base, manifest, period, total, ritmo_posterior):
|
||||
"""Pins down M30: of the children whose first good EEG falls in the period, those with an alteration in it, in
|
||||
total and in one group per alteration. Child 1's EEG of 20 May has a slow posterior rhythm (3.2 Hz at 23 months,
|
||||
against 4.5 to 7.0); its second good EEG of September doesn't count. Fails if a later EEG counts, or the groups
|
||||
stop being answered one by one."""
|
||||
result = proportion(base, manifest, "M30_resultado_eeg", period)
|
||||
assert (result.numerator, result.denominator) == total
|
||||
assert (result.groups["ritmo_posterior"].numerator, result.groups["ritmo_posterior"].denominator) == ritmo_posterior
|
||||
assert result.groups["husos_sueno_n2"].numerator == 0
|
||||
|
||||
|
||||
def test_m30_read_back_from_the_history_keeps_its_groups(base, manifest):
|
||||
"""Pins down: asking again reads the stored answer, groups included. Fails if a stored answer loses its groups or
|
||||
counts every group's units in the total."""
|
||||
first = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
||||
again = proportion(base, manifest, "M30_resultado_eeg", "2025-S1")
|
||||
assert again.stored_before and (again.numerator, again.denominator) == (first.numerator, first.denominator)
|
||||
assert again.groups == first.groups
|
||||
|
||||
|
||||
def test_a_knowledge_cut_off_leaves_out_a_step_loaded_later(tmp_path, manifest):
|
||||
"""Pins down: a step known after the knowledge cut-off doesn't move the child. Child 1's good EEG and its metrics
|
||||
arrive in a second load; asked as of the first load, May still counts child 1 at neuropediatrics and it hasn't
|
||||
left in June. Fails if the status rows stop applying the knowledge cut-off to the steps or to the exit."""
|
||||
def without_the_good_eeg(session):
|
||||
fixture.insertar(session)
|
||||
session.flush()
|
||||
for model, key in ((EegMetrica, "met_eeg_id"), (EegCriterio, "cri_eeg_id"), (Eeg, "eeg_id")):
|
||||
for row in session.exec(select(model).where(getattr(model, key) == "eeg-1b")):
|
||||
session.delete(row)
|
||||
|
||||
base = base_de("tea", tmp_path, without_the_good_eeg)
|
||||
try:
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
||||
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
||||
with base.staging() as session:
|
||||
session.add(Eeg(eeg_id="eeg-1b", eeg_pac_id=1, eeg_fecha_estudio=date(2025, 5, 20), eeg_con_sueno=1,
|
||||
eeg_canales=19, eeg_duracion_min=25.0, eeg_valido=1, eeg_nivel="completo",
|
||||
eeg_ruido_linea_db=3.5))
|
||||
session.commit()
|
||||
base.run("load", allow_undecided=True)
|
||||
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-05", knowledge_cutoff=known) == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-06", knowledge_cutoff=known)[
|
||||
"NEUROPEDIATRIA"] == 2
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-05")["EEG"] == 1
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
|
||||
|
||||
def test_a_knowledge_cut_off_keeps_what_was_known_when_an_earlier_fact_arrives_later(tmp_path, manifest):
|
||||
"""Pins down: an answer as of a load doesn't change when a later load brings an earlier-dated fact. A second load
|
||||
adds an ADOS-2 of 20 Feb for child 3 (its known one is of 28 Feb) and an M-CHAT of 1 Apr for child 7 (its known
|
||||
one is of 1 May). Asked as of the first load, March still counts child 3 at psychology and May still counts
|
||||
child 7; asked as of now, child 7 is in the screening from April. Fails if a child's first fact is chosen among
|
||||
every load's facts and then dropped for being known after the cut-off."""
|
||||
base = base_de("tea", tmp_path)
|
||||
try:
|
||||
base.run(*UNTIL_MODELS, allow_undecided=True)
|
||||
with base.motor.begin() as connection:
|
||||
(first_load,) = connection.execute(text("select max(fin) from carga")).one()
|
||||
known = datetime.fromisoformat(str(first_load)).replace(tzinfo=timezone.utc)
|
||||
with base.staging() as session:
|
||||
session.add(Ados2(ado_id="ado-3-earlier", ado_pac_id=3, ado_fecha=date(2025, 2, 20), ado_modulo="MODULO_2",
|
||||
ado_css=2))
|
||||
session.add(Mchat(mch_id="mch-7-earlier", mch_pac_id=7, mch_fecha=date(2025, 4, 1), mch_puntaje=7))
|
||||
session.commit()
|
||||
base.run("load", allow_undecided=True)
|
||||
later = replace(base, ctx=replace(base.ctx, allow_undecided=True))
|
||||
for period in ("2025-03", "2025-05"):
|
||||
assert composition(later, manifest, "M28_casos_por_estado", period, knowledge_cutoff=known) == STAGES[period]
|
||||
assert composition(later, manifest, "M28_casos_por_estado", "2025-04") == {
|
||||
"SOLO_MCHAT": 1, "PSICOLOGIA": 2, "NEUROPEDIATRIA": 2}
|
||||
finally:
|
||||
base.motor.dispose()
|
||||
@@ -1,50 +0,0 @@
|
||||
"""Sign-in for the web app: an administrator from the environment, users who see some
|
||||
domains, a session cookie, and an API that answers everyone as before."""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from webapi.main import app
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(own_platform, monkeypatch):
|
||||
monkeypatch.setenv("AUTH_ADMIN_EMAIL", "admin@isssteleon.mx")
|
||||
monkeypatch.setenv("AUTH_ADMIN_PASSWORD", "una-clave-larga")
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def login(client, email, password):
|
||||
return client.post("/auth/login", data={"username": email, "password": password})
|
||||
|
||||
|
||||
def test_the_first_administrator_signs_in_and_adds_a_team(client):
|
||||
assert client.get("/users/me").status_code == 401
|
||||
assert login(client, "admin@isssteleon.mx", "mala").status_code == 400
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
me = client.get("/users/me").json()
|
||||
assert me["is_superuser"] and me["domains"] == ["cacu", "cama", "tea"]
|
||||
team = {"email": "cacu@isssteleon.mx", "password": "equipo-cacu", "name": "Equipo CaCu",
|
||||
"domains": ["cacu"]} # fmt: skip
|
||||
assert client.post("/users/register", json=team).status_code == 201
|
||||
client.post("/auth/logout")
|
||||
assert login(client, "cacu@isssteleon.mx", "equipo-cacu").status_code == 204
|
||||
assert client.get("/users/me").json()["domains"] == ["cacu"]
|
||||
other = {"email": "x@isssteleon.mx", "password": "otra-clave"}
|
||||
assert client.post("/users/register", json=other).status_code == 403 # not an admin
|
||||
|
||||
|
||||
def test_the_api_answers_without_a_session(client):
|
||||
# routes that read no platform data (the in-process app's database is the default one)
|
||||
for path in ("/health", "/domains", "/ingest/schema", "/ingest/sources/types"):
|
||||
assert client.get(path).status_code == 200, path
|
||||
|
||||
|
||||
def test_a_restart_keeps_the_administrator_once_and_the_session_secret(client, own_platform):
|
||||
assert login(client, "admin@isssteleon.mx", "una-clave-larga").status_code == 204
|
||||
secret = (own_platform / "auth_secret").read_text()
|
||||
with TestClient(app): # the app starts again on the same data
|
||||
pass
|
||||
assert (own_platform / "auth_secret").read_text() == secret
|
||||
assert client.get("/users/me").status_code == 200 # the session still holds
|
||||
@@ -1,43 +0,0 @@
|
||||
"""Phase 3 and 4 gate, the WebApp: every page loads from the new API. The platform runs as
|
||||
in production (API, Dagster), loaded with the synthetic CaCu and CaMa hospitals (CaMa's
|
||||
models trained, none promoted) and ISSSTELEON's test source; Playwright drives the real
|
||||
pages against it (WebApp/e2e)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from test_conectar import ok, run, wait_for
|
||||
|
||||
from conftest import put_concept_map
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||
PIPELINES = ROOT / "tests" / "fixtures" / "pipelines"
|
||||
|
||||
|
||||
@pytest.mark.webapp
|
||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) # pages read one API either way
|
||||
def test_every_page_loads_from_the_api(api, platform, site):
|
||||
for domain in ("cacu", "cama"):
|
||||
drawn = (PIPELINES / f"hospital_{domain}.json").read_text()
|
||||
put_concept_map(api, f"hospital_{domain}")
|
||||
ok(api.put(f"/ingest/pipelines/{domain}", json=json.loads(
|
||||
drawn.replace("{hospital}", str(HOSPITAL))))) # fmt: skip
|
||||
run(api, domain)
|
||||
# A trained CaMa version, unpromoted: what the governance page shows and refuses.
|
||||
wait_for(api, ok(api.post("/models/cama/train", json={"as_of": "2026-11-24"}))["run_id"])
|
||||
put_concept_map(api, "erick_site")
|
||||
ok(api.put("/ingest/pipelines/site", json=json.loads(site.drawn)))
|
||||
run(api, "site")
|
||||
subprocess.run(["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
||||
env={**os.environ, "API_URL": str(api.base_url).rstrip("/"),
|
||||
"SITE_URL": site.url}) # fmt: skip
|
||||
# The dialog's source is the one an operator draws by hand for this site.
|
||||
drawn = json.loads(site.drawn)["nodes"][0]
|
||||
made = ok(api.get("/ingest/pipelines/asistente"))["pipeline"]["nodes"][0]
|
||||
assert made["guided"]["type"] == "sqlserver" and made["source"] == drawn["source"]
|
||||
assert {k: v for k, v in made["args"].items() if k != "credentials"} == {
|
||||
k: v for k, v in drawn["args"].items() if k != "credentials"} # fmt: skip
|
||||
@@ -0,0 +1,111 @@
|
||||
import datetime as _dt
|
||||
import os
|
||||
from decimal import Decimal
|
||||
|
||||
from flask import Flask, jsonify
|
||||
from flask.json.provider import DefaultJSONProvider
|
||||
|
||||
from webapi.blueprints.cacu import cacu_bp
|
||||
from webapi.blueprints.data import data_bp
|
||||
from webapi.blueprints.governance import governance_bp
|
||||
from webapi.blueprints.imports import imports_bp
|
||||
from webapi.blueprints.reports import reports_bp
|
||||
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
|
||||
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
|
||||
from webapi.cama_recurrence.routes import cama_recurrence_bp
|
||||
from webapi.cama_survival.routes import cama_survival_bp
|
||||
from webapi.follow_up.routes import follow_up_blueprint
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
"""ISO-8601 dates (Flask's default is RFC 822); files are never sent
|
||||
inline in JSON, only their size."""
|
||||
|
||||
@staticmethod
|
||||
def default(o):
|
||||
if isinstance(o, (_dt.datetime, _dt.date, _dt.time)):
|
||||
return o.isoformat()
|
||||
if isinstance(o, Decimal):
|
||||
return float(o)
|
||||
if isinstance(o, (bytes, bytearray)):
|
||||
return f"<{len(o)} bytes>"
|
||||
return DefaultJSONProvider.default(o)
|
||||
|
||||
|
||||
def create_app() -> Flask:
|
||||
app = Flask(__name__)
|
||||
app.json = IsoJSONProvider(app)
|
||||
from webapi.cama_runtime import configure_cama_cohort
|
||||
|
||||
configure_cama_cohort(app)
|
||||
# File sources travel inside the request; cap them per request.
|
||||
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
|
||||
|
||||
# The web client goes through a proxy; browser clients on other origins
|
||||
# are allowed with WEBAPI_CORS_ORIGINS (comma-separated).
|
||||
cors_origins = os.environ.get("WEBAPI_CORS_ORIGINS")
|
||||
if cors_origins:
|
||||
from flask_cors import CORS
|
||||
|
||||
CORS(app, origins=[origin.strip() for origin in cors_origins.split(",")])
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/api")
|
||||
def api_index():
|
||||
"""Every route with its methods and summary, for programmatic clients."""
|
||||
routes = []
|
||||
for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.rule):
|
||||
if rule.endpoint == "static":
|
||||
continue
|
||||
doc = (app.view_functions[rule.endpoint].__doc__ or "").strip()
|
||||
routes.append(
|
||||
{
|
||||
"path": rule.rule,
|
||||
"methods": sorted(rule.methods - {"HEAD", "OPTIONS"}),
|
||||
"summary": " ".join(doc.split("\n\n")[0].split()),
|
||||
}
|
||||
)
|
||||
return jsonify({"routes": routes})
|
||||
|
||||
@app.errorhandler(413)
|
||||
def too_large(_exc):
|
||||
limit_mb = app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
|
||||
return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413
|
||||
|
||||
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
||||
app.register_blueprint(imports_bp, url_prefix="/imports")
|
||||
app.register_blueprint(data_bp, url_prefix="/data")
|
||||
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||
app.register_blueprint(reports_bp, url_prefix="/reportes")
|
||||
# The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest.
|
||||
if os.environ.get("DBT_MANIFEST"):
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.fhir import fhir_blueprint
|
||||
from webapi.kpis import kpis_blueprint
|
||||
|
||||
for domain in ("cacu", "cama", "tea"):
|
||||
repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])
|
||||
app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}")
|
||||
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
|
||||
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
|
||||
url_prefix=f"/{domain}/fhir")
|
||||
# Patient-level follow-up list, marked `simulado` in every response (a CaCu patient's individual risk is FHIR's
|
||||
# `RiskAssessment`, under `/cacu/fhir`). Who may see them is an access rule still to be defined.
|
||||
from persistance import cacu as cacu_repositories
|
||||
from persistance.db import get_cacu_session, get_cama_session
|
||||
|
||||
from webapi.risk_batches import risk_batches_blueprint
|
||||
|
||||
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
||||
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
|
||||
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
|
||||
app.register_blueprint(cama_survival_bp, url_prefix="/cama/supervivencia")
|
||||
app.register_blueprint(cama_recurrence_bp, url_prefix="/cama/recurrencia")
|
||||
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
Recursos gráficos de las exportaciones PDF (webapi/pdf_report.py)
|
||||
|
||||
isssteleon-logo.png
|
||||
Logotipo institucional. Idéntico byte a byte (SHA-256 3ff77526...da758) al de
|
||||
WebApp/public/assets/branding/isssteleon-logo.png. Pendiente: confirmar con ISSSTELEON
|
||||
que puede incrustarse en documentos exportados.
|
||||
|
||||
fonts/Roboto-Regular.ttf, Roboto-Medium.ttf, Roboto-Italic.ttf, Roboto-MediumItalic.ttf
|
||||
Roboto 3.016, The Roboto Project Authors (https://github.com/googlefonts/roboto-classic),
|
||||
SIL Open Font License 1.1 (texto en fonts/LICENSE-Roboto-OFL.txt; el aviso de derechos y de
|
||||
licencia va también dentro de cada archivo). La licencia permite incrustar y redistribuir
|
||||
las fuentes con el programa siempre que se conserve el aviso. Pendiente: confirmar la
|
||||
procedencia exacta de descarga de estos archivos (no consta en el historial) y conservar este
|
||||
aviso en la entrega, que elimina documentos.
|
||||
@@ -1,93 +0,0 @@
|
||||
Copyright 2011 The Roboto Project Authors (https://github.com/googlefonts/roboto-classic) Roboto-Italic[wdth,wght].ttf: Copyright 2011 The Roboto Project Authors (https://github.com/googlefonts/roboto-classic)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user