Integrate CaMa follow-up, descriptive analysis and L3 with dev

Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
This commit is contained in:
Angel Capetillo Zavala
2026-11-17 10:44:07 -06:00
parent 0571b5e6af
commit b1bbbc25b4
27 changed files with 2729 additions and 12 deletions
+258
View File
@@ -0,0 +1,258 @@
"""What this module covers: the routes of CaMa's descriptive analysis (`/cama/analisis`) over the same invented CaMa database
as the follow-up list: contract, selection and suppression shared with the list, consistency between the endpoints,
states without data, validation and the trend by period.
Fixtures: `base` and `app`, a CaMa database loaded from `test_cama_follow_up.insertar` (17 invented patients, 15 in the
BI-RADS cohort at 2025-12-31) through the cycle up to `event_models`, behind a Flask app with the analysis and follow-up
blueprints; needs `DBT_MANIFEST`. The calculations themselves are checked, with exact counts, in
`test_cama_analysis_calculations.py`.
"""
import os
import re
import pytest
from flask import Flask
from sqlmodel import Session
from conftest import base_de
from test_cama_follow_up import CORTE, UNTIL_MODELS, insertar
from webapi.cama_analysis.routes import analysis_blueprint
from webapi.cama_follow_up.routes import follow_up_blueprint
@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_analisis"), 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")
flask.register_blueprint(analysis_blueprint(lambda: Session(base.motor)), url_prefix="/cama/analisis")
return flask.test_client()
def get(app, ruta, **params):
return app.get("/cama/analisis" + ruta, query_string={"corte": CORTE, "meses": 0, **params})
def tend(app, **params):
"""The trend takes only the cut-off: no window, no filters."""
return app.get("/cama/analisis/tendencia", query_string={"corte": CORTE, **params})
def test_the_catalog_lists_what_the_analysis_offers_and_what_it_cannot_calculate(app):
"""Pins down: the catalog names the dimensions with their options, the measures, the horizons, the five sections and the
analyses that are not available with their reasons, and carries the cohort context. Fails if the tab is given
something to draw that has no endpoint, or an unavailable analysis loses its reason."""
c = get(app, "").get_json()
assert [d["clave"] for d in c["dimensiones"]] == ["birads", "grupo_edad", "biopsia"]
assert c["horizontes_dias"] == [30, 90, 180, 365] and c["tipos_periodo"] == ["mes", "semestre"]
assert [s["clave"] for s in c["secciones"]] == ["resumen", "distribucion", "comparacion", "mapa", "tendencia"]
assert {x["clave"] for x in c["no_disponibles"]} >= {"supervivencia", "recaida", "curvas_tiempo_a_evento"}
assert c["cohorte"] == "cama_birads_v1" and re.fullmatch(r"[0-9a-f]{64}", c["revision"]) and c["umbral_supresion"] == 5
assert "simulado" not in c
def test_the_cards_distribution_list_and_legacy_aggregate_agree_on_who_is_in_the_cohort(app):
"""Pins down: the cohort card, the total of the distribution by each dimension, the list's total and the legacy aggregate's
categories all describe the same 15 patients, under one revision. Fails if two parts of the tab count different patients."""
resumen = get(app, "/resumen").get_json()
total = next(i for i in resumen["indicadores"] if i["clave"] == "cohorte")["valor"]
lista = app.get("/cama/seguimiento", query_string={"corte": CORTE, "meses": 0}).get_json()
assert total == lista["paginacion"]["total_items"] == 15
for por in ("birads", "grupo_edad", "biopsia"):
d = get(app, "/distribucion", por=por).get_json()
assert d["total"] == 15 and d["revision"] == resumen["revision"] == lista["revision"]
publicados = sum(i["n"] for i in d["items"] if not i["suprimido"])
assert publicados <= 15
legado = get(app, "/indicadores").get_json()
por_birads = {i["codigo"]: i for i in get(app, "/distribucion", por="birads").get_json()["items"]}
# The legacy contract publishes a category only from the threshold, so an empty one reads as not published.
assert {g["codigo"]: g["n"] for g in legado["grupos"]} == {c: (i["n"] or None) for c, i in por_birads.items()}
assert all(g["n"] is None or g["n"] >= legado["umbral_supresion"] for g in legado["grupos"])
assert legado["simulado"] is True and legado["umbral_supresion"] == 5
def test_small_cohort_figures_are_states_not_numbers(app):
"""Pins down: with 4 patients with a biopsy report and 3 with a known result, the cards of proportions are `suprimido`
without value or interval, the cohort card shows 15, the cards that need a denominator of zero are `sin_datos`, and the
cards of what the data cannot hold are listed apart. Fails if a small group is shown through a card."""
r = get(app, "/resumen", horizonte=90).get_json()
t = {i["clave"]: i for i in r["indicadores"]}
assert t["cohorte"]["valor"] == 15 and t["cohorte"]["estado"] == "disponible"
assert t["con_biopsia"]["estado"] == "suprimido" and t["con_biopsia"]["valor"] is None
assert t["maligno_conocido"]["estado"] == "suprimido" and t["maligno_conocido"]["ic_bajo"] is None
assert r["horizonte_dias"] == 90 and "maligno_90d" in t and {x["clave"] for x in r["no_disponibles"]}
def test_the_distribution_by_biopsy_result_names_every_category_and_opens_its_patients(app):
"""Pins down: by biopsy result the categories are benign, in situ, invasive, report without grade and no biopsy, each with
the Seguimiento filter that opens its patients. Four groups of one patient hide with the group of 11 without biopsy, so
the difference to the total hides them. Fails if a category is missing, a small group can be recovered by subtraction,
or the key is not one the list accepts."""
d = get(app, "/distribucion", por="biopsia").get_json()
assert [i["codigo"] for i in d["items"]] == ["BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR", "SIN_DATO", "SIN_BIOPSIA"]
sin_biopsia = d["items"][-1]
# Four categories of one patient each hide, and the 11 without biopsy goes with them so the difference can't give them away.
assert all(i["suprimido"] and i["n"] is None for i in d["items"])
assert sin_biopsia["seleccion"] == {"biopsia": "SIN_BIOPSIA"}
abierta = app.get("/cama/seguimiento", query_string={"corte": CORTE, "meses": 0, **sin_biopsia["seleccion"]}).get_json()
assert abierta["paginacion"]["total_items"] == 11, "the list accepts the key the distribution gives"
def test_comparison_and_map_say_no_data_instead_of_a_test_or_a_cell_they_cannot_support(app):
"""Pins down: on this small cohort the comparison has no valid test (it says why) and its groups are suppressed; the
map has every cell with a state and no proportions that leak; both refuse the biopsy result as a dimension. Fails if a
p-value is given on a table of fewer than five known results."""
c = get(app, "/comparacion", por="birads", medida="maligno").get_json()
assert c["prueba"]["valida"] is False and c["prueba"]["motivo"]
assert all(g["estado"] in ("suprimido", "sin_datos") for g in c["grupos"])
m = get(app, "/mapa", filas="birads", columnas="grupo_edad").get_json()
assert len(m["celdas"]) == len(m["filas"]["categorias"]) * len(m["columnas"]["categorias"])
assert all(c["resultado"]["valor"] is None for c in m["celdas"])
assert get(app, "/comparacion", por="biopsia").status_code == 400
assert get(app, "/mapa", filas="biopsia", columnas="birads").status_code == 400
assert get(app, "/mapa", filas="birads", columnas="birads").status_code == 400
def test_the_trend_counts_reports_per_period_and_flags_the_period_the_cutoff_cuts(app):
"""Pins down: by month the reports of mammogram and biopsy fall in their months, small counts are hidden, the answer names
its population, unit and biopsy scope, and a cut-off inside a period marks it as incomplete. Fails if a report is counted
in another period, a partial period is presented as whole or the answer carries a test or a cohort it doesn't use."""
t = tend(app, tipo="mes", periodos=12).get_json()
assert [p["periodo"] for p in t["periodos"]][-1] == "2025-12" and len(t["periodos"]) == 12
assert all(p["incompleto"] is False for p in t["periodos"])
assert t["unidad"] == "reportes" and t["poblacion"] and t["alcance_biopsias"] and t["corte"] == CORTE
assert not {"prueba", "cohorte", "revision", "ventana", "filtros"} & set(t)
diciembre = t["periodos"][-1]
assert diciembre["reportes_mastografia"]["total"] in (None, *range(5, 40))
for p in t["periodos"]:
categorias = p["reportes_biopsia"]["por_grado"]
ocultos = [k for k, v in categorias.items() if v["suprimido"]]
assert len(ocultos) != 1 or p["reportes_biopsia"]["total"] is None, "a lone hidden category would be the total minus the published ones"
parcial = app.get("/cama/analisis/tendencia", query_string={"corte": "2025-12-15", "tipo": "mes", "periodos": 3}).get_json()
assert parcial["periodos"][-1]["periodo"] == "2025-12" and parcial["periodos"][-1]["incompleto"] is True
semestres = tend(app, tipo="semestre", periodos=2).get_json()
assert [p["periodo"] for p in semestres["periodos"]] == ["2025-S1", "2025-S2"]
def test_the_trend_is_the_same_whatever_the_cohort_selection_and_refuses_to_take_one(app):
"""Pins down: the trend is general activity, so a window, a filter or the cohort context are 400 instead of being silently
ignored, and the answer of the same cut-off doesn't change with what the other sections have selected. Fails if the trend
attributes a filter or window it doesn't apply."""
base = tend(app, tipo="mes", periodos=6)
assert base.status_code == 200
for extra in ({"meses": 3}, {"birads": "BIRADS_5"}, {"grupo_edad": "50_59"}, {"cohorte": "x", "escenario": "y", "revision": "z"}, {"horizonte": 90}):
assert tend(app, tipo="mes", periodos=6, **extra).status_code == 400, extra
cuerpo = get(app, "/resumen").get_json()
get(app, "/distribucion", por="grupo_edad", birads="BIRADS_5")
assert tend(app, tipo="mes", periodos=6).get_json() == base.get_json()
assert cuerpo["cohorte"] not in str(base.get_json())
def test_a_period_without_reports_has_zero_counts_and_no_proportion(app):
"""Pins down: months before the first report have zero reports, a proportion `sin_datos` and no hidden flag on a zero.
Fails if an empty month turns into a suppressed or a zero-percent figure."""
t = tend(app, tipo="mes", periodos=12).get_json()
vacio = t["periodos"][0]
assert vacio["periodo"] == "2025-01" and vacio["reportes_biopsia"]["por_grado"]["BENIGNO"] == {"n": 0, "suprimido": False}
assert vacio["maligno"]["estado"] == "sin_datos" and vacio["maligno"]["valor"] is None
def test_an_empty_cohort_is_an_answer_with_no_data_in_every_part(app):
"""Pins down: before the first mammogram every endpoint answers 200 with zero patients and states without data, never an
error or a figure. Fails if an empty cohort breaks a part of the tab."""
vacia = {"corte": "2025-01-01", "meses": 0}
resumen = app.get("/cama/analisis/resumen", query_string=vacia).get_json()
t = {i["clave"]: i for i in resumen["indicadores"]}
assert t["cohorte"]["valor"] == 0 and t["maligno_conocido"]["estado"] == "sin_datos" and t["biopsia_90d"]["estado"] == "sin_datos"
d = app.get("/cama/analisis/distribucion", query_string={**vacia, "por": "birads"}).get_json()
assert d["total"] == 0 and all(i["n"] == 0 and i["porcentaje"] is None for i in d["items"])
assert app.get("/cama/analisis/comparacion", query_string={**vacia, "por": "grupo_edad"}).status_code == 200
assert app.get("/cama/analisis/mapa", query_string={**vacia, "filas": "birads", "columnas": "grupo_edad"}).status_code == 200
def test_the_selection_rules_of_the_list_apply_to_the_analysis(app):
"""Pins down: a window or filter selecting fewer than five patients is a 403 with the reason `supresion`, a stale revision a
409, a context quoted in part a 400, and the endpoints share the list's window and filters. Fails if the analysis
answers a group the list refuses."""
assert get(app, "/distribucion", por="birads", birads="BIRADS_6").status_code == 403
assert get(app, "/resumen", meses=1, birads="BIRADS_5").status_code == 403
cuerpo = get(app, "/resumen").get_json()
contexto = {k: cuerpo[k] for k in ("cohorte", "escenario", "revision")}
assert get(app, "/resumen", **contexto).status_code == 200
assert get(app, "/resumen", **{**contexto, "revision": "0" * 64}).status_code == 409
assert get(app, "/resumen", cohorte=contexto["cohorte"]).status_code == 400
filtrado = get(app, "/distribucion", por="grupo_edad", birads="BIRADS_5").get_json()
assert filtrado["filtros"]["birads"] == "BIRADS_5" and filtrado["total"] in (6, 7)
@pytest.mark.parametrize("ruta, params", [
("/distribucion", {}), ("/distribucion", {"por": "edad"}), ("/resumen", {"horizonte": 45}), ("/resumen", {"horizonte": "x"}),
("/comparacion", {"por": "birads", "medida": "otra"}), ("/resumen", {"meses": 0, "periodos": 3}), ("/resumen", {"por": "birads"}), ("/resumen", {"estatus": "ALTA"}), ("/distribucion", {"por": ""}),
])
def test_a_badly_written_request_is_a_400(app, ruta, params):
"""Pins down: a missing or unknown dimension, an unadmitted horizon or period count, a parameter of another route and
the retired status are all 400. Fails if validation lets an unknown request through."""
assert get(app, ruta, **params).status_code == 400
@pytest.mark.parametrize("meses", [0, 1, 3, 6, 12])
@pytest.mark.parametrize("por", ["birads", "grupo_edad", "biopsia"])
def test_each_published_group_opens_exactly_the_patients_it_counts_in_every_window(app, meses, por):
"""Pins down: for the whole cohort and for the windows of 1, 3, 6 and 12 months, every published group of the distribution
opens in the follow-up list, with its key, the same window and the cohort context, onto as many patients as it counts, and
a selection the list suppresses is not published. Fails if a bar leads to a different population than it represents."""
respuesta = get(app, "/distribucion", por=por, meses=meses)
if respuesta.status_code == 403:
assert meses != 0, "only a window may leave the cohort too small"
return
d = respuesta.get_json()
assert d["ventana"]["meses"] == meses
contexto = {k: d[k] for k in ("cohorte", "escenario", "revision")}
abiertos = 0
for item in d["items"]:
if item["suprimido"] or not item["n"]:
continue
lista = app.get("/cama/seguimiento", query_string={"corte": d["corte"], "meses": d["ventana"]["meses"], **contexto, **item["seleccion"]})
assert lista.status_code == 200, (item["codigo"], lista.get_json())
assert lista.get_json()["paginacion"]["total_items"] == item["n"], (meses, por, item["codigo"])
abiertos += 1
assert abiertos or meses != 0 or por == "biopsia", "the whole cohort publishes groups"
@pytest.mark.parametrize("params", [{"tipo": "dia"}, {"periodos": 0}, {"periodos": 99}, {"periodos": "x"}, {"corte": "2999-01-01"}])
def test_a_badly_written_trend_request_is_a_400(app, params):
"""Pins down: an unknown period type, a period count out of range and a cut-off in the future are refused. Fails if the
trend answers a request it can't define."""
assert tend(app, **{"tipo": "mes", **params}).status_code == 400
def test_a_repeated_parameter_is_a_400_and_the_answers_are_not_cached(app):
"""Pins down: `por` twice is refused, and every answer says `no-store`. Fails if a client's choice is ambiguous or a
patient-level selection can be cached."""
assert app.get("/cama/analisis/distribucion?corte=2025-12-31&meses=0&por=birads&por=grupo_edad").status_code == 400
assert get(app, "/resumen").headers["Cache-Control"] == "no-store"
def test_without_the_cohort_view_the_analysis_answers_503(tmp_path):
"""Pins down: a database whose indicator cycle hasn't created the cohort view answers 503 with the reason `cohorte`.
Fails if a missing view is a server error."""
if not os.environ.get("DBT_MANIFEST"):
pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it")
sin_ciclo = base_de("cama", tmp_path, datos=insertar)
try:
flask = Flask(__name__)
flask.register_blueprint(analysis_blueprint(lambda: Session(sin_ciclo.motor)), url_prefix="/cama/analisis")
respuesta = flask.test_client().get("/cama/analisis/resumen", query_string={"corte": CORTE, "meses": 0})
assert respuesta.status_code == 503 and respuesta.get_json()["motivo"] == "cohorte"
finally:
sin_ciclo.motor.dispose()
+226
View File
@@ -0,0 +1,226 @@
"""What this module covers: the statistics, the suppression rule and the calculations of CaMa's descriptive analysis
(`webapi.cama_analysis`), as pure functions: no database, no HTTP.
Fixtures: none. The cohort rows are built here with the exact counts each test needs (`fila`), invented inputs whose
expected figures are written out in the tests; nothing is read from a database.
"""
import math
from datetime import date, timedelta
import pytest
from webapi.cama_analysis import calculations as calc
from webapi.cama_analysis.stats import chi2_homogeneidad, chi2_sf, cuantil, wilson
from webapi.cama_analysis.suppression import proporcion_publicable, suprimir_categorias, suprimir_tabla
from webapi.cama_follow_up.cohort import Fila
CORTE = date(2025, 12, 31)
MAST = date(2025, 1, 1)
MALIGNOS = {"CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"}
CATEGORIAS_BIRADS = [("BIRADS_4A", "BI-RADS 4A"), ("BIRADS_5", "BI-RADS 5"), ("BIRADS_6", "BI-RADS 6")]
CATEGORIAS_EDAD = [("40-49", "40 a 49 años"), ("50-59", "50 a 59 años")]
def fila(i, birads="BIRADS_5", edad="50-59", grado=None, con_reporte=None, dias_biopsia=None, dias_maligno=None, mast=MAST):
"""One patient: `grado` is the shown biopsy result, `dias_*` the days from the mammogram to the earliest biopsy report and
to the earliest malignant one."""
reporte = con_reporte if con_reporte is not None else grado is not None
return Fila(pac_id=i, mastografia_fecha=mast, birads=birads, grupo_edad=edad, biopsia=grado,
biopsia_fecha=mast + timedelta(days=dias_biopsia or 9) if reporte else None,
primera_biopsia_fecha=mast + timedelta(days=dias_biopsia) if dias_biopsia is not None else None,
primer_maligno_fecha=mast + timedelta(days=dias_maligno) if dias_maligno is not None else None)
def cohorte():
"""70 patients: 40 with a known result (30 benign, 5 in situ, 5 invasive), 10 with a report and no grade, 20 without
a biopsy. Days to the first biopsy report: 20 benign at 10 days, 6 malignant at 20 days, the other 24 with a report at 100 days."""
filas, i = [], 0
for grado, n in (("BENIGNO", 30), ("CARCINOMA_IN_SITU", 5), ("CARCINOMA_INVASOR", 5)):
for _ in range(n):
i += 1
filas.append(fila(i, grado=grado))
for k, f in enumerate(filas):
pronto = k < 20 or (grado_es(f) and k % 10 < 6)
dias = 10 if k < 20 else 20 if pronto else 100
maligno = (20 if pronto else 120) if grado_es(f) else None
filas[k] = fila(f.pac_id, grado=f.biopsia, dias_biopsia=dias, dias_maligno=maligno)
for _ in range(10):
i += 1
filas.append(fila(i, grado=None, con_reporte=True, dias_biopsia=100))
for _ in range(20):
i += 1
filas.append(fila(i))
return filas
def grado_es(f):
return f.biopsia in MALIGNOS
def test_wilson_matches_the_closed_form_and_stays_inside_zero_and_one():
"""Pins down: the Wilson interval of 10 of 40 is (14.1 %, 40.3 %), the interval of 0 of n starts at 0 and of n of n ends at
1, and it is symmetric around the midpoint of k and n-k. Fails if the formula or its continuity is changed."""
bajo, alto = wilson(10, 40)
assert (bajo, alto) == pytest.approx((0.1410, 0.4028), abs=0.001)
assert wilson(0, 30)[0] == 0 and wilson(30, 30)[1] == 1
assert wilson(10, 40)[0] == pytest.approx(1 - wilson(30, 40)[1])
with pytest.raises(ValueError):
wilson(5, 0)
@pytest.mark.parametrize("gl, critico", [(1, 3.841458820694124), (2, 5.991464547107979), (3, 7.814727903251179), (4, 9.487729036781154), (9, 16.918977604620448)])
def test_chi_square_tail_at_the_five_percent_critical_values(gl, critico):
"""Pins down: the tail probability at the textbook 5 % critical value of each degree of freedom is 0.05, and at 0 it is
1. Fails if the incomplete gamma function is wrong in its series or its continued fraction."""
assert chi2_sf(critico, gl) == pytest.approx(0.05, abs=1e-9)
assert chi2_sf(0, gl) == 1
def test_the_homogeneity_test_gives_the_statistic_and_refuses_what_the_approximation_cannot_carry():
"""Pins down: groups 20 of 40 and 8 of 40 give chi-square 7.912 with 1 degree of freedom and p 0.0049; two groups with an
expected count under 5, a single group, or one outcome only are not tested, with the reason. Fails if a p-value is
given where the approximation isn't valid."""
prueba = chi2_homogeneidad([(20, 40), (8, 40)])
assert prueba["valida"] and prueba["gl"] == 1 and prueba["estadistico"] == pytest.approx(7.912, abs=0.001)
assert prueba["p"] == pytest.approx(0.00492, abs=0.0001)
assert not chi2_homogeneidad([(1, 10), (2, 10)])["valida"]
assert not chi2_homogeneidad([(20, 40)])["valida"]
assert not chi2_homogeneidad([(0, 40), (0, 40)])["valida"]
def test_quantiles_interpolate_between_the_order_statistics():
"""Pins down: the median of 1 to 4 is 2.5 and the quartiles of 1 to 5 are 2 and 4. Fails if the interpolation changes."""
assert cuantil([4, 1, 3, 2], .5) == 2.5
assert (cuantil([1, 2, 3, 4, 5], .25), cuantil([1, 2, 3, 4, 5], .75)) == (2, 4)
def test_a_proportion_is_published_only_when_the_group_the_cases_and_the_rest_are_not_small():
"""Pins down: 10 of 40 is published; 3 of 40 (3 cases), 38 of 40 (2 non-cases) and 4 of 4 (a group under 5) are not;
0 of 40 is published because zero describes nobody. Fails if a small cell can be read from a proportion."""
assert proporcion_publicable(10, 40, 5) and proporcion_publicable(0, 40, 5)
assert not proporcion_publicable(3, 40, 5) and not proporcion_publicable(38, 40, 5) and not proporcion_publicable(4, 4, 5)
def test_a_hidden_cell_takes_the_smallest_published_one_with_it_until_the_difference_hides_nothing():
"""Pins down: with cells 30, 12, 8, 2 and a published total, the 2 is hidden and so is the 8 (2 + 8 >= 5), so the
difference between the total and the published cells is 10 patients and says nothing of the 2; cells with no small
count hide nothing; zeros are not small. Fails if one hidden cell can be recovered by subtraction."""
assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 2}, 5) == {"c", "d"}
assert suprimir_categorias({"a": 30, "b": 12, "c": 8, "d": 7}, 5) == set()
assert suprimir_categorias({"a": 30, "b": 0, "c": 8}, 5) == set()
assert suprimir_categorias({"a": 3, "b": 2}, 5) == {"a", "b"}
def test_a_table_hides_along_rows_and_columns_until_no_line_gives_a_small_cell_away():
"""Pins down: in a 2 x 2 table with one cell of 1, the secondary suppression covers its row and its column, so the
hidden cells total at least 5 in each line. Fails if a marginal total and the visible cells reveal a hidden cell."""
conteos = {("a", "x"): 20, ("a", "y"): 1, ("b", "x"): 9, ("b", "y"): 30}
ocultas = suprimir_tabla(conteos, 5)
assert ("a", "y") in ocultas
for fila_ in ("a", "b"):
ocultos = sum(conteos[k] for k in ocultas if k[0] == fila_)
assert ocultos == 0 or ocultos >= 5
for columna in ("x", "y"):
ocultos = sum(conteos[k] for k in ocultas if k[1] == columna)
assert ocultos == 0 or ocultos >= 5
def test_the_cards_state_their_numerator_denominator_and_interval():
"""Pins down, on a cohort of 70 (40 with a known result, 10 with a report without a grade, 20 without biopsy): cohort 70;
with a biopsy report 50 of 70; malignant among the known 10 of 40 (25 %) with its Wilson interval; invasive 5 of 40;
a biopsy within 90 days 26 of 70; a malignant result within 90 days 6 of 70; the median days to the report 20 (n 50).
Fails if a numerator, a denominator or a definition changes."""
t = {x["clave"]: x for x in calc.resumen(cohorte(), CORTE, 90, MALIGNOS, 5)}
assert t["cohorte"]["valor"] == 70
assert (t["con_biopsia"]["n"], t["con_biopsia"]["denominador"]) == (50, 70)
assert (t["maligno_conocido"]["n"], t["maligno_conocido"]["denominador"], t["maligno_conocido"]["valor"]) == (10, 40, 25.0)
assert (t["maligno_conocido"]["ic_bajo"], t["maligno_conocido"]["ic_alto"]) == pytest.approx((14.1, 40.3), abs=0.2)
assert (t["invasor_conocido"]["n"], t["invasor_conocido"]["denominador"]) == (5, 40)
assert (t["biopsia_90d"]["n"], t["biopsia_90d"]["denominador"]) == (26, 70)
assert (t["maligno_90d"]["n"], t["maligno_90d"]["denominador"]) == (6, 70)
assert (t["dias_a_biopsia"]["valor"], t["dias_a_biopsia"]["n"]) == (20, 50)
assert all(x["estado"] == "disponible" for x in t.values())
def test_a_horizon_counts_only_the_mammograms_that_have_had_the_time():
"""Pins down: with a 365-day horizon and the cut-off 364 days after the mammograms nobody has had the time, so the
denominator is zero and the card has no data, not a zero percent; a mammogram that is recent at the cut-off is left
out of the 90-day denominator. Fails if a recent mammogram is read as one without a biopsy."""
t = {x["clave"]: x for x in calc.resumen(cohorte(), MAST + timedelta(days=364), 365, MALIGNOS, 5)}
assert t["biopsia_365d"]["estado"] == "sin_datos" and t["biopsia_365d"]["valor"] is None
recientes = cohorte() + [fila(900 + k, mast=CORTE - timedelta(days=10)) for k in range(6)]
t = {x["clave"]: x for x in calc.resumen(recientes, CORTE, 90, MALIGNOS, 5)}
assert t["biopsia_90d"]["denominador"] == 70 and t["cohorte"]["valor"] == 76
def test_a_small_numerator_or_denominator_hides_the_figure_and_its_interval():
"""Pins down: 3 malignant among 20 known results, and 4 patients with a known result, are not published (state
`suprimido`, no value, no interval); an empty cohort has no data. Fails if a small group is shown through a figure."""
pocas = [fila(i, grado="CARCINOMA_INVASOR") for i in range(1, 4)] + [fila(10 + i, grado="BENIGNO") for i in range(17)]
t = {x["clave"]: x for x in calc.resumen(pocas, CORTE, 90, MALIGNOS, 5)}
assert t["maligno_conocido"]["estado"] == "suprimido" and t["maligno_conocido"]["valor"] is None and t["maligno_conocido"]["ic_bajo"] is None
cuatro = {x["clave"]: x for x in calc.resumen([fila(i, grado="BENIGNO") for i in range(4)], CORTE, 90, MALIGNOS, 5)}
assert cuatro["maligno_conocido"]["estado"] == "suprimido"
vacia = {x["clave"]: x for x in calc.resumen([], CORTE, 90, MALIGNOS, 5)}
assert vacia["cohorte"]["valor"] == 0 and vacia["maligno_conocido"]["estado"] == "sin_datos"
def test_the_distribution_adds_up_to_the_selection_and_hides_small_groups_by_complement():
"""Pins down: 30 + 12 + 8 + 2 patients by BI-RADS: the total is 52, shares are of the selection with Wilson intervals,
the 2 and the 8 are not published. Fails if the cells and the total disagree or a hidden cell can be subtracted."""
filas = ([fila(i, birads="BIRADS_5") for i in range(30)] + [fila(100 + i, birads="BIRADS_4A") for i in range(12)]
+ [fila(200 + i, birads="BIRADS_6") for i in range(2)])
d = calc.distribucion(filas, "birads", [("BIRADS_4A", "4A"), ("BIRADS_5", "5"), ("BIRADS_6", "6")], 5)
por = {i["codigo"]: i for i in d["items"]}
assert d["total"] == 44 and por["BIRADS_5"]["n"] == 30 and por["BIRADS_5"]["porcentaje"] == pytest.approx(68.18, abs=0.01)
assert por["BIRADS_6"]["suprimido"] and por["BIRADS_6"]["n"] is None and por["BIRADS_6"]["ic_bajo"] is None
assert por["BIRADS_4A"]["suprimido"], "the smallest published cell is hidden with the small one"
assert sum(i["n"] for i in d["items"] if not i["suprimido"]) == 30
assert por["BIRADS_5"]["seleccion"] == {"birads": "BIRADS_5"}
def test_the_comparison_shares_the_denominator_of_known_results_and_tests_only_valid_tables():
"""Pins down: by BI-RADS, 20 of 40 and 8 of 40 known results are malignant (50 % and 20 %), the test is the chi-square 7.9
with p 0.005, patients without a result are not in the denominator, and a group of fewer than five known results is
suppressed and left out of the test. Fails if the denominator includes patients without biopsy or the test uses a hidden group."""
filas = ([fila(i, birads="BIRADS_4A", grado="CARCINOMA_INVASOR") for i in range(20)] + [fila(30 + i, birads="BIRADS_4A", grado="BENIGNO") for i in range(20)]
+ [fila(100 + i, birads="BIRADS_5", grado="CARCINOMA_IN_SITU") for i in range(8)] + [fila(130 + i, birads="BIRADS_5", grado="BENIGNO") for i in range(32)]
+ [fila(300 + i, birads="BIRADS_5") for i in range(25)] + [fila(400 + i, birads="BIRADS_6", grado="BENIGNO") for i in range(3)])
c = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "maligno", MALIGNOS, 5)
g = {x["codigo"]: x for x in c["grupos"]}
assert (g["BIRADS_4A"]["casos"], g["BIRADS_4A"]["total"], g["BIRADS_4A"]["valor"]) == (20, 40, 50.0)
assert (g["BIRADS_5"]["casos"], g["BIRADS_5"]["total"], g["BIRADS_5"]["valor"]) == (8, 40, 20.0)
assert g["BIRADS_6"]["estado"] == "suprimido"
assert c["prueba"]["valida"] and c["prueba"]["p"] == pytest.approx(0.00492, abs=0.0001)
invasor = calc.comparacion(filas, "birads", CATEGORIAS_BIRADS, "invasor", MALIGNOS, 5)
assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_4A"] == 20
assert {x["codigo"]: x["casos"] for x in invasor["grupos"]}["BIRADS_5"] == 0
def test_the_map_crosses_two_dimensions_and_its_cells_add_up_to_the_selection():
"""Pins down: BI-RADS by age group: each patient is in one cell, the published cells never exceed the selection, the
proportion of a cell is among its known results and a hidden cell, secondary ones included, has neither count nor proportion. Fails if a patient
is counted twice or a hidden cell leaks through its proportion."""
filas = ([fila(i, birads="BIRADS_5", edad="50-59", grado="BENIGNO") for i in range(12)]
+ [fila(100 + i, birads="BIRADS_5", edad="40-49", grado="CARCINOMA_INVASOR") for i in range(7)]
+ [fila(200 + i, birads="BIRADS_4A", edad="50-59") for i in range(9)] + [fila(300, birads="BIRADS_4A", edad="40-49")])
m = calc.mapa(filas, "birads", "grupo_edad", CATEGORIAS_BIRADS, CATEGORIAS_EDAD, "maligno", MALIGNOS, 5)
celdas = {(c["fila"], c["columna"]): c for c in m["celdas"]}
assert celdas[("BIRADS_5", "50-59")]["n"] == 12 and celdas[("BIRADS_5", "50-59")]["resultado"]["casos"] == 0
oculta = celdas[("BIRADS_4A", "40-49")]
assert oculta["suprimido"] and oculta["n"] is None and oculta["resultado"]["valor"] is None
# The 40-49 column then holds a hidden 1 and a published 7: the 7 goes with it, so the column can't give the 1 away.
assert celdas[("BIRADS_5", "40-49")]["suprimido"] and celdas[("BIRADS_5", "40-49")]["resultado"]["valor"] is None
assert celdas[("BIRADS_4A", "50-59")]["suprimido"], "and the 4A row hides its 9 for the same reason"
assert sum(c["n"] for c in m["celdas"] if not c["suprimido"]) <= len(filas)
assert celdas[("BIRADS_5", "50-59")]["seleccion"] == {"birads": "BIRADS_5", "grupo_edad": "50-59"}
def test_the_catalog_of_unavailable_analyses_names_a_reason_for_each():
"""Pins down: survival, recurrence, treatment adherence, the time-to-event curves and their tests, and BRCA, stage and
size are listed as unavailable, each with its reason. Fails if one of them is dropped or loses its reason."""
assert {x["clave"] for x in calc.NO_DISPONIBLES} == {"supervivencia", "recaida", "adherencia_tratamiento", "curvas_tiempo_a_evento",
"riesgos_proporcionales", "brca_estadio_tamano"}
assert all(x["motivo"] and x["titulo"] for x in calc.NO_DISPONIBLES)
assert not math.isnan(wilson(1, 2)[0])
+52
View File
@@ -0,0 +1,52 @@
"""Integration with dev: no duplicate routes, retained access hook and individual contract."""
from test_cama_analysis import app, base
from test_cama_follow_up import CORTE
def test_application_has_one_handler_per_cama_route():
from webapi import create_app
application = create_app()
assert application.config['CAMA_COHORT_READER']._cama_default_reader is True
rules = list(application.url_map.iter_rules())
for path in ('/cama/seguimiento', '/cama/seguimiento/exportacion',
'/cama/analisis/indicadores', '/cama/pacientes/<pac_id>'):
assert len([r for r in rules if r.rule == path]) == 1
assert application.test_client().get('/health').get_json() == {'status': 'ok'}
def test_individual_route_is_a_row_of_the_selected_list(app):
q = {'corte': CORTE, 'meses': 0}
listing = app.get('/cama/seguimiento', query_string=q).get_json()
q.update({k: listing[k] for k in ('cohorte', 'escenario', 'revision')})
patient = listing['items'][0]
detail = app.get('/cama/pacientes/' + patient['pac_id'], query_string=q)
assert detail.status_code == 200
assert detail.get_json()['item'] == patient
assert detail.get_json()['revision'] == listing['revision']
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={**q, 'page': 2, 'page_size': 2}).get_json()['item'] == patient
assert app.get('/cama/pacientes/999999999', query_string=q).status_code == 404
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={**q, 'revision': '0'*64}).status_code == 409
assert app.get('/cama/pacientes/' + patient['pac_id'], query_string={'corte': CORTE, 'meses': 0, 'birads': 'BIRADS_6'}).status_code == 403
def test_configured_access_hook_is_preserved(app):
app.application.config['CAMA_COHORT_ACCESS'] = lambda req: False
for path in ('/cama/seguimiento', '/cama/pacientes/1', '/cama/analisis/resumen'):
assert app.get(path).status_code == 403
def test_explicit_dev_reader_keeps_list_detail_and_aggregate_consistent():
from webapi import create_app
application = create_app()
rows = [dict(pac_id=str(i), mastografia_fecha='2026-01-01', birads='BIRADS_5',
grupo_edad='50-59', biopsia=None, biopsia_fecha=None) for i in range(1, 7)]
application.config['CAMA_COHORT_READER'] = lambda cutoff: rows
client = application.test_client()
query = {'corte': '2026-10-20', 'meses': 0}
listing = client.get('/cama/seguimiento', query_string=query).get_json()
assert listing['paginacion']['total_items'] == 6
assert client.get('/cama/pacientes/1', query_string=query).get_json()['item'] == rows[0]
aggregate = client.get('/cama/analisis/indicadores?corte=2026-10-20').get_json()
assert aggregate['revision'] == listing['revision']
application.config['CAMA_COHORT_READER'] = None
assert client.get('/cama/seguimiento', query_string=query).status_code == 503
+370
View File
@@ -0,0 +1,370 @@
"""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.
"""
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: 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"} for i in cuerpo["items"])
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"]
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")]
+310
View File
@@ -0,0 +1,310 @@
"""What this module covers: the three CaMa measures of L3, answered on request from dbt's semantic layer over the follow-up
fixture's invented patients (plus three on a period boundary and the diagnosing notes of the cases below): the detection
rate (`CAMA_TASA_DETECCION_HISTOPATOLOGICA`, C1), the time from the mammogram's result to the diagnosis
(`CAMA_DIAS_RESULTADO_DIAGNOSTICO`, C3r) and the histopathological result by BI-RADS (`CAMA_HISTOPATOLOGIA_BIRADS`, C2
stratified by BI-RADS). Every number here is worked out by hand from the cases, not read from the measure.
Fixtures: `base`, the CaMa database loaded from `insertar_l3` through the cycle up to `event_models` (dbt's views, the three
new ones included); `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it). Suppression is off (threshold 1).
Cases added to the follow-up fixture's (see `test_cama_follow_up.py`):
- P18 / P19 / P20: biopsies reported on the last day of a semester (06-30), the first day of the next (07-01) and the last
day of the year (12-31): which period each report counts in, and the inclusive event cut-off.
- Notes (a diagnosing note is a CIE-10 of the list written by oncologic surgery): P01 12 days after her report, P07 the
same day, P08 a note between her mammogram and her report (not counted) and one 37 days after it, P09 193 days after
(beyond the horizon), P03 an earlier breast cancer note (leaves her out), P04 a note by a specialty that doesn't
diagnose, P12 the same day, P20 39 days after.
"""
import os
from dataclasses import replace
from datetime import date, datetime, timedelta, timezone
from pathlib import Path
import pytest
from core.cama.models import BiopsiaMama, Mastografia, NotaMedica, Paciente
from sqlalchemy import text
from sqlmodel import Session, select
from conftest import base_de
from test_cama_follow_up import UNTIL_MODELS, insertar
from webapi.compositions import answer_composition, composition_definitions
from webapi.durations import answer_duration, duration_definitions
from webapi.fhir.measures import measure_report
from webapi.metrics import Question, answer, measure_definitions
from webapi.orchestration.reference.rules import RUTA_PARAMETROS
D = date
TASA = "cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA"
DIAS = "cama/CAMA_DIAS_RESULTADO_DIAGNOSTICO"
HISTO = "cama/CAMA_HISTOPATOLOGIA_BIRADS"
BIRADS_PACIENTE = "cama/CAMA_BIRADS456_PACIENTE"
DIAS_TOMA = "cama/CAMA_DIAS_TOMA_DIAGNOSTICO"
ONCOLOGIA, FAMILIAR = "CIRUGIA ONCOLOGICA", "MEDICINA FAMILIAR"
NUEVOS = {
"P18": (D(1970, 1, 1), [(D(2025, 6, 20), "B4A", D(2025, 6, 25))]),
"P19": (D(1970, 1, 1), [(D(2025, 6, 25), "B5", D(2025, 6, 28))]),
"P20": (D(1970, 1, 1), [(D(2025, 12, 20), "B5", D(2025, 12, 24))]),
}
# (patient, request date, report date, grade): the mammogram of each of them is its first
BIOPSIAS_NUEVAS = (
("P18", D(2025, 6, 26), D(2025, 6, 30), "BENIGNO"),
("P19", D(2025, 6, 29), D(2025, 7, 1), "CARCINOMA_INVASOR"),
("P20", D(2025, 12, 28), D(2025, 12, 31), "CARCINOMA_IN_SITU"),
)
# (patient, date, CIE-10, specialty)
NOTAS = (
("P01", D(2025, 12, 20), "R92", ONCOLOGIA),
("P07", D(2025, 12, 17), "N60", ONCOLOGIA),
("P08", D(2025, 12, 5), "R92", ONCOLOGIA),
("P08", D(2026, 1, 15), "R92", ONCOLOGIA),
("P09", D(2026, 5, 20), "R92", ONCOLOGIA),
("P03", D(2025, 1, 10), "C50", FAMILIAR),
("P03", D(2025, 12, 1), "R92", ONCOLOGIA),
("P04", D(2025, 11, 10), "R92", FAMILIAR),
("P12", D(2025, 12, 22), "Z123", ONCOLOGIA),
("P20", D(2026, 2, 1), "R92", ONCOLOGIA),
)
CORTE = D(2025, 12, 31)
def insertar_l3(sesion: Session) -> None:
insertar(sesion)
pacientes = {h: Paciente(pac_id_hospital=h, pac_sexo="Femenino", pac_fecha_nacimiento=n) for h, (n, _) in NUEVOS.items()}
sesion.add_all(pacientes.values())
sesion.flush()
mastografias = {}
for hospital, (_, tomas) in NUEVOS.items():
toma, birads, reporte = tomas[0]
mastografias[hospital] = 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, solicitud, reporte, grado in BIOPSIAS_NUEVAS:
m = mastografias[hospital]
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))
todos = {p.pac_id_hospital: p for p in sesion.exec(select(Paciente))}
sesion.add_all(NotaMedica(pac_id=todos[h].pac_id, pac_id_hospital=h, nm_id_hospital=f"NM-{i:03d}", nm_fecha=fecha,
nm_cie_codigo=cie, nm_especialidad=esp) for i, (h, fecha, cie, esp) in enumerate(NOTAS, start=1))
sesion.commit()
@pytest.fixture(scope="module")
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
@pytest.fixture(scope="module")
def base(tmp_path_factory, manifest):
carpeta = tmp_path_factory.mktemp("cama_l3")
sin_supresion = carpeta / "parametros.toml"
sin_supresion.write_text(RUTA_PARAMETROS.read_text(encoding="utf-8").replace("valor = 5", "valor = 1"), encoding="utf-8")
base = base_de("cama", carpeta, datos=insertar_l3)
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()
def repositories(base) -> dict:
d = base.dominio
return {"parameters": d.def_parametro_repository, "periods": d.dim_periodo_repository, "history": d.history_repository,
"queries": d.dbt_query_repository, "allow_undecided": True}
def proporcion(base, manifest, periodo, corte=None):
r = answer("cama", measure_definitions(manifest)[TASA], Question(TASA, periodo, corte), **repositories(base))
return r.numerator, r.denominator
def duracion(base, manifest, periodo, corte=None, url=DIAS):
return answer_duration("cama", duration_definitions(manifest)[url], Question(url, periodo, corte), **repositories(base))
def composicion(base, manifest, periodo, corte=None, conocimiento=None, url=HISTO):
return answer_composition("cama", composition_definitions(manifest)[url], Question(url, periodo, corte, conocimiento),
**repositories(base))
def matriz(resultado) -> dict:
return {(b, c): n for b, por in resultado.strata["birads"].items() for c, n in por.items()}
# --- the detection rate -----------------------------------------------------------------------------------------------
def test_the_detection_rate_counts_biopsy_reports_with_a_known_result_by_the_day_of_the_report(base, manifest):
"""Pins down: the rate's units are biopsy reports dated by the report, over those with a known grade. The semester 1 holds
P18's benign report of 06-30 (the last day); the semester 2 holds P19's invasive of 07-01 (the first), P20's in situ of 12-31
(the last), P01's invasive, P04's benign and P06's two (benign and in situ): 6 known and 4 malignant; P05's has no grade, so it
is outside both parts. Fails if a boundary day falls in the wrong period, a report without grade enters the denominator, or
each patient (P06 has two reports) counts once instead of each report."""
assert proporcion(base, manifest, "2025-S1") == (0, 1)
assert proporcion(base, manifest, "2025-S2") == (4, 6)
def test_the_detection_rate_by_month_adds_up_to_the_semesters_and_the_cutoff_is_inclusive(base, manifest):
"""Pins down: the months of a semester hold the same reports as the semester (every report is in exactly one month), and a
cut-off on the day of a report counts it while the day before doesn't. Fails if the monthly and the semester counts drift
or the event cut-off excludes its own day."""
meses = ["2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"]
por_mes = [proporcion(base, manifest, m) for m in meses]
assert (sum(n for n, _ in por_mes), sum(d for _, d in por_mes)) == proporcion(base, manifest, "2025-S2")
assert proporcion(base, manifest, "2025-12") == (2, 2)
assert proporcion(base, manifest, "2025-12", D(2025, 12, 31)) == (2, 2)
assert proporcion(base, manifest, "2025-12", D(2025, 12, 30)) == (1, 1)
def test_the_detection_rate_is_a_proportion_among_biopsies_and_not_the_confirmation_of_suspicious_mammograms(base, manifest):
"""Pins down: the rate and the confirmation proportion answer different questions over the same data. In the semester 2 the
rate counts 6 biopsy reports with a result; the confirmation counts mammograms of suspicion with a biopsy (its denominator
is mammograms, not reports). Fails if the two measures end up with the same counts."""
confirmacion = "cama/CAMA_CONFIRMACION_BIRADS45"
r = answer("cama", measure_definitions(manifest)[confirmacion], Question(confirmacion, "2025-S2"), **repositories(base))
assert (r.numerator, r.denominator) != (4, 6)
assert r.denominator >= 15, "its denominator is the mammograms of suspicion of the period"
def test_the_detection_flags_of_the_view_follow_the_parameters(base):
"""Pins down: the view's flags are the grade lists of dbt's vars, which a test keeps equal to the parameter table's: known
result = the catalog's grades, malignant = `cama.biopsia_cancer`. Fails if the two copies drift apart."""
import tomllib
reglas = tomllib.loads(RUTA_PARAMETROS.read_text(encoding="utf-8"))
with base.motor.connect() as c:
flags = {(g, k, m) for g, k, m in c.execute(text("select distinct grado, con_resultado, maligno from cama_deteccion_biopsia"))}
cancer = set(reglas["cama"]["biopsia_cancer"]["valor"])
catalogo = {x["clave"] for x in reglas["cama"]["catalogos"]["biopsia"]["valor"]}
assert flags == {(g, int(g in catalogo), int(g in cancer)) for g in {f[0] for f in flags}}
assert {None, "BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR"} == {f[0] for f in flags}
assert (None, 0, 0) in flags
# --- the time from the result to the diagnosis -------------------------------------------------------------------------
def test_the_time_from_result_to_diagnosis_counts_from_the_report_to_the_first_note_on_or_after_it(base, manifest):
"""Pins down, in the semester 2 (16 mammograms with a report, P03's left out by her earlier breast cancer note): five have a
diagnosing note within the horizon: P01 12 days, P07 and P12 the same day (0), P08 37 (her 12-05 note is before her report
and doesn't count) and P20 39; the other eleven are excluded and counted (P09's note is 193 days after, P04's is of a
specialty that doesn't diagnose, the rest have none). Median 12. Fails if a note before the report is used, the horizon
isn't applied, a non-diagnosing specialty counts or an excluded mammogram isn't counted."""
r = duracion(base, manifest, "2025-S2")
assert (r.initial, r.n, r.excluded, r.median) == (16, 5, 11, 12.0)
def test_the_event_cutoff_leaves_out_the_notes_after_it_and_does_not_measure_what_is_still_inside_the_horizon(base, manifest):
"""Pins down, at 2025-12-31: the notes of 2026 don't exist yet (P08's and P20's) and every mammogram of the semester is
still inside its horizon (180 days from its report), so those without a note are neither measured nor excluded: three
observations (0, 0 and 12 days, median 0) are the whole population. The same rule as the mammogram-to-result measure: a
mammogram is excluded only once its horizon has passed without a note. Fails if a note after the cut-off is measured or if
a mammogram that can still get its note is counted as excluded."""
r = duracion(base, manifest, "2025-S2", CORTE)
assert (r.initial, r.n, r.excluded, r.median) == (3, 3, 0, 0.0)
# Once every horizon of the semester has passed (the last report is 2025-12-27) the unmeasured are excluded and counted.
tarde = duracion(base, manifest, "2025-S2", D(2026, 7, 1))
assert (tarde.initial, tarde.n, tarde.excluded) == (16, 5, 11)
def test_the_result_to_diagnosis_days_are_the_mammogram_to_diagnosis_days_minus_the_days_to_the_report(base):
"""Pins down: for a mammogram whose first note is on or after its report, the days from the report equal the days of the
mammogram-to-diagnosis measure minus the days from the mammogram to its report (the same note, another origin): P01 19-7,
P07 7-7, P12 7-7. P08 is the difference by design (that measure takes her 12-05 note, this one her 01-15 note). Fails if the
two measures read different notes where they should read the same."""
with base.motor.connect() as c:
nuevo = {h: d for h, d in c.execute(text(
"select p.pac_id_hospital, r.dias_reporte_diagnostico from cama_resultado_diagnostico r join paciente p on p.pac_id = r.pac_id"))}
viejo = {h: (d, t) for h, d, t in c.execute(text(
"select p.pac_id_hospital, m.dias_toma_diagnostico, m.dias_toma_reporte from cama_tomas_mastografia m "
"join paciente p on p.pac_id = m.pac_id"))}
for h in ("P01", "P07", "P12"):
assert nuevo[h] == viejo[h][0] - viejo[h][1], h
assert (nuevo["P08"], viejo["P08"][0]) == (37, 3)
def test_a_mammogram_without_a_report_is_not_in_the_population_and_the_report_date_gives_the_period(base):
"""Pins down: the model holds one row per mammogram with a report, dated by it: all 24 mammograms of the fixture have one,
and P16's second (reported 2026-01-05) is dated 2026, outside the semester of its mammogram. Fails if the period is read from
the date of the mammogram."""
with base.motor.connect() as c:
filas = c.execute(text("select p.pac_id_hospital, r.fecha_toma, r.fecha_reporte from cama_resultado_diagnostico r "
"join paciente p on p.pac_id = r.pac_id where p.pac_id_hospital = 'P16' order by 2")).all()
assert [tuple(map(str, f[1:])) for f in filas] == [("2025-05-01", "2025-05-08"), ("2025-12-20", "2026-01-05")]
# --- the histopathological result by BI-RADS ---------------------------------------------------------------------------
def test_the_matrix_of_the_semester_2_at_the_cutoff(base, manifest):
"""Pins down, at 2025-12-31, one patient through her most severe mammogram of the semester: BI-RADS 5 (P01 invasive, P02
without biopsy because hers is reported in 2026, P03 and P17 without biopsy, P04 benign, P05 a biopsy without grade, P06 in
situ from her two biopsies, P20 in situ reported that same day), 4A (P07-P11 without biopsy), 6 (P12) and 4 without subcategory
(P14). P15's semester-2 mammogram is a 2 and P16's 5 is reported in 2026: neither enters. P19 (a semester-1 mammogram) is out.
Fails if the chosen mammogram, the biopsy of it, the cut-off or the grouping change."""
r = composicion(base, manifest, "2025-S2", CORTE)
assert matriz(r) == {
("B5", "CARCINOMA_INVASOR"): 1, ("B5", "CARCINOMA_IN_SITU"): 2, ("B5", "BENIGNO"): 1, ("B5", "SIN_DATO"): 1, ("B5", "SIN_BIOPSIA"): 3,
("B4A", "SIN_BIOPSIA"): 5, ("B6", "SIN_BIOPSIA"): 1, ("B4", "SIN_BIOPSIA"): 1,
}
assert sum(r.categories.values()) == 15
def test_without_a_cutoff_the_biopsy_reported_later_and_the_late_report_count(base, manifest):
"""Pins down: with no event cut-off P02's biopsy (reported 2026-01-10, in situ) is hers and P16's BI-RADS 5 (reported
2026-01-05) is her semester's: one more in situ, and one more without biopsy. Fails if a cut-off is applied by default."""
r = composicion(base, manifest, "2025-S2")
assert matriz(r)[("B5", "CARCINOMA_IN_SITU")] == 3 and matriz(r)[("B5", "SIN_BIOPSIA")] == 3
assert sum(r.categories.values()) == 16
def test_the_semester_1_matrix_holds_each_patient_once(base, manifest):
"""Pins down: P13 (BI-RADS 6, no biopsy), P15 (BI-RADS 5 of June, no biopsy), P18 (4A with her benign report of 06-30) and P19
(BI-RADS 5 with her invasive report of 07-01, in the next semester: the biopsy belongs to her mammogram, not to the period of
its report); P16's BI-RADS 1 is not admitted. Fails if a biopsy reported in the next period is lost."""
r = composicion(base, manifest, "2025-S1", CORTE)
assert matriz(r) == {("B6", "SIN_BIOPSIA"): 1, ("B5", "SIN_BIOPSIA"): 1, ("B4A", "BENIGNO"): 1, ("B5", "CARCINOMA_INVASOR"): 1}
@pytest.mark.parametrize("periodo", ["2025-S1", "2025-S2", "2025-06", "2025-07", "2025-08", "2025-09", "2025-10", "2025-11", "2025-12"])
def test_the_matrix_counts_the_same_patients_as_the_birads_measure_in_every_period(base, manifest, periodo):
"""Pins down: each period's BI-RADS strata equal the patients per category of CAMA_BIRADS456_PACIENTE (same rule: her most
severe mammogram of the period), so Resumen's two cards never count different patients. Fails if the two measures choose
other mammograms."""
histo = composicion(base, manifest, periodo, CORTE)
birads = composicion(base, manifest, periodo, CORTE, url=BIRADS_PACIENTE)
por_birads = {b: sum(cs.values()) for b, cs in histo.strata["birads"].items()}
assert por_birads == {b: n for b, n in birads.categories.items() if n}
assert sum(histo.categories.values()) == sum(birads.categories.values())
def test_a_knowledge_cutoff_later_the_same_day_still_sees_the_biopsies(base, manifest):
"""Pins down the datetime compare of the biopsy's knowledge date: with a knowledge cut-off one second after the last load (the
same day as the loads) every biopsy is known, as with none; with one before the first load nothing is. Fails if the biopsy's
date is compared as text against the cut-off (`...T...` against `... ...`), which hid every biopsy on the day of the load."""
with base.motor.connect() as c:
ultima = c.execute(text("select max(inicio) from carga")).scalar()
primera = c.execute(text("select min(inicio) from carga")).scalar()
ultima = datetime.fromisoformat(str(ultima)).replace(tzinfo=timezone.utc) if isinstance(ultima, str) else ultima.replace(tzinfo=timezone.utc)
primera = datetime.fromisoformat(str(primera)).replace(tzinfo=timezone.utc) if isinstance(primera, str) else primera.replace(tzinfo=timezone.utc)
sin = composicion(base, manifest, "2025-S2", CORTE)
con = composicion(base, manifest, "2025-S2", CORTE, ultima + timedelta(seconds=1))
assert matriz(con) == matriz(sin)
antes = composicion(base, manifest, "2025-S2", CORTE, primera - timedelta(days=1))
assert antes.categories == {}
def test_the_report_publishes_the_cross_of_birads_and_result_as_two_components(base, manifest):
"""Pins down the FHIR report of the matrix: a stratifier coded by BI-RADS and by the biopsy grade whose strata carry the two
components and the patients of each cell; the categories stratifier keeps the totals. Fails if the cross is published as
marginals (the page couldn't rebuild the matrix) or a cell's count is not the matrix's."""
definicion = composition_definitions(manifest)[HISTO]
periodo = base.dominio.dim_periodo_repository.get("2025-S2")
resultado = composicion(base, manifest, "2025-S2", CORTE)
informe = measure_report(definicion, Question(HISTO, "2025-S2", CORTE), resultado, periodo, datetime.now(timezone.utc))
grupo = informe["group"][0]
assert [[c["coding"][0]["code"] for c in s["code"]] for s in grupo["stratifier"]] == [["biopsia_grado"], ["birads", "biopsia_grado"]]
celdas = {tuple(c["value"]["coding"][0]["code"] for c in s["component"]): s["population"][0]["count"]
for s in grupo["stratifier"][1]["stratum"]}
assert celdas == matriz(resultado)
assert sum(celdas.values()) == grupo["population"][0]["count"] == 15
+58
View File
@@ -0,0 +1,58 @@
"""Isolated compiled-SQL regressions: repeated reports and identities across sources."""
import json
import sqlite3
from datetime import date, timedelta
import pytest
from test_cama_l3_measures import manifest
def sql(manifest, name):
nodes = json.loads(manifest.read_text())["nodes"].values()
return next(n["compiled_code"] for n in nodes if n["name"] == name)
@pytest.mark.parametrize("days,expected", [(179, 179), (180, None)])
def test_one_mammogram_uses_first_report_and_exclusive_180_day_horizon(manifest, days, expected):
db = sqlite3.connect(":memory:")
db.executescript('''
create table cama_mastografias(procedimiento_id, fuente_id, pac_id, fecha_toma, fecha_reporte, reporte_carga_id, reporte_id);
create table cama_linea_de_tiempo(pac_id, tipo, fecha, conocida_en);
create table dim_fecha(fecha, dia_num);
create table carga(carga_id, inicio);
create table procedimiento(procedimiento_id, fuente_tabla, fuente_id, pac_id, fecha, carga_id, padre_id, estudio_id, clase);
create table observacion_clinica(procedimiento_id, resultado_id, valor_id, valor_fuente, carga_id);
insert into carga values(1, '2026-11-17 00:00:00');
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-06-20',1,10);
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-07-10',1,11);
insert into cama_mastografias values(1,'1',1,'2025-06-01','2025-06-20',1,12);
insert into cama_linea_de_tiempo values(1,'diagnostico','2025-06-19','2026-11-17');
insert into procedimiento values(1,'source','1',1,'2025-06-01',1,null,'mastografia','toma');
insert into procedimiento select reporte_id,'source',cast(reporte_id as text),pac_id,fecha_reporte,reporte_carga_id,procedimiento_id,'mastografia','reporte' from cama_mastografias;
''')
start = date(2025, 6, 20)
end = start + timedelta(days=days)
db.execute("insert into cama_linea_de_tiempo values(1,'diagnostico',?,'2026-11-17')", (end.isoformat(),))
for i in range(-30, 210):
db.execute("insert into dim_fecha values(?,?)", ((start + timedelta(days=i)).isoformat(), i))
db.execute("create view cama_resultado_diagnostico as " + sql(manifest, "cama_resultado_diagnostico"))
assert db.execute('select procedimiento_id, fecha_reporte, dias_reporte_diagnostico from cama_resultado_diagnostico').fetchall() == [(1, '2025-06-20', expected)]
# A note between reports belongs to the selected first report, never yields a negative interval.
db.execute("insert into cama_linea_de_tiempo values(1,'diagnostico','2025-06-25','2026-11-17')")
assert db.execute('select dias_reporte_diagnostico from cama_resultado_diagnostico').fetchall() == [(5,)]
def test_detection_uses_platform_report_identity_even_when_source_ids_collide(manifest):
db = sqlite3.connect(":memory:")
db.executescript('''
create table cama_reportes_biopsia(procedimiento_id, fuente_id, pac_id, fecha_reporte, grado, reporte_conocido_en);
insert into cama_reportes_biopsia values(1,'7',1,'2025-06-30','BENIGNO','2026-11-17');
insert into cama_reportes_biopsia values(2,'7',2,'2025-07-01','CARCINOMA_INVASOR','2026-11-17');
insert into cama_reportes_biopsia values(3,'7',3,'2025-07-01',null,'2026-11-17');
''')
db.execute('create view cama_deteccion_biopsia as ' + sql(manifest, 'cama_deteccion_biopsia'))
assert db.execute('select sum(maligno), sum(con_resultado), count(distinct procedimiento_id) from cama_deteccion_biopsia').fetchone() == (1, 2, 3)
from webapi.metrics import measure_definitions
d = measure_definitions(manifest)['cama/CAMA_TASA_DETECCION_HISTOPATOLOGICA']
assert d.denominator.measure_expr == d.numerator.measure_expr == 'procedimiento_id'
+94
View File
@@ -0,0 +1,94 @@
"""What this module covers: the publication metadata of CaMa's FHIR `Measure`s (figures and category captions), read
from dbt's manifest alone.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's
reference parameters, whose CaMa catalogs hold the captions and colours the dbt definitions repeat.
"""
import os
import tomllib
from pathlib import Path
import pytest
from webapi.fhir.measures import CATEGORY_LABEL, FIGURES, labels, measure_resource
from webapi.kpis import definitions_of
REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml"
@pytest.fixture(scope="module")
def manifest():
path = os.environ.get("DBT_MANIFEST")
if not path:
pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it")
return Path(path)
@pytest.fixture(scope="module")
def measures(manifest):
"""Each CaMa measure as the API serves it, by its FHIR id."""
titles = labels(manifest)
return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, "")))
for d in definitions_of("cama", manifest).values()}
def figures(measure: dict) -> list[str]:
return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES]
def captions(measure: dict) -> dict[str, tuple[str, str]]:
"""The measure's declared categories, in order: code -> (caption, colour)."""
found = {}
for e in measure["extension"]:
if e["url"] == CATEGORY_LABEL:
part = {p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
found[part["codigo"]] = (part["etiqueta"], part["color"])
return found
def catalog(name: str) -> dict[str, tuple[str, str]]:
with REFERENCE.open("rb") as f:
entries = tomllib.load(f)["cama"]["catalogos"][name]["valor"]
return {e["clave"]: (e["etiqueta"], e["color"]) for e in entries}
def no_data() -> tuple[str, str]:
with REFERENCE.open("rb") as f:
v = tomllib.load(f)["cama"]["catalogos"]["sin_dato"]["valor"]
return v["etiqueta"], v["color"]
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
"""Pins down: a distribution offers the donut and the bars, a duration its box plot, and the proportion and the
analysis' measure none. Fails if a figure is declared that the page has no builder for, or one is dropped."""
expected = {"CAMA-BIOPSIAS": ["fig_c2_donas", "fig_c2_barras"], "CAMA-BIRADS": ["fig_c2_donas", "fig_c2_barras"],
"CAMA-BIRADS456-MASTOGRAFIA": ["fig_c2_donas", "fig_c2_barras"],
"CAMA-BIRADS456-PACIENTE": ["fig_c2_donas", "fig_c2_barras"],
"CAMA-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-EU38A": ["fig_c3r_caja"],
"CAMA-CONFIRMACION-BIRADS45": [], "CAMA-BIRADS-CANCER-INVASOR": [],
"CAMA-DIAS-RESULTADO-DIAGNOSTICO": ["fig_c3r_caja"], "CAMA-TASA-DETECCION-HISTOPATOLOGICA": [],
"CAMA-HISTOPATOLOGIA-BIRADS": []}
assert {i: figures(m) for i, m in measures.items()} == expected
def test_the_category_captions_are_the_reference_catalogs(measures):
"""Pins down: the captions, colours and order the dbt definitions publish equal `cama.catalogos.*` in the
reference parameters (BI-RADS, BI-RADS 4 to 6, biopsy grade, plus «Sin dato» where a unit can lack the value).
Fails if either side is edited without the other."""
sin_dato = {"SIN_DATO": no_data()}
assert captions(measures["CAMA-BIRADS"]) == {**catalog("birads"), **sin_dato}
assert captions(measures["CAMA-BIRADS456-PACIENTE"]) == catalog("birads_4_a_6")
assert captions(measures["CAMA-BIRADS456-MASTOGRAFIA"]) == catalog("birads_4_a_6")
assert captions(measures["CAMA-BIOPSIAS"]) == {**catalog("biopsia"), **sin_dato}
assert list(captions(measures["CAMA-BIRADS"])) == [*catalog("birads"), "SIN_DATO"]
# The histopathological result by BI-RADS: the biopsy grades, then the patients without a biopsy and without a grade.
assert captions(measures["CAMA-HISTOPATOLOGIA-BIRADS"]) == {**catalog("biopsia"), "SIN_BIOPSIA": ("Sin biopsia reportada", "#C9CDD2"), **sin_dato}
def test_the_measures_without_categories_declare_none(measures):
"""Pins down: proportions and durations carry no category captions. Fails if one is attached to a measure that
has no categories."""
for fhir_id in ("CAMA-CONFIRMACION-BIRADS45", "CAMA-DIAS-TOMA-DIAGNOSTICO", "CAMA-EU38A", "CAMA-DIAS-RESULTADO-DIAGNOSTICO",
"CAMA-TASA-DETECCION-HISTOPATOLOGICA"):
assert captions(measures[fhir_id]) == {}
+1 -1
View File
@@ -45,7 +45,7 @@ def test_every_measure_and_one_report_of_each_are_valid_fhir(domain_client):
with strata included. Fails if the serialization of a scoring, a stratifier or a population breaks FHIR's shape."""
domain, client = domain_client
measures = valid(client.get(f"/{domain}/fhir/Measure").get_json())
assert measures["total"] == {"cacu": 7, "cama": 8}[domain]
assert measures["total"] == {"cacu": 7, "cama": 11}[domain]
for item in measures["entry"]:
response = client.get(f"/{domain}/fhir/Measure/{item['resource']['id']}/$evaluate-measure?periodo=2025-S1")
assert response.status_code in (200, 409), response.get_json()
+3 -3
View File
@@ -84,11 +84,11 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base):
measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows."""
resumen = base.run("definitions")["definitions"]
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers and its eight measures;
# CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures;
# TEA: the age group and its ten measures.
assert resumen["definitions"] == {"cacu": 10, "cama": 13, "tea": 11}[base.proyecto]
assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[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() == {"cacu": 7, "cama": 8, "tea": 10}[base.proyecto]
assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto]
assert base.run("definitions")["definitions"]["borradas"] == 0