Files
ISSSTELEON/Persistance/tests/test_dbt_repositories.py
T

109 lines
5.6 KiB
Python

"""What this module covers: `persistance.edges.dbt`, reading what dbt owns: the timeline from its view
(`DbtTimelineRepository`) and the queries it compiled (`DbtQueryRepository`).
Fixtures: `database`, an in-memory SQLite database with a table behind a `cacu_linea_de_tiempo` view holding three
events, dates as text as dbt-sqlite leaves them, and a session factory over it.
"""
from datetime import date, datetime, timezone
import pytest
from sqlalchemy import create_engine, text
from sqlalchemy.pool import StaticPool
from sqlmodel import Session
from persistance.edges.dbt import DbtQueryRepository, DbtRelationError, DbtTimelineRepository
from persistance.edges.silver import TIMELINE_COLUMNS
EVENTS = [
(2, "2025-02-01", "2025-06-01T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", None, None, "citologiacervical", "3"),
(1, "2025-03-01", "2025-03-02T00:00:00+00:00", "medicion", "biopsia", "cin", "LIEAG", None, "biopsiacervical", "7"),
(1, "2025-01-05", "2025-01-06T00:00:00+00:00", "procedimiento", "citologia", "citologia_cervical", "SATISFACTORIA", None, "citologiacervical", "1"),
]
@pytest.fixture
def database():
"""The view over a plain table, and a session factory on the same in-memory connection."""
engine = create_engine("sqlite://", poolclass=StaticPool, connect_args={"check_same_thread": False})
with engine.begin() as connection:
connection.execute(text(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})"))
connection.execute(text("create view cacu_linea_de_tiempo as select * from eventos"))
for row in EVENTS:
connection.execute(text(f"insert into eventos values ({', '.join(':c%d' % i for i in range(10))})"),
{f"c{i}": value for i, value in enumerate(row)})
return engine, lambda: Session(engine)
def test_timeline_comes_from_the_view_in_order_with_dates(database):
"""Pins down: every event of the view, with the column contract, ordered by patient and date, and `fecha` as a
date although SQLite stores text. Fails if the view's name, the order or the date type changes."""
_, session_factory = database
rows = DbtTimelineRepository(session_factory, "cacu").read()
assert [(row["pac_id"], row["fuente_id"]) for row in rows] == [(1, "1"), (1, "7"), (2, "3")]
assert tuple(rows[0]) == TIMELINE_COLUMNS and rows[0]["fecha"] == date(2025, 1, 5)
def test_filters_run_in_the_query(database):
"""Pins down: `patients`, `until` and `known_until` each narrow the rows, the last as an aware datetime against the
load times as stored. Fails if a filter is ignored or the load time is compared as text."""
_, session_factory = database
repository = DbtTimelineRepository(session_factory, "cacu")
assert {row["pac_id"] for row in repository.read(patients=[2])} == {2}
assert [row["fuente_id"] for row in repository.read(until=date(2025, 2, 1))] == ["1", "3"]
assert [row["fuente_id"] for row in repository.read(known_until=datetime(2025, 3, 1, tzinfo=timezone.utc))] == ["1"]
def test_a_missing_view_names_the_dbt_command(database):
"""Pins down: reading a domain whose view isn't created says which `dbt run` creates it. Fails if the driver's
error reaches the caller unexplained."""
_, session_factory = database
with pytest.raises(DbtRelationError, match="dbt run --select cama_linea_de_tiempo"):
DbtTimelineRepository(session_factory, "cama").read()
def test_a_compiled_query_gives_one_dict_per_row(database):
"""Pins down: a query dbt compiled runs as written and returns its own columns. Fails if the rows lose their
column names or the query is altered."""
_, session_factory = database
rows = DbtQueryRepository(session_factory).read(
"with b as (select pac_id from cacu_linea_de_tiempo where tipo = 'biopsia') select distinct pac_id from b")
assert rows == [{"pac_id": 1}]
def test_a_query_compiled_with_placeholders_takes_its_values_and_lists(database):
"""Pins down: a query compiled with bind placeholders runs with the values given, a list filling `in :name`, so
one compiled query serves every period. Fails if `parameters` stops being bound or lists stop expanding."""
_, session_factory = database
rows = DbtQueryRepository(session_factory).read(
"select pac_id, fecha from cacu_linea_de_tiempo where fecha >= :desde and tipo in :tipos order by fecha",
{"desde": "2025-02-01", "tipos": ["citologia", "biopsia"]})
assert rows == [{"pac_id": 2, "fecha": "2025-02-01"}, {"pac_id": 1, "fecha": "2025-03-01"}]
def test_an_empty_result_keeps_its_columns(database):
"""Pins down: a query with no rows still says which columns it selects, so whoever reads it can count zero.
Fails if `rows` builds the column names from the rows."""
_, session_factory = database
columns, rows = DbtQueryRepository(session_factory).rows(
"select pac_id, tipo from cacu_linea_de_tiempo where fecha > :hasta", {"hasta": "2030-01-01"})
assert (columns, rows) == (["pac_id", "tipo"], [])
def test_reading_writes_nothing(database):
"""Pins down: both repositories read on a read-only session and leave the database as it was. Fails if a read
starts committing or creating objects."""
engine, session_factory = database
DbtTimelineRepository(session_factory, "cacu").read()
DbtQueryRepository(session_factory).read("select count(*) as n from cacu_linea_de_tiempo")
with engine.connect() as connection:
names = connection.execute(text("select name from sqlite_master order by name")).fetchall()
assert names == [("cacu_linea_de_tiempo",), ("eventos",)]