Personal AI, On Personal Devices
Python
test: add 26 tests for SendBlue channel and webhook
Jon Saad-Falcon1252531551e2
diff --git a/tests/channels/test_sendblue.py b/tests/channels/test_sendblue.pynew file mode 100644index 00000000..0a775364--- /dev/null+++ b/tests/channels/test_sendblue.py@@ -0,0 +1,257 @@+"""Tests for SendBlue iMessage/SMS channel.++Covers: init, env-var fallback, connect, send (mocked httpx), webhook+handler, event emission, and registry registration.+"""++from __future__ import annotations++import json+from unittest.mock import MagicMock, patch++import pytest++from openjarvis.channels._stubs import ChannelStatus+from openjarvis.core.events import EventBus, EventType+from openjarvis.core.registry import ChannelRegistry++[email protected](autouse=True)+def _register_sendblue():+ if not ChannelRegistry.contains("sendblue"):+ from openjarvis.channels.sendblue import SendBlueChannel++ ChannelRegistry.register_value("sendblue", SendBlueChannel)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _make_channel(**overrides):+ from openjarvis.channels.sendblue import SendBlueChannel++ defaults = {+ "api_key_id": "test_key",+ "api_secret_key": "test_secret",+ "from_number": "+15551234567",+ }+ defaults.update(overrides)+ return SendBlueChannel(**defaults)+++def _mock_httpx_post(status=200, body=None):+ """Return a mock httpx response."""+ resp = MagicMock()+ resp.status_code = status+ resp.text = json.dumps(body or {})+ resp.json.return_value = body or {}+ return resp+++# ---------------------------------------------------------------------------+# Init / env vars+# ---------------------------------------------------------------------------+++class TestInit:+ def test_from_params(self):+ ch = _make_channel()+ assert ch.channel_id == "sendblue"+ assert ch._api_key_id == "test_key"+ assert ch._api_secret_key == "test_secret"+ assert ch._from_number == "+15551234567"+ assert ch.status() == ChannelStatus.DISCONNECTED++ def test_from_env_vars(self, monkeypatch):+ monkeypatch.setenv("SENDBLUE_API_KEY_ID", "env_key")+ monkeypatch.setenv("SENDBLUE_API_SECRET_KEY", "env_secret")+ monkeypatch.setenv("SENDBLUE_FROM_NUMBER", "+19998887777")++ from openjarvis.channels.sendblue import SendBlueChannel++ ch = SendBlueChannel()+ assert ch._api_key_id == "env_key"+ assert ch._api_secret_key == "env_secret"+ assert ch._from_number == "+19998887777"++ def test_no_credentials(self):+ from openjarvis.channels.sendblue import SendBlueChannel++ ch = SendBlueChannel()+ ch.connect()+ assert ch.status() == ChannelStatus.ERROR+++# ---------------------------------------------------------------------------+# Connect / disconnect+# ---------------------------------------------------------------------------+++class TestConnect:+ def test_connect_with_creds(self):+ ch = _make_channel()+ ch.connect()+ assert ch.status() == ChannelStatus.CONNECTED++ def test_disconnect(self):+ ch = _make_channel()+ ch.connect()+ ch.disconnect()+ assert ch.status() == ChannelStatus.DISCONNECTED+++# ---------------------------------------------------------------------------+# Send+# ---------------------------------------------------------------------------+++class TestSend:+ def test_send_success(self):+ ch = _make_channel()+ ch.connect()+ with patch("httpx.post", return_value=_mock_httpx_post(200)):+ result = ch.send("+19998887777", "Hello!")+ assert result is True++ def test_send_includes_from_number(self):+ ch = _make_channel(from_number="+15559876543")+ ch.connect()+ with patch("httpx.post", return_value=_mock_httpx_post(200)) as mock:+ ch.send("+19998887777", "Hi!")+ call_kwargs = mock.call_args+ payload = call_kwargs.kwargs.get("json") or call_kwargs[1].get("json")+ assert payload["number"] == "+19998887777"+ assert payload["content"] == "Hi!"+ assert payload["from_number"] == "+15559876543"++ def test_send_api_error_returns_false(self):+ ch = _make_channel()+ ch.connect()+ with patch("httpx.post", return_value=_mock_httpx_post(401)):+ result = ch.send("+19998887777", "Hello!")+ assert result is False++ def test_send_network_error_returns_false(self):+ ch = _make_channel()+ ch.connect()+ with patch("httpx.post", side_effect=Exception("Network error")):+ result = ch.send("+19998887777", "Hello!")+ assert result is False++ def test_send_no_credentials_returns_false(self):+ from openjarvis.channels.sendblue import SendBlueChannel++ ch = SendBlueChannel()+ result = ch.send("+19998887777", "Hello!")+ assert result is False++ def test_send_publishes_event(self):+ bus = EventBus(record_history=True)+ ch = _make_channel(bus=bus)+ ch.connect()+ with patch("httpx.post", return_value=_mock_httpx_post(200)):+ ch.send("+19998887777", "Hello!")+ event_types = [e.event_type for e in bus.history]+ assert EventType.CHANNEL_MESSAGE_SENT in event_types+++# ---------------------------------------------------------------------------+# Webhook handler+# ---------------------------------------------------------------------------+++class TestWebhookHandler:+ def test_incoming_message_triggers_handlers(self):+ ch = _make_channel()+ received = []+ ch.on_message(lambda msg: received.append(msg))++ ch.handle_webhook({+ "from_number": "+19127130720",+ "to_number": "+15551234567",+ "content": "Hello Jarvis",+ "message_handle": "msg-001",+ "is_outbound": False,+ "status": "RECEIVED",+ "service": "iMessage",+ })++ assert len(received) == 1+ assert received[0].sender == "+19127130720"+ assert received[0].content == "Hello Jarvis"+ assert received[0].channel == "sendblue"++ def test_outbound_messages_ignored(self):+ ch = _make_channel()+ received = []+ ch.on_message(lambda msg: received.append(msg))++ ch.handle_webhook({+ "from_number": "+15551234567",+ "content": "Outbound message",+ "is_outbound": True,+ })++ assert len(received) == 0++ def test_empty_content_ignored(self):+ ch = _make_channel()+ received = []+ ch.on_message(lambda msg: received.append(msg))++ ch.handle_webhook({+ "from_number": "+19127130720",+ "content": "",+ "is_outbound": False,+ })++ assert len(received) == 0++ def test_incoming_publishes_event(self):+ bus = EventBus(record_history=True)+ ch = _make_channel(bus=bus)++ ch.handle_webhook({+ "from_number": "+19127130720",+ "content": "Test",+ "message_handle": "msg-002",+ "is_outbound": False,+ "service": "iMessage",+ })++ event_types = [e.event_type for e in bus.history]+ assert EventType.CHANNEL_MESSAGE_RECEIVED in event_types+ event = [+ e for e in bus.history+ if e.event_type == EventType.CHANNEL_MESSAGE_RECEIVED+ ][0]+ assert event.data["sender"] == "+19127130720"+ assert event.data["service"] == "iMessage"++ def test_handler_exception_does_not_crash(self):+ ch = _make_channel()+ ch.on_message(lambda msg: 1 / 0) # Will raise ZeroDivisionError++ # Should not raise+ ch.handle_webhook({+ "from_number": "+19127130720",+ "content": "Test",+ "message_handle": "msg-003",+ "is_outbound": False,+ })+++# ---------------------------------------------------------------------------+# Properties+# ---------------------------------------------------------------------------+++class TestProperties:+ def test_from_number(self):+ ch = _make_channel(from_number="+15559876543")+ assert ch.from_number == "+15559876543"++ def test_list_channels(self):+ ch = _make_channel()+ assert ch.list_channels() == ["sendblue"]diff --git a/tests/server/test_sendblue_webhook.py b/tests/server/test_sendblue_webhook.pynew file mode 100644index 00000000..352ab2e0--- /dev/null+++ b/tests/server/test_sendblue_webhook.py@@ -0,0 +1,239 @@+"""Integration tests for the SendBlue webhook endpoint.++Tests the /webhooks/sendblue route, health check endpoint, and the+full flow from incoming webhook -> bridge -> agent -> send response.+"""++from __future__ import annotations++import json+from unittest.mock import MagicMock, patch++import pytest+from fastapi import FastAPI+from starlette.testclient import TestClient++from openjarvis.channels._stubs import ChannelStatus+from openjarvis.core.registry import ChannelRegistry++[email protected](autouse=True)+def _register_sendblue():+ if not ChannelRegistry.contains("sendblue"):+ from openjarvis.channels.sendblue import SendBlueChannel++ ChannelRegistry.register_value("sendblue", SendBlueChannel)+++def mock_bridge():+ bridge = MagicMock()+ bridge.handle_incoming.return_value = "Here are your results..."+ return bridge+++def sendblue_channel():+ from openjarvis.channels.sendblue import SendBlueChannel++ ch = SendBlueChannel(+ api_key_id="test_key",+ api_secret_key="test_secret",+ from_number="+15551234567",+ )+ ch.connect()+ return ch+++def webhook_app(mock_bridge, sendblue_channel):+ from openjarvis.server.webhook_routes import create_webhook_router++ app = FastAPI()+ router = create_webhook_router(+ bridge=mock_bridge,+ sendblue_channel=sendblue_channel,+ )+ app.include_router(router)+ return app+++def client(webhook_app):+ return TestClient(webhook_app)+++# ---------------------------------------------------------------------------+# Webhook endpoint+# ---------------------------------------------------------------------------+++class TestSendBlueWebhook:+ def test_incoming_message_returns_200(self, client):+ resp = client.post(+ "/webhooks/sendblue",+ json={+ "from_number": "+19127130720",+ "to_number": "+15551234567",+ "content": "Hello Jarvis",+ "message_handle": "msg-001",+ "is_outbound": False,+ "status": "RECEIVED",+ "service": "iMessage",+ },+ )+ assert resp.status_code == 200++ def test_outbound_status_callback_ignored(self, client, mock_bridge):+ resp = client.post(+ "/webhooks/sendblue",+ json={+ "from_number": "+15551234567",+ "content": "Sent message",+ "is_outbound": True,+ },+ )+ assert resp.status_code == 200+ mock_bridge.handle_incoming.assert_not_called()++ def test_empty_content_ignored(self, client, mock_bridge):+ resp = client.post(+ "/webhooks/sendblue",+ json={+ "from_number": "+19127130720",+ "content": "",+ "is_outbound": False,+ },+ )+ assert resp.status_code == 200+ mock_bridge.handle_incoming.assert_not_called()++ def test_missing_from_number_ignored(self, client, mock_bridge):+ resp = client.post(+ "/webhooks/sendblue",+ json={+ "content": "Hello",+ "is_outbound": False,+ },+ )+ assert resp.status_code == 200+ mock_bridge.handle_incoming.assert_not_called()++ def test_webhook_secret_validation(self, mock_bridge):+ """When a webhook secret is set, reject requests without it."""+ from openjarvis.channels.sendblue import SendBlueChannel+ from openjarvis.server.webhook_routes import create_webhook_router++ ch = SendBlueChannel(+ api_key_id="k",+ api_secret_key="s",+ from_number="+1555",+ webhook_secret="mysecret",+ )+ ch.connect()++ app = FastAPI()+ router = create_webhook_router(+ bridge=mock_bridge, sendblue_channel=ch+ )+ app.include_router(router)+ c = TestClient(app)++ # Without secret header -> rejected+ resp = c.post(+ "/webhooks/sendblue",+ json={+ "from_number": "+19127130720",+ "content": "Hello",+ "is_outbound": False,+ },+ )+ assert resp.status_code == 403++ # With correct secret -> accepted+ resp = c.post(+ "/webhooks/sendblue",+ json={+ "from_number": "+19127130720",+ "content": "Hello",+ "is_outbound": False,+ "message_handle": "msg-002",+ },+ headers={"x-sendblue-secret": "mysecret"},+ )+ assert resp.status_code == 200++ def test_no_bridge_returns_200(self, sendblue_channel):+ """When no bridge exists, webhook should not crash."""+ from openjarvis.server.webhook_routes import create_webhook_router++ app = FastAPI()+ router = create_webhook_router(+ bridge=None, sendblue_channel=sendblue_channel+ )+ app.include_router(router)+ c = TestClient(app)++ resp = c.post(+ "/webhooks/sendblue",+ json={+ "from_number": "+19127130720",+ "content": "Hello",+ "is_outbound": False,+ },+ )+ assert resp.status_code == 200+++# ---------------------------------------------------------------------------+# Health endpoint (requires agent_manager_routes)+# ---------------------------------------------------------------------------+++class TestSendBlueHealth:+ @pytest.fixture+ def health_app(self, sendblue_channel):+ app = FastAPI()+ app.state.sendblue_channel = sendblue_channel+ app.state.channel_bridge = MagicMock()+ app.state.channel_bridge._channels = {"sendblue": sendblue_channel}++ from openjarvis.server.agent_manager_routes import (+ create_agent_manager_router,+ )++ mgr = MagicMock()+ mgr.list_agents.return_value = []+ routers = create_agent_manager_router(mgr)+ sendblue_router = routers[4] # 5th element is sendblue_router+ app.include_router(sendblue_router)+ return app++ def test_health_ready(self, health_app):+ c = TestClient(health_app)+ resp = c.get("/v1/channels/sendblue/health")+ assert resp.status_code == 200+ data = resp.json()+ assert data["channel_connected"] is True+ assert data["bridge_wired"] is True+ assert data["ready"] is True++ def test_health_not_ready(self):+ app = FastAPI()+ # No sendblue_channel or bridge on state++ from openjarvis.server.agent_manager_routes import (+ create_agent_manager_router,+ )++ mgr = MagicMock()+ mgr.list_agents.return_value = []+ routers = create_agent_manager_router(mgr)+ sendblue_router = routers[4]+ app.include_router(sendblue_router)++ c = TestClient(app)+ resp = c.get("/v1/channels/sendblue/health")+ assert resp.status_code == 200+ data = resp.json()+ assert data["ready"] is False