File size: 7,647 Bytes
56c063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/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)