preliminary release
This commit is contained in:
@@ -14,6 +14,10 @@ import pytest
|
||||
# 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,oracle")
|
||||
# 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"))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -54,3 +58,46 @@ def _migrate(domain: str) -> None:
|
||||
|
||||
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 sembrar_base(proyecto: str, motor) -> None:
|
||||
"""La base de demostración del kit: staging sintético, carga y todos los indicadores calculados.
|
||||
|
||||
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para
|
||||
TEA: cada definición de `measures_de(proyecto)` queda calculada en los
|
||||
periodos de 2025 que publica (`SEMESTRES`, y los doce meses si publica
|
||||
meses).
|
||||
"""
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
|
||||
base_de_prueba(motor, proyecto)
|
||||
|
||||
|
||||
def cliente_de(proyecto: str, tmp_path_factory):
|
||||
"""Generador para la fixture `client` de un proyecto: una base SQLite temporal ya sembrada."""
|
||||
from persistance import db
|
||||
from persistance.settings import settings
|
||||
|
||||
ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db"
|
||||
obtener_motor = getattr(db, f"get_{proyecto}_engine")
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
|
||||
obtener_motor.cache_clear()
|
||||
try:
|
||||
sembrar_base(proyecto, obtener_motor())
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
obtener_motor().dispose()
|
||||
obtener_motor.cache_clear()
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit."""
|
||||
|
||||
import pytest
|
||||
from conftest import MESES, SEMESTRES, cliente_de
|
||||
from indicadores_kit.registry.measures import RAIZ, measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
|
||||
PROYECTO = "cacu"
|
||||
INDICADOR = "ind1"
|
||||
DEFINICIONES = measures_de(PROYECTO)
|
||||
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
yield from cliente_de(PROYECTO, tmp_path_factory)
|
||||
|
||||
|
||||
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def _x(respuesta) -> list[str]:
|
||||
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get(f"/{PROYECTO}/indicadores")
|
||||
|
||||
assert response.status_code == 200
|
||||
lista = response.get_json()
|
||||
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||
|
||||
|
||||
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||
"""Los que su TOML marca `oculto` (p. ej. cacu_riesgo_banda hasta MD-Q5) no salen en el catálogo, pero responden."""
|
||||
ocultos = {nombre for nombre, medida in DEFINICIONES.items() if medida.extension.publicacion.oculto}
|
||||
|
||||
assert ocultos
|
||||
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||
|
||||
assert ids == set(DEFINICIONES) - ocultos
|
||||
for indicador in ocultos:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
|
||||
|
||||
|
||||
def test_un_indicador_retirado_da_404(client):
|
||||
"""T-22a (ADR-MD-009): los retirados (`<proyecto>/retirados/` del kit) ni se calculan ni se sirven."""
|
||||
retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")]
|
||||
|
||||
assert retirados
|
||||
for indicador in retirados:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404
|
||||
|
||||
|
||||
def test_figura_con_semestres(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.mimetype == "application/json"
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
|
||||
assert set(_x(response)) == set(SEMESTRES)
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
|
||||
response = _figura(client)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
|
||||
|
||||
|
||||
def test_figura_con_meses(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(MESES)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S3",
|
||||
"?periodos=2025-13x",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=2025-T1", # un tipo que el indicador no publica
|
||||
"?periodos=2025-S1,2025-03", # tipos mezclados
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, query=query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("CACU_NO_EXISTE", FIGURA, ""),
|
||||
(INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato
|
||||
(INDICADOR, "fig_no_existe", ""),
|
||||
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, query="?periodos=2025-S1")
|
||||
|
||||
|
||||
# --- Todos los indicadores del proyecto ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura)
|
||||
|
||||
assert response.status_code == 200, (indicador, figura)
|
||||
assert set(response.get_json()) >= {"data", "layout"}
|
||||
|
||||
|
||||
def test_una_distribucion_sin_periodos_es_la_del_semestre_mas_reciente(client):
|
||||
assert figuras_de(DEFINICIONES["cacu_eu7"]) == ["fig_c2_barras", "fig_c2_donas"]
|
||||
|
||||
por_defecto = _figura(client, "cacu_eu7", "fig_c2_donas")
|
||||
del_ultimo = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={SEMESTRES[-1]}")
|
||||
de_todos = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={','.join(SEMESTRES)}")
|
||||
|
||||
assert por_defecto.get_json() == del_ultimo.get_json()
|
||||
assert len(de_todos.get_json()["data"]) == len(SEMESTRES) * len(por_defecto.get_json()["data"])
|
||||
|
||||
|
||||
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||
|
||||
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"}
|
||||
|
||||
|
||||
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||
|
||||
|
||||
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||
|
||||
assert all(set(fila) == CATALOGO for fila in lista)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||
assert fila["estratos"] == medida.extension.estratos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = _ruta(client, indicador, "periodos")
|
||||
datos = _ruta(client, indicador, "datos")
|
||||
metadatos = _ruta(client, indicador, "metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||
assert de_semestre == SEMESTRES
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||
|
||||
|
||||
def test_datos_con_meses(client):
|
||||
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["tipo_periodo"] == "mes"
|
||||
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||
|
||||
|
||||
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||
|
||||
(reporte,) = cuerpo["reportes"]
|
||||
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _ruta(client, INDICADOR, "datos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "ruta", "query"),
|
||||
[
|
||||
("NO_EXISTE", "datos", ""),
|
||||
("NO_EXISTE", "periodos", ""),
|
||||
("NO_EXISTE", "metadatos", ""),
|
||||
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||
],
|
||||
)
|
||||
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||
response = _ruta(client, indicador, ruta, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
# --- Los filtros (T-19f) ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?filtro=grupo_edad", "?filtro=:25-34", "?filtro=grupo_edad:25-34,grupo_edad:35-44",
|
||||
"?filtro=grupo_edad:25-34", "?filtro=ronda:1"])
|
||||
def test_un_filtro_mal_escrito_o_no_declarado_da_400(client, query):
|
||||
"""IND1 no declara filtros (EU7 y EU13 sí, desde T-24f): todo `?filtro=` da 400, en datos y en figuras."""
|
||||
for response in (_ruta(client, INDICADOR, "datos", query), _figura(client, query=query)):
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_sin_filtro_los_datos_no_traen_la_llave_filtros(client):
|
||||
assert "filtros" not in _ruta(client, INDICADOR, "datos").get_json()
|
||||
|
||||
|
||||
def test_los_filtros_se_leen_como_estrato_y_valor():
|
||||
from webapi.indicadores import filtros_pedidos
|
||||
|
||||
assert filtros_pedidos(None) == {} and filtros_pedidos("") == {}
|
||||
assert filtros_pedidos("grupo_edad:25-34,ronda:1") == {"grupo_edad": "25-34", "ronda": "1"}
|
||||
with pytest.raises(ValueError, match="mal escrito"):
|
||||
filtros_pedidos("grupo_edad")
|
||||
|
||||
|
||||
# --- La ficha técnica (T-24e) ---
|
||||
|
||||
# Las llaves de /metadatos antes de T-24e: no se quita ni se renombra ninguna.
|
||||
METADATOS = {
|
||||
"id", "titulo", "version", "estado", "contrato", "tipo_calculo", "unidad", "sentido", "descripcion",
|
||||
"tipos_periodo", "figuras", "estratos", "grupos", "categorias", "grupos_de_categoria", "estandares",
|
||||
"ficha", "parametros",
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_los_metadatos_traen_referencias_poblaciones_y_figuras_sin_perder_llaves(client, indicador):
|
||||
cuerpo = _ruta(client, indicador, "metadatos").get_json()
|
||||
|
||||
assert set(cuerpo) == METADATOS | {"referencias", "poblaciones", "figuras_detalle"}
|
||||
assert cuerpo["poblaciones"]
|
||||
assert [d["figura"] for d in cuerpo["figuras_detalle"]] == cuerpo["figuras"]
|
||||
if not DEFINICIONES[indicador].extension.publicacion.oculto:
|
||||
assert all(d["descripcion"] and d["como_leer"] for d in cuerpo["figuras_detalle"])
|
||||
assert all(set(p) == {"grupo", "codigo", "descripcion"} and p["descripcion"] for p in cuerpo["poblaciones"])
|
||||
|
||||
|
||||
def test_la_ficha_de_eu7_cita_el_lineamiento_europeo(client):
|
||||
cuerpo = _ruta(client, "cacu_eu7", "metadatos").get_json()
|
||||
|
||||
assert cuerpo["referencias"] == [{
|
||||
"tipo": "citation",
|
||||
"etiqueta": "European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)",
|
||||
"ref": "indicador 7",
|
||||
}] # fmt: skip
|
||||
assert cuerpo["poblaciones"] == [{
|
||||
"grupo": "total",
|
||||
"codigo": "measure-observation",
|
||||
"descripcion": DEFINICIONES["cacu_eu7"].group[0].population[0].description,
|
||||
}] # fmt: skip
|
||||
|
||||
|
||||
# --- EU7 por estrato (T-24f): la dona y sus barras ---
|
||||
|
||||
|
||||
def test_eu7_por_estatus_da_categoria_por_valor_con_etiquetas_y_totales(client):
|
||||
cuerpo = _ruta(client, "cacu_eu7", "datos", "?estrato=estatus_seguimiento").get_json()
|
||||
|
||||
assert cuerpo["estrato"] == "estatus_seguimiento" and cuerpo["valores_estrato"]
|
||||
assert set(cuerpo["etiquetas_estrato"]) == set(cuerpo["valores_estrato"])
|
||||
assert {f["estrato"] for f in cuerpo["filas"]} == set(cuerpo["valores_estrato"])
|
||||
assert {t["estrato"] for t in cuerpo["totales_estrato"]} == set(cuerpo["valores_estrato"])
|
||||
|
||||
|
||||
def test_eu7_se_puede_filtrar_por_grupo_de_edad(client):
|
||||
valor = _ruta(client, "cacu_eu7", "datos", "?estrato=grupo_edad").get_json()["valores_estrato"][0]
|
||||
response = _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["filtros"] == {"grupo_edad": valor}
|
||||
|
||||
|
||||
def test_el_catalogo_publica_los_filtros_con_sus_valores(client):
|
||||
"""T-24f (contrato de T-24a §3): con ellos se arma `?filtro=estrato:valor`."""
|
||||
por_id = {fila["id"]: fila for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||
|
||||
assert por_id[INDICADOR]["filtros"] == [] # IND1 no declara filtros
|
||||
(edad, estatus) = por_id["cacu_eu7"]["filtros"]
|
||||
assert (edad["estrato"], edad["etiqueta"]) == ("grupo_edad", "Grupo de edad")
|
||||
assert [v["valor"] for v in edad["valores"]][-1] == "sin_dato"
|
||||
assert (estatus["estrato"], estatus["etiqueta"]) == ("estatus_seguimiento", "Estatus de seguimiento")
|
||||
assert estatus["valores"] == [
|
||||
{"valor": "PRE_COLPOSCOPIA", "etiqueta": "Pre colposcopia"},
|
||||
{"valor": "POST_COLPOSCOPIA", "etiqueta": "Post colposcopia"},
|
||||
{"valor": "POST_TRATAMIENTO", "etiqueta": "Post tratamiento"},
|
||||
{"valor": "INFO_INSUFICIENTE", "etiqueta": "Información insuficiente"},
|
||||
]
|
||||
valor = edad["valores"][0]["valor"]
|
||||
assert _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}").status_code == 200
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Rutas de indicadores de CAMA: base SQLite temporal sembrada con los fixtures del kit."""
|
||||
|
||||
import pytest
|
||||
from conftest import MESES, SEMESTRES, cliente_de
|
||||
from indicadores_kit.registry.measures import RAIZ, measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
|
||||
PROYECTO = "cama"
|
||||
INDICADOR = "cama_confirmacion_birads45"
|
||||
DEFINICIONES = measures_de(PROYECTO)
|
||||
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
yield from cliente_de(PROYECTO, tmp_path_factory)
|
||||
|
||||
|
||||
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def _x(respuesta) -> list[str]:
|
||||
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get(f"/{PROYECTO}/indicadores")
|
||||
|
||||
assert response.status_code == 200
|
||||
lista = response.get_json()
|
||||
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||
|
||||
|
||||
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||
"""Provisional (oct 2026): cama_birads no se muestra.
|
||||
|
||||
cama_birads lo sustituyen cama_birads_456_paciente y cama_birads_456_mastografia.
|
||||
cama_confirmacion_birads45 vuelve a mostrarse: su tarjeta destacada y su
|
||||
gráfica de tendencia (usuario, 2026-10-16).
|
||||
"""
|
||||
ocultos = {"cama_birads"} # cama_riesgo_banda es propuesta desde T-21h: no se calcula ni se sirve
|
||||
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||
|
||||
assert ids == set(DEFINICIONES) - ocultos
|
||||
for indicador in ocultos:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
|
||||
|
||||
|
||||
def test_un_indicador_retirado_da_404(client):
|
||||
"""T-22a (ADR-MD-009): los retirados (`<proyecto>/retirados/` del kit) ni se calculan ni se sirven."""
|
||||
retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")]
|
||||
|
||||
assert retirados
|
||||
for indicador in retirados:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404
|
||||
|
||||
|
||||
def test_figura_con_semestres(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.mimetype == "application/json"
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
|
||||
assert set(_x(response)) == set(SEMESTRES)
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
|
||||
response = _figura(client)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
|
||||
|
||||
|
||||
def test_figura_con_meses(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(MESES)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S3",
|
||||
"?periodos=2025-13x",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=2025-T1", # un tipo que el indicador no publica
|
||||
"?periodos=2025-S1,2025-03", # tipos mezclados
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, query=query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("CAMA_NO_EXISTE", FIGURA, ""),
|
||||
(INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato
|
||||
(INDICADOR, "fig_no_existe", ""),
|
||||
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, query="?periodos=2025-S1")
|
||||
|
||||
|
||||
# --- Todos los indicadores del proyecto ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura)
|
||||
|
||||
assert response.status_code == 200, (indicador, figura)
|
||||
assert set(response.get_json()) >= {"data", "layout"}
|
||||
|
||||
|
||||
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||
|
||||
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"}
|
||||
|
||||
|
||||
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||
|
||||
|
||||
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||
|
||||
assert all(set(fila) == CATALOGO for fila in lista)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||
assert fila["estratos"] == medida.extension.estratos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = _ruta(client, indicador, "periodos")
|
||||
datos = _ruta(client, indicador, "datos")
|
||||
metadatos = _ruta(client, indicador, "metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||
assert de_semestre == SEMESTRES
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||
|
||||
|
||||
def test_datos_con_meses(client):
|
||||
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["tipo_periodo"] == "mes"
|
||||
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||
|
||||
|
||||
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||
|
||||
(reporte,) = cuerpo["reportes"]
|
||||
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _ruta(client, INDICADOR, "datos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "ruta", "query"),
|
||||
[
|
||||
("NO_EXISTE", "datos", ""),
|
||||
("NO_EXISTE", "periodos", ""),
|
||||
("NO_EXISTE", "metadatos", ""),
|
||||
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||
],
|
||||
)
|
||||
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||
response = _ruta(client, indicador, ruta, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
@@ -1,183 +0,0 @@
|
||||
"""Endpoint tests for `/tea/indicadores`, `/cacu/indicadores` and
|
||||
`/cama/indicadores`: the read side of the bronze/silver/gold pipeline
|
||||
(Persistance/persistance/aristas, indicadores_kit). Seeds one patient,
|
||||
runs the real `cargar`/`registro`/`definiciones`/`calcular` steps, then
|
||||
hits the HTTP layer."""
|
||||
from datetime import date
|
||||
from functools import partial
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("tea")
|
||||
|
||||
from core.tea.models import Pacientes
|
||||
from persistance import db as persistance_db
|
||||
from persistance.tea import (
|
||||
staging_repository, carga_repository, def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository,
|
||||
)
|
||||
from indicadores_kit.tea import etl
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with __import__("sqlmodel").Session(persistance_db.get_tea_engine()) as session:
|
||||
session.add(Pacientes(pac_id_hospital="H-1", pac_fecha_nacimiento=date(2020, 1, 1), pac_sexo="F"))
|
||||
session.commit()
|
||||
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
|
||||
tablas = tablas_de("tea")
|
||||
measures = measures_de("tea")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2024, 2024, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("tea"), tablas=tablas))
|
||||
nombre, medida = next(iter(measures.items()))
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2024, 1, 1), date(2025, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
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_list_indicadores(client):
|
||||
"""Only the 5 TEA measures not marked `oculto` in their own TOML publish
|
||||
to the catalog (the K01-K08/M02-M19 family is draft/internal); a hidden
|
||||
id still answers `/datos` directly, see `test_indicador_datos_...`."""
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
indicadores = response.get_json()
|
||||
assert isinstance(indicadores, list)
|
||||
assert len(indicadores) == 5
|
||||
assert {"id", "titulo", "contrato", "unidad", "sentido", "tipos_periodo", "estratos", "figuras"} <= indicadores[0].keys()
|
||||
|
||||
|
||||
def test_indicador_datos_returns_valid_json_no_bare_nan(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2024-S1,2024-S2")
|
||||
assert response.status_code == 200
|
||||
# Pandas renders missing scores as NaN; the response must not leak the
|
||||
# bare (invalid-JSON) token -- it has to come through as `null`.
|
||||
assert "NaN" not in response.get_data(as_text=True)
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert set(body["periodos"]) == {"2024-S1", "2024-S2"}
|
||||
assert {row["periodo"] for row in body["filas"]} == {"2024-S1", "2024-S2"}
|
||||
|
||||
|
||||
def test_indicador_datos_without_periodos_defaults_to_available_ones(client):
|
||||
"""Unlike the old endpoint, omitting `periodos` is not an error: it
|
||||
reports whatever periods already have a computed report."""
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["periodos"]
|
||||
|
||||
|
||||
def test_indicador_datos_unknown_indicador_is_404(client):
|
||||
response = client.get("/tea/indicadores/NOPE/datos?periodos=2024-S1")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_indicador_datos_malformed_periodo_is_400(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=no-es-un-periodo")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_indicador_periodos_endpoint(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/periodos")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert isinstance(body["periodos"], list)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cacu_client(wire_domain):
|
||||
"""CaCu reproduces a real id mismatch TEA's fixture doesn't: some of its
|
||||
TOML files are named in lowercase (`cacu_biopsias.toml`, the
|
||||
`measures_de` dict key) while their `measure.url` ends in uppercase
|
||||
(`cacu/CACU_BIOPSIAS`, the id `indicador_definicion.indicador` and the
|
||||
catalog publish) -- caught live by driving the WebApp dashboard against
|
||||
a real CaCu indicator, not by the TEA-only fixture above."""
|
||||
wire_domain("cacu")
|
||||
|
||||
from sqlmodel import Session
|
||||
from persistance import db as persistance_db
|
||||
from persistance.cacu import (
|
||||
staging_repository, carga_repository, def_parametro_repository as cacu_def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository, vistas_repository,
|
||||
)
|
||||
from indicadores_kit.cacu import etl, fixtures
|
||||
from indicadores_kit.cdm.etl import lote_de_resultados
|
||||
from indicadores_kit.esquema import ddl_de_vistas
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with Session(persistance_db.get_cacu_engine()) as session:
|
||||
fixtures.insertar(session)
|
||||
session.commit()
|
||||
|
||||
tablas = tablas_de("cacu")
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
pacientes = staging_repository.leer({"pacientes": etl.STAGING["pacientes"]})["pacientes"]
|
||||
lote_resultados = lote_de_resultados(
|
||||
pacientes, staging_repository.leer(etl.STAGING_DE_RESULTADOS), etl.FUENTES_DE_RESULTADOS, tablas=tablas,
|
||||
)
|
||||
carga_repository.guardar_lote(**lote_resultados.para_guardar())
|
||||
vistas_repository.construir(ddl_de_vistas("cacu"))
|
||||
|
||||
measures = measures_de("cacu")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
cacu_def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2025, 2025, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("cacu"), tablas=tablas))
|
||||
for medida in measures.values():
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2025, 1, 1), date(2026, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
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_indicador_datos_uses_the_toml_key_not_measure_url(cacu_client):
|
||||
"""`cacu_biopsias`'s own `measure.url` ends in `CACU_BIOPSIAS` (uppercase),
|
||||
but `registrar_indicadores` publishes and looks measures up by
|
||||
`measures_de()`'s dict key (the lowercase TOML file stem) throughout, so
|
||||
the mismatch never reaches a client -- unlike the old, since-replaced
|
||||
`webapi.indicadores`, which published the uppercase `measure.url` id and
|
||||
needed its own `_measure_por_indicador` lookup to reconcile the two."""
|
||||
catalogo = cacu_client.get("/cacu/indicadores").get_json()
|
||||
assert any(i["id"] == "cacu_biopsias" for i in catalogo)
|
||||
assert not any(i["id"] == "CACU_BIOPSIAS" for i in catalogo)
|
||||
|
||||
response = cacu_client.get("/cacu/indicadores/cacu_biopsias/datos?periodos=2025-S1,2025-S2")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["filas"]
|
||||
@@ -0,0 +1,177 @@
|
||||
import pytest
|
||||
from indicadores_kit.registry.measures import RAIZ, measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
from indicadores_kit.tea import fixtures
|
||||
|
||||
DEFINICIONES = measures_de("tea")
|
||||
PERIODOS = ",".join(fixtures.PERIODOS)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""Una base de TEA temporal, con los 20 indicadores calculados (16 en el catálogo), por `TEA_DATABASE_URL`."""
|
||||
# Dentro de la fixture: la configuración de Persistance se lee al importarla,
|
||||
# y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes.
|
||||
from persistance.db import get_tea_engine
|
||||
from persistance.settings import settings
|
||||
|
||||
ruta = tmp_path_factory.mktemp("tea") / "tea.db"
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
|
||||
get_tea_engine.cache_clear()
|
||||
try:
|
||||
fixtures.base_de_prueba(get_tea_engine())
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
get_tea_engine().dispose()
|
||||
get_tea_engine.cache_clear()
|
||||
|
||||
|
||||
def _figura(client, indicador: str, figura: str, query: str = ""):
|
||||
return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
|
||||
lista = response.get_json()
|
||||
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
|
||||
|
||||
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||
"""Provisional (oct 2026): solo se muestran M21, M22 y los tres destacados (M23 a M25)."""
|
||||
visibles = {
|
||||
"M21_diagnosticados_con_eeg",
|
||||
"M22_diagnosticados_sin_eeg",
|
||||
"M23_pacientes_evaluados",
|
||||
"M24_confirmacion_diagnostico",
|
||||
"M25_dias_mchat_diagnostico",
|
||||
}
|
||||
ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()}
|
||||
|
||||
assert ids == visibles
|
||||
for oculto in sorted(set(DEFINICIONES) - visibles):
|
||||
assert client.get(f"/tea/indicadores/{oculto}/metadatos").status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200, figura
|
||||
assert response.mimetype == "application/json"
|
||||
assert "data" in response.get_json()
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||
(figura,) = figuras_de(DEFINICIONES["M21_diagnosticados_con_eeg"])
|
||||
|
||||
response = _figura(client, "M21_diagnosticados_con_eeg", figura)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["M21_diagnosticados_con_eeg"].title
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=,",
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("K99_no_existe", "fig_c1_grupos", ""),
|
||||
("M21_diagnosticados_con_eeg", "fig_c3r_caja", ""), # figura de otro contrato
|
||||
("M21_diagnosticados_con_eeg", "fig_no_existe", ""),
|
||||
("M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte
|
||||
("M21_diagnosticados_con_eeg", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"),
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_paciente_por_id_entero(client):
|
||||
response = client.get("/tea/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "T-01"
|
||||
|
||||
assert client.get("/tea/pacientes/abc").status_code == 404
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2025-S1")
|
||||
|
||||
|
||||
# --- Los periodos, los datos y los metadatos ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = client.get(f"/tea/indicadores/{indicador}/periodos")
|
||||
datos = client.get(f"/tea/indicadores/{indicador}/datos?periodos={PERIODOS}")
|
||||
metadatos = client.get(f"/tea/indicadores/{indicador}/metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert [p["periodo"] for p in periodos.get_json()["periodos"]] == sorted(fixtures.PERIODOS)
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["id"], cuerpo["contrato"]) == (indicador, medida.extension.contrato)
|
||||
assert cuerpo["filas"] and {fila["periodo"] for fila in cuerpo["filas"]} == set(fixtures.PERIODOS)
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["ficha"]["codigo"] == medida.extension.ficha.codigo
|
||||
|
||||
|
||||
def test_los_grupos_de_los_datos_van_en_el_orden_de_la_ficha(client):
|
||||
response = client.get(f"/tea/indicadores/M21_diagnosticados_con_eeg/datos?periodos={PERIODOS}")
|
||||
|
||||
grupos = list(response.get_json()["grupos"])
|
||||
assert grupos != sorted(grupos) # el orden de la ficha, no el alfabético
|
||||
assert grupos[-1] == "TOTAL"
|
||||
|
||||
|
||||
def test_un_indicador_retirado_da_404(client):
|
||||
"""T-22a (ADR-MD-009): los retirados (`tea/retirados/` del kit) ni se calculan ni se sirven."""
|
||||
retirados = [ruta.stem for ruta in (RAIZ / "tea" / "retirados").glob("*.toml")]
|
||||
|
||||
assert len(retirados) == 18
|
||||
for indicador in retirados:
|
||||
assert client.get(f"/tea/indicadores/{indicador}/metadatos").status_code == 404
|
||||
@@ -100,7 +100,6 @@ def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
"target": "tea.EegEstudio",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"paciente": "eeg_pac_id",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""The Hamilton pipeline computes exactly what Orquestacion's own executor does."""
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Session
|
||||
|
||||
|
||||
def _seed_and_run(proyecto, tmp_path, run):
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.conexion import apuntar
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
url = f"sqlite:///{tmp_path / f'{proyecto}.db'}"
|
||||
apuntar(proyecto, url)
|
||||
ctx = Contexto(proyecto, 2025, 2025, permitir_sin_definir=True, repos=repositorios_de(proyecto))
|
||||
correr_orquestacion(ctx, solo=["migrar"])
|
||||
with Session(sa.create_engine(url)) as sesion:
|
||||
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
|
||||
sesion.commit()
|
||||
run(ctx)
|
||||
engine = sa.create_engine(url)
|
||||
with engine.connect() as conn:
|
||||
reports = conn.execute(sa.text(
|
||||
"SELECT measure_url, periodo_id, status, tipo FROM measure_report ORDER BY 1, 2, 3, 4")).all()
|
||||
units = conn.execute(sa.text(
|
||||
"SELECT r.measure_url, r.periodo_id, u.grupo, u.unidad_id, u.resultado_id, u.valor_id, u.numero "
|
||||
"FROM measure_report_unidad u JOIN measure_report r USING (report_id) ORDER BY 1, 2, 3, 4, 5")).all()
|
||||
engine.dispose()
|
||||
return reports, units
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "tea"])
|
||||
def test_hamilton_matches_the_orquestacion_executor(proyecto, tmp_path_factory):
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
|
||||
from webapi.pipeline import correr as correr_hamilton
|
||||
|
||||
nombres = None
|
||||
|
||||
def by_executor(ctx):
|
||||
nonlocal nombres
|
||||
nombres = [p.arista for p in correr_orquestacion(ctx) if p.arista != "migrar"]
|
||||
|
||||
expected = _seed_and_run(proyecto, tmp_path_factory.mktemp("orquestacion"), by_executor)
|
||||
got = _seed_and_run(proyecto, tmp_path_factory.mktemp("hamilton"),
|
||||
lambda ctx: correr_hamilton(ctx, solo=nombres))
|
||||
assert expected[0] and expected[1]
|
||||
assert got == expected
|
||||
@@ -0,0 +1,159 @@
|
||||
"""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.indicadores_vivos import ColaDeRecalculo
|
||||
|
||||
cola = ColaDeRecalculo()
|
||||
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
||||
assert cola.atender() == ["cacu"]
|
||||
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
||||
assert estado["estado"] == "ok", estado
|
||||
assert estado["pendiente"] is False
|
||||
assert {p["arista"] for p in estado["pasos"]} >= {"cargar", "calcular"}
|
||||
assert client.get("/cacu/indicadores").get_json()
|
||||
|
||||
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
|
||||
|
||||
|
||||
def test_hamilton_pipeline_orders_the_kit_steps_like_the_graph():
|
||||
"""Same steps, same dependency order as Orquestacion's own graph."""
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.aristas import FUENTES, aristas_de
|
||||
from orquestacion.grafo import orden
|
||||
|
||||
from webapi.pipeline import _order, modulo
|
||||
from hamilton import driver
|
||||
|
||||
for proyecto in ("tea", "cacu", "cama"):
|
||||
aristas = aristas_de(proyecto)
|
||||
dr = driver.Builder().with_modules(modulo(Contexto(proyecto, 2025, 2025), aristas)).build()
|
||||
nombres = [a.nombre for a in aristas]
|
||||
hamilton_order = _order(dr, nombres)
|
||||
graph_order = [a.nombre for a in orden(aristas, FUENTES)]
|
||||
assert set(hamilton_order) == set(graph_order)
|
||||
for arista in aristas:
|
||||
for anterior in dr.graph.nodes[arista.nombre].dependencies:
|
||||
assert hamilton_order.index(anterior.name) < hamilton_order.index(arista.nombre)
|
||||
@@ -231,3 +231,20 @@ def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
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="POTENCIALES_EVOCADOS").ord_tipo_estudio == "POTENCIALES_EVOCADOS_AUDITIVOS"
|
||||
assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "EVALUACION_PSICOLOGICA_TEA"
|
||||
|
||||
@@ -7,6 +7,7 @@ from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
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);
|
||||
@@ -30,8 +31,8 @@ def test_every_registered_schema_is_constructible(entity_key):
|
||||
schema_cls()
|
||||
|
||||
|
||||
def test_entity_registry_has_twenty_two_entries():
|
||||
assert len(ENTITY_REGISTRY) == 22
|
||||
def test_entity_registry_has_twenty_four_entries():
|
||||
assert len(ENTITY_REGISTRY) == 24
|
||||
|
||||
|
||||
def test_entity_registry_keys_cover_all_three_domains():
|
||||
@@ -42,12 +43,14 @@ def test_entity_registry_keys_cover_all_three_domains():
|
||||
assert "cacu.BiopsiaCervical" in keys
|
||||
assert "cacu.NotaMedica" in keys
|
||||
assert "cacu.BiometriaHematica" in keys
|
||||
assert "cacu.EpisodioClinico" in keys
|
||||
assert "cama.Paciente" in keys
|
||||
assert "cama.OrdenesEstudio" in keys
|
||||
assert "cama.Mastografia" in keys
|
||||
assert "cama.BiopsiaMama" in keys
|
||||
assert "cama.NotaMedica" in keys
|
||||
assert "cama.BiometriaHematica" in keys
|
||||
assert "cama.EpisodioClinico" in keys
|
||||
assert "tea.Pacientes" in keys
|
||||
assert "tea.OrdenesEstudio" in keys
|
||||
assert "tea.NotaMedica" in keys
|
||||
@@ -90,3 +93,16 @@ def test_cacu_biopsia_cervical_coerces_cin_grado_alias():
|
||||
|
||||
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,67 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, solo en DEV y 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: cuándo existe, la forma y los códigos de error.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
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"])
|
||||
assert "pac_id" 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_fuera_de_dev_la_ruta_no_existe(fuera_de_dev):
|
||||
assert fuera_de_dev.get("/cacu/seguimiento").status_code == 404
|
||||
@@ -0,0 +1,61 @@
|
||||
"""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
|
||||
Reference in New Issue
Block a user