"""What this module covers: `GET /cacu/riesgos/lotes` and the confirm/void routes (`webapi.risk_batches`): which batches are listed, that confirming or voiding moves a batch off the list and that the route rejects a missing reason or an unknown batch. The reads and writes behind it are Persistance's, tested there. Fixtures: `client`, the app over the kit's CaCu demonstration database (`conftest.cliente_de`); `batches`, two batches over a fresh surveillance build, both still preliminary. """ from datetime import date, datetime, timezone import pytest from conftest import cliente_de @pytest.fixture(scope="module") def client(tmp_path_factory): yield from cliente_de("cacu", tmp_path_factory) @pytest.fixture(scope="module") def batches(client): """Three preliminary batches over one patient of the demo data: `older` and `newer` are confirmed/voided by the tests that exercise those routes; `untouched` stays preliminary for the tests that must not change a batch's state (an unknown id, a missing reason).""" from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro from persistance import cacu from persistance.db import get_cacu_session pac_id = cacu.persona_repository.list(limit=1)[0].pac_id with get_cacu_session() as session: build = CohorteArmado(url="cacu/cohorte_vigilancia", version="0.3.0", definicion_sha="d", reglas_sha="r", parametros="{}", datos_as_of=date(2026, 12, 31), huella="risk-batches", marco_sha="m", n_miembros=1, armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc)) session.add(build) session.flush() session.add(CohorteMiembro(armado_id=build.armado_id, pac_id=pac_id, fecha_indice=date(2025, 3, 1), indice_fuente_tabla="citologiacervical", indice_fuente_id=str(pac_id))) session.commit() build_id = build.armado_id provenance = {"modelo_nombre": "cacu-cin2_logistic", "modelo_sha": "s", "mlflow_run_id": "r"} def batch(version, risk, ahora): lote_id, _ = cacu.cohort_repository.save_batch(build_id, {**provenance, "modelo_version": version}, "cin2_12m", [(pac_id, date(2025, 1, 1), 1.0, risk, None, None)], ahora=ahora) return lote_id older = batch("1", 0.1, datetime(2026, 10, 1, tzinfo=timezone.utc)) newer = batch("2", 0.2, datetime(2026, 10, 2, tzinfo=timezone.utc)) untouched = batch("3", 0.3, datetime(2026, 10, 3, tzinfo=timezone.utc)) return older, newer, untouched def test_pending_batches_are_listed_newest_first(client, batches): """Pins down: every preliminary batch is listed, newest first, with the fields the WebApp reads. Fails if the order is reversed or a field is renamed.""" older, newer, untouched = batches body = client.get("/cacu/riesgos/lotes").get_json() assert [b["lote_id"] for b in body if b["lote_id"] in batches] == [untouched, newer, older] listed = next(b for b in body if b["lote_id"] == untouched) assert set(listed) == {"lote_id", "modelo_nombre", "modelo_version", "evaluado_en", "n_evaluaciones"} assert (listed["modelo_nombre"], listed["modelo_version"], listed["n_evaluaciones"]) == ("cacu-cin2_logistic", "3", 1) def test_confirming_drops_a_batch_off_the_pending_list(client, batches): """Pins down: confirming a batch moves its evaluations to `final` and it stops being listed as pending. Fails if it stays listed, or the evaluations aren't actually changed.""" older, _, _ = batches response = client.post(f"/cacu/riesgos/lotes/{older}/confirmar", json={"reason": "revisado por clĂ­nica"}) assert response.status_code == 200 and response.get_json() == {"lote_id": older, "evaluaciones_cambiadas": 1} assert older not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()] def test_voiding_also_drops_a_batch_off_the_pending_list(client, batches): """Pins down: voiding is the other way out of the pending list, distinct from confirming. Fails if it confirms instead of voiding, or leaves the batch pending.""" _, newer, _ = batches response = client.post(f"/cacu/riesgos/lotes/{newer}/anular", json={"reason": "modelo equivocado"}) assert response.status_code == 200 and response.get_json()["evaluaciones_cambiadas"] == 1 assert newer not in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()] def test_a_decision_needs_a_reason(client, batches): """Pins down: confirming or voiding with no reason is refused and changes nothing. Fails if the batch moves anyway, which would leave a decision with no recorded motive (ADR-MD-008).""" _, _, untouched = batches response = client.post(f"/cacu/riesgos/lotes/{untouched}/confirmar", json={"reason": " "}) assert response.status_code == 400 assert untouched in [b["lote_id"] for b in client.get("/cacu/riesgos/lotes").get_json()] def test_an_unknown_batch_is_404(client): """Pins down: a `lote_id` with no evaluations is 404, not a silent no-op. Fails if it answers 200 having changed nothing.""" assert client.post("/cacu/riesgos/lotes/987654321/confirmar", json={"reason": "revisado"}).status_code == 404 def test_a_decision_that_collides_with_another_is_409(client, monkeypatch): """Pins down: two decisions of one batch at the same moment (a double click reaching both workers) give the second a 409 instead of a server error. Fails if the unique version of an evaluation surfaces as a 500.""" from persistance import cacu from sqlalchemy.exc import IntegrityError def collide(*args, **kwargs): raise IntegrityError("INSERT", {}, Exception("UNIQUE constraint failed")) monkeypatch.setattr(cacu.cohort_repository, "change_state", collide) assert client.post("/cacu/riesgos/lotes/1/confirmar", json={"reason": "revisado"}).status_code == 409