"""What this module covers: `models.cohorts.cacu.post_colposcopy.frame`: the index cytology, each exclusion in its order, the attrition counts, and the definition's TOML. Fixtures: none; each test builds its timeline rows with `_row`. """ from datetime import date, timedelta from models.cohorts.cacu import post_colposcopy from models.cohorts.definition import cohort_path, read_definition RULES = {"event_grades": ["LIEAG", "CIS", "CARCINOMA"], "colposcopy_result_days": 90, "referral_lookback_days": 365} START, END, CUTOFF = date(2025, 1, 1), date(2026, 1, 1), date(2026, 12, 31) COLPOSCOPY = date(2025, 1, 1) def _row(pac_id, tipo, fecha, valor=None, fuente_id="a", fuente_tabla="t"): return {"pac_id": pac_id, "fecha": fecha, "tipo": tipo, "valor_codigo": valor, "fuente_tabla": fuente_tabla, "fuente_id": f"{pac_id}{fuente_id}"} def _after(days): return COLPOSCOPY + timedelta(days=days) def _patient(pac_id, *extra, referral=True, index_result="LIEBG"): """A patient with a colposcopy, a referral result 30 days before it, and an index cytology 200 days after.""" rows = [_row(pac_id, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(pac_id, "citologia", _after(200), fuente_id="i")] if referral: rows.append(_row(pac_id, "bethesda", _after(-30), "ASC-US", fuente_id="r")) if index_result: rows.append(_row(pac_id, "bethesda", _after(200), index_result, fuente_id="i")) return rows + list(extra) def _run(rows, rules=RULES): return post_colposcopy.frame(rows, rules, START, END, CUTOFF) def test_index_is_the_first_cytology_after_the_biopsy_window(): """Pins down, as dbt's index unit test does: a cytology 30 days after the colposcopy is within the biopsy window and doesn't count; the one at 200 days is the index, even with a later colposcopy. A patient with no colposcopy, and one whose first cytology falls outside the recruitment window, have no index. Fails if the index stops waiting for the biopsies, takes a later colposcopy, or ignores the window.""" rows = _patient(1, _row(1, "colposcopia", _after(59), fuente_id="c2"), _row(1, "citologia", _after(30), fuente_id="e")) rows += [_row(2, "citologia", _after(200), fuente_id="d"), _row(2, "bethesda", _after(200), "LIEBG", fuente_id="d")] rows += [_row(3, "colposcopia", date(2025, 11, 1), fuente_id="c"), _row(3, "citologia", date(2026, 6, 1), fuente_id="e"), _row(3, "bethesda", date(2026, 6, 1), "LIEBG", fuente_id="e"), _row(3, "bethesda", date(2025, 10, 1), "LIEBG", fuente_id="r")] members, attrition = _run(rows) assert [(m.pac_id, m.fecha_indice, m.indice_fuente_id) for m in members] == [(1, _after(200), "1i")] assert attrition[0] == ("candidatas", 1) def test_index_needs_more_than_the_wait_days(): """Pins down: a cytology exactly `colposcopy_result_days` after the colposcopy is too early, one day more is the index. Fails if the comparison becomes `>=`.""" rows = [_row(1, "colposcopia", COLPOSCOPY, fuente_id="c"), _row(1, "bethesda", _after(-1), "LIEBG", fuente_id="r"), _row(1, "citologia", _after(90), fuente_id="x"), _row(1, "citologia", _after(91), fuente_id="y"), _row(1, "vph", _after(91), "POSITIVO", fuente_id="y")] members, _ = _run(rows) assert [m.indice_fuente_id for m in members] == ["1y"] def test_index_ignores_cytologies_after_the_cutoff(): """Pins down: a cytology after the cut-off is not an index. Fails if the cut-off stops applying.""" rows = _patient(1) members, attrition = post_colposcopy.frame(rows, RULES, START, END, _after(100)) assert members == [] and attrition[0] == ("candidatas", 0) def test_member_carries_the_index_results(): """Pins down: the member's variables are the squamous, glandular and HPV results of the index cytology only, and a missing one is None. Fails if results of other samples leak in or a variable is renamed.""" rows = _patient(1, _row(1, "glandular", _after(200), "AGC", fuente_id="i"), _row(1, "vph", _after(250), "POSITIVO", fuente_id="z")) members, _ = _run(rows) assert members[0].variables == {"pap_0": "LIEBG", "glandular_0": "AGC", "hpv_0": None} def test_prior_event_excludes_a_biopsy_with_the_outcome_before_the_index(): """Pins down: a CIN2+ biopsy before the index date flags the patient; a negative one, or a CIN2+ on the index date, doesn't. Fails if the event grades or the strict `<` change.""" rows = (_patient(1, _row(1, "biopsia", _after(10), "CIS")) + _patient(2, _row(2, "biopsia", _after(10), "NEGATIVO")) + _patient(3, _row(3, "biopsia", _after(200), "LIEAG"))) members, attrition = _run(rows) assert [m.pac_id for m in members] == [2, 3] assert attrition[:2] == [("candidatas", 3), ("sin prior_event", 2)] def test_prior_treatment_excludes_a_treatment_before_the_index(): """Pins down: a treatment before the index date flags the patient (she belongs to the post-treatment cohort); one on the index date doesn't. Fails if the interval's end or the event type change.""" rows = (_patient(1, _row(1, "tratamiento", _after(100))) + _patient(2, _row(2, "tratamiento", _after(200)))) members, attrition = _run(rows) assert [m.pac_id for m in members] == [2] assert attrition[2] == ("sin prior_treatment", 1) def test_no_referral_result_looks_back_from_the_colposcopy(): """Pins down, as dbt's unit test does: a result 100 days before the colposcopy is the referral and the patient stays; one 400 days before (past the lookback) or one after the colposcopy leaves her out; 365 days exactly still counts. Fails if the lookback, its direction or the result types change.""" def case(pac_id, tipo, days, valor="LIEBG"): return _patient(pac_id, _row(pac_id, tipo, _after(days), valor, fuente_id="q"), referral=False) rows = (case(1, "vph", -100, "POSITIVO") + case(2, "bethesda", -400) + case(3, "bethesda", 14) + case(4, "glandular", -365, "AGC") + case(5, "vph", -366, "POSITIVO")) members, attrition = _run(rows) assert [m.pac_id for m in members] == [1, 4] assert attrition[3] == ("sin no_referral_result", 2) def test_no_referral_result_needs_a_value(): """Pins down: a referral row without a code is not a result. Fails if null codes start to count.""" rows = _patient(1, _row(1, "bethesda", _after(-10), None, fuente_id="q"), referral=False) members, _ = _run(rows) assert members == [] def test_no_index_result_needs_a_result_of_the_index_cytology(): """Pins down: an index cytology with only a glandular result (or only HPV) stays; one with none, or whose results belong to another sample, is left out. Fails if the rule reads only the squamous result or ignores the sample.""" rows = (_patient(1, _row(1, "glandular", _after(200), "AGC", fuente_id="i"), index_result=None) + _patient(2, _row(2, "vph", _after(200), "NEGATIVO", fuente_id="i"), index_result=None) + _patient(3, index_result=None) + _patient(4, _row(4, "bethesda", _after(200), None, fuente_id="i"), index_result=None) + _patient(5, _row(5, "vph", _after(250), "POSITIVO", fuente_id="z"), index_result=None)) members, attrition = _run(rows) assert [m.pac_id for m in members] == [1, 2] assert attrition[4] == ("sin no_index_result", 2) def test_attrition_charges_each_rule_only_for_what_it_removes_from_the_rest(): """Pins down: a patient flagged by several rules is charged to the first in order. Fails if each rule counted against all candidates.""" rows = _patient(1, _row(1, "biopsia", _after(10), "CIS"), _row(1, "tratamiento", _after(20)), referral=False, index_result=None) rows += _patient(2) members, attrition = _run(rows) assert [m.pac_id for m in members] == [2] assert attrition == [("candidatas", 2), ("sin prior_event", 1), ("sin prior_treatment", 1), ("sin no_referral_result", 1), ("sin no_index_result", 1)] def test_definition_loads_and_resolves_the_frame(): """Pins down: the TOML loads through `read_definition`, with the dbt rule parameters, and its `expression` resolves to `post_colposcopy.frame`. Fails if a required key is dropped or the expression is renamed.""" definition = read_definition(cohort_path("cacu", "post_colposcopy")) assert definition.url == "cacu/cohorte_post_colposcopia" assert definition.function() is post_colposcopy.frame assert definition.reglas["event_grades"] == ["LIEAG", "CIS", "CARCINOMA"] assert (definition.reglas["colposcopy_result_days"], definition.reglas["referral_lookback_days"]) == (90, 365) assert [v.nombre for v in definition.variables] == ["pap_0", "glandular_0", "hpv_0"]