Download tests/test_core_events.py from Modulo-6/api: direct link, hf CLI and curl.
- Browser
- Download file 13.7 kB
-
https://huggingface.co/spaces/Modulo-6/api/resolve/main/tests/test_core_events.py
- Command line
-
hf download hf://spaces/Modulo-6/api/tests/test_core_events.py
-
curl -L -o test_core_events.py https://huggingface.co/spaces/Modulo-6/api/resolve/main/tests/test_core_events.py
13.7 kB
| """ | |
| Tests de la publicación saliente al bus del Core (`app/integrations/core_events.py`) y | |
| de que los 4 puntos de notificación (`hce.notify_resultado_solicitud`, | |
| `monitoreo.notify_alta`/`notify_baja`, `facturacion.notify_cama_lista`) sigan haciendo el | |
| mismo request REST que hoy, sin cambios observables, mientras el `event_type_id` | |
| correspondiente esté en `None` (default actual — ver `M6_DISEÑO.md` §7). | |
| """ | |
| from datetime import datetime, timezone | |
| from app.config import settings | |
| from app.integrations import core_events, facturacion, hce, monitoreo | |
| from tests.factories import make_cama | |
| # ─── publish_event: no-op mientras no haya event_type_id ────────────────── | |
| def test_publish_event_sin_id_no_hace_ningun_request(monkeypatch): | |
| called = [] | |
| monkeypatch.setattr("app.integrations.core_events._post", lambda *a, **k: called.append((a, k))) | |
| result = core_events.publish_event(None, {"foo": "bar"}) | |
| assert result is True | |
| assert called == [] | |
| def test_publish_event_con_id_publica_al_core(monkeypatch): | |
| calls = [] | |
| def _fake_post(url, body): | |
| calls.append((url, body)) | |
| return {"id": 999} | |
| monkeypatch.setattr(core_events, "_post", _fake_post) | |
| result = core_events.publish_event(14, {"foo": "bar"}) | |
| assert result is True | |
| assert len(calls) == 1 | |
| url, body = calls[0] | |
| assert url == f"{settings.m10_core_url}/events/log" | |
| assert body["event_type_id"] == 14 | |
| assert body["publisher_module"] == "internacion" | |
| assert body["payload"] == '{"foo": "bar"}' | |
| def test_publish_event_con_id_pero_post_falla_devuelve_false(monkeypatch): | |
| monkeypatch.setattr(core_events, "_post", lambda *a, **k: None) | |
| assert core_events.publish_event(14, {"foo": "bar"}) is False | |
| # ─── notify_* : REST sin cambios + publish_event adicional (hoy no-op) ───── | |
| def test_notify_resultado_solicitud_solo_publica_evento_sin_rest(monkeypatch): | |
| """Corrección 2026-07: el REST a M1 (`/hce/solicitudes/{id}/resultado`) se deprecó — ese | |
| path no existe en el contrato real de M1. Canal único: el evento del bus.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "hce_solicitud_resuelta_event_type_id", 25) | |
| rest_calls = [] | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.hce._post", | |
| lambda url, payload: rest_calls.append((url, payload)) or {"ok": True}, | |
| ) | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True, | |
| ) | |
| ok = hce.notify_resultado_solicitud("HCE-SOL-1", "APROBADA", motivo=None) | |
| assert ok is True | |
| assert len(rest_calls) == 0 # el REST ya no se llama | |
| assert len(publish_calls) == 1 | |
| event_type_id, event_payload = publish_calls[0] | |
| assert event_type_id == 25 | |
| assert event_payload["solicitud_hce_id"] == "HCE-SOL-1" | |
| assert event_payload["resultado"] == "APROBADA" | |
| def test_notify_alta_sin_event_type_id_usa_rest_como_backup(monkeypatch): | |
| """Cuando monitoreo_alta_event_type_id es None, va directo al HTTP sin llamar publish_event.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "monitoreo_alta_event_type_id", None) | |
| rest_calls = [] | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.monitoreo._post", | |
| lambda url, payload: rest_calls.append((url, payload)) or {"ok": True}, | |
| ) | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True, | |
| ) | |
| ok = monitoreo.notify_alta(7, cama_id=9) | |
| assert ok is True | |
| assert len(rest_calls) == 1 | |
| assert rest_calls[0][1]["cama_id"] == 9 | |
| assert len(publish_calls) == 0 # no se llama publish_event cuando event_type_id es None | |
| def test_notify_baja_sin_event_type_id_usa_rest_como_backup(monkeypatch): | |
| """Cuando monitoreo_baja_event_type_id es None, va directo al HTTP sin llamar publish_event.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "monitoreo_baja_event_type_id", None) | |
| rest_calls = [] | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.monitoreo._post", | |
| lambda url, payload: rest_calls.append((url, payload)) or {"ok": True}, | |
| ) | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True, | |
| ) | |
| ok = monitoreo.notify_baja(7, cama_id=9) | |
| assert ok is True | |
| assert len(rest_calls) == 1 | |
| assert rest_calls[0][1]["cama_id"] == 9 | |
| assert len(publish_calls) == 0 # no se llama publish_event cuando event_type_id es None | |
| def test_notify_alta_con_event_type_id_publica_al_bus_con_cama_id(monkeypatch): | |
| """Con monitoreo_alta_event_type_id=26 configurado (id real de M9), publica al bus con | |
| cama_id incluido en el payload.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "monitoreo_alta_event_type_id", 26) | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True, | |
| ) | |
| ok = monitoreo.notify_alta(7, cama_id=9) | |
| assert ok is True | |
| assert len(publish_calls) == 1 | |
| event_type_id, payload = publish_calls[0] | |
| assert event_type_id == 26 | |
| assert payload["cama_id"] == 9 | |
| def test_notify_baja_con_event_type_id_publica_al_bus_con_cama_id(monkeypatch): | |
| """Con monitoreo_baja_event_type_id=27 configurado (id real de M9), publica al bus con | |
| cama_id incluido en el payload.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "monitoreo_baja_event_type_id", 27) | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda event_type_id, payload: publish_calls.append((event_type_id, payload)) or True, | |
| ) | |
| ok = monitoreo.notify_baja(7, cama_id=9) | |
| assert ok is True | |
| assert len(publish_calls) == 1 | |
| event_type_id, payload = publish_calls[0] | |
| assert event_type_id == 27 | |
| assert payload["cama_id"] == 9 | |
| def test_notify_cama_lista_desactivado_no_envia_nada(monkeypatch): | |
| """Pausa manual (2026-07, `facturacion_cierre_habilitado=False` por default): no se manda | |
| nada a M7, ni evento ni REST, y la función devuelve True (fire-and-forget).""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "facturacion_cierre_habilitado", False) | |
| rest_calls = [] | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.facturacion._post", | |
| lambda *a, **k: rest_calls.append((a, k)) or {"ok": True}, | |
| ) | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda *a, **k: publish_calls.append((a, k)) or True, | |
| ) | |
| cama = make_cama(id=315, paciente_id=7) | |
| ok = facturacion.notify_cama_lista(cama, db=None) | |
| assert ok is True | |
| assert rest_calls == [] | |
| assert publish_calls == [] | |
| def test_notify_cama_lista_sigue_llamando_rest_con_payload_minimo(monkeypatch): | |
| """El REST directo es fallback/testing manual según M7 — payload mínimo, sin cambios.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "facturacion_cierre_habilitado", True) | |
| monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", None) | |
| rest_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.facturacion._post", | |
| lambda url, payload: rest_calls.append((url, payload)) or {"ok": True}, | |
| ) | |
| monkeypatch.setattr("app.integrations.core_events.publish_event", lambda *a, **k: True) | |
| cama = make_cama(id=315, paciente_id=7) | |
| ok = facturacion.notify_cama_lista(cama, db=None) | |
| assert ok is True | |
| assert len(rest_calls) == 1 | |
| url, payload = rest_calls[0] | |
| assert url == f"{settings.m7_facturacion_url}/api/v1/webhooks/internacion/cama-lista" | |
| assert payload == { | |
| "evento": "CAMA_LISTA", | |
| "idEventoExterno": payload["idEventoExterno"], | |
| "camaId": "315", | |
| "idPacienteExterno": 7, | |
| "timestampEvento": payload["timestampEvento"], | |
| } | |
| assert payload["timestampEvento"].endswith("Z") | |
| def test_notify_cama_lista_publica_evento_rico_con_datos_del_episodio(monkeypatch): | |
| """El evento del Core (event_type_id=19, confirmado por M7) lleva el payload rico | |
| CIERRE_INTERNACION con los datos del episodio persistidos en la Cama.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "facturacion_cierre_habilitado", True) | |
| monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", 19) | |
| monkeypatch.setattr("app.integrations.facturacion._post", lambda *a, **k: {"ok": True}) | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda event_type_id, payload, publisher_module="internacion": publish_calls.append( | |
| (event_type_id, payload, publisher_module) | |
| ) | |
| or True, | |
| ) | |
| cama = make_cama( | |
| id=315, | |
| paciente_id=7, | |
| solicitud_hce_id="HCE-SOL-00123", | |
| fecha_ingreso=datetime(2026, 6, 20, 14, 30, tzinfo=timezone.utc), | |
| alta_tipo="ALTA_MEDICA", | |
| alta_timestamp=datetime(2026, 6, 25, 10, 0, tzinfo=timezone.utc), | |
| ) | |
| facturacion.notify_cama_lista(cama, db=None) | |
| assert len(publish_calls) == 1 | |
| event_type_id, payload, publisher_module = publish_calls[0] | |
| assert event_type_id == 19 | |
| assert publisher_module == "modulo_6" | |
| assert payload["evento"] == "CIERRE_INTERNACION" | |
| assert "camaId" not in payload # no es parte del contrato de M7 — ver M6_DISEÑO.md §7.2 | |
| assert "camasUtilizadas" not in payload | |
| assert payload["idInternacionExterna"] == "HCE-SOL-00123" | |
| assert payload["idEpisodioExterno"] is None # bloqueante externo — M1 no lo provee aún | |
| assert payload["idPacienteExterno"] == 7 # int — InternacionM6Request.idPacienteExterno es Long | |
| assert payload["fechaIngreso"] == "2026-06-20T14:30:00Z" | |
| assert payload["fechaAlta"] == "2026-06-25T10:00:00Z" | |
| assert payload["tipoAlta"] == "ALTA_MEDICA" | |
| assert "timestampEvento" in payload and payload["timestampEvento"].endswith("Z") | |
| def test_notify_cama_lista_manda_episodio_id_como_entero_cuando_esta_poblado(monkeypatch): | |
| """episodio_id llega a la cama desde la solicitud/traslado (M1 lo crea al crear la | |
| solicitud — ver M6_INTEGRACION_M1_HCE.md §4.3), no desde el webhook de alta médica. | |
| Tiene que salir como entero en el evento, igual que idPacienteExterno.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "facturacion_cierre_habilitado", True) | |
| monkeypatch.setattr(settings, "facturacion_cama_lista_event_type_id", 19) | |
| monkeypatch.setattr("app.integrations.facturacion._post", lambda *a, **k: {"ok": True}) | |
| publish_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.core_events.publish_event", | |
| lambda event_type_id, payload, publisher_module="internacion": publish_calls.append( | |
| (event_type_id, payload, publisher_module) | |
| ) | |
| or True, | |
| ) | |
| cama = make_cama(id=315, paciente_id=7, episodio_id=700) | |
| facturacion.notify_cama_lista(cama, db=None) | |
| _, payload, _ = publish_calls[0] | |
| assert payload["idEpisodioExterno"] == 700 | |
| assert isinstance(payload["idEpisodioExterno"], int) | |
| # ─── notify_movimiento: endpoint real de M1 (corrección 2026-07) ─────────── | |
| def test_notify_movimiento_arma_payload_real_de_internacion_ingreso(monkeypatch): | |
| """El path viejo (/hce/movimientos) no existe en el contrato real de M1 — el real es | |
| /internacion/ingreso (IngresoInternacionRequest), reusado tanto para ingreso como para | |
| traslado reenviando el mismo id_episodio.""" | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| rest_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.hce._post", | |
| lambda url, payload: rest_calls.append((url, payload)) or {"ok": True}, | |
| ) | |
| cama = make_cama(id=12, numero=4, sector="UTI", tipo="CRITICA", episodio_id=700) | |
| actor = {"usuario_id": 20, "rol": "MEDICO"} | |
| ok = hce.notify_movimiento(cama, paciente_id=10500, actor=actor) | |
| assert ok is True | |
| assert len(rest_calls) == 1 | |
| url, payload = rest_calls[0] | |
| assert url == f"{settings.m1_hce_url}/api/v1/internacion/ingreso" | |
| assert payload["id_paciente"] == 10500 | |
| assert payload["id_episodio"] == 700 | |
| assert payload["sector"] == "UTI" | |
| assert payload["habitacion"] == "CRITICA" | |
| assert payload["cama"] == "Cama 4" | |
| assert payload["medico_solicitante"] == "20" | |
| assert "fecha_ingreso" in payload | |
| def test_notify_movimiento_sin_actor_manda_medico_solicitante_null(monkeypatch): | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| rest_calls = [] | |
| monkeypatch.setattr( | |
| "app.integrations.hce._post", | |
| lambda url, payload: rest_calls.append((url, payload)) or {"ok": True}, | |
| ) | |
| cama = make_cama(id=12, numero=4, sector="UTI", tipo="CRITICA", episodio_id=700) | |
| ok = hce.notify_movimiento(cama, paciente_id=10500, actor=None) | |
| assert ok is True | |
| _, payload = rest_calls[0] | |
| assert payload["medico_solicitante"] is None | |