English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports
This commit is contained in:
+12
-12
@@ -5,8 +5,8 @@
|
||||
`<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.orquestacion`:
|
||||
una base del dominio por prueba, migrada por el paso `migrar`, con el staging
|
||||
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
|
||||
@@ -20,9 +20,9 @@ from sqlalchemy import create_engine
|
||||
from sqlmodel import Session
|
||||
|
||||
from indicadores_kit.registry.parametros import RUTA_PARAMETROS
|
||||
from webapi.orquestacion import Contexto, correr
|
||||
from webapi.orquestacion.conexion import apuntar
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
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).
|
||||
@@ -40,13 +40,13 @@ class Base:
|
||||
"""El proyecto, su contexto (con los repositorios de Persistance) y su dominio en Persistance."""
|
||||
|
||||
proyecto: str
|
||||
ctx: Contexto
|
||||
ctx: Context
|
||||
dominio: object
|
||||
motor: object
|
||||
|
||||
def correr(self, *pasos: str, **cambios) -> dict:
|
||||
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.nombre: p.resumen for p in correr(replace(self.ctx, **cambios), solo=pasos)}
|
||||
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."""
|
||||
@@ -56,10 +56,10 @@ class Base:
|
||||
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'}"
|
||||
apuntar(proyecto, url)
|
||||
point_to(proyecto, url)
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
ctx = Contexto(proyecto, ANIO, ANIO, dbt_manifest=Path(manifest) if manifest else None, repos=repositorios_de(proyecto))
|
||||
correr(ctx, solo=["migrar"])
|
||||
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"indicadores_kit.{proyecto}.fixtures").insertar)(sesion)
|
||||
@@ -137,7 +137,7 @@ 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.correr("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos", permitir_sin_definir=True)
|
||||
base.run("catalogs", "load", "views", "registry", "definitions", "event_models", allow_undecided=True)
|
||||
try:
|
||||
from webapi import create_app
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""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 `modelos` (dbt's views); `manifest`, dbt's
|
||||
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).
|
||||
"""
|
||||
@@ -20,7 +20,7 @@ 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 = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos")
|
||||
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -34,8 +34,8 @@ def manifest():
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cama", tmp_path)
|
||||
base.correr(*UNTIL_MODELS, parametros=sin_supresion, permitir_sin_definir=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True))
|
||||
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()
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ 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 (`catalogos` … `modelos`; needs `DBT_MANIFEST`).
|
||||
created by the cycle (`catalogs` … `event_models`; needs `DBT_MANIFEST`).
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -70,8 +70,8 @@ def test_each_case_answers_what_its_rules_say(tmp_path, sin_supresion, url, case
|
||||
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.correr("catalogos", "cargar", "registro", "definiciones", "modelos", parametros=sin_supresion,
|
||||
permitir_sin_definir=True)
|
||||
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"),
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
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 `modelos` (which creates dbt's event models);
|
||||
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.
|
||||
"""
|
||||
@@ -22,11 +22,11 @@ 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.orquestacion import correr
|
||||
from webapi.orchestration import run
|
||||
|
||||
IND1, EU13, EU7 = "cacu/IND1", "cacu/CACU_EU13", "cacu/CACU_EU7"
|
||||
STATUS = "estatus_seguimiento"
|
||||
HASTA_MODELOS = ("catalogos", "cargar", "vistas", "registro", "definiciones", "modelos")
|
||||
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"
|
||||
|
||||
@@ -42,8 +42,8 @@ def manifest():
|
||||
@pytest.fixture
|
||||
def base(tmp_path, sin_supresion, manifest):
|
||||
base = base_de("cacu", tmp_path)
|
||||
base.correr(*HASTA_MODELOS, parametros=sin_supresion, permitir_sin_definir=True)
|
||||
yield replace(base, ctx=replace(base.ctx, parametros=sin_supresion, permitir_sin_definir=True))
|
||||
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()
|
||||
|
||||
|
||||
@@ -120,12 +120,12 @@ def reports(base) -> int:
|
||||
|
||||
|
||||
def reload(base, change) -> None:
|
||||
"""Changes the staging as the ingestion would and runs `cargar`: a new load, known later than everything before."""
|
||||
"""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()
|
||||
correr(base.ctx, solo=["cargar"])
|
||||
run(base.ctx, only=["load"])
|
||||
|
||||
|
||||
def test_ind1_answers_what_the_kit_computed(base, definition, kit):
|
||||
|
||||
@@ -14,8 +14,8 @@ import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlmodel import Session
|
||||
|
||||
from webapi.orquestacion import Contexto, correr
|
||||
from webapi.orquestacion.conexion import apuntar
|
||||
from webapi.orchestration import Context, run
|
||||
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).
|
||||
@@ -32,25 +32,25 @@ def bases(request, tmp_path_factory):
|
||||
proyecto = request.param
|
||||
carpeta = tmp_path_factory.mktemp(proyecto)
|
||||
url = f"sqlite:///{carpeta / 'orquestada.db'}"
|
||||
apuntar(proyecto, url)
|
||||
# `observar` lee una regla sin definir en los dos proyectos (I-MD1): se pide a propósito, como `montar` de
|
||||
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 = Contexto(proyecto, ANIO, ANIO, permitir_sin_definir=True, dbt_manifest=Path(os.environ["DBT_MANIFEST"]))
|
||||
correr(ctx, solo=["migrar"])
|
||||
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"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
|
||||
sesion.commit()
|
||||
pasos = correr(ctx)
|
||||
pasos = run(ctx)
|
||||
return proyecto, ctx, motor, None, pasos
|
||||
|
||||
|
||||
def test_corre_todos_los_pasos_en_orden(bases):
|
||||
proyecto, _, _, _, pasos = bases
|
||||
nombres = [p.nombre for p in pasos]
|
||||
# `migrar` 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] == "migrar" and nombres.index("catalogos") < nombres.index("cargar")
|
||||
assert nombres.index("cargar") < nombres.index("modelos") and "calcular" not in nombres
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ def test_volver_a_correr_no_agrega_reportes(bases):
|
||||
_, ctx, motor, _, _ = bases
|
||||
with motor.connect() as con:
|
||||
antes = con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one()
|
||||
correr(ctx)
|
||||
run(ctx)
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM measure_report")).scalar_one() == antes
|
||||
|
||||
@@ -68,9 +68,9 @@ def test_volver_a_correr_no_agrega_reportes(bases):
|
||||
def test_en_cacu_arma_su_cohorte_una_vez(bases):
|
||||
proyecto, ctx, motor, _, pasos = bases
|
||||
if proyecto != "cacu":
|
||||
assert "cohortes" not in [p.nombre for p in pasos] # T-21h: TEA y CaMa, solo propuestas
|
||||
assert "cohorts" not in [p.name for p in pasos] # T-21h: TEA y CaMa, solo propuestas
|
||||
return
|
||||
(armado_id, nuevo), = [p.resumen for p in pasos if p.nombre == "cohortes"][0].values()
|
||||
(armado_id, nuevo), = [p.summary for p in pasos if p.name == "cohorts"][0].values()
|
||||
with motor.connect() as con:
|
||||
assert con.execute(text("SELECT COUNT(*) FROM cohorte_armado")).scalar_one() == 1
|
||||
assert con.execute(text("SELECT n_miembros FROM cohorte_armado")).scalar_one() == con.execute(
|
||||
|
||||
@@ -13,14 +13,14 @@ from indicadores_kit.registry.edades import grupos_de_cortes
|
||||
from indicadores_kit.registry.parametros import RUTA_PARAMETROS, valores_del_archivo
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from webapi.orquestacion.proyecto import tipos_de_periodo
|
||||
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 ("cargar",)
|
||||
return ("load",)
|
||||
|
||||
|
||||
|
||||
@@ -38,19 +38,19 @@ def cargas(proyecto) -> tuple[str, ...]:
|
||||
|
||||
|
||||
def test_el_registro_se_puede_repetir_y_agrega_los_periodos_que_faltan(base):
|
||||
base.correr("registro")
|
||||
base.correr("registro", anio_inicio=ANIO - 1)
|
||||
base.run("registry")
|
||||
base.run("registry", year_from=ANIO - 1)
|
||||
|
||||
tablas = tablas_de(base.proyecto)
|
||||
esperados = periodos_de_tipos(tipos_de_periodo(base.proyecto, base.ctx.dbt_manifest), ANIO - 1, ANIO, tablas=tablas)
|
||||
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.correr("registro")
|
||||
base.correr("registro", anio_fin=ANIO + 1) # repetir deja la tabla igual, con el año nuevo
|
||||
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"])
|
||||
@@ -66,13 +66,13 @@ def test_el_registro_llena_dim_fecha_y_dim_grupo_edad_desde_los_toml(base):
|
||||
|
||||
|
||||
def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path):
|
||||
base.correr("registro")
|
||||
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.correr("registro", anio_inicio=ANIO - 1, anio_fin=ANIO + 1, parametros=malo)
|
||||
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
|
||||
@@ -80,15 +80,15 @@ def test_un_archivo_de_parametros_invalido_no_toca_el_registro(base, tmp_path):
|
||||
|
||||
|
||||
def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
|
||||
"""Pins down: `definiciones` seeds the publication catalog from dbt's manifest, once. Fails if a stratum or a
|
||||
"""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.correr("definiciones")["definiciones"]
|
||||
resumen = base.run("definitions")["definitions"]
|
||||
|
||||
# CaCu: three strata and its seven measures; CaMa: its seven measures, without strata.
|
||||
assert resumen["definiciones"] == {"cacu": 10, "cama": 7}[base.proyecto]
|
||||
assert resumen["definitions"] == {"cacu": 10, "cama": 7}[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() == 7 # seven measures in each domain
|
||||
assert base.correr("definiciones")["definiciones"]["borradas"] == 0
|
||||
assert base.run("definitions")["definitions"]["borradas"] == 0
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -3,38 +3,38 @@
|
||||
import pytest
|
||||
from hamilton import driver
|
||||
|
||||
from webapi.orquestacion import ciclo, pasos_de
|
||||
from webapi.orchestration import cycle, steps_of
|
||||
|
||||
|
||||
def dependencias(proyecto: str) -> dict[str, set[str]]:
|
||||
dr = driver.Builder().with_modules(ciclo).with_config({"con_cohortes": proyecto == "cacu"}).build()
|
||||
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()
|
||||
pendientes = list(deps[paso])
|
||||
while pendientes:
|
||||
anterior = pendientes.pop()
|
||||
pending = list(deps[paso])
|
||||
while pending:
|
||||
anterior = pending.pop()
|
||||
if anterior not in previos:
|
||||
previos.add(anterior)
|
||||
pendientes.extend(deps[anterior])
|
||||
pending.extend(deps[anterior])
|
||||
return previos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
def test_cada_paso_corre_despues_de_lo_que_necesita(proyecto):
|
||||
deps = dependencias(proyecto)
|
||||
assert deps["migrar"] == set()
|
||||
assert {"migrar", "catalogos"} <= antes(deps, "cargar") # decisión 6 de §9
|
||||
assert {"cargar"} <= antes(deps, "modelos")
|
||||
assert {"registro"} <= antes(deps, "observar")
|
||||
assert {"cargar", "catalogos"} <= antes(deps, "verificar_plata")
|
||||
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_solo_cacu_arma_cohortes_y_estima_por_ahora():
|
||||
"""T-21h: las cohortes de TEA y CaMa son propuestas (`cohortes/propuestas/`); queda su infraestructura."""
|
||||
assert {"cohortes", "estimar"} <= set(pasos_de("cacu"))
|
||||
assert {"cohorts", "estimate"} <= set(steps_of("cacu"))
|
||||
for proyecto in ("cama", "tea"):
|
||||
assert not {"cohortes", "estimar"} & set(pasos_de(proyecto))
|
||||
assert not {"cohorts", "estimate"} & set(steps_of(proyecto))
|
||||
|
||||
@@ -31,7 +31,7 @@ CORTE = date(2025, 12, 31)
|
||||
|
||||
|
||||
def ultima_carga(base):
|
||||
return max(base.ctx.repos.plata.carga.list(limit=100), key=lambda c: c.carga_id)
|
||||
return max(base.ctx.repos.silver.loads.list(limit=100), key=lambda c: c.carga_id)
|
||||
|
||||
|
||||
def contar(base, sql: str) -> int:
|
||||
@@ -60,7 +60,7 @@ def cambiar_staging(base) -> str:
|
||||
|
||||
def filas_del_catalogo(base) -> dict[str, int]:
|
||||
"""Cuántas filas tiene cada tabla de catálogo en la base."""
|
||||
plata = base.ctx.repos.plata.catalogos
|
||||
plata = base.ctx.repos.silver.catalogs
|
||||
with base.staging() as sesion:
|
||||
return {
|
||||
"estudios": len(sesion.exec(select(plata.model)).all()),
|
||||
@@ -74,15 +74,15 @@ def test_catalogos_deja_en_la_base_las_filas_del_toml(base):
|
||||
del_toml = {"estudios": len(catalogo.estudios), "resultados": len(catalogo.resultados),
|
||||
"valores": len(catalogo.valores)}
|
||||
|
||||
assert base.correr("catalogos")["catalogos"] == {**del_toml, "retirados": 0}
|
||||
assert base.run("catalogs")["catalogs"] == {**del_toml, "retirados": 0}
|
||||
assert filas_del_catalogo(base) == del_toml
|
||||
|
||||
|
||||
def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
base.correr("catalogos")
|
||||
base.run("catalogs")
|
||||
antes = filas_del_catalogo(base)
|
||||
|
||||
assert base.correr("catalogos")["catalogos"]["retirados"] == 0
|
||||
assert base.run("catalogs")["catalogs"]["retirados"] == 0
|
||||
assert filas_del_catalogo(base) == antes
|
||||
|
||||
|
||||
@@ -90,14 +90,14 @@ def test_volver_a_correr_catalogos_no_cambia_nada(base):
|
||||
|
||||
|
||||
def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
|
||||
base.correr("catalogos")
|
||||
carga = base.correr("cargar")["cargar"]
|
||||
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.bronce.staging.leer(
|
||||
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
|
||||
@@ -108,10 +108,10 @@ def test_cargar_lleva_el_staging_a_persona_y_la_plata(base):
|
||||
|
||||
|
||||
def test_volver_a_cargar_sin_cambios_no_toca_nada(base):
|
||||
base.correr("catalogos", "cargar")
|
||||
base.run("catalogs", "load")
|
||||
antes = plata_de(base)
|
||||
|
||||
segunda = base.correr("cargar")["cargar"]
|
||||
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"):
|
||||
@@ -119,11 +119,11 @@ def test_volver_a_cargar_sin_cambios_no_toca_nada(base):
|
||||
|
||||
|
||||
def test_un_cambio_en_staging_toca_un_procedimiento(base):
|
||||
base.correr("catalogos", "cargar")
|
||||
base.run("catalogs", "load")
|
||||
antes = plata_de(base)
|
||||
cambiar_staging(base)
|
||||
|
||||
segunda = base.correr("cargar")["cargar"]
|
||||
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
|
||||
|
||||
@@ -134,9 +134,9 @@ def test_un_cambio_en_staging_toca_un_procedimiento(base):
|
||||
|
||||
|
||||
def test_las_vistas_se_construyen_y_se_pueden_repetir(base):
|
||||
primera = base.correr("vistas")["vistas"]
|
||||
primera = base.run("views")["views"]
|
||||
|
||||
assert base.correr("vistas")["vistas"] == primera
|
||||
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"]
|
||||
|
||||
@@ -166,9 +166,9 @@ observables = pytest.mark.parametrize("proyecto", ["cacu", "cama"])
|
||||
|
||||
@observables
|
||||
def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla):
|
||||
base.correr("cargar", "registro", parametros=con_regla("2024-06-01"))
|
||||
base.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
|
||||
cuantos = base.correr("observar", corte=CORTE)["observar"]
|
||||
cuantos = base.run("observe", cutoff=CORTE)["observe"]
|
||||
|
||||
periodos = base.dominio.periodo_observacion_repository.list()
|
||||
assert cuantos == len(periodos) == base.dominio.persona_repository.count()
|
||||
@@ -178,9 +178,9 @@ def test_observar_deja_un_periodo_de_extraccion_por_paciente(base, con_regla):
|
||||
|
||||
@observables
|
||||
def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_regla):
|
||||
base.correr("cargar", "registro", parametros=con_regla())
|
||||
base.run("load", "registry", parameters=con_regla())
|
||||
|
||||
base.correr("observar")
|
||||
base.run("observe")
|
||||
|
||||
carga = ultima_carga(base)
|
||||
assert {p.fecha_fin for p in base.dominio.periodo_observacion_repository.list()} == {
|
||||
@@ -189,10 +189,10 @@ def test_sin_corte_la_observacion_termina_el_dia_de_la_ultima_carga(base, con_re
|
||||
|
||||
@observables
|
||||
def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
|
||||
base.correr("cargar", "registro", parametros=con_regla())
|
||||
base.run("load", "registry", parameters=con_regla())
|
||||
|
||||
primera = base.correr("observar", corte=date(2025, 6, 30))["observar"]
|
||||
segunda = base.correr("observar", corte=CORTE)["observar"]
|
||||
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}
|
||||
@@ -200,37 +200,37 @@ def test_observar_se_puede_repetir_sin_duplicar(base, con_regla):
|
||||
|
||||
@observables
|
||||
def test_la_regla_de_inicio_sin_definir_hay_que_pedirla_a_proposito(base):
|
||||
base.correr("cargar", "registro")
|
||||
base.run("load", "registry")
|
||||
|
||||
with pytest.raises(ParametroSinDefinir, match="inicio_datos"):
|
||||
base.correr("observar", corte=CORTE)
|
||||
assert base.correr("observar", corte=CORTE, permitir_sin_definir=True)["observar"] == (
|
||||
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.correr("cargar")
|
||||
base.run("load")
|
||||
|
||||
with pytest.raises(KeyError, match="preparar_registro|registro"):
|
||||
base.correr("observar", corte=CORTE)
|
||||
base.run("observe", cutoff=CORTE)
|
||||
|
||||
|
||||
@observables
|
||||
def test_un_corte_anterior_al_inicio_de_los_datos_se_rechaza(base, con_regla):
|
||||
base.correr("cargar", "registro", parametros=con_regla("2024-06-01"))
|
||||
base.run("load", "registry", parameters=con_regla("2024-06-01"))
|
||||
|
||||
with pytest.raises(ValueError, match="anterior al inicio"):
|
||||
base.correr("observar", corte=date(2024, 5, 31))
|
||||
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.correr("registro", parametros=con_regla())
|
||||
base.run("registry", parameters=con_regla())
|
||||
|
||||
with pytest.raises(ObservacionSinCorte):
|
||||
base.correr("observar")
|
||||
base.run("observe")
|
||||
|
||||
|
||||
# --- La carga doble (F5, ADR-MD-007): CaCu, CaMa y TEA ---
|
||||
@@ -239,7 +239,7 @@ def test_sin_corte_y_sin_cargas_no_hay_de_donde_tomarlo(base, con_regla):
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_verificar_plata_en_cacu_cuenta_los_valores_fuera_de_catalogo_del_fixture(base):
|
||||
conteos = base.correr("catalogos", "cargar", "verificar_plata")["verificar_plata"]
|
||||
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`.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""La regla de §6: ningún paso abre una sesión; todo va por `ctx.repos`.
|
||||
|
||||
Las subclases viven en `persistance/aristas/` y Persistance las instancia con su
|
||||
fábrica de sesión (ADR-MD-005). Solo `conexion.py` nombra a `persistance.db`: cambia a
|
||||
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.
|
||||
"""
|
||||
|
||||
@@ -10,10 +10,10 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from webapi.orquestacion.repositorios import repositorios_de
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
PAQUETE = Path(__file__).parents[1] / "webapi" / "orquestacion"
|
||||
EXENTOS = {"conexion.py"}
|
||||
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")
|
||||
|
||||
|
||||
@@ -25,6 +25,6 @@ def test_ningun_modulo_fuera_de_repositorios_abre_sesiones(modulo):
|
||||
|
||||
@pytest.mark.parametrize("proyecto, con_cohortes", [("cacu", True), ("cama", True)])
|
||||
def test_cada_proyecto_tiene_sus_repositorios(proyecto, con_cohortes):
|
||||
repos = repositorios_de(proyecto)
|
||||
assert (repos.oro.cohorte is not None) == con_cohortes
|
||||
assert repos.oro.calculo.model.__tablename__ == "measure_report"
|
||||
repos = repositories_of(proyecto)
|
||||
assert (repos.gold.cohorts is not None) == con_cohortes
|
||||
assert repos.gold.calculation.model.__tablename__ == "measure_report"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""El paso `estimar` y la orden `confirmar-riesgos` (ADR-MD-008), con un estimador de prueba.
|
||||
"""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.
|
||||
"""
|
||||
@@ -8,7 +8,7 @@ from dataclasses import dataclass
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.orquestacion.__main__ import confirmar_riesgos, main
|
||||
from webapi.orchestration.__main__ import confirm_risks, main
|
||||
|
||||
URL = "cacu/cohorte_vigilancia"
|
||||
|
||||
@@ -43,7 +43,7 @@ class EstimadorFijo:
|
||||
|
||||
@pytest.fixture
|
||||
def cacu(base):
|
||||
base.correr("catalogos", "cargar", "modelos", "cohortes", permitir_sin_definir=True)
|
||||
base.run("catalogs", "load", "event_models", "cohorts", allow_undecided=True)
|
||||
return base
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ def cuenta(base, sql):
|
||||
def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
estimador = EstimadorFijo()
|
||||
|
||||
(lote_id, nuevo) = cacu.correr("estimar", estimadores={URL: estimador})["estimar"][URL]
|
||||
(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
|
||||
@@ -68,23 +68,23 @@ def test_estimar_escribe_un_riesgo_por_miembro_del_ultimo_armado(cacu):
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu"])
|
||||
def test_estimar_otra_vez_no_duplica_y_sin_estimadores_no_hace_nada(cacu):
|
||||
(primero, _) = cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
|
||||
(primero, _) = cacu.run("estimate", estimators={URL: EstimadorFijo()})["estimate"][URL]
|
||||
|
||||
assert cacu.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL] == (primero, False)
|
||||
assert cacu.correr("estimar")["estimar"] == {}
|
||||
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.correr("estimar", estimadores={URL: EstimadorFijo()})["estimar"][URL]
|
||||
(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(["confirmar-riesgos", "cacu", str(lote_id), "--motivo", "revisado"])
|
||||
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 confirmar_riesgos("cacu", lote_id, "error de captura", anular=True) == 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
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""What this module covers: the timeline `repositorios_de` wires into `ctx.repos.plata` is dbt's view
|
||||
"""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
|
||||
(`catalogos`, `cargar`, `modelos`; needs `DBT_MANIFEST`); `kit_rows`, the rows the kit's timeline query gave on
|
||||
(`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).
|
||||
"""
|
||||
|
||||
@@ -28,7 +28,7 @@ def proyecto():
|
||||
def loaded(base):
|
||||
if not os.environ.get("DBT_MANIFEST"):
|
||||
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
|
||||
base.correr("catalogos", "cargar", "modelos")
|
||||
base.run("catalogs", "load", "event_models")
|
||||
return base
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ 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.plata.timeline.read(until=CORTE)
|
||||
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)
|
||||
@@ -56,7 +56,7 @@ def test_the_timeline_is_the_kit_s_plus_the_inferred_procedures(loaded, kit_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.plata.timeline.read(patients=patients, until=CORTE)
|
||||
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]
|
||||
|
||||
@@ -64,7 +64,7 @@ def test_the_patient_filter_keeps_only_those_patients(loaded, kit_rows):
|
||||
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.plata.timeline
|
||||
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)
|
||||
|
||||
@@ -47,11 +47,11 @@ def seeded(client):
|
||||
CohorteVariable(armado_id=build.armado_id, pac_id=scored, variable="c", valor_numerico=0.0)])
|
||||
session.commit()
|
||||
build_id = build.armado_id
|
||||
batch, _ = cacu.cohorte_repository.guardar_lote(
|
||||
batch, _ = cacu.cohort_repository.save_batch(
|
||||
build_id, {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "1", "mlflow_run_id": "r", "modelo_sha": "s"},
|
||||
"cin2_12m", [(scored, 3.0, 0.3, None, None), (scored, 1.0, 0.1, None, None)],
|
||||
ahora=datetime(2026, 10, 1, tzinfo=timezone.utc))
|
||||
cacu.cohorte_repository.cambiar_estado(batch, "final", "revisado")
|
||||
cacu.cohort_repository.change_state(batch, "final", "revisado")
|
||||
return scored, unscored, outside
|
||||
|
||||
|
||||
|
||||
@@ -97,15 +97,15 @@ def test_report_endpoints(client):
|
||||
|
||||
|
||||
def test_indicators_recompute_from_imported_rows(client):
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
from webapi.recomputation import RecomputationQueue
|
||||
|
||||
cola = ColaDeRecalculo()
|
||||
cola = RecomputationQueue()
|
||||
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
||||
assert cola.atender() == ["cacu"]
|
||||
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"]} >= {"cargar", "modelos"}
|
||||
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"}
|
||||
|
||||
Reference in New Issue
Block a user