""" Integration tests for the monitoring and health check system. Tests the complete monitoring infrastructure including metrics, health checks, and alerting. """ import pytest import asyncio import time from datetime import datetime, timedelta from unittest.mock import Mock, patch, AsyncMock from typing import Dict, Any from shared.monitoring import ( monitoring_system, MetricsCollector, PerformanceMonitor, ApplicationMonitor, HealthChecker, get_system_health ) from shared.alerting import ( alert_manager, AlertRule, AlertType, AlertSeverity, Alert ) from shared.models import MCPServerHealth from orchestrator.health_monitor import HealthMonitor from orchestrator.mcp_client_manager import MCPClientManager class TestMetricsCollection: """Test metrics collection functionality.""" def test_metrics_collector_basic_functionality(self): """Test basic metrics collection operations.""" collector = MetricsCollector(max_points=100) # Record some metrics collector.record_metric("test.counter", 1.0, {"tag": "value"}) collector.record_metric("test.counter", 2.0, {"tag": "value"}) collector.record_metric("test.gauge", 50.0) # Get metrics counter_metrics = collector.get_metrics("test.counter") gauge_metrics = collector.get_metrics("test.gauge") assert len(counter_metrics) == 2 assert len(gauge_metrics) == 1 assert counter_metrics[0].value == 1.0 assert counter_metrics[1].value == 2.0 assert gauge_metrics[0].value == 50.0 def test_metrics_collector_latest_values(self): """Test getting latest metric values.""" collector = MetricsCollector() collector.record_metric("cpu.usage", 10.0) collector.record_metric("cpu.usage", 20.0) collector.record_metric("memory.usage", 30.0) latest = collector.get_latest_values() assert latest["cpu.usage"] == 20.0 assert latest["memory.usage"] == 30.0 def test_metrics_collector_max_points_limit(self): """Test that metrics collector respects max points limit.""" collector = MetricsCollector(max_points=3) # Add more metrics than the limit for i in range(5): collector.record_metric("test.metric", float(i)) metrics = collector.get_metrics("test.metric") # Should only keep the last 3 points assert len(metrics) == 3 assert metrics[0].value == 2.0 # First kept value assert metrics[2].value == 4.0 # Last value class TestPerformanceMonitor: """Test performance monitoring functionality.""" @pytest.mark.asyncio async def test_performance_monitor_lifecycle(self): """Test performance monitor start/stop lifecycle.""" collector = MetricsCollector() monitor = PerformanceMonitor(collector) assert not monitor.monitoring # Start monitoring await monitor.start_monitoring(interval=0.1) assert monitor.monitoring # Let it collect some metrics await asyncio.sleep(0.2) # Stop monitoring await monitor.stop_monitoring() assert not monitor.monitoring @pytest.mark.asyncio async def test_performance_monitor_metrics_collection(self): """Test that performance monitor collects system metrics.""" collector = MetricsCollector() monitor = PerformanceMonitor(collector) # Manually trigger metrics collection await monitor._collect_system_metrics() # Check that metrics were recorded latest = collector.get_latest_values() # Should have at least basic metrics (even if psutil is not available) assert "system.cpu_percent" in latest assert "system.memory_rss_mb" in latest class TestApplicationMonitor: """Test application monitoring functionality.""" def test_request_recording(self): """Test recording API requests.""" collector = MetricsCollector() monitor = ApplicationMonitor(collector) # Record some requests monitor.record_request("/api/test", "GET") monitor.record_request("/api/test", "POST") monitor.record_request("/api/other", "GET") # Check metrics were recorded latest = collector.get_latest_values() assert "app.requests_total" in latest def test_error_recording(self): """Test recording application errors.""" collector = MetricsCollector() monitor = ApplicationMonitor(collector) # Record some errors monitor.record_error("/api/test", "ValidationError", "POST") monitor.record_error("/api/test", "DatabaseError", "GET") # Check metrics were recorded latest = collector.get_latest_values() assert "app.errors_total" in latest @pytest.mark.asyncio async def test_operation_timing(self): """Test operation timing functionality.""" collector = MetricsCollector() monitor = ApplicationMonitor(collector) # Time an operation async with monitor.time_operation("test_operation"): await asyncio.sleep(0.1) # Check timing metric was recorded metrics = collector.get_metrics("app.operation_duration_seconds") assert len(metrics) > 0 assert metrics[0].value >= 0.1 # Should be at least 0.1 seconds def test_analysis_stage_recording(self): """Test recording analysis stage metrics.""" collector = MetricsCollector() monitor = ApplicationMonitor(collector) # Record analysis stages monitor.record_analysis_stage("data_cleaning", 5.2, True) monitor.record_analysis_stage("hypothesis_testing", 3.1, False) # Check metrics were recorded duration_metrics = collector.get_metrics("app.analysis_stage_duration_seconds") count_metrics = collector.get_metrics("app.analysis_stage_count") assert len(duration_metrics) == 2 assert len(count_metrics) == 2 def test_mcp_call_recording(self): """Test recording MCP server call metrics.""" collector = MetricsCollector() monitor = ApplicationMonitor(collector) # Record MCP calls monitor.record_mcp_call("data_cleaning", "upload_dataset", 1.5, True) monitor.record_mcp_call("hypothesis_testing", "generate_hypotheses", 2.3, False) # Check metrics were recorded duration_metrics = collector.get_metrics("app.mcp_call_duration_seconds") count_metrics = collector.get_metrics("app.mcp_call_count") assert len(duration_metrics) == 2 assert len(count_metrics) == 2 class TestHealthChecker: """Test health checking functionality.""" @pytest.mark.asyncio async def test_health_check_registration_and_execution(self): """Test registering and executing health checks.""" checker = HealthChecker() # Register a simple health check def simple_health_check(): return True checker.register_health_check("test_component", simple_health_check) # Execute health check status = await checker.check_component_health("test_component") assert status.component == "test_component" assert status.is_healthy is True assert status.status_message == "OK" @pytest.mark.asyncio async def test_health_check_with_detailed_result(self): """Test health check with detailed result dictionary.""" checker = HealthChecker() def detailed_health_check(): return { "healthy": True, "message": "All systems operational", "metrics": {"response_time": 0.5, "connections": 10} } checker.register_health_check("detailed_component", detailed_health_check) status = await checker.check_component_health("detailed_component") assert status.is_healthy is True assert status.status_message == "All systems operational" assert status.metrics["response_time"] == 0.5 assert status.metrics["connections"] == 10 @pytest.mark.asyncio async def test_health_check_failure(self): """Test health check failure handling.""" checker = HealthChecker() def failing_health_check(): raise Exception("Health check failed") checker.register_health_check("failing_component", failing_health_check) status = await checker.check_component_health("failing_component") assert status.is_healthy is False assert "Health check error" in status.status_message @pytest.mark.asyncio async def test_async_health_check(self): """Test asynchronous health check.""" checker = HealthChecker() async def async_health_check(): await asyncio.sleep(0.01) # Simulate async work return {"healthy": True, "message": "Async check passed"} checker.register_health_check("async_component", async_health_check) status = await checker.check_component_health("async_component") assert status.is_healthy is True assert status.status_message == "Async check passed" @pytest.mark.asyncio async def test_check_all_health(self): """Test checking health of all registered components.""" checker = HealthChecker() # Register multiple health checks checker.register_health_check("component1", lambda: True) checker.register_health_check("component2", lambda: False) checker.register_health_check("component3", lambda: {"healthy": True, "message": "OK"}) # Check all health all_health = await checker.check_all_health() assert len(all_health) == 3 assert all_health["component1"].is_healthy is True assert all_health["component2"].is_healthy is False assert all_health["component3"].is_healthy is True def test_overall_health_status(self): """Test overall health status calculation.""" checker = HealthChecker() # All healthy checker.health_status = { "comp1": MCPServerHealth(server_name="comp1", is_healthy=True, response_time_ms=100, last_check=datetime.now()), "comp2": MCPServerHealth(server_name="comp2", is_healthy=True, response_time_ms=150, last_check=datetime.now()) } assert checker.get_overall_health() is True # One unhealthy checker.health_status["comp2"].is_healthy = False assert checker.get_overall_health() is False # No components checker.health_status = {} assert checker.get_overall_health() is False class TestAlertingSystem: """Test alerting system functionality.""" def test_alert_rule_creation(self): """Test creating alert rules.""" rule = AlertRule( name="test_rule", alert_type=AlertType.ERROR_RATE, severity=AlertSeverity.HIGH, threshold=0.05, window_minutes=5, description="Test alert rule" ) assert rule.name == "test_rule" assert rule.alert_type == AlertType.ERROR_RATE assert rule.severity == AlertSeverity.HIGH assert rule.threshold == 0.05 assert rule.window_minutes == 5 def test_alert_creation(self): """Test creating alerts.""" alert = Alert( id="test_alert_1", rule_name="test_rule", alert_type=AlertType.ERROR_RATE, severity=AlertSeverity.HIGH, message="Error rate exceeded threshold", triggered_at=datetime.now(), metadata={"threshold": 0.05} ) assert alert.id == "test_alert_1" assert alert.rule_name == "test_rule" assert alert.severity == AlertSeverity.HIGH assert alert.resolved_at is None @pytest.mark.asyncio async def test_alert_manager_lifecycle(self): """Test alert manager start/stop lifecycle.""" from shared.alerting import AlertManager manager = AlertManager() assert not manager.monitoring_active # Start monitoring await manager.start_monitoring() assert manager.monitoring_active # Stop monitoring await manager.stop_monitoring() assert not manager.monitoring_active def test_alert_rule_management(self): """Test adding, enabling, and disabling alert rules.""" from shared.alerting import AlertManager manager = AlertManager() # Add a rule rule = AlertRule( name="custom_rule", alert_type=AlertType.RESPONSE_TIME, severity=AlertSeverity.MEDIUM, threshold=1000.0, window_minutes=10 ) manager.add_rule(rule) assert "custom_rule" in manager.rules # Disable rule manager.disable_rule("custom_rule") assert not manager.rules["custom_rule"].enabled # Enable rule manager.enable_rule("custom_rule") assert manager.rules["custom_rule"].enabled # Remove rule manager.remove_rule("custom_rule") assert "custom_rule" not in manager.rules class TestMCPHealthMonitor: """Test MCP server health monitoring.""" @pytest.mark.asyncio async def test_health_monitor_initialization(self): """Test health monitor initialization.""" mock_mcp_client = Mock(spec=MCPClientManager) mock_mcp_client.connections = {} monitor = HealthMonitor(mock_mcp_client) assert monitor.mcp_client == mock_mcp_client assert monitor.health_status == {} assert monitor.consecutive_failures == {} assert monitor.consecutive_successes == {} @pytest.mark.asyncio async def test_health_check_server_success(self): """Test successful server health check.""" mock_mcp_client = Mock(spec=MCPClientManager) mock_connection = AsyncMock() mock_connection.health_check.return_value = True mock_mcp_client.connections = {"test_server": mock_connection} monitor = HealthMonitor(mock_mcp_client) health_status = await monitor._check_server_health("test_server") assert health_status.server_name == "test_server" assert health_status.is_healthy is True assert health_status.error_message is None assert health_status.response_time_ms > 0 @pytest.mark.asyncio async def test_health_check_server_failure(self): """Test failed server health check.""" mock_mcp_client = Mock(spec=MCPClientManager) mock_connection = AsyncMock() mock_connection.health_check.side_effect = Exception("Connection failed") mock_mcp_client.connections = {"test_server": mock_connection} monitor = HealthMonitor(mock_mcp_client) health_status = await monitor._check_server_health("test_server") assert health_status.server_name == "test_server" assert health_status.is_healthy is False assert "Connection failed" in health_status.error_message @pytest.mark.asyncio async def test_health_check_timeout(self): """Test health check timeout handling.""" mock_mcp_client = Mock(spec=MCPClientManager) mock_connection = AsyncMock() # Simulate timeout async def slow_health_check(): await asyncio.sleep(1) return True mock_connection.health_check = slow_health_check mock_mcp_client.connections = {"test_server": mock_connection} monitor = HealthMonitor(mock_mcp_client) monitor.response_timeout = 0.1 # Very short timeout health_status = await monitor._check_server_health("test_server") assert health_status.is_healthy is False assert "timeout" in health_status.error_message.lower() def test_pipeline_health_status(self): """Test pipeline health status calculation.""" mock_mcp_client = Mock(spec=MCPClientManager) monitor = HealthMonitor(mock_mcp_client) # Set up health status for pipeline servers pipeline_servers = [ "data_cleaning", "hypothesis_testing", "preprocessing", "feature_engineering", "model_training", "action_generation" ] # All healthy for server in pipeline_servers: monitor.health_status[server] = MCPServerHealth( server_name=server, is_healthy=True, response_time_ms=100, last_check=datetime.now() ) assert monitor.is_pipeline_healthy() is True # One server unhealthy monitor.health_status["data_cleaning"].is_healthy = False assert monitor.is_pipeline_healthy() is False def test_health_summary(self): """Test health summary generation.""" mock_mcp_client = Mock(spec=MCPClientManager) monitor = HealthMonitor(mock_mcp_client) # Add some health status monitor.health_status = { "server1": MCPServerHealth(server_name="server1", is_healthy=True, response_time_ms=100, last_check=datetime.now()), "server2": MCPServerHealth(server_name="server2", is_healthy=False, response_time_ms=200, last_check=datetime.now()), "server3": MCPServerHealth(server_name="server3", is_healthy=True, response_time_ms=150, last_check=datetime.now()) } summary = monitor.get_health_summary() assert summary["total_servers"] == 3 assert summary["healthy_servers"] == 2 assert summary["unhealthy_servers"] == 1 assert summary["average_response_time_ms"] == 125.0 # (100 + 150) / 2 class TestMonitoringSystemIntegration: """Test complete monitoring system integration.""" @pytest.mark.asyncio async def test_monitoring_system_startup_shutdown(self): """Test monitoring system startup and shutdown.""" # Start monitoring await monitoring_system.start_monitoring() assert monitoring_system.monitoring_active # Stop monitoring await monitoring_system.stop_monitoring() assert not monitoring_system.monitoring_active @pytest.mark.asyncio async def test_get_system_health_integration(self): """Test getting comprehensive system health.""" # Start monitoring to ensure health checks are registered await monitoring_system.start_monitoring() try: health_data = await get_system_health() assert "timestamp" in health_data assert "monitoring_active" in health_data assert "metrics" in health_data assert "health" in health_data assert "overall_healthy" in health_data # Should have default health checks assert "database" in health_data["health"] assert "system_resources" in health_data["health"] finally: await monitoring_system.stop_monitoring() def test_monitoring_dashboard_data(self): """Test monitoring dashboard data structure.""" dashboard_data = monitoring_system.get_monitoring_dashboard() assert "timestamp" in dashboard_data assert "monitoring_active" in dashboard_data assert "metrics" in dashboard_data assert "health" in dashboard_data assert "overall_healthy" in dashboard_data # Metrics should have expected structure metrics = dashboard_data["metrics"] assert "latest_values" in metrics assert "total_metrics" in metrics def test_metrics_export(self): """Test metrics export functionality.""" # Record some test metrics monitoring_system.metrics_collector.record_metric("test.export", 1.0) monitoring_system.metrics_collector.record_metric("test.export", 2.0) # Export metrics exported = monitoring_system.export_metrics("json") assert isinstance(exported, str) # Should be valid JSON import json data = json.loads(exported) assert "test.export" in data @pytest.mark.asyncio async def test_end_to_end_monitoring_scenario(): """Test a complete end-to-end monitoring scenario.""" # Start monitoring system await monitoring_system.start_monitoring() try: # Simulate application activity monitoring_system.app_monitor.record_request("/api/analysis", "POST") monitoring_system.app_monitor.record_request("/api/health", "GET") monitoring_system.app_monitor.record_error("/api/analysis", "ValidationError", "POST") # Record some custom metrics monitoring_system.metrics_collector.record_metric("custom.test_metric", 42.0) # Perform health checks await monitoring_system.health_checker.check_all_health() # Get comprehensive health status health_data = await get_system_health() # Verify data structure assert health_data["monitoring_active"] is True assert "latest_values" in health_data["metrics"] assert len(health_data["health"]) >= 2 # At least database and system_resources # Check that our custom metric was recorded latest_values = health_data["metrics"]["latest_values"] assert "custom.test_metric" in latest_values assert latest_values["custom.test_metric"] == 42.0 finally: await monitoring_system.stop_monitoring() if __name__ == "__main__": pytest.main([__file__, "-v"])