Files
WebApi/tests/test_orquestacion_plata.py
T
rockdrigo 73cbf0cfb8 The catalog step seeds each domain's mappings, and a mapping is written only if the function still holds
How: `catalog_rows` turns the TOML's study codes, captions and each value's code, label and aliases into the
`catalogo` system's rows; the `catalogs` step adds the system and the forms with no row yet
(`mapeos_nuevos`). `register` normalizes the form and adds the row through `SourceMappingRepository.add`
with `check_stored`, which runs `check_function` on the stored rows of the same form; captions aren't
checked, since one caption may introduce several results. `ctx.repos.silver.mappings` is the domain's
repository.

Implications: the database keeps every mapping across deploys; a person's change is never overwritten, and
a second code for a form in force is refused before it's written. Loads still read the TOML's aliases.
2026-11-13 15:31:21 -06:00

255 lines
9.4 KiB
Python

"""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