Files
models/tests/test_export_cohort.py
T

185 lines
8.9 KiB
Python

"""What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file
goes, what it holds, that it's written once, and that the timeline is read from dbt's view without changing the database.
Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build
cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and
one of a patient outside the build; `timeline_db`, a SQLite file with a `cacu_linea_de_tiempo` view and its repository.
"""
import importlib.util
import sqlite3
from datetime import date, datetime, timezone
from pathlib import Path
import pyarrow.parquet as pq
import pytest
from persistance.aristas.oro import CohortBuild, CohortMember
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from sqlmodel import Session, create_engine
ROOT = Path(__file__).resolve().parents[1]
MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"),
CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")]
@pytest.fixture
def script():
"""The script as a module."""
spec = importlib.util.spec_from_file_location("export_cohort", ROOT / "scripts" / "export_cohort.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _build(armado_id=1, known_until=None, n_miembros=2):
return CohortBuild(armado_id, "cacu/cohorte_vigilancia", "1.0", "huella", "marco", date(2025, 12, 31), known_until,
n_miembros, datetime(2026, 1, 1, tzinfo=timezone.utc))
@pytest.fixture
def build():
"""A build with a clinical cut-off and a load cut-off."""
return _build(known_until=datetime(2026, 1, 2, 8, tzinfo=timezone.utc))
def _event(pac_id, fecha, conocida_en, fuente_id):
return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "medicion", "tipo": "bethesda",
"codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "citologiacervical",
"fuente_id": fuente_id}
@pytest.fixture
def events():
"""Dates as text, as SQLite returns them from a subquery."""
return [_event(20, "2025-03-01", "2025-03-02 10:00:00", "kept-20"),
_event(10, "2025-02-01", "2025-02-02 10:00:00.5", "kept-10"),
_event(10, "2026-02-01", "2026-01-01 00:00:00", "after-datos-as-of"),
_event(20, "2025-06-01", "2026-01-03 00:00:00", "loaded-after-the-build"),
_event(99, "2025-02-01", "2025-02-02 00:00:00", "not-a-member")]
def test_table_keeps_members_within_both_cut_offs_in_the_file_order(script, build, events):
"""Pins down: only members' events, up to `datos_as_of` and loaded by `conocida_hasta`, ordered by patient, each
with its index date. Fails if a cut-off or the join with the members is lost, or the rows aren't sorted."""
table = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}')
assert table.column("fuente_id").to_pylist() == ["kept-10", "kept-20"]
assert table.column("fecha_indice").to_pylist() == [date(2025, 1, 1), date(2025, 2, 1)]
assert table.schema.names == script.SCHEMA.names
def test_table_carries_the_lineage(script, build, events):
"""Pins down: the file explains itself: the build's identity and cut-offs are in its metadata. Fails if a key
a reader relies on is dropped or renamed."""
metadata = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}').schema.metadata
lineage = {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
assert lineage["armado_id"] == "1" and lineage["url"] == build.url and lineage["n_members"] == "2"
assert lineage["domain"] == "cacu" and lineage["producer"] == "kit" and lineage["datos_as_of"] == "2025-12-31"
assert lineage["parametros"] == '{"corte": "2025-12-31"}'
def test_a_member_without_events_is_refused(script, build, events):
"""Pins down: every member has at least one row, so a timeline that lost someone stops the export. Fails if the
file is written with fewer members than the build."""
with pytest.raises(ValueError, match="1 members"):
script.build_table([e for e in events if e["pac_id"] != 20], MEMBERS, build, domain="cacu", parametros=None)
def test_file_is_written_once(script, build, events, tmp_path):
"""Pins down: a second run reuses the file without rebuilding it. Fails if `ensure` calls `make_table` again."""
calls = []
def make_table():
calls.append(1)
return script.build_table(events, MEMBERS, build, domain="cacu", parametros=None)
path, first = script.ensure(build, tmp_path, make_table)
_, second = script.ensure(build, tmp_path, make_table)
assert path == tmp_path / "cacu" / "cohorte_vigilancia" / "1.parquet"
assert (first, second, len(calls)) == ("exported", "reused", 1)
assert pq.read_metadata(path).num_rows == 2
def test_file_of_another_build_is_refused(script, build, events, tmp_path):
"""Pins down: a file whose lineage names another build isn't reused. Fails if `ensure` trusts the path alone."""
other = tmp_path / "cacu" / "cohorte_vigilancia"
other.mkdir(parents=True)
pq.write_table(script.build_table(events, MEMBERS, _build(armado_id=7), domain="cacu", parametros=None), other / "1.parquet")
with pytest.raises(ValueError, match="doesn't belong"):
script.ensure(build, tmp_path, lambda: pytest.fail("must not export"))
def test_failed_export_leaves_no_file(script, build, events, tmp_path, monkeypatch):
"""Pins down: when the last step of the write fails, neither the file nor the temporary one stays behind, so a
later run can't take a partial file as the build's. Fails if `write_once` stops removing the temporary file."""
table = script.build_table(events, MEMBERS, build, domain="cacu", parametros=None)
def fail(*_):
raise OSError("disk full")
monkeypatch.setattr(Path, "replace", fail)
with pytest.raises(OSError, match="disk full"):
script.write_once(table, tmp_path / "cacu" / "1.parquet")
assert not list((tmp_path / "cacu").iterdir())
@pytest.mark.parametrize("url", ["sqlite:////data/cacu.db", "sqlite:///file:/data/cacu.db?immutable=1&uri=true"])
def test_files_live_next_to_the_database(script, monkeypatch, url):
"""Pins down: `cohorts/` next to the SQLite file, in both URL forms. Fails if a read-only URL's `file:` prefix
ends up in the path."""
monkeypatch.delenv("COHORTS_DIR", raising=False)
assert script.cohorts_root(url) == Path("/data/cohorts")
def test_cohorts_dir_replaces_the_folder(script, monkeypatch):
"""Pins down: `COHORTS_DIR` wins, for read-only data folders and server engines. Fails if it's ignored."""
monkeypatch.setenv("COHORTS_DIR", "/writable")
assert script.cohorts_root("mysql://host/cacu") == Path("/writable")
def test_server_engine_needs_cohorts_dir(script, monkeypatch):
"""Pins down: a server database has no data folder, so the script says what to set. Fails if it guesses a path."""
monkeypatch.delenv("COHORTS_DIR", raising=False)
with pytest.raises(ValueError, match="COHORTS_DIR"):
script.cohorts_root("mysql://host/cacu")
@pytest.fixture
def timeline_db(tmp_path):
"""A SQLite file with one event behind a `cacu_linea_de_tiempo` view, and a repository over it."""
path = tmp_path / "cacu.db"
connection = sqlite3.connect(path)
connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})")
connection.execute("create view cacu_linea_de_tiempo as select * from eventos")
connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a', null, 't', '1')")
connection.commit()
connection.close()
engine = create_engine(f"sqlite:///{path}")
return path, TimelineRepository(lambda: Session(engine))
def test_read_timeline_reads_the_view_and_changes_nothing(script, timeline_db):
"""Pins down: the rows come from the domain's view, with the column contract, and the read adds no object. Fails
if the script reads another relation, or starts creating objects in the database."""
path, repository = timeline_db
rows = script.read_timeline(repository, "cacu")
assert [(row["pac_id"], row["valor_codigo"]) for row in rows] == [(10, "a")]
connection = sqlite3.connect(path)
assert connection.execute("select name from sqlite_master order by name").fetchall() == [("cacu_linea_de_tiempo",), ("eventos",)]
connection.close()
def test_missing_view_says_how_to_create_it(script, timeline_db):
"""Pins down: without the view the error names the dbt command to run. Fails if the driver's error reaches the
user unexplained, or if the message stops naming the domain's model."""
_, repository = timeline_db
with pytest.raises(script.TimelineViewError, match="dbt run --select cama_linea_de_tiempo"):
script.read_timeline(repository, "cama")