Files
WebApi/tests/test_cacu_measure_metadata.py
edgar d156bf3c99 test(cacu): cover the times along the screening route
The CaCu catalog holds fourteen measures. A fixture adds H-007, who goes the whole route in order, and a test pins the
population, the cases and the median of each of the five new times.
2026-11-22 00:23:23 -06:00

218 lines
12 KiB
Python

"""What this module covers: the publication metadata of CaCu's FHIR `Measure`s (figures, category captions and the
optional category groups) read from dbt's manifest alone, and the checks that keep a composition's groups consistent.
Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's
reference parameters, whose CaCu catalogs and lists hold the captions, colours and memberships the dbt definitions
repeat; Transformation's `dbt_project.yml` next to the manifest, whose variables repeat the same lists.
"""
import os
import tomllib
from datetime import date, datetime, timezone
from pathlib import Path
from types import SimpleNamespace
import pytest
from fhir.resources.R4B import get_fhir_model_class
from webapi.compositions import CompositionAnswer, InvalidCategoryGroups, category_groups
from webapi.fhir.measures import CATEGORY_GROUP, CATEGORY_LABEL, FIGURES, labels, measure_report, measure_resource
from webapi.kpis import definitions_of
REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml"
GROUPED = {"CACU-EU7": "citologia_anomala", "CACU-CONFIRMACION-CITOLOGIA": "deteccion_grados"}
@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)
def _measures(domain: str, manifest: Path) -> dict[str, dict]:
titles = labels(manifest)
return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, "")))
for d in definitions_of(domain, manifest).values()}
@pytest.fixture(scope="module")
def measures(manifest):
"""Each CaCu measure as the API serves it, by its FHIR id."""
return _measures("cacu", manifest)
def reference(*keys: str):
with REFERENCE.open("rb") as f:
node = tomllib.load(f)
for key in keys:
node = node[key]
return node["valor"]
def figures(measure: dict) -> list[str]:
return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES]
def categories(measure: dict) -> dict[str, dict[str, str]]:
"""The measure's declared categories, in order: code -> its parts (etiqueta, color and, if any, grupo)."""
return {part["codigo"]: part for part in (
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
for e in measure["extension"] if e["url"] == CATEGORY_LABEL)}
def groups(measure: dict) -> dict[str, str]:
"""The measure's category groups, in order: code -> caption."""
return {part["codigo"]: part["etiqueta"] for part in (
{p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]}
for e in measure["extension"] if e["url"] == CATEGORY_GROUP)}
def test_each_contract_publishes_the_figures_the_page_can_draw(measures):
"""Pins down: the two distributions offer the donut and the bars and the nine durations their box plot; the C1
proportions and the risk bands none, because no figure is approved for them yet. Fails if a figure is declared
that the page has no builder for, or one is dropped."""
assert {i: figures(m) for i, m in measures.items()} == {
"CACU-EU7": ["fig_c2_donas", "fig_c2_barras"], "CACU-CONFIRMACION-CITOLOGIA": ["fig_c2_donas", "fig_c2_barras"],
"CACU-EU-TIEMPO-REPORTE": ["fig_c3r_caja"], "CACU-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"],
"CACU-DIAS-TOMA-TRATAMIENTO": ["fig_c3r_caja"], "CACU-DIAS-DIAGNOSTICO-TRATAMIENTO": ["fig_c3r_caja"],
"CACU-DIAS-TOMA-COLPOSCOPIA": ["fig_c3r_caja"], "CACU-DIAS-TOMA-BIOPSIA": ["fig_c3r_caja"],
"CACU-DIAS-RESULTADO-COLPOSCOPIA": ["fig_c3r_caja"], "CACU-DIAS-COLPOSCOPIA-BIOPSIA": ["fig_c3r_caja"],
"CACU-DIAS-BIOPSIA-DIAGNOSTICO": ["fig_c3r_caja"],
"CACU-EU13": [], "IND1": [], "CACU-RIESGO-BANDA": []}
def test_the_category_captions_are_the_reference_catalogs(measures):
"""Pins down: the captions, colours and order of the cytology distribution equal `cacu.catalogos.citologia` plus
`cacu.catalogos.sin_dato`, and the confirmation's grades `cacu.catalogos.biopsia`. Fails if either side is edited
without the other."""
sin_dato = reference("cacu", "catalogos", "sin_dato")
citologia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "citologia")}
eu7 = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-EU7"]).items()}
assert eu7 == {**citologia, "SIN_DATO": (sin_dato["etiqueta"], sin_dato["color"])}
biopsia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "biopsia")}
confirmacion = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-CONFIRMACION-CITOLOGIA"]).items()}
assert list(confirmacion)[:len(biopsia)] == list(biopsia)
assert {c: confirmacion[c] for c in biopsia} == biopsia
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
def test_the_anomalous_group_is_the_reference_list(measures, manifest, fhir_id):
"""Pins down: a grouped composition's ANORMAL members are exactly the parameter list the grouping is defined by
(`cacu.citologia_anomala` for EU7, `cacu.deteccion_grados` for the confirmation) and the dbt variable of the same
name; the other declared categories are NO_ANORMAL, «Sin dato» its own group and «Sin biopsia aún» none. Fails if
a membership drifts from the lists the measures count with."""
yaml = pytest.importorskip("yaml")
lista = GROUPED[fhir_id]
project = manifest.parent.parent / "dbt_project.yml"
dbt_vars = yaml.safe_load(project.read_text(encoding="utf-8"))["vars"] if project.exists() else None
parts = categories(measures[fhir_id])
anomalous = sorted(c for c, p in parts.items() if p.get("grupo") == "ANORMAL")
assert anomalous == sorted(reference("cacu", lista))
if dbt_vars is not None:
assert anomalous == sorted(dbt_vars[lista])
assert all(p.get("grupo") == "NO_ANORMAL" for c, p in parts.items()
if c not in anomalous and c not in ("SIN_DATO", "SIN_BIOPSIA"))
assert parts["SIN_DATO"]["grupo"] == "SIN_DATO"
assert "grupo" not in parts.get("SIN_BIOPSIA", {})
def test_the_group_captions_are_the_reference_ones(measures):
"""Pins down: EU7's groups are `cacu.catalogos.resultado_anormal` plus «Sin dato», and the confirmation's
«Menor que LIEAG» / «LIEAG o más» plus its no-data category's caption, in that order. Fails if a caption drifts."""
resultado = {e["clave"]: e["etiqueta"] for e in reference("cacu", "catalogos", "resultado_anormal")}
assert groups(measures["CACU-EU7"]) == {**resultado, "SIN_DATO": "Sin dato"}
assert groups(measures["CACU-CONFIRMACION-CITOLOGIA"]) == {
"NO_ANORMAL": "Menor que LIEAG", "ANORMAL": "LIEAG o más", "SIN_DATO": "Biopsia sin grado"}
def test_measures_without_groups_publish_none(manifest, measures):
"""Pins down: groups are opt-in. CaCu's other measures and every CaMa and TEA measure publish neither a
`categoria-grupo` nor a `grupo` inside a category. Fails if the new extensions leak onto measures that don't
declare them (their clients see exactly what they see without groups)."""
others = {**{i: m for i, m in measures.items() if i not in GROUPED},
**_measures("cama", manifest), **_measures("tea", manifest)}
for fhir_id, measure in others.items():
assert not groups(measure), fhir_id
assert all("grupo" not in part for part in categories(measure).values()), fhir_id
@pytest.mark.parametrize("fhir_id", sorted(GROUPED))
def test_a_grouped_measure_is_valid_fhir_r4b(measures, fhir_id):
"""Pins down: the nested `grupo` and the `categoria-grupo` extensions keep the Measure valid FHIR R4B. Fails if
the extensions are shaped in a way FHIR's models reject."""
get_fhir_model_class("Measure").model_validate(measures[fhir_id])
def test_a_composite_stratum_carries_its_caption(manifest):
"""Pins down: in a composition's report, a stratum value of a crossed stratifier (status by result) carries the
caption of `meta.etiquetas_estrato` as its display, and a value without one (an age group) keeps the code alone.
Fails if the captions stop reaching the report or start replacing codes."""
definition = next(d for d in definitions_of("cacu", manifest).values() if d.measure_id == "CACU_EU7")
result = CompositionAnswer(report_id=1, categories={"NORMAL": 2, "ASC-US": 1}, stored_before=True, strata={
"estatus_seguimiento": {"PRE_COLPOSCOPIA": {"NORMAL": 2}, "POST_COLPOSCOPIA": {"ASC-US": 1}},
"grupo_edad": {"25-34": {"NORMAL": 2, "ASC-US": 1}}})
question = SimpleNamespace(event_cutoff=None, knowledge_cutoff=None)
period = SimpleNamespace(inicio=date(2025, 7, 1), fin=date(2026, 1, 1))
report = measure_report(definition, question, result, period, datetime(2026, 1, 2, tzinfo=timezone.utc))
shown = {}
for stratifier in report["group"][0]["stratifier"][1:]:
for stratum in stratifier["stratum"]:
value = stratum["component"][0]["value"]["coding"][0]
shown[value["code"]] = value.get("display")
assert shown == {"PRE_COLPOSCOPIA": "Pre colposcopia", "POST_COLPOSCOPIA": "Post colposcopia", "25-34": None}
get_fhir_model_class("MeasureReport").model_validate(report)
RULE = {"sin_dato": "SIN_DATO", "etiquetas": {
"A": {"etiqueta": "A", "color": "#000000", "grupo": "G1"}, "B": {"etiqueta": "B", "color": "#000000", "grupo": "G2"},
"APARTE": {"etiqueta": "Aparte", "color": "#000000"},
"SIN_DATO": {"etiqueta": "Sin dato", "color": "#000000", "grupo": "SIN_DATO"}},
"grupos": {"G1": "Uno", "G2": "Dos", "SIN_DATO": "Sin dato"}}
def _with(**changes) -> dict:
rule = {**RULE, "etiquetas": {k: dict(v) for k, v in RULE["etiquetas"].items()}, "grupos": dict(RULE["grupos"])}
for path, value in changes.items():
*parents, last = path.split("__")
node = rule
for p in parents:
node = node[p]
if value is None:
node.pop(last, None)
else:
node[last] = value
return rule
def test_valid_groups_are_returned_in_order_and_a_category_may_stay_apart():
"""Pins down: declared and used groups come back in their declared order, and a category without `grupo` (one kept
apart) is allowed. Fails if a valid declaration is rejected or reordered."""
assert list(category_groups("x", RULE).items()) == [("G1", "Uno"), ("G2", "Dos"), ("SIN_DATO", "Sin dato")]
def test_a_composition_without_groups_has_none():
"""Pins down: groups are optional; neither `grupos` nor any `grupo` means none. Fails if declaring groups becomes
mandatory (CaMa's and TEA's compositions declare none)."""
rule = {k: v for k, v in RULE.items() if k != "grupos"}
rule["etiquetas"] = {c: {k: v for k, v in s.items() if k != "grupo"} for c, s in RULE["etiquetas"].items()}
assert category_groups("x", rule) == {}
@pytest.mark.parametrize("rule, message", [
(_with(grupos=None), "`grupos` is missing"),
(_with(etiquetas__A__grupo="G9"), "undeclared groups"),
(_with(grupos__G3="Tres"), "groups without categories"),
(_with(grupos__G1=" "), "non-empty caption"),
(_with(etiquetas__SIN_DATO__grupo="G1", grupos__SIN_DATO=None), "goes alone"),
(_with(etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "goes alone"),
(_with(etiquetas__SIN_DATO__grupo=None, etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "no-data category's own"),
])
def test_invalid_groups_fail_the_load(rule, message):
"""Pins down: each way a declaration can't be read as a partition fails with its reason (a group named but
missing, one declared but unused, an empty caption, the no-data category mixed with others or without its own
group). Fails if one of them is accepted, because the page would draw a wrong or incomplete grouping."""
with pytest.raises(InvalidCategoryGroups, match=message):
category_groups("x", rule)