Files
collina-smart-assistant/tests/test_generador_evolution.py
T
Jorem Juárez f21b2a6c69 feat(generador): estampado de réplicas autónomas (Etapa 2, Fases 0-5)
- generador/: ficha.py (validación cliente.yml), registro.py (registry.json
  + puertos), plantillas.py (.env/compose/README/scripts), nucleo.py
  (estampar/validar_paquete/desplegar), evolution.py (API client),
  CLI python -m generador (estampar|validar|whatsapp|desplegar|listar|eliminar)
- src/api/webhook_evolution.py: adaptador webhook nativo Evolution →
  WebhookMessage (réplicas sin n8n); registrado en main.py
- fichas/ejemplo-demo.yml: ficha demo con credenciales falsas
- Solo-generar es default; --desplegar explícito. El generador solo LEE
  el molde (git archive de HEAD) y ESCRIBE en replicas/ (gitignored)
- 31 tests nuevos (Evolution mockeado con httpx.MockTransport): 158 verdes
2026-07-20 19:05:06 -06:00

147 lines
5.6 KiB
Python

"""Tests Fase 3: aprovisionamiento Evolution (API mockeada, sin red) y
adaptador del webhook nativo /webhook/evolution."""
import json
import httpx
import pytest
from generador.evolution import ClienteEvolution, ErrorEvolution, aprovisionar
from src.api.webhook_evolution import mapear_evento
# ── mock del servidor Evolution ─────────────────────────────────────
class EvolutionFalso:
"""Simula los endpoints de Evolution v2 y registra cada request."""
def __init__(self, instancias=(), estado="connecting"):
self.instancias = set(instancias)
self.estado = estado
self.requests: list[tuple[str, str, dict | None]] = []
def handler(self, request: httpx.Request) -> httpx.Response:
ruta = request.url.path
cuerpo = json.loads(request.content) if request.content else None
self.requests.append((request.method, ruta, cuerpo))
if request.headers.get("apikey") != "clave-buena":
return httpx.Response(401, json={"error": "Unauthorized"})
if ruta == "/instance/fetchInstances":
nombre = request.url.params.get("instanceName")
lista = [{"name": n} for n in self.instancias if n == nombre]
return httpx.Response(200, json=lista)
if ruta == "/instance/create":
self.instancias.add(cuerpo["instanceName"])
return httpx.Response(201, json={"instance": {"instanceName": cuerpo["instanceName"]}})
if ruta.startswith("/webhook/set/"):
return httpx.Response(200, json={"webhook": cuerpo["webhook"]})
if ruta.startswith("/instance/connectionState/"):
return httpx.Response(200, json={"instance": {"state": self.estado}})
if ruta.startswith("/instance/connect/"):
return httpx.Response(200, json={"base64": "data:image/png;base64,aWc=", "code": "xyz"})
if ruta.startswith("/instance/delete/"):
self.instancias.discard(ruta.rsplit("/", 1)[1])
return httpx.Response(200, json={})
return httpx.Response(404, json={"error": f"ruta no simulada: {ruta}"})
def _cliente(falso: EvolutionFalso, apikey="clave-buena") -> ClienteEvolution:
return ClienteEvolution(
"http://evolution.fake", apikey,
transport=httpx.MockTransport(falso.handler),
)
def test_aprovisionar_crea_instancia_y_webhook():
falso = EvolutionFalso()
estado = aprovisionar(_cliente(falso), "cliente-uno", "https://bot.cliente.mx")
assert estado == "connecting"
metodos_rutas = [(m, r) for m, r, _ in falso.requests]
assert ("POST", "/instance/create") in metodos_rutas
assert ("POST", "/webhook/set/cliente-uno") in metodos_rutas
# el webhook apunta al adaptador nativo de la réplica
webhook_body = next(c for m, r, c in falso.requests if r == "/webhook/set/cliente-uno")
assert webhook_body["webhook"]["url"] == "https://bot.cliente.mx/webhook/evolution"
assert webhook_body["webhook"]["events"] == ["MESSAGES_UPSERT"]
assert webhook_body["webhook"]["webhookBase64"] is True
def test_aprovisionar_no_recrea_instancia_existente():
falso = EvolutionFalso(instancias={"cliente-uno"}, estado="open")
estado = aprovisionar(_cliente(falso), "cliente-uno", "https://bot.cliente.mx")
assert estado == "open"
assert ("POST", "/instance/create") not in [(m, r) for m, r, _ in falso.requests]
def test_apikey_invalida_error_claro():
falso = EvolutionFalso()
with pytest.raises(ErrorEvolution, match="401"):
_cliente(falso, apikey="clave-mala").crear_instancia("x")
def test_obtener_qr():
falso = EvolutionFalso()
qr = _cliente(falso).obtener_qr("cliente-uno")
assert qr["base64"].startswith("data:image/png;base64,")
# ── adaptador /webhook/evolution (mapeo nativo → WebhookMessage) ────
def _evento(**overrides) -> dict:
base = {
"event": "messages.upsert",
"instance": "cliente-uno",
"data": {
"key": {"remoteJid": "5214421234567@s.whatsapp.net", "fromMe": False, "id": "ABC"},
"message": {"conversation": "ayuda"},
},
}
base.update(overrides)
return base
def test_mapea_texto_simple():
msg = mapear_evento(_evento())
assert msg is not None
assert msg.numero == "5214421234567@s.whatsapp.net"
assert msg.mensaje == "ayuda"
assert msg.instance == "cliente-uno"
assert msg.media_type is None
def test_mapea_extended_text():
e = _evento()
e["data"]["message"] = {"extendedTextMessage": {"text": "cotiza Jetta pr 500,000"}}
msg = mapear_evento(e)
assert msg.mensaje == "cotiza Jetta pr 500,000"
def test_ignora_fromme_grupos_y_otros_eventos():
e = _evento()
e["data"]["key"]["fromMe"] = True
assert mapear_evento(e) is None
e = _evento()
e["data"]["key"]["remoteJid"] = "123-456@g.us"
assert mapear_evento(e) is None
assert mapear_evento(_evento(event="connection.update")) is None
# variante con guión bajo (Evolution a veces manda MESSAGES_UPSERT)
assert mapear_evento(_evento(event="MESSAGES_UPSERT")) is not None
def test_mapea_documento_pdf_con_base64():
e = _evento()
e["data"]["message"] = {
"documentMessage": {"mimetype": "application/pdf", "caption": "cotización"},
"base64": "JVBERi0xLjQK",
}
msg = mapear_evento(e)
assert msg.media_type == "document"
assert msg.mime_type == "application/pdf"
assert msg.pdf_base64 == "JVBERi0xLjQK"
assert msg.mensaje == "cotización"
# message_key viaja para el fallback de descarga vía Evolution
assert msg.message_key["id"] == "ABC"