Files
WebApi/tests/test_cama_follow_up.py
T

422 lines
25 KiB
Python

"""What this module covers: CaMa's follow-up list and its file (`webapi.cama_follow_up`): who is in the BI-RADS cohort
at a cut-off, the window and filters, suppression of small selections, pages, revision and request validation.
Fixtures: `app`, a Flask app with only the follow-up blueprint over a CaMa database loaded from `insertar` through the
cycle up to `event_models` (needs `DBT_MANIFEST`: the cohort view comes from dbt's manifest). `insertar` writes 17
invented patients with the cases below; their names (`P01`...) are the source ids. Nothing here touches real data.
Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6):
BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day.
P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it.
No patient has a post-treatment fact in her timeline, so everyone is under observation; `con_postratamiento` adds some.
"""
import json
import os
import re
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import pytest
from core.cama.models import BiopsiaMama, Mastografia, Paciente
from flask import Flask
from sqlmodel import Session, select
from conftest import base_de
from webapi.cama_follow_up import cohort, listing
from webapi.cama_follow_up.routes import follow_up_blueprint
UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models")
CORTE = "2025-12-31"
D = date
# patient -> (birth date, [(mammogram date, BI-RADS, report date or None)])
PACIENTES = {
"P01": (D(1960, 5, 5), [(D(2025, 12, 1), "B5", D(2025, 12, 8))]),
"P02": (D(1975, 1, 1), [(D(2025, 11, 20), "B5", D(2025, 11, 27))]),
"P03": (D(1975, 1, 1), [(D(2025, 11, 5), "B5", D(2025, 11, 12))]),
"P04": (D(1976, 1, 1), [(D(2025, 10, 10), "B5", D(2025, 10, 17))]),
"P05": (D(1980, 3, 3), [(D(2025, 9, 1), "B5", D(2025, 9, 8))]),
"P06": (D(1950, 1, 1), [(D(2025, 8, 15), "B5", D(2025, 8, 22))]),
"P07": (D(1975, 1, 1), [(D(2025, 12, 10), "B4A", D(2025, 12, 17))]),
"P08": (D(1975, 1, 1), [(D(2025, 12, 2), "B4A", D(2025, 12, 9))]),
"P09": (D(1965, 6, 6), [(D(2025, 11, 1), "B4A", D(2025, 11, 8))]),
"P10": (D(1965, 6, 6), [(D(2025, 10, 1), "B4A", D(2025, 10, 8))]),
"P11": (D(1965, 6, 6), [(D(2025, 7, 1), "B4A", D(2025, 7, 8))]),
"P12": (D(1985, 1, 1), [(D(2025, 12, 15), "B6", D(2025, 12, 22))]),
"P13": (D(1985, 1, 1), [(D(2025, 6, 1), "B6", D(2025, 6, 8))]),
"P14": (D(1975, 1, 1), [(D(2025, 12, 20), "B4", D(2025, 12, 27))]),
"P15": (D(1975, 1, 1), [(D(2025, 6, 1), "B5", D(2025, 6, 8)), (D(2025, 12, 5), "B2", D(2025, 12, 12))]),
"P16": (D(1975, 1, 1), [(D(2025, 5, 1), "B1", D(2025, 5, 8)), (D(2025, 12, 20), "B5", D(2026, 1, 5))]),
"P17": (D(1975, 1, 1), [(D(2025, 12, 12), "B4A", D(2025, 12, 19)), (D(2025, 12, 12), "B5", D(2025, 12, 19))]),
}
# (patient, index of its mammogram, request date, report date, grade)
BIOPSIAS = (
("P01", 0, D(2025, 12, 5), D(2025, 12, 20), "CARCINOMA_INVASOR"),
("P02", 0, D(2025, 12, 1), D(2026, 1, 10), "CARCINOMA_IN_SITU"), # reported after the cut-off
("P04", 0, D(2025, 10, 15), D(2025, 10, 30), "BENIGNO"),
("P05", 0, D(2025, 9, 10), D(2025, 9, 25), None), # a report without a grade
("P06", 0, D(2025, 9, 1), D(2025, 9, 10), "BENIGNO"), # two biopsies of one mammogram: the later report is shown
("P06", 0, D(2025, 10, 1), D(2025, 10, 20), "CARCINOMA_IN_SITU"),
)
EN_COHORTE = {f"P{n:02d}" for n in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17)}
def insertar(sesion: Session) -> None:
pacientes = {h: Paciente(pac_id_hospital=h, pac_sexo="Femenino", pac_fecha_nacimiento=n)
for h, (n, _) in PACIENTES.items()}
sesion.add_all(pacientes.values())
sesion.flush()
mastografias: dict[tuple[str, int], Mastografia] = {}
for hospital, (_, tomas) in PACIENTES.items():
for indice, (toma, birads, reporte) in enumerate(tomas):
mastografias[hospital, indice] = Mastografia(
pac_id=pacientes[hospital].pac_id, pac_id_hospital=hospital, mast_fecha_toma=toma,
mast_calidad_imagen="SATISFACTORIO", mast_birads=birads, mast_fecha_reporte=reporte)
sesion.add_all(mastografias.values())
sesion.flush()
for hospital, indice, solicitud, reporte, grado in BIOPSIAS:
m = mastografias[hospital, indice]
sesion.add(BiopsiaMama(pac_id=m.pac_id, pac_id_hospital=hospital, mast_id=m.mast_id, bx_fecha_solicitud=solicitud,
bx_fecha_reporte=reporte, bx_grado_histologico=grado))
sesion.commit()
@pytest.fixture(scope="module")
def base(tmp_path_factory):
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
base = base_de("cama", tmp_path_factory.mktemp("cama"), datos=insertar)
base.run(*UNTIL_MODELS, allow_undecided=True)
yield base
base.motor.dispose()
@pytest.fixture
def app(base):
flask = Flask(__name__)
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
return flask.test_client()
def get(app, ruta="/cama/seguimiento", **params):
return app.get(ruta, query_string={"corte": CORTE, "meses": 0, **params})
def pacs(respuesta) -> list[str]:
return [i["pac_id"] for i in respuesta.get_json()["items"]]
def hospital_de(base) -> dict[str, str]:
"""pac_id (text) -> the source id, to translate the invented names back."""
with Session(base.motor) as sesion:
return {str(p.pac_id): p.pac_id_hospital for p in sesion.exec(select(Paciente))}
def test_the_cohort_holds_each_patient_once_through_her_latest_reported_mammogram(base, app):
"""Pins down: the cohort at 2025-12-31 is exactly the patients whose latest mammogram reported by then is BI-RADS
4 to 6, once each: P15's latest is a 2 and P16's 5 is reported after the cut-off. Fails if a patient is listed twice,
if an earlier BI-RADS 5 outlives a later 2, or if a report after the cut-off counts."""
cuerpo = get(app, page_size=200).get_json()
nombres = hospital_de(base)
assert {nombres[p] for p in pacs(get(app, page_size=200))} == EN_COHORTE
assert len(pacs(get(app, page_size=200))) == len(set(pacs(get(app, page_size=200)))) == 15
assert cuerpo["paginacion"]["total_items"] == 15
def test_the_same_data_gives_the_same_cohort_and_a_later_cutoff_adds_what_was_reported(base, app):
"""Pins down: asking twice gives the same rows in the same order, including P17 (two mammograms the same day, one
row), and a cut-off after P16's report brings its BI-RADS 5 in. Fails if the choice depends on row order, or if the
cut-off doesn't move the cohort."""
primero, segundo = get(app, page_size=200).get_json(), get(app, page_size=200).get_json()
assert primero["items"] == segundo["items"]
nombres = hospital_de(base)
despues = get(app, corte="2026-01-31", page_size=200)
assert "P16" in {nombres[p] for p in pacs(despues)}
assert [i["birads"] for i in despues.get_json()["items"] if nombres[i["pac_id"]] == "P16"] == ["BIRADS_5"]
def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app):
"""Pins down: P01's invasive carcinoma shows with its report date; P02's biopsy, reported in 2026, doesn't exist at
2025-12-31 and does at 2026-01-31; P05's report without a grade shows its date and no result. Fails if a later
biopsy leaks into an earlier cut-off or a gradeless report is read as no biopsy."""
nombres = hospital_de(base)
en = lambda r: {nombres[i["pac_id"]]: i for i in r.get_json()["items"]}
antes, despues = en(get(app, page_size=200)), en(get(app, corte="2026-01-31", page_size=200))
assert (antes["P01"]["biopsia"], antes["P01"]["biopsia_fecha"]) == ("CARCINOMA_INVASOR", "2025-12-20")
assert (antes["P02"]["biopsia"], antes["P02"]["biopsia_fecha"]) == (None, None)
assert (despues["P02"]["biopsia"], despues["P02"]["biopsia_fecha"]) == ("CARCINOMA_IN_SITU", "2026-01-10")
assert (antes["P05"]["biopsia"], antes["P05"]["biopsia_fecha"]) == (None, "2025-09-25")
assert (antes["P06"]["biopsia"], antes["P06"]["biopsia_fecha"]) == ("CARCINOMA_IN_SITU", "2025-10-20")
def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app):
"""Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its
date, and the clinical scenario: no status, priority, days or pseudonym, and no source id anywhere in the body.
Fails if a column the data doesn't support is added, or the hospital's identifier leaks."""
respuesta = get(app, page_size=200)
cuerpo = respuesta.get_json()
assert cuerpo["simulado"] is True
assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha",
"escenario_clinico"} for i in cuerpo["items"])
assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"}
assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"])
assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"]
assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES)
assert respuesta.headers["Cache-Control"] == "no-store"
def test_age_groups_come_from_the_platform_parameter_at_the_cutoff(base, app):
"""Pins down: groups are `cama.grupos_edad` (`<40`, `40-49`, `50-59`, `60-69`, `70+`); a patient born on 1976-01-01 is
still 49 on 2025-12-31 and turns 50 the next day; a missing or later birth date is `SIN_DATO`. Fails if the age is
counted in years of birth or the groups are written in the code."""
nombres = hospital_de(base)
edad = lambda c: {nombres[i["pac_id"]]: i["grupo_edad"] for i in get(app, corte=c, page_size=200).get_json()["items"]}
assert edad(CORTE)["P04"] == "40-49" and edad(CORTE)["P01"] == "60-69" and edad(CORTE)["P06"] == "70+"
assert edad("2026-01-31")["P04"] == "50-59"
grupos = listing.grupos_de_edad(Session(base.motor))
assert grupos == ["<40", "40-49", "50-59", "60-69", "70+"]
assert cohort.grupo_de_edad(None, D(2025, 1, 1), []) == cohort.SIN_DATO
assert cohort.grupo_de_edad(D(2026, 1, 1), D(2025, 1, 1), []) == cohort.SIN_DATO
def test_filters_combine_with_and_and_the_window_follows_the_mammogram_date(base, app):
"""Pins down: BI-RADS 5 selects six patients; adding the biopsy filter narrows with AND (a group of fewer than five
is then refused); a one-month window keeps the mammograms of December. Fails if filters are ORed or the window
reads another date."""
# P01-P06 and, when it wins the tie of its two mammograms, P17.
assert len(pacs(get(app, birads="BIRADS_5", page_size=200))) in (6, 7)
assert len(pacs(get(app, birads="BIRADS_4A", page_size=200))) in (5, 6)
assert get(app, birads="BIRADS_5", biopsia="BENIGNO").status_code == 403
un_mes = get(app, meses=1, page_size=200)
assert un_mes.status_code == 200
assert {i["mastografia_fecha"][:7] for i in un_mes.get_json()["items"]} == {"2025-12"}
assert un_mes.get_json()["ventana"] == {"meses": 1, "desde": "2025-12-01", "hasta": CORTE}
def test_a_selection_of_fewer_than_five_is_never_served_by_any_route(base, app):
"""Pins down: groups of 1 to 4 (BI-RADS 6, BI-RADS 4 without subcategory, a rare combination) and filtered
selections of none get 403 with the reason `supresion`, on the list and on the file alike. Fails if a filter or a
window combination isolates a small group, or the file skips the rule the list applies."""
for ruta in ("/cama/seguimiento", "/cama/seguimiento/exportacion"):
for filtros in ({"birads": "BIRADS_6"}, {"birads": "BIRADS_4"}, {"birads": "BIRADS_5", "biopsia": "SIN_DATO"},
{"grupo_edad": "<40"}):
respuesta = get(app, ruta, **filtros)
assert respuesta.status_code == 403, (ruta, filtros)
assert respuesta.get_json()["motivo"] == "supresion"
assert get(app, meses=1, birads="BIRADS_5").status_code == 403 # a window is a filter too
def test_the_whole_cohort_is_refused_when_it_has_one_to_four_patients_and_is_empty_when_it_has_none(base, app):
"""Pins down: the only selection that may be empty is the whole cohort with no window and no filter; with two
patients it is refused. Fails if a small whole cohort is published or an empty one is an error."""
assert get(app, corte="2025-06-20").status_code == 403
vacia = get(app, corte="2025-01-01")
assert vacia.status_code == 200 and vacia.get_json()["items"] == []
assert vacia.get_json()["paginacion"] == {"page": 1, "page_size": 50, "total_items": 0, "total_pages": 0}
assert vacia.get_json()["ventana"]["desde"] == "2025-01-01"
def test_pages_are_stable_and_a_page_past_the_last_is_a_404(base, app):
"""Pins down: three pages of six give 15 rows in the same order as one big page, newest mammogram first and `pac_id`
after; page 4 is 404. Fails if pages overlap or reorder, or a page beyond the end answers 200."""
todo = pacs(get(app, page_size=200))
paginas = [pacs(get(app, page_size=6, page=n)) for n in (1, 2, 3)]
assert [p for pagina in paginas for p in pagina] == todo
assert [len(p) for p in paginas] == [6, 6, 3]
assert get(app, page_size=6, page=4).status_code == 404
fechas = [i["mastografia_fecha"] for i in get(app, page_size=200).get_json()["items"]]
assert fechas == sorted(fechas, reverse=True)
def test_the_file_has_the_rows_of_the_pages_and_a_size_limit(base, app, monkeypatch):
"""Pins down: `/seguimiento/exportacion` returns every row of the selection with the list's header; it is refused
over `EXPORTACION_MAXIMA` (413). Fails if the file and the list disagree about who is selected."""
archivo = get(app, "/cama/seguimiento/exportacion").get_json()
assert [i["pac_id"] for i in archivo["items"]] == pacs(get(app, page_size=200)) and archivo["total_items"] == 15
assert archivo["revision"] == get(app).get_json()["revision"]
monkeypatch.setattr(listing, "EXPORTACION_MAXIMA", 3)
assert get(app, "/cama/seguimiento/exportacion").status_code == 413
def test_the_revision_names_cohort_version_data_and_cutoff(base, app):
"""Pins down: quoting the revision read opens the same list; another cut-off, a new load of data and another
cohort give another revision, and a stale one is a 409. Fails if the revision ignores a part, or a client can read a
list under a revision that isn't the server's."""
cuerpo = get(app).get_json()
contexto = {k: cuerpo[k] for k in ("cohorte", "escenario", "revision")}
assert re.fullmatch(r"[0-9a-f]{64}", cuerpo["revision"])
assert get(app, **contexto).status_code == 200
otro_corte = get(app, corte="2026-01-31").get_json()["revision"]
assert otro_corte != cuerpo["revision"]
assert get(app, **{**contexto, "revision": otro_corte}).status_code == 409
assert get(app, **{**contexto, "cohorte": "otra"}).status_code == 409
assert get(app, **{**contexto, "escenario": "otro"}).status_code == 409
assert get(app, **{**contexto, "revision": ""}).status_code == 400
assert get(app, cohorte=contexto["cohorte"]).status_code == 400 # the three go together
def test_new_loaded_rows_change_the_revision_and_a_load_without_changes_does_not(base, app):
"""Pins down: a load that added rows gives the cohort a new build and so a new revision; a load that added or changed
none (a recalculation) leaves it. Fails if every cycle invalidates the clients' pages, or new data goes unnoticed."""
from webapi.orchestration.tables.cama import TABLAS
antes = get(app).get_json()["revision"]
with Session(base.motor) as sesion:
sesion.add(TABLAS.Carga(fuente="mastografia", inicio=datetime(2026, 1, 1, tzinfo=timezone.utc), filas_nuevas=0, filas_cambiadas=0, filas_sin_cambio=9))
sesion.commit()
assert get(app).get_json()["revision"] == antes
sesion.add(TABLAS.Carga(fuente="mastografia", inicio=datetime(2026, 1, 2, tzinfo=timezone.utc), filas_nuevas=1))
sesion.commit()
assert get(app).get_json()["revision"] != antes
@pytest.mark.parametrize("params", [
{"corte": "31/12/2025"}, {"corte": "2025-02-30"}, {"corte": "2999-01-01"}, {"meses": 2}, {"meses": "x"},
{"page": 0}, {"page_size": 201}, {"birads": "BIRADS_9"}, {"grupo_edad": "20-29"}, {"biopsia": "MALIGNO"},
{"estatus": "ALTA"}, {"prioridad": "ALTA"}, {"birads": ""},
])
def test_a_badly_written_request_is_a_400_before_anything_is_counted(app, params):
"""Pins down: a malformed date, a future one, a window or page out of range, an unknown parameter (the retired
status and priority included) or filter value is a 400, never a small-group 403. Fails if validation moves after
the selection."""
assert get(app, **params).status_code == 400
def test_a_repeated_parameter_is_a_400(app):
"""Pins down: `birads` twice is refused, so a request can't hide a filter. Fails if the first or last one is taken."""
assert app.get("/cama/seguimiento?corte=2025-12-31&meses=0&birads=BIRADS_5&birads=BIRADS_6").status_code == 400
def test_the_defaults_are_today_and_a_three_month_window(app):
"""Pins down: without `corte` the cut-off is today and without `meses` the window is three months; none of the
invented 2025 mammograms is that recent, so the window selects nobody and is refused. Fails if the defaults change."""
respuesta = app.get("/cama/seguimiento")
assert respuesta.status_code == 403 and respuesta.get_json()["motivo"] == "supresion"
assert json.loads(get(app).get_data())["ventana"]["meses"] == 0
assert date.today() - timedelta(days=1) > D(2025, 12, 31)
def test_without_the_cohort_view_the_answer_is_an_informative_503(tmp_path):
"""Pins down: a database whose indicator cycle hasn't created the event views answers 503 with the reason `cohorte`
on both routes, not a server error. Fails if a missing view surfaces as a 500 or an empty list."""
sin_ciclo = base_de("cama", tmp_path, datos=insertar)
try:
flask = Flask(__name__)
flask.register_blueprint(follow_up_blueprint(lambda: Session(sin_ciclo.motor)), url_prefix="/cama")
cliente = flask.test_client()
for ruta in ("/cama/seguimiento", "/cama/seguimiento/exportacion"):
respuesta = cliente.get(ruta, query_string={"corte": CORTE, "meses": 0})
assert respuesta.status_code == 503 and respuesta.get_json()["motivo"] == "cohorte"
finally:
sin_ciclo.motor.dispose()
@pytest.fixture
def con_vista_a_mano(tmp_path):
"""A CaMa database with the platform's parameters and the cohort's candidates written by hand: the view is replaced by
a table, so a test can hold the contradictory duplicates that staging can't produce."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
base = base_de("cama", tmp_path, datos=lambda sesion: None)
base.run(*UNTIL_MODELS, allow_undecided=True)
from sqlalchemy import text
def escribir(filas):
with base.motor.begin() as c:
c.execute(text("drop view cama_cohorte_birads"))
c.execute(text("create table cama_cohorte_birads (pac_id integer, procedimiento_id integer, fuente_id text, fecha_toma date, "
"reporte_id integer, fecha_reporte date, birads text, fecha_nacimiento date, biopsia_id integer, "
"biopsia_fuente_id text, biopsia_fecha_reporte date, biopsia_grado text)"))
for fila in filas:
c.execute(text("insert into cama_cohorte_birads values (:pac_id, :procedimiento_id, :fuente_id, :fecha_toma, :reporte_id, "
":fecha_reporte, :birads, :fecha_nacimiento, :biopsia_id, :biopsia_fuente_id, :biopsia_fecha_reporte, :biopsia_grado)"),
{"biopsia_id": None, "biopsia_fuente_id": None, "biopsia_fecha_reporte": None, "biopsia_grado": None, **fila})
yield base, escribir
base.motor.dispose()
MAMOGRAFIA = {"pac_id": 1, "procedimiento_id": 10, "fuente_id": "10", "fecha_toma": "2025-11-01", "reporte_id": 11,
"fecha_reporte": "2025-11-08", "fecha_nacimiento": "1970-01-01"}
@pytest.mark.parametrize("orden", [1, -1])
def test_contradictory_duplicates_resolve_the_same_way_whatever_the_row_order(con_vista_a_mano, orden):
"""Pins down: one report with two different BI-RADS (4A and 5) counts as the more severe, a biopsy report with two
grades on the same date shows the more severe, identical rows repeated by a join count once, and the answer doesn't
depend on the order the rows come in. Fails if the first row read wins, a patient appears twice, or the choice
changes with the order."""
base, escribir = con_vista_a_mano
filas = [
{**MAMOGRAFIA, "birads": "B4A", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "BENIGNO"},
{**MAMOGRAFIA, "birads": "B5", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "CARCINOMA_INVASOR"},
{**MAMOGRAFIA, "birads": "B5", "biopsia_id": 20, "biopsia_fuente_id": "20", "biopsia_fecha_reporte": "2025-11-20", "biopsia_grado": "CARCINOMA_INVASOR"},
]
escribir(filas[::orden])
with Session(base.motor) as sesion:
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
assert len(cohorte_) == 1
assert (cohorte_[0].birads, cohorte_[0].biopsia) == ("BIRADS_5", "CARCINOMA_INVASOR")
def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_stay_two(con_vista_a_mano):
"""Pins down: a mammogram with two reports counts through the later report; two patients stay two rows. Fails if both
reports become two rows of one patient."""
base, escribir = con_vista_a_mano
escribir([
{**MAMOGRAFIA, "birads": "B4A", "reporte_id": 11, "fecha_reporte": "2025-11-08"},
{**MAMOGRAFIA, "birads": "B5", "reporte_id": 12, "fecha_reporte": "2025-11-15"},
{**MAMOGRAFIA, "pac_id": 2, "procedimiento_id": 30, "fuente_id": "30", "reporte_id": 31, "birads": "B6"},
])
with Session(base.motor) as sesion:
cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31))
assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")]
@pytest.fixture
def con_postratamiento(tmp_path):
"""The same 17 patients, with the timeline replaced by a table holding post-treatment facts: P01 to P05 on
2025-11-01 and P06 on 2026-01-15, after the cut-off."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
from sqlalchemy import text
base = base_de("cama", tmp_path, datos=insertar)
base.run(*UNTIL_MODELS, allow_undecided=True)
hechos = {**{f"P0{n}": "2025-11-01" for n in range(1, 6)}, "P06": "2026-01-15"}
with base.motor.begin() as c:
for drop in ("drop view cama_linea_de_tiempo", "drop table cama_linea_de_tiempo"):
try:
with c.begin_nested():
c.execute(text(drop))
except Exception:
pass
c.execute(text("create table cama_linea_de_tiempo (pac_id integer, tipo text, fecha date)"))
for hospital, fecha in hechos.items():
c.execute(text("insert into cama_linea_de_tiempo select pac_id, 'escenario_postratamiento', :f from paciente "
"where pac_id_hospital = :h"), {"f": fecha, "h": hospital})
flask = Flask(__name__)
flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama")
yield base, flask.test_client()
base.motor.dispose()
def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observation_otherwise(con_postratamiento):
"""Pins down: a patient is `POST_TRATAMIENTO` once her timeline's `escenario_postratamiento` fact is on or before the
cut-off (P01-P05 at 2025-12-31, P06 only from 2026-01-15) and `EN_OBSERVACION` otherwise; the filter selects by it
and offers both values with their labels. Fails if a fact after the cut-off counts, if the scenario is read from
something other than the timeline, or if the filter stops being offered."""
base, app = con_postratamiento
nombres = hospital_de(base)
escenario = lambda corte: {nombres[i["pac_id"]]: i["escenario_clinico"]
for i in get(app, corte=corte, page_size=200).get_json()["items"]}
al_corte = escenario(CORTE)
assert {h for h, e in al_corte.items() if e == "POST_TRATAMIENTO"} == {"P01", "P02", "P03", "P04", "P05"}
assert {e for h, e in al_corte.items() if h not in {"P01", "P02", "P03", "P04", "P05"}} == {"EN_OBSERVACION"}
assert escenario("2026-01-31")["P06"] == "POST_TRATAMIENTO"
filtrada = get(app, escenario_clinico="POST_TRATAMIENTO", page_size=200)
assert {nombres[p] for p in pacs(filtrada)} == {"P01", "P02", "P03", "P04", "P05"}
filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico")
assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"},
{"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}]