b1bbbc25b4
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.
259 lines
16 KiB
Python
259 lines
16 KiB
Python
"""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()
|