Files
models/tests/pipelines/test_reading_nodes.py
T

186 lines
8.6 KiB
Python

"""What this module covers: the reading nodes of `models.pipelines.reading` (`cohort_build`, `members`, `known_until`, `timeline`)
run by a Hamilton driver built from that module alone, and their place in the asset graph.
Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain
`timeline_events` table; it returns the `CohortRepository` and a `TimelineRepository` bound to
`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and
executes the requested nodes.
"""
import json
from datetime import date, datetime, timezone
import pytest
from core.cacu.base import CaCuModel
from core.cacu.indicadores.models import (
CohorteArmado,
CohorteExclusion,
CohorteMiembro,
CohorteVariable,
EvaluacionRiesgo,
EvaluacionRiesgoLote,
)
from core.indicadores.cohortes import TablasCohorte
from hamilton import driver
from persistance.edges.gold import CohortRepository
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
from persistance.assets import Asset, InvalidGraph, validate
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, create_engine
from models.pipelines import reading
TABLES = TablasCohorte(CohorteArmado, CohorteMiembro, CohorteExclusion, CohorteVariable, EvaluacionRiesgoLote,
EvaluacionRiesgo)
ASSETS = {name: Asset(name) for name in ("cohorte_armado", "cohorte_miembro", "linea_de_tiempo")}
metadata = MetaData()
events = Table(
"timeline_events", metadata,
Column("pac_id", Integer), Column("fecha", Date), Column("conocida_en", DateTime),
Column("clase", String), Column("tipo", String), Column("codigo", String),
Column("valor_codigo", String), Column("valor_numerico", Float),
Column("fuente_tabla", String), Column("fuente_id", String),
)
def _event(pac_id, fecha, conocida_en, fuente_id):
return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "procedimiento",
"tipo": "citologia", "codigo": "citologia_cervical", "valor_codigo": "NORMAL", "valor_numerico": None,
"fuente_tabla": "citologiacervical", "fuente_id": fuente_id}
EVENTS = [
_event(10, date(2025, 2, 1), datetime(2025, 2, 2), "kept-10"),
_event(20, date(2025, 3, 1), datetime(2025, 3, 2), "kept-20"),
_event(10, date(2026, 2, 1), datetime(2026, 1, 1), "after-datos-as-of"),
_event(20, date(2025, 6, 1), datetime(2026, 1, 3), "loaded-after-the-build"),
_event(99, date(2025, 2, 1), datetime(2025, 2, 2), "not-a-member"),
_event(10, date(2025, 4, 1), datetime(2099, 1, 1), "loaded-in-the-future"),
]
def timeline_query(*, patients, until, known_until):
"""Stands in for the kit's query: same columns and filters, over `timeline_events`."""
query = select(*(events.c[name] for name in TIMELINE_COLUMNS)).order_by(events.c.pac_id, events.c.fecha)
if patients is not None:
query = query.where(events.c.pac_id.in_(patients))
if until is not None:
query = query.where(events.c.fecha <= until)
if known_until is not None:
query = query.where(events.c.conocida_en <= known_until.replace(tzinfo=None))
return query
@pytest.fixture
def repositories():
"""Build 1 of `cacu/cohorte_vigilancia`: clinical cut-off 2025-12-31, load cut-off 2026-01-02 08:00
UTC, members 20 and 10 (inserted in that order). Build 2 has no members; build 3 has member 10 and no
load cut-off. `EVENTS` has one event per member inside both cut-offs, one past the clinical cut-off,
one loaded after build 1, one of a patient outside the cohort and one loaded in the future.
"""
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
CaCuModel.metadata.create_all(engine)
metadata.create_all(engine)
load_cut = {1: "2026-01-02T08:00:00+00:00", 2: "2026-01-02T08:00:00+00:00", 3: None}
with Session(engine) as session:
session.add_all([
CohorteArmado(armado_id=armado_id, url="cacu/cohorte_vigilancia", version="0.2.0", definicion_sha="d",
reglas_sha="r", parametros=json.dumps({"corte": "2025-12-31", "conocida_hasta": cut}),
datos_as_of=date(2025, 12, 31), huella=f"h{armado_id}", marco_sha=f"m{armado_id}",
n_miembros=0, armado_en=datetime(2026, 1, 2, 8, tzinfo=timezone.utc))
for armado_id, cut in load_cut.items()
])
session.add_all([
CohorteMiembro(armado_id=armado_id, pac_id=pac_id, fecha_indice=fecha,
indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))
for armado_id, pac_id, fecha in ((1, 20, date(2025, 3, 1)), (1, 10, date(2025, 2, 1)),
(3, 10, date(2025, 2, 1)))
])
session.commit()
session.connection().execute(insert(events), EVENTS)
session.commit()
factory = lambda: Session(engine) # noqa: E731
return CohortRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
def _run(repositories, build_id, nodes=("members", "timeline")):
cohort_repository, timeline_repository = repositories
dr = driver.Builder().with_modules(reading).build()
return dr.execute(list(nodes), inputs={**ASSETS, "cohort_repository": cohort_repository,
"timeline_repository": timeline_repository, "build_id": build_id})
def test_reads_the_members_and_their_timeline_of_a_build(repositories):
"""Pins down: a driver with only the reading nodes returns the build's members ordered by `pac_id`
with `MEMBER_COLUMNS`, and a timeline with `TIMELINE_COLUMNS` holding only the members' events.
Fails if `members` loses its order or columns, or `timeline` stops filtering by the members.
"""
result = _run(repositories, 1)
assert list(result["members"].columns) == list(reading.MEMBER_COLUMNS)
assert result["members"]["pac_id"].tolist() == [10, 20]
assert list(result["timeline"].columns) == list(TIMELINE_COLUMNS)
assert 99 not in result["timeline"]["pac_id"].tolist()
def test_the_timeline_is_cut_where_the_build_was_made(repositories):
"""Pins down: the timeline keeps events up to the build's `datos_as_of` and loaded by its
`conocida_hasta`, so reading it again gives the build's input.
Fails if `timeline` reads with no cut-off, or takes the cut-offs from anywhere but the build.
"""
timeline = _run(repositories, 1)["timeline"]
assert timeline["fuente_id"].tolist() == ["kept-10", "kept-20"]
def test_a_build_without_a_load_cut_off_is_read_up_to_now(repositories):
"""Pins down: when the build has no `conocida_hasta`, `known_until` is the moment of the read (UTC),
never `None`, and the timeline is cut there.
Fails if `known_until` lets `None` through (the read couldn't be repeated) or isn't the one the
timeline used.
"""
before = datetime.now(timezone.utc)
result = _run(repositories, 3, nodes=("known_until", "timeline"))
assert before <= result["known_until"] <= datetime.now(timezone.utc)
assert result["timeline"]["fuente_id"].tolist() == ["kept-10"]
def test_a_build_without_members_reads_an_empty_timeline(repositories):
"""Pins down: a build with no members gives empty frames with their columns, not everyone's timeline.
Fails if an empty member list reaches the query as "no patient filter".
"""
result = _run(repositories, 2)
assert result["members"].empty and list(result["members"].columns) == list(reading.MEMBER_COLUMNS)
assert result["timeline"].empty and list(result["timeline"].columns) == list(TIMELINE_COLUMNS)
def test_an_unknown_build_fails(repositories):
"""Pins down: asking for a build that doesn't exist raises `UnknownBuild` naming it.
Fails if `cohort_build` lets `None` through to the other nodes.
"""
with pytest.raises(reading.UnknownBuild, match="404"):
_run(repositories, 404, nodes=("cohort_build",))
def test_the_assets_read_are_sources_of_the_graph():
"""Pins down: the reading nodes read three assets nobody in `models` produces (`cohorte_armado`,
`cohorte_miembro`, `linea_de_tiempo`), so the graph validates only with them declared as sources.
Fails if a node stops declaring the asset it reads, or reads one more without saying so.
"""
nodes = driver.Builder().with_modules(reading).build().list_available_variables()
with pytest.raises(InvalidGraph) as error:
validate(nodes)
assert len(str(error.value).splitlines()) == 3
validate(nodes, sources=set(ASSETS))