Files
models/tests/test_contract.py
T
edgar c8bca59334 contract: translate the risk estimation contract to English
riesgo.py becomes contract.py: RiskEstimator, Risk, Provenance and the
CacuStandIn, TeaStandIn and CamaStandIn stand-ins. Fields that mirror
the batch columns keep their names, and the stand-ins' provenance is
unchanged. Tests say why each one exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 19:30:08 +00:00

153 lines
6.3 KiB
Python

"""What this module covers: the `RiskEstimator` contract and the three stand-ins in `models.contract`
(`CacuStandIn`, `TeaStandIn`, `CamaStandIn`).
Fixtures: no pytest fixtures. Each stand-in has a small hand-written frame (`COLUMNS*`, `ROWS*`) shaped like
its cohort's: `pac_id`, `fecha_indice`, outcome columns and the predictors the rule reads. `monkeypatch`
changes a rule to check that the provenance follows it.
"""
import pytest
from models import contract
from models.contract import CAMA_RULE, TEA_RULE, CacuStandIn, CamaStandIn, Risk, RiskEstimator, TeaStandIn
COLUMNS = ["pac_id", "fecha_indice", "c", "pap_0", "hpv_0"]
ROWS = [(1, "2024-07-01", 0, "NORMAL", "NEGATIVO"), (2, "2024-08-01", 0, "LIEAG", "POSITIVO"),
(3, "2024-09-01", 0, None, None)]
def test_the_cacu_stand_in_meets_the_contract():
"""Pins down: `CacuStandIn` is a `RiskEstimator` (runtime check of the protocol).
Fails if the protocol or the stand-in renames `cohort_url`, `outcome`, `provenance` or `estimate`.
"""
assert isinstance(CacuStandIn(), RiskEstimator)
def test_one_risk_per_member_and_horizon_in_frame_order():
"""Pins down: `estimate` returns one `Risk` per member and horizon, members in the frame's order,
probabilities in [0, 1], no interval.
Fails if risks are grouped by horizon, reordered, or the interval stops being `None`.
"""
risks = CacuStandIn(horizons=(0.0, 1.0)).estimate(COLUMNS, ROWS)
assert [(r.pac_id, r.horizonte_anios) for r in risks] == [(1, 0.0), (1, 1.0), (2, 0.0), (2, 1.0), (3, 0.0), (3, 1.0)]
assert all(isinstance(r, Risk) and 0 <= r.probabilidad <= 1 and r.ic_bajo is None for r in risks)
def test_the_cacu_rule_adds_per_baseline_predictor():
"""Pins down: normal or missing results add nothing; an abnormal pap and a positive HPV add their terms.
Fails if a term of `CACU_RULE` changes or a null pap starts counting as abnormal.
"""
p = {r.pac_id: r.probabilidad for r in CacuStandIn().estimate(COLUMNS, ROWS)}
assert p == {1: 0.01, 2: 0.16, 3: 0.01}
def test_it_is_deterministic():
"""Pins down: two instances give the same risks and the same provenance.
Fails if anything random or time-dependent enters the stand-in.
"""
a, b = CacuStandIn(), CacuStandIn()
assert a.estimate(COLUMNS, ROWS) == b.estimate(COLUMNS, ROWS)
assert a.provenance() == b.provenance()
def test_provenance_has_the_four_keys_and_its_sha_follows_the_rule(monkeypatch):
"""Pins down: `Provenance.as_dict()` has exactly the four keys a batch stores, none empty, and
`modelo_sha` changes when the rule changes.
Fails if a provenance field is renamed (the batch columns wouldn't match) or the sha stops covering
the rule.
"""
provenance = CacuStandIn().provenance()
assert set(provenance.as_dict()) == {"modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha"}
assert all(provenance.as_dict().values())
monkeypatch.setitem(contract.CACU_RULE, "vph_positivo", 0.2)
assert CacuStandIn().provenance().modelo_sha != provenance.modelo_sha
def test_without_its_predictors_it_fails_and_names_them():
"""Pins down: a frame without a predictor the rule reads raises `ValueError` naming it.
Fails if a missing column is silently treated as null.
"""
with pytest.raises(ValueError, match="pap_0"):
CacuStandIn().estimate(["pac_id", "hpv_0"], [(1, None)])
COLUMNS_TEA = ["pac_id", "fecha_indice", "d", "t", "mchat_0", "apgar_5min", "ingreso_ucin", "n_antecedentes",
"hipoacusia_0"]
def test_the_tea_stand_in_meets_the_contract_and_reads_its_cohort():
"""Pins down: `TeaStandIn` is a `RiskEstimator` over `tea/cohorte_tamizaje` at 4 years.
Fails if its default cohort or horizon changes.
"""
estimator = TeaStandIn()
assert isinstance(estimator, RiskEstimator)
assert estimator.cohort_url == "tea/cohorte_tamizaje" and estimator.horizons == (4.0,)
def test_the_tea_rule_adds_mchat_nicu_and_low_apgar():
"""Pins down: a low-risk M-CHAT adds nothing; a high-risk one, NICU admission and a low Apgar each add
their term; missing values add nothing.
Fails if a term of `TEA_RULE` is dropped or the Apgar cut-off changes side.
"""
rows = [(1, None, None, None, "RIESGO_BAJO", 9.0, 0.0, 0, None),
(2, None, None, None, "RIESGO_ALTO", 6.0, 1.0, 2, "LEVE"),
(3, None, None, None, None, None, None, 0, None)]
r = TEA_RULE
assert [x.probabilidad for x in TeaStandIn().estimate(COLUMNS_TEA, rows)] == pytest.approx(
[r["base"], r["base"] + r["mchat_alto"] + r["ucin"] + r["apgar_bajo"], r["base"]])
def test_the_tea_stand_in_without_its_predictors_fails():
"""Pins down: a TEA frame without `mchat_0` raises `ValueError` naming it.
Fails if the TEA stand-in stops checking its columns.
"""
with pytest.raises(ValueError, match="mchat_0"):
TeaStandIn().estimate(["pac_id", "fecha_indice"], [])
COLUMNS_CAMA = ["pac_id", "fecha_indice", "d", "t", "birads_0", "calidad_0", "n_ordenes_previas"]
def test_the_cama_stand_in_meets_the_contract_and_reads_its_cohort():
"""Pins down: `CamaStandIn` is a `RiskEstimator` over `cama/cohorte_tamizaje` at 1 year.
Fails if its default cohort or horizon changes.
"""
estimator = CamaStandIn()
assert isinstance(estimator, RiskEstimator)
assert estimator.cohort_url == "cama/cohorte_tamizaje" and estimator.horizons == (1.0,)
def test_the_cama_rule_adds_by_index_birads_and_4a_counts_as_4():
"""Pins down: BI-RADS 2 and a missing BI-RADS add nothing; 4A adds as 4; 5 adds its term.
Fails if `BIRADS_SUSPICION` loses the 4A/4B/4C mapping or a term of `CAMA_RULE` changes.
"""
rows = [(1, None, None, None, "B2", None, 0), (2, None, None, None, "B4A", None, 0),
(3, None, None, None, "B5", None, 0), (4, None, None, None, None, None, 0)]
r = CAMA_RULE
assert [x.probabilidad for x in CamaStandIn().estimate(COLUMNS_CAMA, rows)] == pytest.approx(
[r["base"], r["base"] + r["birads_4"], r["base"] + r["birads_5"], r["base"]])
def test_the_cama_stand_in_without_its_predictor_fails():
"""Pins down: a CaMa frame without `birads_0` raises `ValueError` naming it.
Fails if the CaMa stand-in stops checking its columns.
"""
with pytest.raises(ValueError, match="birads_0"):
CamaStandIn().estimate(["pac_id", "fecha_indice"], [])