File size: 5,712 Bytes
f6c0922 4e6d616 f6c0922 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | """
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
|