- Fix production bug in send_whatsapp_message: access 'instance_url' instead of 'server_url' to match SendMessageScheme TypedDict definition - Update webhook test to use test_app with in-memory dependencies - Mock send_whatsapp_message to avoid real HTTP calls in tests - Add assertions to verify correct parameters passed to send_whatsapp_message Bug: send_whatsapp_message accessed request_data['server_url'] but SendMessageScheme defines field as 'instance_url', causing KeyError when webhook tries to send WhatsApp messages.
60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
import pytest
|
|
from unittest.mock import AsyncMock, Mock
|
|
from types import SimpleNamespace
|
|
from httpx import ASGITransport, AsyncClient
|
|
from naliiabotapi.api.dependencies import get_agent
|
|
|
|
|
|
class TestWebhookChatBot:
|
|
"""Tests for WebhookChatBot."""
|
|
|
|
@pytest.mark.anyio
|
|
async def tests_webhook_success(
|
|
self, send_message_payload, test_app, monkeypatch
|
|
):
|
|
"""Test that the webhook endpoint returns a successful response.
|
|
|
|
Usa test_app con in-memory dependencies y mockea send_whatsapp_message
|
|
para evitar llamadas HTTP reales durante el test.
|
|
"""
|
|
# Mock del agente
|
|
mock_agent = SimpleNamespace()
|
|
mock_agent.ainvoke = AsyncMock(
|
|
return_value={"messages": [SimpleNamespace(content="Respuesta mock")]}
|
|
)
|
|
|
|
# Mock de send_whatsapp_message para evitar llamadas HTTP reales
|
|
mock_send_whatsapp = AsyncMock(return_value={"status": "sent"})
|
|
monkeypatch.setattr(
|
|
"naliiabotapi.api.v1.webhooks.chat_hook.send_whatsapp_message",
|
|
mock_send_whatsapp,
|
|
)
|
|
|
|
# Override de dependencia del agente
|
|
test_app.dependency_overrides[get_agent] = lambda: mock_agent
|
|
|
|
async with AsyncClient(
|
|
transport=ASGITransport(app=test_app),
|
|
base_url="http://localhost:8010",
|
|
) as client:
|
|
response = await client.post("/webhook", json=send_message_payload)
|
|
|
|
# Cleanup
|
|
test_app.dependency_overrides.clear()
|
|
|
|
# Verificaciones
|
|
assert response.status_code == 200
|
|
response_data = response.json()
|
|
assert response_data.get("reply") == "Respuesta mock"
|
|
assert response_data.get("status") == "sent"
|
|
|
|
# Verificar que se llamó al mock del agente
|
|
mock_agent.ainvoke.assert_called_once()
|
|
|
|
# Verificar que se llamó a send_whatsapp_message con los parámetros correctos
|
|
mock_send_whatsapp.assert_called_once()
|
|
whatsapp_call = mock_send_whatsapp.call_args[0][0]
|
|
assert whatsapp_call["instance_url"] == "http://localhost:8080"
|
|
assert whatsapp_call["instance_name"] == "ALEJANDRO AYALA"
|
|
assert whatsapp_call["text"] == "Respuesta mock"
|