test_telegram_integration.py 14 KB

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