ai_data_scientist / scripts /test_monitoring_endpoints.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
7.65 kB
#!/usr/bin/env python3
"""
Test script to verify monitoring endpoints are working correctly.
This script tests the monitoring system without requiring authentication.
"""
import asyncio
import sys
import json
from pathlib import Path
# Add project root to path
sys.path.insert(0, str(Path(__file__).parent.parent))
from shared.monitoring import monitoring_system, get_system_health
from shared.alerting import alert_manager, get_active_alerts, get_alert_summary
from shared.system_monitor import system_monitor, get_system_resource_status, get_system_summary
async def test_monitoring_system():
"""Test the monitoring system components."""
print("πŸ” Testing Monitoring System Components")
print("=" * 50)
try:
# Test 1: Start monitoring system
print("\n1. Starting monitoring system...")
await monitoring_system.start_monitoring()
print("βœ… Monitoring system started successfully")
# Test 2: Record some test metrics
print("\n2. Recording test metrics...")
monitoring_system.metrics_collector.record_metric("test.cpu_usage", 45.2)
monitoring_system.metrics_collector.record_metric("test.memory_usage", 67.8)
monitoring_system.app_monitor.record_request("/api/test", "GET")
monitoring_system.app_monitor.record_error("/api/test", "ValidationError", "POST")
print("βœ… Test metrics recorded successfully")
# Test 3: Get system health
print("\n3. Getting system health...")
health_data = await get_system_health()
print(f"βœ… System health retrieved: {health_data['overall_healthy']}")
print(f" - Monitoring active: {health_data['monitoring_active']}")
print(f" - Total metrics: {health_data['metrics']['total_metrics']}")
print(f" - Health components: {len(health_data['health'])}")
# Test 4: Test alerting system
print("\n4. Testing alerting system...")
await alert_manager.start_monitoring()
active_alerts = get_active_alerts()
alert_summary = get_alert_summary()
print(f"βœ… Alerting system active: {alert_summary['monitoring_active']}")
print(f" - Total rules: {alert_summary['total_rules']}")
print(f" - Active alerts: {alert_summary['active_alerts']}")
# Test 5: Test system resource monitoring
print("\n5. Testing system resource monitoring...")
await system_monitor.start_monitoring()
resource_status = await get_system_resource_status()
system_summary = get_system_summary()
print(f"βœ… System resources status: {resource_status.status}")
print(f" - CPU: {resource_status.cpu_percent:.1f}%")
print(f" - Memory: {resource_status.memory_percent:.1f}%")
print(f" - Disk: {resource_status.disk_percent:.1f}%")
if resource_status.warnings:
print(f" - Warnings: {len(resource_status.warnings)}")
# Test 6: Export metrics
print("\n6. Testing metrics export...")
exported_metrics = monitoring_system.export_metrics("json")
metrics_data = json.loads(exported_metrics)
print(f"βœ… Metrics exported successfully")
print(f" - Metric types: {len(metrics_data)}")
# Test 7: Test monitoring dashboard data
print("\n7. Testing monitoring dashboard...")
dashboard_data = monitoring_system.get_monitoring_dashboard()
print(f"βœ… Dashboard data retrieved")
print(f" - Timestamp: {dashboard_data['timestamp']}")
print(f" - Overall healthy: {dashboard_data['overall_healthy']}")
print("\n" + "=" * 50)
print("πŸŽ‰ All monitoring tests passed successfully!")
return True
except Exception as e:
print(f"\n❌ Test failed with error: {e}")
import traceback
traceback.print_exc()
return False
finally:
# Cleanup
print("\n🧹 Cleaning up...")
try:
await monitoring_system.stop_monitoring()
await alert_manager.stop_monitoring()
await system_monitor.stop_monitoring()
print("βœ… Cleanup completed")
except Exception as e:
print(f"⚠️ Cleanup warning: {e}")
async def test_health_checks():
"""Test health check functionality."""
print("\nπŸ₯ Testing Health Check System")
print("=" * 50)
try:
# Test health checker
health_checker = monitoring_system.health_checker
# Register a test health check
def test_health_check():
return {
"healthy": True,
"message": "Test component is healthy",
"metrics": {"response_time": 0.1, "connections": 5}
}
health_checker.register_health_check("test_component", test_health_check)
# Check individual component
print("\n1. Testing individual health check...")
status = await health_checker.check_component_health("test_component")
print(f"βœ… Component health: {status.is_healthy}")
print(f" - Message: {status.status_message}")
print(f" - Metrics: {status.metrics}")
# Check all health
print("\n2. Testing all health checks...")
all_health = await health_checker.check_all_health()
print(f"βœ… All health checks completed: {len(all_health)} components")
# Test overall health
overall_healthy = health_checker.get_overall_health()
print(f"βœ… Overall system health: {overall_healthy}")
return True
except Exception as e:
print(f"\n❌ Health check test failed: {e}")
import traceback
traceback.print_exc()
return False
def print_system_info():
"""Print system information."""
print("πŸ–₯️ System Information")
print("=" * 50)
try:
import psutil
print(f"βœ… psutil available: {psutil.version}")
print(f" - CPU cores: {psutil.cpu_count()}")
print(f" - Memory: {psutil.virtual_memory().total / (1024**3):.1f} GB")
except ImportError:
print("⚠️ psutil not available - limited system monitoring")
try:
import platform
print(f"βœ… Platform: {platform.system()} {platform.release()}")
print(f" - Python: {platform.python_version()}")
except Exception as e:
print(f"⚠️ Platform info error: {e}")
async def main():
"""Main test function."""
print("πŸš€ MCP AI Data Scientist - Monitoring System Test")
print("=" * 60)
# Print system info
print_system_info()
# Run tests
monitoring_success = await test_monitoring_system()
health_success = await test_health_checks()
# Summary
print("\n" + "=" * 60)
print("πŸ“Š Test Summary")
print("=" * 60)
print(f"Monitoring System: {'βœ… PASS' if monitoring_success else '❌ FAIL'}")
print(f"Health Checks: {'βœ… PASS' if health_success else '❌ FAIL'}")
overall_success = monitoring_success and health_success
print(f"\nOverall Result: {'πŸŽ‰ ALL TESTS PASSED' if overall_success else '❌ SOME TESTS FAILED'}")
return 0 if overall_success else 1
if __name__ == "__main__":
exit_code = asyncio.run(main())
sys.exit(exit_code)