Download tests/test_webhooks.py from Modulo-6/api: direct link, hf CLI and curl.
- Browser
- Download file 20.9 kB
-
https://huggingface.co/spaces/Modulo-6/api/resolve/56cbf830009b23ee66fd20816a073e1bc83080f2/tests/test_webhooks.py
- Command line
-
hf download hf://spaces/Modulo-6/api@56cbf830009b23ee66fd20816a073e1bc83080f2/tests/test_webhooks.py
-
curl -L -o test_webhooks.py https://huggingface.co/spaces/Modulo-6/api/resolve/56cbf830009b23ee66fd20816a073e1bc83080f2/tests/test_webhooks.py
20.9 kB
| """ | |
| Tests de los endpoints webhook entrantes (HCE, Monitoreo, Turnos). | |
| Mockean la capa CRUD e integraciones externas para ejercitar routing + | |
| reglas de negocio + serialización, sin DB real. | |
| """ | |
| from datetime import datetime, timezone | |
| from fastapi.testclient import TestClient | |
| from tests.factories import make_cama, make_quirofano, make_reserva | |
| WEBHOOKS_PREFIX = "/api/v1/webhooks" | |
| TURNOS_PREFIX = "/api/v1/turnos" | |
| _NOW_ISO = datetime.now(timezone.utc).isoformat() | |
| # ─── Alta médica (M1 HCE) ────────────────────────────────────────────────── | |
| def test_alta_medica_ok(client: TestClient, admin_headers, monkeypatch): | |
| cama = make_cama(estado="OCUPADA", paciente_id=7) | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama) | |
| monkeypatch.setattr("app.crud.cama.save", lambda db, c: c) | |
| monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda *a, **k: True) | |
| payload = { | |
| "paciente_id": 7, | |
| "medico_firmante_id": 10, | |
| "tipo_alta": "ALTA_MEDICA", | |
| "timestamp": _NOW_ISO, | |
| } | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/alta-medica", json=payload, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| data = resp.json() | |
| assert "cama_id" in data | |
| def test_alta_medica_ok_aunque_monitoreo_falle(client: TestClient, admin_headers, monkeypatch): | |
| """ | |
| notify_baja (M9) es fire-and-forget (M6_DISEÑO.md §2): que M9 esté caído no debe | |
| revertir el alta. Antes de la limpieza de código zombie, esto bloqueaba con 502. | |
| """ | |
| cama = make_cama(estado="OCUPADA", paciente_id=7) | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama) | |
| monkeypatch.setattr("app.crud.cama.save", lambda db, c: c) | |
| monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda *a, **k: False) | |
| payload = { | |
| "paciente_id": 7, | |
| "medico_firmante_id": 10, | |
| "tipo_alta": "ALTA_MEDICA", | |
| "timestamp": _NOW_ISO, | |
| } | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/alta-medica", json=payload, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| assert resp.json()["estado_cama"] == "EN_LIMPIEZA" | |
| def test_alta_medica_notifica_a_facturacion(client: TestClient, admin_headers, monkeypatch): | |
| """ | |
| El alta médica dispara notify_cama_lista (fire-and-forget) para cerrar la internación | |
| del lado de M7. El alta no debe fallar aunque M7 esté caído. | |
| """ | |
| cama = make_cama(estado="OCUPADA", paciente_id=7) | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama) | |
| monkeypatch.setattr("app.crud.cama.save", lambda db, c: c) | |
| monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda *a, **k: True) | |
| facturacion_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.facturacion.notify_cama_lista", | |
| lambda c, db: facturacion_calls.append(c) or True, | |
| ) | |
| payload = { | |
| "paciente_id": 7, | |
| "medico_firmante_id": 10, | |
| "tipo_alta": "ALTA_MEDICA", | |
| "timestamp": _NOW_ISO, | |
| } | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/alta-medica", json=payload, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| assert len(facturacion_calls) == 1 | |
| def test_alta_medica_no_pisa_episodio_id_de_la_cama(client: TestClient, admin_headers, monkeypatch): | |
| """ | |
| Regresión: episodio_id lo puebla la internación/traslado (M1 lo crea al crear la | |
| solicitud), no el webhook de alta médica — que ya no trae ese campo. Antes de esta | |
| corrección, procesar_alta_medica pisaba cama.episodio_id con el valor (siempre None) | |
| del webhook de alta ANTES de disparar notify_cama_lista, así que el evento a M7 salía | |
| con idEpisodioExterno: null aunque el episodio ya estuviera cargado en la cama. | |
| """ | |
| cama = make_cama(estado="OCUPADA", paciente_id=7, episodio_id=500) | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama) | |
| monkeypatch.setattr("app.crud.cama.save", lambda db, c: c) | |
| monkeypatch.setattr("app.integrations.monitoreo.notify_baja", lambda *a, **k: True) | |
| facturacion_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.facturacion.notify_cama_lista", | |
| lambda c, db: facturacion_calls.append(c) or True, | |
| ) | |
| payload = { | |
| "paciente_id": 7, | |
| "medico_firmante_id": 10, | |
| "tipo_alta": "ALTA_MEDICA", | |
| "timestamp": _NOW_ISO, | |
| } | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/alta-medica", json=payload, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| assert facturacion_calls[0].episodio_id == 500 | |
| def test_alta_medica_404(client: TestClient, admin_headers, monkeypatch): | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: None) | |
| payload = { | |
| "paciente_id": 7, | |
| "medico_firmante_id": 10, | |
| "tipo_alta": "ALTA_MEDICA", | |
| "timestamp": _NOW_ISO, | |
| } | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/alta-medica", json=payload, headers=admin_headers) | |
| assert resp.status_code == 404 | |
| # ─── Alerta emergencia (M9 Monitoreo) ───────────────────────────────────── | |
| def test_alerta_emergencia_ok(client: TestClient, admin_headers, monkeypatch): | |
| cama = make_cama(estado="OCUPADA", paciente_id=7) | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama) | |
| monkeypatch.setattr("app.crud.cama.save", lambda db, c: c) | |
| monkeypatch.setattr("app.integrations.hce.notify_evento_episodio", lambda *a, **k: None) | |
| payload = {"paciente_id": 7, "timestamp": _NOW_ISO} | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/monitoreo/alerta-emergencia", json=payload, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| data = resp.json() | |
| assert data["cama_id"] == 101 | |
| def test_alerta_emergencia_404(client: TestClient, admin_headers, monkeypatch): | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: None) | |
| payload = {"paciente_id": 7, "timestamp": _NOW_ISO} | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/monitoreo/alerta-emergencia", json=payload, headers=admin_headers) | |
| assert resp.status_code == 404 | |
| # ─── Alerta resuelta (M9 Monitoreo) ─────────────────────────────────────── | |
| def test_alerta_resuelta_ok(client: TestClient, admin_headers, monkeypatch): | |
| cama = make_cama(estado="CODIGO_ROJO", paciente_id=7) | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: cama) | |
| monkeypatch.setattr("app.crud.cama.save", lambda db, c: c) | |
| payload = {"paciente_id": 7, "timestamp": _NOW_ISO} | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/monitoreo/alerta-resuelta", json=payload, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| data = resp.json() | |
| assert data["cama_id"] == 101 | |
| def test_alerta_resuelta_404(client: TestClient, admin_headers, monkeypatch): | |
| monkeypatch.setattr("app.crud.cama.get_by_paciente", lambda db, pid, estados: None) | |
| payload = {"paciente_id": 7, "timestamp": _NOW_ISO} | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/monitoreo/alerta-resuelta", json=payload, headers=admin_headers) | |
| assert resp.status_code == 404 | |
| # ─── Cirugía urgente (M1 HCE) — algoritmo ASAP ─────────────────────────── | |
| # | |
| # El webhook manda `fecha_hora_inicio` ("no antes de") y `fecha_hora_fin_estimada` | |
| # (de ahí sale la duración); M6 calcula el inicio real más temprano posible entre | |
| # los quirófanos compatibles. Ver cama_service.crear_reserva_urgente / _earliest_start. | |
| _URG_PAYLOAD_BASE = { | |
| "solicitud_urgencia_hce_id": "URG-001", | |
| "paciente_id": 7, | |
| "medico_cirujano_id": 22, | |
| "medico_solicitante_id": 10, | |
| "fecha_hora_inicio": "2025-01-18T10:00:00Z", | |
| "fecha_hora_fin_estimada": "2025-01-18T11:00:00Z", # duración: 1h | |
| "timestamp": _NOW_ISO, | |
| } | |
| def test_cirugia_urgente_quirofano_libre_201(client: TestClient, admin_headers, monkeypatch): | |
| """Caso base: hay un quirófano sin ninguna reserva futura -> se asigna de | |
| inmediato en el horario pedido, sin desplazar nada.""" | |
| reserva_urgente = make_reserva( | |
| origen="EMERGENCIA", prioridad="URGENTE", | |
| fecha_hora_inicio=datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 11, 0, tzinfo=timezone.utc), | |
| ) | |
| create_calls = [] | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: None) | |
| monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: [make_quirofano()]) | |
| monkeypatch.setattr("app.crud.reserva.get_futuras", lambda db, cama_id, desde: []) | |
| def _create_urgente(db, cama_id, data): | |
| create_calls.append((cama_id, data)) | |
| return reserva_urgente | |
| monkeypatch.setattr("app.crud.reserva.create_urgente", _create_urgente) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 201 | |
| data = resp.json() | |
| assert data["reserva"]["estado"] == "RESERVADA" | |
| assert data["reservas_desplazadas"] == [] | |
| # El horario asignado es exactamente el pedido: no hubo que empujarlo. | |
| assert create_calls[0][1].fecha_hora_inicio == datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc) | |
| def test_cirugia_urgente_sin_quirofanos_compatibles_409(client: TestClient, admin_headers, monkeypatch): | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: None) | |
| monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: []) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 409 | |
| assert resp.json()["detail"]["codigo"] == "SIN_QUIROFANO_COMPATIBLE" | |
| def test_cirugia_urgente_excluye_quirofanos_no_operables(client: TestClient, admin_headers, monkeypatch): | |
| """FUERA_DE_SERVICIO / EN_LIMPIEZA / BAJA_PERMANENTE no deben considerarse.""" | |
| exclude_calls = [] | |
| def _get_quirofanos(db, hospital_id=None, specialty_id=None, exclude_estados=None, estado=None): | |
| exclude_calls.append(exclude_estados) | |
| return [make_quirofano()] | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: None) | |
| monkeypatch.setattr("app.crud.cama.get_quirofanos", _get_quirofanos) | |
| monkeypatch.setattr("app.crud.reserva.get_futuras", lambda db, cama_id, desde: []) | |
| monkeypatch.setattr("app.crud.reserva.create_urgente", lambda db, cama_id, data: make_reserva(prioridad="URGENTE")) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 201 | |
| assert set(exclude_calls[0]) == {"FUERA_DE_SERVICIO", "BAJA_PERMANENTE", "EN_LIMPIEZA"} | |
| def test_cirugia_urgente_desplaza_y_reprograma(client: TestClient, admin_headers, monkeypatch): | |
| """Si el único quirófano tiene una programada superpuesta, se REPROGRAMA (no se | |
| cancela): se la mueve a continuación de la urgente y se llama reschedule_turno.""" | |
| programada = make_reserva( | |
| id=3, turno_id=5501, origen="PROGRAMADA", prioridad="MEDIA", | |
| fecha_hora_inicio=datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 12, 0, tzinfo=timezone.utc), | |
| ) | |
| urgente = make_reserva( | |
| id=9, origen="EMERGENCIA", prioridad="URGENTE", | |
| fecha_hora_inicio=datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 11, 0, tzinfo=timezone.utc), | |
| ) | |
| reschedule_calls = [] | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: None) | |
| monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: [make_quirofano()]) | |
| # La programada no es bloqueante (no es EN_CURSO ni URGENTE) -> earliest_start | |
| # no se empuja, pero cae en la ventana elegida y se marca como desplazable. | |
| monkeypatch.setattr("app.crud.reserva.get_futuras", lambda db, cama_id, desde: [programada]) | |
| monkeypatch.setattr("app.crud.reserva.get_superpuestas", lambda *a, **k: []) | |
| monkeypatch.setattr("app.crud.reserva.create_urgente", lambda db, cama_id, data: urgente) | |
| monkeypatch.setattr("app.crud.reserva.save", lambda db, r: r) | |
| monkeypatch.setattr( | |
| "app.integrations.turnos.reschedule_turno", | |
| lambda turno_id, starts_at, ends_at: reschedule_calls.append((turno_id, starts_at, ends_at)) or True, | |
| ) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 201 | |
| data = resp.json() | |
| assert len(data["reservas_desplazadas"]) == 1 | |
| assert data["reservas_desplazadas"][0]["turno_id"] == 5501 | |
| # Se reprogramó (no se canceló): la programada conserva estado RESERVADA. | |
| assert programada.estado == "RESERVADA" | |
| assert programada.desplazada_por_reserva_id == urgente.id | |
| # reschedule_turno fue llamado con el turno desplazado, arrancando al terminar la urgente. | |
| assert len(reschedule_calls) == 1 | |
| turno_id, starts_at, ends_at = reschedule_calls[0] | |
| assert turno_id == 5501 | |
| assert starts_at == datetime(2025, 1, 18, 11, 0, tzinfo=timezone.utc) | |
| # Duración original preservada (2h). | |
| assert ends_at == datetime(2025, 1, 18, 13, 0, tzinfo=timezone.utc) | |
| def test_cirugia_urgente_en_curso_no_se_desplaza_empuja_inicio(client: TestClient, admin_headers, monkeypatch): | |
| """Una reserva EN_CURSO nunca se reprograma: define cuándo se libera el | |
| quirófano. El inicio de la urgente se empuja hasta que termina.""" | |
| en_curso = make_reserva( | |
| id=4, estado="EN_CURSO", prioridad="MEDIA", | |
| fecha_hora_inicio=datetime(2025, 1, 18, 9, 0, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 10, 30, tzinfo=timezone.utc), | |
| ) | |
| create_calls = [] | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: None) | |
| monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: [make_quirofano()]) | |
| monkeypatch.setattr("app.crud.reserva.get_futuras", lambda db, cama_id, desde: [en_curso]) | |
| def _create_urgente(db, cama_id, data): | |
| create_calls.append(data) | |
| return make_reserva( | |
| prioridad="URGENTE", fecha_hora_inicio=data.fecha_hora_inicio, | |
| fecha_hora_fin_estimada=data.fecha_hora_fin_estimada, | |
| ) | |
| monkeypatch.setattr("app.crud.reserva.create_urgente", _create_urgente) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 201 | |
| assert resp.json()["reservas_desplazadas"] == [] | |
| # Pedido a las 10:00, pero la EN_CURSO libera recién a las 10:30 -> arranca ahí. | |
| assert create_calls[0].fecha_hora_inicio == datetime(2025, 1, 18, 10, 30, tzinfo=timezone.utc) | |
| assert en_curso.estado == "EN_CURSO" # no se tocó | |
| def test_cirugia_urgente_elige_quirofano_libre_sobre_uno_con_urgente(client: TestClient, admin_headers, monkeypatch): | |
| """Una reserva URGENTE ya existente es bloqueante: nunca se desplaza. Si hay | |
| otro quirófano libre, el algoritmo debe preferirlo (menor earliest_start).""" | |
| q_ocupado = make_quirofano(id=501) | |
| q_libre = make_quirofano(id=502) | |
| urgente_existente = make_reserva( | |
| id=5, estado="RESERVADA", prioridad="URGENTE", cama_id=501, | |
| fecha_hora_inicio=datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 11, 0, tzinfo=timezone.utc), | |
| ) | |
| def _get_futuras(db, cama_id, desde): | |
| return [urgente_existente] if cama_id == 501 else [] | |
| create_calls = [] | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: None) | |
| monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: [q_ocupado, q_libre]) | |
| monkeypatch.setattr("app.crud.reserva.get_futuras", _get_futuras) | |
| def _create_urgente(db, cama_id, data): | |
| create_calls.append((cama_id, data)) | |
| return make_reserva(prioridad="URGENTE", cama_id=cama_id) | |
| monkeypatch.setattr("app.crud.reserva.create_urgente", _create_urgente) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 201 | |
| assert resp.json()["reservas_desplazadas"] == [] | |
| cama_elegida, data_creada = create_calls[0] | |
| assert cama_elegida == 502 | |
| assert data_creada.fecha_hora_inicio == datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc) | |
| def test_cirugia_urgente_desplaza_varias_reservas(client: TestClient, admin_headers, monkeypatch): | |
| """Con ventanas arbitrarias, más de una reserva programada puede caer dentro | |
| del hueco elegido para la urgencia: todas se reprograman.""" | |
| programada_a = make_reserva( | |
| id=6, turno_id=601, prioridad="BAJA", | |
| fecha_hora_inicio=datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 10, 30, tzinfo=timezone.utc), | |
| ) | |
| programada_b = make_reserva( | |
| id=7, turno_id=602, prioridad="MEDIA", | |
| fecha_hora_inicio=datetime(2025, 1, 18, 10, 30, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 11, 0, tzinfo=timezone.utc), | |
| ) | |
| urgente = make_reserva( | |
| id=10, prioridad="URGENTE", | |
| fecha_hora_inicio=datetime(2025, 1, 18, 10, 0, tzinfo=timezone.utc), | |
| fecha_hora_fin_estimada=datetime(2025, 1, 18, 11, 0, tzinfo=timezone.utc), | |
| ) | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: None) | |
| monkeypatch.setattr("app.crud.cama.get_quirofanos", lambda *a, **k: [make_quirofano()]) | |
| monkeypatch.setattr("app.crud.reserva.get_futuras", lambda db, cama_id, desde: [programada_a, programada_b]) | |
| monkeypatch.setattr("app.crud.reserva.get_superpuestas", lambda *a, **k: []) | |
| monkeypatch.setattr("app.crud.reserva.create_urgente", lambda db, cama_id, data: urgente) | |
| monkeypatch.setattr("app.crud.reserva.save", lambda db, r: r) | |
| monkeypatch.setattr("app.integrations.turnos.reschedule_turno", lambda *a, **k: True) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 201 | |
| desplazadas = resp.json()["reservas_desplazadas"] | |
| assert {d["turno_id"] for d in desplazadas} == {601, 602} | |
| def test_cirugia_urgente_idempotente_200(client: TestClient, admin_headers, monkeypatch): | |
| """Reintento de M1 con la misma solicitud_urgencia_hce_id: no se crea de nuevo.""" | |
| existing = make_reserva(prioridad="URGENTE", solicitud_urgencia_hce_id="URG-001") | |
| create_calls = [] | |
| monkeypatch.setattr("app.crud.reserva.get_by_urgencia_hce_id", lambda db, hce_id: existing) | |
| monkeypatch.setattr( | |
| "app.crud.reserva.create_urgente", | |
| lambda db, cama_id, data: create_calls.append(1) or make_reserva(), | |
| ) | |
| resp = client.post(f"{WEBHOOKS_PREFIX}/hce/cirugia-urgente", json=_URG_PAYLOAD_BASE, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| assert resp.json()["reservas_desplazadas"] == [] | |
| assert create_calls == [] | |
| # ─── Cancelación de reserva de quirófano (M2 Turnos) ───────────────────── | |
| def test_cancelar_reserva_quirofano_ok(client: TestClient, admin_headers, monkeypatch): | |
| reserva = make_reserva() | |
| monkeypatch.setattr("app.crud.reserva.get_by_turno", lambda db, turno_id: reserva) | |
| monkeypatch.setattr("app.crud.reserva.save", lambda db, r: r) | |
| payload = {"motivo": "paciente cancela", "timestamp": _NOW_ISO} | |
| resp = client.post(f"{TURNOS_PREFIX}/5501/cancelacion", json=payload, headers=admin_headers) | |
| assert resp.status_code == 200 | |
| data = resp.json() | |
| assert data["reserva_id"] == 1 | |
| assert data["estado"] == "CANCELADA" | |
| def test_cancelar_reserva_quirofano_404(client: TestClient, admin_headers, monkeypatch): | |
| monkeypatch.setattr("app.crud.reserva.get_by_turno", lambda db, turno_id: None) | |
| payload = {"motivo": "paciente cancela", "timestamp": _NOW_ISO} | |
| resp = client.post(f"{TURNOS_PREFIX}/9999/cancelacion", json=payload, headers=admin_headers) | |
| assert resp.status_code == 404 | |
| def test_cancelar_reserva_en_curso_409(client: TestClient, admin_headers, monkeypatch): | |
| monkeypatch.setattr("app.crud.reserva.get_by_turno", lambda db, turno_id: make_reserva(estado="EN_CURSO")) | |
| payload = {"motivo": "intento cancelar", "timestamp": _NOW_ISO} | |
| resp = client.post(f"{TURNOS_PREFIX}/5501/cancelacion", json=payload, headers=admin_headers) | |
| assert resp.status_code == 409 | |