Spaces:
Runtime error
Runtime error
Download tests/test_core_events.py from MateFerreyra/Modulo-6: direct link, hf CLI and curl.
- Browser
- Download file 9.06 kB
-
https://huggingface.co/spaces/MateFerreyra/Modulo-6/resolve/main/tests/test_core_events.py
- Command line
-
hf download hf://spaces/MateFerreyra/Modulo-6/tests/test_core_events.py
-
curl -L -o test_core_events.py https://huggingface.co/spaces/MateFerreyra/Modulo-6/resolve/main/tests/test_core_events.py
9.06 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_sigue_llamando_rest_igual_que_antes(monkeypatch): | |
| monkeypatch.setattr(settings, "mock_external_services", False) | |
| monkeypatch.setattr(settings, "hce_solicitud_resuelta_event_type_id", None) | |
| 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) == 1 | |
| url, rest_payload = rest_calls[0] | |
| assert url == f"{settings.m1_hce_url}/api/v1/hce/solicitudes/HCE-SOL-1/resultado" | |
| assert "solicitud_hce_id" not in rest_payload # el body REST no cambia | |
| assert len(publish_calls) == 1 | |
| event_type_id, event_payload = publish_calls[0] | |
| assert event_type_id is None # no configurado todavía | |
| assert event_payload["solicitud_hce_id"] == "HCE-SOL-1" | |
| 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) | |
| assert ok is True | |
| assert len(rest_calls) == 1 | |
| 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) | |
| assert ok is True | |
| assert len(rest_calls) == 1 | |
| assert len(publish_calls) == 0 # no se llama publish_event cuando event_type_id es None | |
| 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_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_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_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) | |