CaCu FHIR: follow-up search and filters, stage extensions, and the referral PPV contract test

Patient search accepts follow-up age bounds and a partial name or identifier over the
whole query. Diagnostic reports carry the stage states and dates up to a cut-off. The
integration test expects the referral PPV measures and the screening-round strata of the
cytology distribution, and checks their counts, intervals and nesting.
This commit is contained in:
Angel Capetillo Zavala
2026-11-27 18:42:48 -06:00
parent 9c89c9e10d
commit 1b5fa748af
2 changed files with 109 additions and 5 deletions
+61 -1
View File
@@ -55,6 +55,50 @@ CODES = { # platform code -> the current platform's
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
"result": "citologia_alto_grado"} # fmt: skip
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
# Measures with no legacy reference fixture: checked by invariants.
NEW_MEASURES = {"CACU_VPH_GENOTIPO", "CACU_BIOPSIA_RESULTADOS", "CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
"CACU_TIEMPO_DIAGNOSTICO_CIE10", "CACU_VPP_COLPOSCOPIA", "CACU_VPP_BIOPSIA"}
NEW_STRATA = {"screening_round", "result_initial", "result_subsequent"} # of CACU_EU7
RESULTS = set(CODES) | set(CODES.values()) | {"ASC-US", "ASC-H", "AGC", "CIS", "adenocarcinoma"}
def _count(stratum: dict, key: str, code: str = "initial-population") -> int:
return stratum.get(key, {}).get(code, 0)
def _check_eu7_rounds(populations: dict, strata: dict, where: tuple) -> None:
"""The screening rounds partition the evaluated patients, and each round's results do too."""
rounds = strata.get("screening_round", {})
assert sum(c["initial-population"] for c in rounds.values()) == populations["initial-population"], where
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
for rnd in ("initial", "subsequent"):
results = strata.get(f"result_{rnd}", {})
assert sum(c["initial-population"] for c in results.values()) == _count(rounds, rnd), where
assert set(results) <= RESULTS, where
def _check_ppv(populations: dict, score, extensions: dict, strata: dict, where: tuple) -> None:
"""A referral PPV: counts of patients, one denominator, nested numerators and groups."""
total, den = populations["numerator"], populations["denominator"]
assert populations["initial-population"] == den and 0 <= total <= den, where
if den:
assert score == pytest.approx(total / den) and 0 <= extensions["ic-bajo"] <= score <= extensions["ic-alto"] <= 1, where
else:
assert score is None and not extensions, where
levels = strata.get("histology_level", {})
if den:
assert set(levels) == {"LIEBG+", "LIEAG+", "invasive"}, where
assert all(c["denominator"] == den for c in levels.values()), where
low, high, invasive = (levels[k]["numerator"] for k in ("LIEBG+", "LIEAG+", "invasive"))
assert total == low >= high >= invasive >= 0, where
cytology = strata.get("referral_cytology", {})
nested = [_count(cytology, g, "denominator") for g in ("ASCUS+", "LSIL+", "HSIL+")]
assert nested == sorted(nested, reverse=True), where
for cell in cytology.values():
assert 0 <= cell["numerator"] <= cell["denominator"] <= den, where
rounds = strata.get("screening_round", {})
assert sum(c["denominator"] for c in rounds.values()) == den, where
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
def _patients(q) -> dict[str, int]:
@@ -107,7 +151,20 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
# (no risk batch yet, so the risk bands are empty as they were).
reference = json.loads((REFERENCE / "indicators.json").read_text())
(measures,) = pages(api, "/cacu/fhir/Measure")
published = {e["resource"]["name"] for e in measures["entry"]}
assert published == set(reference) | NEW_MEASURES
for measure in [e["resource"] for e in measures["entry"]]:
if measure["name"] not in reference: # New measures have no legacy fixture.
if measure["name"].startswith("CACU_VPP_"):
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
reports = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
assert len(reports) == len(PERIODS), measure["name"]
for entry in reports:
populations, score, extensions, strata = _report(entry, measure["name"])
_check_ppv(populations, score, extensions, strata,
(measure["name"], entry["resource"]["period"]["start"]))
continue
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
"event-cutoff": CAPTURED_ON} # fmt: skip
found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
@@ -116,7 +173,10 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
a, b = _report(ours, name), _report(theirs, name)
where = (name, ours["resource"]["period"]["start"])
assert a[0] == b[0] and a[3] == b[3], where
legacy = {k: v for k, v in a[3].items() if name != "CACU_EU7" or k not in NEW_STRATA}
assert a[0] == b[0] and legacy == b[3], where
if name == "CACU_EU7": # the new round breakdowns leave every legacy figure as it was
_check_eu7_rounds(a[0], a[3], where)
if cohort: # scores its count; the current platform gave none
assert b[1] is None and a[1] == a[0]["initial-population"], where
continue