""" Tests de auditoría: endpoint GET REST, instrumentación de los servicios y garantía de que el registro es best-effort (nunca rompe la operación de negocio). El tiempo real lo maneja Supabase Realtime directamente; no hay WebSocket en M6. """ from datetime import datetime, timezone from types import SimpleNamespace from unittest.mock import MagicMock from fastapi.testclient import TestClient from app.crud import auditoria as auditoria_crud from tests.factories import make_cama PREFIX = "/api/v1/auditoria" _NOW = datetime(2026, 6, 26, 12, 0, tzinfo=timezone.utc) def make_evento(**overrides) -> SimpleNamespace: data = { "id": 1, "entidad": "CAMA", "entidad_id": "101", "cama_id": 101, "evento": "CAMA_CAMBIO_ESTADO", "estado_anterior": "OCUPADA", "estado_nuevo": "EN_LIMPIEZA", "paciente_id": 7, "usuario_id": "1", "rol": "ADMINISTRATIVO", "origen": "API", "descripcion": "Cama 101: OCUPADA → EN_LIMPIEZA", "detalle": {"motivo": "alta"}, "hospital_id": "HOSP-001", "creado_en": _NOW, } data.update(overrides) return SimpleNamespace(**data) # ─── Auth / roles ────────────────────────────────────────────────────────── def test_get_auditoria_sin_token_401(client: TestClient): assert client.get(PREFIX).status_code == 401 def test_get_auditoria_rol_limpieza_403(client: TestClient, limpieza_headers): assert client.get(PREFIX, headers=limpieza_headers).status_code == 403 # ─── Listado REST ──────────────────────────────────────────────────────────── def test_get_auditoria_ok(client: TestClient, medico_headers, monkeypatch): monkeypatch.setattr( "app.crud.auditoria.get_all", lambda *a, **k: ([make_evento(), make_evento(id=2, evento="CAMA_BAJA")], 2), ) resp = client.get(f"{PREFIX}?cama_id=101", headers=medico_headers) assert resp.status_code == 200 data = resp.json() assert data["total"] == 2 assert data["eventos"][0]["evento"] == "CAMA_CAMBIO_ESTADO" assert data["eventos"][0]["cama_id"] == 101 def test_get_auditoria_pasa_filtros_al_crud(client: TestClient, admin_headers, monkeypatch): capturado = {} def fake_get_all(db, **kwargs): capturado.update(kwargs) return [], 0 monkeypatch.setattr("app.crud.auditoria.get_all", fake_get_all) resp = client.get( f"{PREFIX}?cama_id=5&evento=CAMA_BAJA&paciente_id=9&limit=10&offset=20", headers=admin_headers, ) assert resp.status_code == 200 assert capturado["cama_id"] == 5 assert capturado["evento"] == "CAMA_BAJA" assert capturado["paciente_id"] == 9 assert capturado["limit"] == 10 assert capturado["offset"] == 20 def test_get_auditoria_limit_invalido_422(client: TestClient, admin_headers): assert client.get(f"{PREFIX}?limit=9999", headers=admin_headers).status_code == 422 # ─── Instrumentación de servicios ──────────────────────────────────────────── def test_crear_cama_registra_evento(client: TestClient, admin_headers, monkeypatch): eventos = [] monkeypatch.setattr("app.crud.cama.create", lambda db, data: make_cama(numero=data.numero)) monkeypatch.setattr( "app.crud.auditoria.registrar", lambda db, **kw: eventos.append(kw), ) payload = { "numero": 101, "piso": 1, "sector": "SALA_COMUN", "tipo": "ESTANDAR", "hospital_id": "HOSP-001", } resp = client.post("/api/v1/camas", json=payload, headers=admin_headers) assert resp.status_code == 201 assert len(eventos) == 1 assert eventos[0]["evento"] == "CAMA_CREADA" assert eventos[0]["actor"] == {"usuario_id": "1", "rol": "ADMINISTRATIVO"} def test_baja_cama_registra_evento(client: TestClient, admin_headers, monkeypatch): eventos = [] monkeypatch.setattr("app.crud.cama.get_by_id", lambda db, cid: make_cama(estado="DISPONIBLE")) monkeypatch.setattr("app.crud.cama.save", lambda db, cama: cama) monkeypatch.setattr("app.crud.auditoria.registrar", lambda db, **kw: eventos.append(kw)) resp = client.delete("/api/v1/camas/101", headers=admin_headers) assert resp.status_code == 200 assert any(e["evento"] == "CAMA_BAJA" and e["estado_nuevo"] == "BAJA_PERMANENTE" for e in eventos) # ─── Best-effort: la auditoría nunca rompe la operación ────────────────────── def test_registrar_no_propaga_si_falla(monkeypatch): db = MagicMock() db.table.side_effect = RuntimeError("base caída") # No debe lanzar ninguna excepción. assert auditoria_crud.registrar(db, entidad="CAMA", entidad_id=1, evento="CAMA_CREADA") is None def test_crear_cama_ok_aunque_falle_auditoria(client: TestClient, admin_headers, monkeypatch): monkeypatch.setattr("app.crud.cama.create", lambda db, data: make_cama(numero=data.numero)) # registrar real captura su propia excepción internamente; aquí verificamos # que el flujo del endpoint no se ve afectado. monkeypatch.setattr("app.crud.auditoria.registrar", lambda db, **kw: None) payload = { "numero": 102, "piso": 1, "sector": "SALA_COMUN", "tipo": "ESTANDAR", "hospital_id": "HOSP-001", } resp = client.post("/api/v1/camas", json=payload, headers=admin_headers) assert resp.status_code == 201