4
0

test_telegram_integration.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. #!/usr/bin/env python3
  2. """
  3. Integration tests for the Telegram notification service.
  4. All configuration is read from the database via telegram_config_service.
  5. Run: pytest tests/test_telegram_integration.py -v
  6. """
  7. import asyncio
  8. import sys
  9. from pathlib import Path
  10. import pytest
  11. # Add the project root to path so imports work when executed directly.
  12. sys.path.insert(0, str(Path(__file__).parent.parent))
  13. from dotenv import load_dotenv
  14. load_dotenv()
  15. from services.notifications.telegram_config_service import load_config # noqa: E402
  16. from services.notifications.telegram_integration import ( # noqa: E402
  17. initialize_telegram_service,
  18. send_security_alert_telegram,
  19. send_system_alert_telegram,
  20. send_telegram_notification,
  21. send_user_activity_alert_telegram,
  22. telegram_health_check,
  23. )
  24. from services.notifications.telegram_service import ( # noqa: E402
  25. NotificationPriority,
  26. get_telegram_service,
  27. parse_http_proxy_url,
  28. )
  29. def print_separator(title=""):
  30. """Imprimir separador visual"""
  31. print("\n" + "=" * 60)
  32. if title:
  33. print(f" {title}")
  34. print("=" * 60)
  35. print()
  36. def check_configuration():
  37. """Verify Telegram configuration from the database."""
  38. print_separator("Verificación de Configuración")
  39. cfg = load_config()
  40. print(f"TELEGRAM_ENABLED: {cfg['enabled']}")
  41. print(
  42. f"TELEGRAM_API_ID: {'✓ Configurado' if cfg.get('api_id') else '✗ No configurado'}"
  43. )
  44. print(
  45. f"TELEGRAM_API_HASH: {'✓ Configurado' if cfg.get('api_hash') else '✗ No configurado'}"
  46. )
  47. print(
  48. f"TELEGRAM_BOT_TOKEN: {'✓ Configurado' if cfg.get('bot_token') else '✗ No configurado'}"
  49. )
  50. print(
  51. f"TELEGRAM_PHONE: {'✓ Configurado' if cfg.get('phone') else '✗ No configurado'}"
  52. )
  53. print(f"TELEGRAM_SESSION_NAME: {cfg.get('session_name')}")
  54. recipients = cfg.get("recipients", [])
  55. print(f"TELEGRAM_RECIPIENTS: {recipients if recipients else '✗ No configurado'}")
  56. if not cfg["enabled"]:
  57. print(
  58. "\n⚠️ Telegram deshabilitado — actívalo desde Admin → Telegram Configuration"
  59. )
  60. return False
  61. if not cfg.get("api_id") or not cfg.get("api_hash"):
  62. print("\n❌ Faltan credenciales de API")
  63. print(" Obtén tus credenciales en: https://my.telegram.org/apps")
  64. return False
  65. if not cfg.get("bot_token") and not cfg.get("phone"):
  66. print("\n❌ Falta BOT_TOKEN o PHONE")
  67. print(" Configura bot_token o phone desde el panel de administración")
  68. return False
  69. if not cfg.get("recipients") or not any(r.strip() for r in cfg["recipients"]):
  70. print("\n❌ Faltan destinatarios")
  71. print(" Configura los destinatarios desde Admin → Telegram Configuration")
  72. return False
  73. print("\n✅ Configuración completa")
  74. return True
  75. def _require_telegram_config():
  76. """Skip the test if Telegram is not configured in the DB."""
  77. cfg = load_config()
  78. if not cfg.get("enabled") or not cfg.get("api_id") or not cfg.get("api_hash"):
  79. pytest.skip(
  80. "Telegram not configured in DB — set via Admin → Telegram Configuration"
  81. )
  82. return cfg
  83. @pytest.mark.asyncio
  84. async def test_connection():
  85. """Probar conexión a Telegram"""
  86. print_separator("Test de Conexión")
  87. cfg = _require_telegram_config()
  88. try:
  89. service = get_telegram_service(
  90. api_id=int(cfg["api_id"]),
  91. api_hash=cfg["api_hash"],
  92. bot_token=cfg.get("bot_token") or None,
  93. phone=cfg.get("phone") or None,
  94. session_name=cfg.get("session_name") or "squidstats_bot",
  95. enabled=True,
  96. )
  97. print("Conectando a Telegram...")
  98. await service.connect()
  99. print("✅ Conexión establecida")
  100. print("\nObteniendo información de la cuenta...")
  101. health = await service.health_check()
  102. print("\n📊 Estado del servicio:")
  103. print(f" Habilitado: {health['enabled']}")
  104. print(f" Conectado: {health['connected']}")
  105. print(f" Modo Bot: {health['bot_mode']}")
  106. print(f" Sesión: {health['session']}")
  107. if health["connected"]:
  108. print(f" User ID: {health.get('user_id', 'N/A')}")
  109. print(f" Username: {health.get('username', 'N/A')}")
  110. print("\n✅ Test de conexión exitoso")
  111. else:
  112. error = health.get("error", "Unknown error")
  113. print(f"\n❌ No se pudo conectar: {error}")
  114. return False
  115. await service.disconnect()
  116. return True
  117. except Exception as e:
  118. print(f"\n❌ Error en test de conexión: {e}")
  119. import traceback
  120. traceback.print_exc()
  121. return False
  122. @pytest.mark.asyncio
  123. async def test_send_basic_notification():
  124. """Probar envío de notificación básica"""
  125. print_separator("Test de Notificación Básica")
  126. cfg = _require_telegram_config()
  127. recipients = cfg.get("recipients", [])
  128. if not recipients:
  129. pytest.skip("No recipients configured in DB")
  130. try:
  131. service = get_telegram_service()
  132. await service.connect()
  133. recipient = recipients[0]
  134. print(f"Enviando notificación de prueba a: {recipient}")
  135. success = await service.send_notification(
  136. recipient=recipient,
  137. message="🧪 Test de notificación desde SquidStats\n\nSi recibes este mensaje, la integración funciona correctamente.",
  138. priority=NotificationPriority.NORMAL,
  139. source="Test Suite",
  140. )
  141. if success:
  142. print("✅ Notificación enviada exitosamente")
  143. else:
  144. print("❌ No se pudo enviar la notificación")
  145. await service.disconnect()
  146. return success
  147. except Exception as e:
  148. print(f"❌ Error enviando notificación: {e}")
  149. import traceback
  150. traceback.print_exc()
  151. return False
  152. @pytest.mark.asyncio
  153. async def test_priority_notifications():
  154. """Probar notificaciones con diferentes prioridades"""
  155. print_separator("Test de Prioridades")
  156. cfg = _require_telegram_config()
  157. recipients = cfg.get("recipients", [])
  158. if not recipients:
  159. pytest.skip("No recipients configured in DB")
  160. try:
  161. service = get_telegram_service()
  162. await service.connect()
  163. recipient = recipients[0]
  164. priorities = [
  165. (NotificationPriority.LOW, "Información de baja prioridad"),
  166. (NotificationPriority.NORMAL, "Notificación estándar"),
  167. (NotificationPriority.HIGH, "Advertencia importante"),
  168. (NotificationPriority.CRITICAL, "¡Alerta crítica!"),
  169. ]
  170. for priority, message in priorities:
  171. print(f"Enviando {priority.name}...")
  172. await service.send_notification(
  173. recipient=recipient,
  174. message=message,
  175. priority=priority,
  176. source="Priority Test",
  177. )
  178. await asyncio.sleep(1) # Evitar rate limiting
  179. print("✅ Todas las prioridades enviadas")
  180. await service.disconnect()
  181. return True
  182. except Exception as e:
  183. print(f"❌ Error en test de prioridades: {e}")
  184. return False
  185. @pytest.mark.asyncio
  186. async def test_formatted_notifications():
  187. """Probar notificaciones con datos extra"""
  188. print_separator("Test de Mensajes Formateados")
  189. cfg = _require_telegram_config()
  190. recipients = cfg.get("recipients", [])
  191. if not recipients:
  192. pytest.skip("No recipients configured in DB")
  193. try:
  194. service = get_telegram_service()
  195. await service.connect()
  196. recipient = recipients[0]
  197. print("Enviando notificación con metadata...")
  198. await service.send_notification(
  199. recipient=recipient,
  200. message="Alerta del sistema detectada",
  201. priority=NotificationPriority.HIGH,
  202. source="System Monitor",
  203. extra_data={
  204. "CPU": "85%",
  205. "RAM": "7.2 GB / 16 GB",
  206. "Disco": "45.3 GB disponibles",
  207. "Uptime": "5 días, 3 horas",
  208. },
  209. )
  210. print("✅ Notificación formateada enviada")
  211. await service.disconnect()
  212. return True
  213. except Exception as e:
  214. print(f"❌ Error en test de formato: {e}")
  215. return False
  216. def test_integration_wrapper():
  217. """Probar wrapper de integración (funciones síncronas)"""
  218. print_separator("Test de Wrapper de Integración")
  219. try:
  220. # Inicializar servicio
  221. print("Inicializando servicio de Telegram...")
  222. if not initialize_telegram_service():
  223. print(
  224. "⚠️ Telegram no está configurado o está deshabilitado en este entorno de pruebas"
  225. )
  226. pytest.skip("Telegram integration not configured")
  227. print("✅ Servicio inicializado")
  228. # Health check
  229. print("\nVerificando estado...")
  230. health = telegram_health_check()
  231. print(f"Estado: {health}")
  232. if not health.get("connected"):
  233. print("⚠️ No conectado - algunas funciones no estarán disponibles")
  234. # Enviar notificación genérica
  235. print("\nEnviando notificación genérica...")
  236. success1 = send_telegram_notification(
  237. notification_type="info",
  238. message="Test de integración wrapper",
  239. source="Integration Test",
  240. )
  241. print(f"Resultado: {'✅ Enviado' if success1 else '❌ Fallo'}")
  242. # Enviar alerta de seguridad
  243. print("\nEnviando alerta de seguridad...")
  244. success2 = send_security_alert_telegram(
  245. alert_type="Acceso sospechoso detectado",
  246. details={
  247. "IP": "192.168.1.100",
  248. "Usuario": "test_user",
  249. "Timestamp": "2026-01-17 15:00:00",
  250. },
  251. )
  252. print(f"Resultado: {'✅ Enviado' if success2 else '❌ Fallo'}")
  253. # Enviar alerta del sistema
  254. print("\nEnviando alerta del sistema...")
  255. success3 = send_system_alert_telegram(
  256. alert_message="Uso elevado de recursos detectado",
  257. metrics={"CPU": "92%", "Memoria": "14.8 GB / 16 GB", "Temperatura": "78°C"},
  258. )
  259. print(f"Resultado: {'✅ Enviado' if success3 else '❌ Fallo'}")
  260. # Enviar alerta de actividad de usuario
  261. print("\nEnviando alerta de actividad de usuario...")
  262. success4 = send_user_activity_alert_telegram(
  263. username="john_doe",
  264. activity_data={
  265. "Requests": "1,234",
  266. "Datos descargados": "45.3 GB",
  267. "Sitios únicos": "87",
  268. },
  269. )
  270. print(f"Resultado: {'✅ Enviado' if success4 else '❌ Fallo'}")
  271. all_success = all([success1, success2, success3, success4])
  272. if all_success:
  273. print("\n✅ Todos los tests del wrapper exitosos")
  274. else:
  275. print("\n⚠️ Algunos tests fallaron")
  276. assert all_success, "Al menos un test del wrapper falló"
  277. except Exception as e:
  278. print(f"\n❌ Error en test de wrapper: {e}")
  279. import traceback
  280. traceback.print_exc()
  281. pytest.fail(f"Error en test de wrapper: {e}")
  282. async def run_async_tests():
  283. """Ejecutar tests asíncronos"""
  284. results = []
  285. # Test de conexión
  286. results.append(await test_connection())
  287. await asyncio.sleep(2)
  288. # Test de notificación básica
  289. results.append(await test_send_basic_notification())
  290. await asyncio.sleep(2)
  291. # Test de prioridades
  292. results.append(await test_priority_notifications())
  293. await asyncio.sleep(2)
  294. # Test de formato
  295. results.append(await test_formatted_notifications())
  296. return results
  297. def test_proxy_parsing():
  298. """Test parsing de URLs de proxy HTTP"""
  299. print_separator("🧪 Test de Parsing de Proxy")
  300. test_cases = [
  301. # (input, expected_output_keys)
  302. ("", None),
  303. ("http://proxy.example.com:8080", ["proxy_type", "addr", "port"]),
  304. (
  305. "http://user:pass@proxy.example.com:8080",
  306. ["proxy_type", "addr", "port", "username", "password"],
  307. ),
  308. ("https://proxy.example.com:8080", None), # Solo HTTP soportado
  309. ("invalid-url", None),
  310. ]
  311. all_passed = True
  312. for i, (proxy_url, expected_keys) in enumerate(test_cases, 1):
  313. try:
  314. result = parse_http_proxy_url(proxy_url)
  315. if expected_keys is None:
  316. if result is None:
  317. print(f"✅ Test {i}: '{proxy_url}' → None (correcto)")
  318. else:
  319. print(f"❌ Test {i}: '{proxy_url}' → {result} (esperaba None)")
  320. all_passed = False
  321. else:
  322. if result and all(key in result for key in expected_keys):
  323. print(f"✅ Test {i}: '{proxy_url}' → {result}")
  324. else:
  325. print(
  326. f"❌ Test {i}: '{proxy_url}' → {result} (faltan keys: {expected_keys})"
  327. )
  328. all_passed = False
  329. except Exception as e:
  330. print(f"❌ Test {i}: Error parsing '{proxy_url}': {e}")
  331. all_passed = False
  332. if all_passed:
  333. print("\n✅ Todos los tests de proxy pasaron")
  334. else:
  335. print("\n❌ Algunos tests de proxy fallaron")
  336. assert all_passed, "El parsing de proxy falló en uno o más casos"
  337. def main():
  338. """Función principal"""
  339. print_separator("🧪 Test de Integración de Telegram")
  340. # Verificar configuración
  341. if not check_configuration():
  342. print("\n❌ Configuración incompleta. Corrige los errores y vuelve a intentar.")
  343. sys.exit(1)
  344. # Test de parsing de proxy
  345. proxy_test_passed = test_proxy_parsing()
  346. # Ejecutar tests asíncronos
  347. print("\n🚀 Iniciando tests asíncronos...")
  348. async_results = asyncio.run(run_async_tests())
  349. # Ejecutar tests síncronos (wrapper)
  350. print("\n🚀 Iniciando tests de wrapper...")
  351. sync_result = True
  352. try:
  353. test_integration_wrapper()
  354. except AssertionError as e:
  355. print(f"\n❌ Test de wrapper falló: {e}")
  356. sync_result = False
  357. except Exception as e:
  358. print(f"\n❌ Error inesperado en el test de wrapper: {e}")
  359. import traceback
  360. traceback.print_exc()
  361. sync_result = False
  362. # Resumen
  363. print_separator("📊 Resumen de Tests")
  364. tests = [
  365. ("Parsing de Proxy", proxy_test_passed),
  366. ("Conexión", async_results[0] if len(async_results) > 0 else False),
  367. ("Notificación básica", async_results[1] if len(async_results) > 1 else False),
  368. ("Prioridades", async_results[2] if len(async_results) > 2 else False),
  369. ("Formato", async_results[3] if len(async_results) > 3 else False),
  370. ("Wrapper de integración", sync_result),
  371. ]
  372. for test_name, result in tests:
  373. status = "✅ PASS" if result else "❌ FAIL"
  374. print(f"{status} - {test_name}")
  375. total = len(tests)
  376. passed = sum(1 for _, result in tests if result)
  377. print(f"\n📈 Resultados: {passed}/{total} tests exitosos")
  378. if passed == total:
  379. print(
  380. "\n🎉 ¡Todos los tests pasaron! La integración de Telegram está funcionando correctamente."
  381. )
  382. return 0
  383. else:
  384. print("\n⚠️ Algunos tests fallaron. Revisa los logs para más detalles.")
  385. return 1
  386. if __name__ == "__main__":
  387. try:
  388. exit_code = main()
  389. sys.exit(exit_code)
  390. except KeyboardInterrupt:
  391. print("\n\n⚠️ Test interrumpido por el usuario")
  392. sys.exit(130)
  393. except Exception as e:
  394. print(f"\n\n❌ Error fatal: {e}")
  395. import traceback
  396. traceback.print_exc()
  397. sys.exit(1)