""" Tests del router de Solicitudes y del webhook entrante de HCE (M1). Mockean la capa CRUD. Se evitan deliberadamente los flujos de aprobación que disparan llamadas a módulos externos (Core/HCE/Monitoreo); esos se cubren con tests dedicados que mockean la capa de integraciones. """ from datetime import datetime, timezone from fastapi.testclient import TestClient from tests.factories import make_cama, make_solicitud PREFIX = "/api/v1/solicitudes" def _webhook_payload(**overrides) -> dict: payload = { "tipo": "INTERNACION", "solicitud_hce_id": "HCE-SOL-001", "paciente_id": 7, "medico_solicitante_id": 10, "cama_solicitada_id": 101, "timestamp": datetime.now(timezone.utc).isoformat(), } payload.update(overrides) return payload # ─── Auth / roles ────────────────────────────────────────────────────────── def test_get_solicitudes_sin_token_401(client: TestClient): assert client.get(PREFIX).status_code == 401 def test_resolver_solicitud_rol_no_admin_403(client: TestClient, medico_headers): resp = client.patch(f"{PREFIX}/SOL-00001", json={"accion": "RECHAZAR"}, headers=medico_headers) assert resp.status_code == 403 # ─── Listado / detalle ───────────────────────────────────────────────────── def test_get_solicitudes_ok(client: TestClient, medico_headers, monkeypatch): monkeypatch.setattr("app.crud.solicitud.get_all", lambda *a, **k: [make_solicitud()]) resp = client.get(PREFIX, headers=medico_headers) assert resp.status_code == 200 data = resp.json() assert data["total"] == 1 assert data["solicitudes"][0]["id"] == "SOL-00001" assert data["solicitudes"][0]["estado"] == "PENDIENTE" def test_get_solicitud_404(client: TestClient, medico_headers, monkeypatch): monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: None) resp = client.get(f"{PREFIX}/SOL-99999", headers=medico_headers) assert resp.status_code == 404 # ─── Resolución ──────────────────────────────────────────────────────────── def test_resolver_solicitud_ya_resuelta_409(client: TestClient, admin_headers, monkeypatch): monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: make_solicitud(estado="APROBADA")) resp = client.patch(f"{PREFIX}/SOL-00001", json={"accion": "RECHAZAR"}, headers=admin_headers) assert resp.status_code == 409 # ─── Webhook entrante (M1 HCE) ───────────────────────────────────────────── def test_recibir_solicitud_webhook_ok(client: TestClient, admin_headers, monkeypatch): monkeypatch.setattr("app.crud.solicitud.get_by_hce_id", lambda db, hce_id: None) monkeypatch.setattr("app.crud.solicitud.create", lambda db, data: make_solicitud()) resp = client.post("/api/v1/webhooks/hce/solicitud", json=_webhook_payload(), headers=admin_headers) assert resp.status_code == 200 data = resp.json() assert data["estado"] == "PENDIENTE" assert data["solicitud_id"] == "SOL-00001" def test_get_solicitud_ok(client: TestClient, medico_headers, monkeypatch): monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: make_solicitud()) resp = client.get(f"{PREFIX}/SOL-00001", headers=medico_headers) assert resp.status_code == 200 data = resp.json() assert data["id"] == "SOL-00001" assert data["estado"] == "PENDIENTE" def test_resolver_solicitud_aprobar_ok(client: TestClient, admin_headers, monkeypatch): sol = make_solicitud() monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: sol) monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama(estado="DISPONIBLE")) monkeypatch.setattr("app.crud.cama.save", lambda db, c: c) monkeypatch.setattr("app.crud.solicitud.save", lambda db, s: s) monkeypatch.setattr("app.integrations.core.validate_patient", lambda pid: {"id": pid}) monkeypatch.setattr("app.integrations.hce.get_contraindicaciones", lambda pid: []) monkeypatch.setattr("app.integrations.hce.notify_movimiento", lambda *a, **k: None) monkeypatch.setattr("app.integrations.hce.notify_resultado_solicitud", lambda *a, **k: None) monkeypatch.setattr("app.integrations.monitoreo.notify_alta", lambda *a, **k: None) resp = client.patch( f"{PREFIX}/SOL-00001", json={"accion": "APROBAR"}, headers=admin_headers, ) assert resp.status_code == 200 data = resp.json() assert data["estado"] == "APROBADA" assert data["accion"] == "APROBAR" def test_resolver_solicitud_rechazar_ok(client: TestClient, admin_headers, monkeypatch): sol = make_solicitud() monkeypatch.setattr("app.crud.solicitud.get_by_id", lambda db, num: sol) monkeypatch.setattr("app.crud.solicitud.save", lambda db, s: s) monkeypatch.setattr("app.integrations.hce.notify_resultado_solicitud", lambda *a, **k: None) resp = client.patch( f"{PREFIX}/SOL-00001", json={"accion": "RECHAZAR", "motivo": "sin camas"}, headers=admin_headers, ) assert resp.status_code == 200 data = resp.json() assert data["estado"] == "RECHAZADA" assert data["accion"] == "RECHAZAR" def test_recibir_solicitud_webhook_idempotente(client: TestClient, admin_headers, monkeypatch): """Reintento de M1 con el mismo solicitud_hce_id no crea una solicitud nueva.""" existente = make_solicitud() called = {"create": False} def fail_create(db, data): called["create"] = True return make_solicitud(solicitud_id="SOL-99999") monkeypatch.setattr("app.crud.solicitud.get_by_hce_id", lambda db, hce_id: existente) monkeypatch.setattr("app.crud.solicitud.create", fail_create) resp = client.post("/api/v1/webhooks/hce/solicitud", json=_webhook_payload(), headers=admin_headers) assert resp.status_code == 200 assert resp.json()["solicitud_id"] == "SOL-00001" assert called["create"] is False