0c69140d2e
The 161-day diagnosis of the fixture is out of the 120-day window, and the sample-to-treatment horizon (180) leaves the August and October samples pending. The comparison with the kit's oracle (180 days to the diagnosis) is marked as an expected divergence until the oracle is regenerated with the project's horizon. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
138 lines
7.6 KiB
Python
138 lines
7.6 KiB
Python
"""What this module covers: `webapi.kpis`, the route that answers a measure's periods on request as a FHIR `Bundle`
|
|
of `MeasureReport`s.
|
|
|
|
Fixtures: `base`, `manifest` and `kit` from `test_metrics_on_request` (the CaCu fixture database through the cycle,
|
|
dbt's manifest, the kit's snapshot; skipped without `DBT_MANIFEST`); `client`, a Flask app with only this domain's KPI
|
|
blueprint.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from flask import Flask
|
|
|
|
from test_metrics_on_request import EU7, EU13, IND1, base, kit, manifest, reports # noqa: F401
|
|
from webapi.kpis import kpis_blueprint
|
|
|
|
|
|
@pytest.fixture
|
|
def client(base, manifest): # noqa: F811
|
|
app = Flask(__name__)
|
|
app.register_blueprint(kpis_blueprint("cacu", base.dominio, manifest), url_prefix="/cacu")
|
|
return app.test_client()
|
|
|
|
|
|
def counts(resource: dict) -> dict[str, int]:
|
|
(group,) = resource["group"]
|
|
return {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
|
|
|
|
|
|
def history_entry(resource: dict) -> int:
|
|
(entry,) = [e for e in resource["extension"] if e["url"].endswith("/reporte-id")]
|
|
return entry["valueInteger"]
|
|
|
|
|
|
def test_a_measure_s_periods_come_as_a_bundle_of_measure_reports(base, client, kit): # noqa: F811
|
|
"""Pins down the contract: one `MeasureReport` per period asked, in order, with the kit's numbers. Fails if the
|
|
route stops answering each period, changes the shape, or the counts drift from what the cycle published."""
|
|
response = client.get("/cacu/indicadores/IND1?periodos=2025-S1,2025-S2")
|
|
bundle = response.get_json(force=True)
|
|
|
|
assert response.status_code == 200 and response.mimetype == "application/fhir+json"
|
|
assert (bundle["resourceType"], bundle["type"], bundle["total"]) == ("Bundle", "searchset", 2)
|
|
for entry, period_id in zip(bundle["entry"], ("2025-S1", "2025-S2")):
|
|
report = entry["resource"]
|
|
assert report["resourceType"] == "MeasureReport" and report["measure"] == "cacu/IND1|0.3.2"
|
|
numerator, denominator = kit[IND1][period_id]["published"]["total|total"]
|
|
assert counts(report) == {"initial-population": denominator, "denominator": denominator,
|
|
"numerator": numerator}
|
|
if os.environ.get("MEASURE_REPORT_OUT"):
|
|
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_ind1.json").write_text(
|
|
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
|
|
|
|
def test_without_a_knowledge_cutoff_the_last_load_makes_the_answer_stable(base, client): # noqa: F811
|
|
"""Pins down: by default the knowledge cut-off is the last load's start, so asking again before the next load
|
|
reads the stored answer. Fails if the default becomes "now", which would store a new answer per request."""
|
|
first = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
|
|
before = reports(base)
|
|
second = client.get("/cacu/indicadores/IND1?periodos=2025-S1").get_json(force=True)
|
|
|
|
assert history_entry(second["entry"][0]["resource"]) == history_entry(first["entry"][0]["resource"])
|
|
assert reports(base) == before
|
|
|
|
|
|
def test_a_measure_with_strata_brings_its_stratifier(client):
|
|
"""Pins down: EU13's reports carry its strata, by age and by follow-up status. Fails if the route drops one."""
|
|
bundle = client.get("/cacu/indicadores/CACU_EU13?periodos=2025-S1").get_json(force=True)
|
|
stratifiers = bundle["entry"][0]["resource"]["group"][0]["stratifier"]
|
|
|
|
assert [s["code"][0]["text"] for s in stratifiers] == ["grupo_edad", "estatus_seguimiento"]
|
|
if os.environ.get("MEASURE_REPORT_OUT"):
|
|
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu13.json").write_text(
|
|
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
|
|
|
|
def test_the_list_names_what_is_answered_on_request(client):
|
|
"""Pins down: `/indicadores` lists the measures the manifest defines for the domain. Fails if one is missing."""
|
|
listed = {m["id"] for m in client.get("/cacu/indicadores").get_json()}
|
|
|
|
assert listed == {IND1.split("/")[1], EU13.split("/")[1], EU7.split("/")[1], "CACU_EU_TIEMPO_REPORTE",
|
|
"CACU_DIAS_TOMA_DIAGNOSTICO", "CACU_DIAS_TOMA_TRATAMIENTO", "CACU_DIAS_DIAGNOSTICO_TRATAMIENTO",
|
|
"CACU_DIAS_TOMA_COLPOSCOPIA", "CACU_DIAS_TOMA_BIOPSIA", "CACU_DIAS_RESULTADO_COLPOSCOPIA",
|
|
"CACU_DIAS_COLPOSCOPIA_BIOPSIA", "CACU_DIAS_BIOPSIA_DIAGNOSTICO",
|
|
"CACU_CONFIRMACION_CITOLOGIA", "CACU_RIESGO_BANDA"}
|
|
|
|
|
|
def test_a_duration_comes_as_a_report_with_its_median_and_quartiles(client):
|
|
"""Pins down the route for durations: the samples measurable and measured as populations, the median as the
|
|
score in days with the quartiles as its extensions, and the event cut-off it was asked at (the last load's day
|
|
by default). 2025-S2's samples resolved in 40 and 161 days, and the 120-day horizon keeps only the first. Fails if a duration stops being served or its
|
|
contract changes."""
|
|
bundle = client.get("/cacu/indicadores/CACU_DIAS_TOMA_DIAGNOSTICO?periodos=2025-S2").get_json(force=True)
|
|
(entry,) = bundle["entry"]
|
|
report = entry["resource"]
|
|
(group,) = report["group"]
|
|
assert report["measure"] == "cacu/CACU_DIAS_TOMA_DIAGNOSTICO|0.2.3"
|
|
assert {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]} == {
|
|
"initial-population": 4, "measure-observation": 1}
|
|
assert group["measureScore"]["value"] == 40.0 and group["measureScore"]["unit"] == "d"
|
|
assert [e["valueDecimal"] for e in group["measureScore"]["extension"]] == [40.0, 40.0]
|
|
assert any(e["url"].endswith("corte-evento") for e in report["extension"])
|
|
if os.environ.get("MEASURE_REPORT_OUT"):
|
|
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_dias.json").write_text(
|
|
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
|
|
|
|
@pytest.mark.parametrize(("path", "status"), [
|
|
("/cacu/indicadores/NOPE?periodos=2025-S1", 404),
|
|
("/cacu/indicadores/IND1", 400),
|
|
("/cacu/indicadores/IND1?periodos=2025-S1&corte_evento=30-06-2025", 400),
|
|
("/cacu/indicadores/IND1?periodos=2025-S1&corte_conocimiento=ayer", 400),
|
|
("/cacu/indicadores/IND1?periodos=2031-S1", 404),
|
|
])
|
|
def test_a_bad_question_gets_a_clear_error(client, path, status):
|
|
"""Pins down the errors: an unknown measure or period is 404, a missing or misspelled parameter 400. Fails if one
|
|
of them becomes a 500."""
|
|
response = client.get(path)
|
|
|
|
assert response.status_code == status and "error" in response.get_json()
|
|
|
|
|
|
def test_a_composition_comes_with_its_categories(client, kit):
|
|
"""Pins down: EU7's reports carry the categories as a `resultado` stratifier, with the kit's counts, under the
|
|
route's default knowledge cut-off (the last load). Fails if the route stops telling compositions from
|
|
proportions, or a result's knowledge date stops being compared as the type it's stored in."""
|
|
bundle = client.get("/cacu/indicadores/CACU_EU7?periodos=2025-S1,2025-S2").get_json(force=True)
|
|
stratifiers = [e["resource"]["group"][0]["stratifier"][0] for e in bundle["entry"]]
|
|
|
|
assert [s["code"] for s in stratifiers] == [[{"text": "resultado"}]] * 2
|
|
for stratifier, period_id in zip(stratifiers, ("2025-S1", "2025-S2")):
|
|
expected = {k.split("|")[2]: n for k, n in kit[EU7][period_id]["published"].items() if k.startswith("total|")}
|
|
assert {s["value"]["text"]: s["population"][0]["count"] for s in stratifier["stratum"]} == expected
|
|
if os.environ.get("MEASURE_REPORT_OUT"):
|
|
Path(os.environ["MEASURE_REPORT_OUT"]).with_name("bundle_eu7.json").write_text(
|
|
json.dumps(bundle, indent=2, ensure_ascii=False), encoding="utf-8")
|