""" Comprehensive unit tests for shared modules. Tests individual functions and classes in isolation. """ import pytest import asyncio from unittest.mock import Mock, patch, AsyncMock from datetime import datetime, timedelta import json import os from pathlib import Path # Import shared modules from shared.config import Config, get_config from shared.validation import ValidationError, validate_file_upload, validate_dataset_format from shared.error_handling import ErrorHandler, MCPError, ValidationError as VError from shared.caching import CacheManager, cache_key_generator from shared.memory_manager import MemoryManager from shared.query_optimizer import QueryOptimizer from shared.performance_monitor import PerformanceMonitor from shared.alerting import AlertManager, Alert, AlertLevel @pytest.mark.unit class TestConfig: """Test configuration management.""" def test_config_initialization(self): """Test config object initialization.""" config = Config() assert hasattr(config, 'database_url') assert hasattr(config, 'gemini_api_key') assert hasattr(config, 'clerk_secret_key') def test_config_from_env(self): """Test config loading from environment variables.""" with patch.dict(os.environ, { 'DATABASE_URL': 'postgresql://test:test@localhost/test', 'GEMINI_API_KEY': 'test_key', 'CLERK_SECRET_KEY': 'test_clerk_key' }): config = Config() assert config.database_url == 'postgresql://test:test@localhost/test' assert config.gemini_api_key == 'test_key' assert config.clerk_secret_key == 'test_clerk_key' def test_get_config_singleton(self): """Test that get_config returns the same instance.""" config1 = get_config() config2 = get_config() assert config1 is config2 def test_config_validation(self): """Test config validation for required fields.""" config = Config() # Test that missing required config raises appropriate errors with patch.dict(os.environ, {}, clear=True): config = Config() # Should handle missing environment variables gracefully @pytest.mark.unit class TestValidation: """Test validation utilities.""" def test_validate_file_upload_success(self): """Test successful file upload validation.""" # Mock file data file_data = b"col1,col2,col3\n1,2,3\n4,5,6" filename = "test.csv" result = validate_file_upload(file_data, filename) assert result['valid'] is True assert result['file_type'] == 'csv' assert result['size'] > 0 def test_validate_file_upload_invalid_extension(self): """Test file upload validation with invalid extension.""" file_data = b"some data" filename = "test.txt" with pytest.raises(ValidationError): validate_file_upload(file_data, filename) def test_validate_file_upload_too_large(self): """Test file upload validation with file too large.""" # Create large file data (mock) large_data = b"x" * (100 * 1024 * 1024 + 1) # > 100MB filename = "large.csv" with pytest.raises(ValidationError): validate_file_upload(large_data, filename) def test_validate_dataset_format_csv(self): """Test CSV dataset format validation.""" csv_data = "col1,col2,col3\n1,2,3\n4,5,6" result = validate_dataset_format(csv_data.encode(), 'csv') assert result['valid'] is True assert result['columns'] == ['col1', 'col2', 'col3'] assert result['rows'] == 2 def test_validate_dataset_format_invalid_csv(self): """Test invalid CSV dataset format validation.""" invalid_csv = "col1,col2\n1,2,3,4\n5,6" # Inconsistent columns with pytest.raises(ValidationError): validate_dataset_format(invalid_csv.encode(), 'csv') @pytest.mark.unit class TestErrorHandling: """Test error handling utilities.""" def test_mcp_error_creation(self): """Test MCPError creation and attributes.""" error = MCPError("Test error", "TEST_CODE", {"detail": "test"}) assert str(error) == "Test error" assert error.error_code == "TEST_CODE" assert error.details == {"detail": "test"} def test_validation_error_creation(self): """Test ValidationError creation.""" error = VError("Invalid input", "field_name") assert str(error) == "Invalid input" assert error.field == "field_name" @pytest.mark.asyncio async def test_error_handler_handle_error(self): """Test ErrorHandler error processing.""" handler = ErrorHandler() test_error = Exception("Test exception") result = await handler.handle_error(test_error, "test_context") assert result['error'] is True assert result['message'] == "Test exception" assert result['context'] == "test_context" @pytest.mark.asyncio async def test_error_handler_retry_logic(self): """Test ErrorHandler retry logic.""" handler = ErrorHandler() # Mock function that fails twice then succeeds call_count = 0 async def failing_function(): nonlocal call_count call_count += 1 if call_count < 3: raise Exception("Temporary failure") return "success" result = await handler.retry_with_backoff(failing_function, max_retries=3) assert result == "success" assert call_count == 3 @pytest.mark.unit class TestCaching: """Test caching functionality.""" def test_cache_key_generator(self): """Test cache key generation.""" key = cache_key_generator("test_prefix", "param1", "param2") assert key.startswith("test_prefix:") assert "param1" in key assert "param2" in key @pytest.mark.asyncio async def test_cache_manager_set_get(self): """Test cache manager set and get operations.""" cache = CacheManager() await cache.set("test_key", {"data": "test_value"}, ttl=60) result = await cache.get("test_key") assert result == {"data": "test_value"} @pytest.mark.asyncio async def test_cache_manager_expiration(self): """Test cache expiration.""" cache = CacheManager() await cache.set("expire_key", "test_value", ttl=1) # Wait for expiration await asyncio.sleep(1.1) result = await cache.get("expire_key") assert result is None @pytest.mark.asyncio async def test_cache_manager_delete(self): """Test cache deletion.""" cache = CacheManager() await cache.set("delete_key", "test_value") await cache.delete("delete_key") result = await cache.get("delete_key") assert result is None @pytest.mark.unit class TestMemoryManager: """Test memory management utilities.""" def test_memory_manager_initialization(self): """Test MemoryManager initialization.""" manager = MemoryManager(max_memory_mb=1024) assert manager.max_memory_bytes == 1024 * 1024 * 1024 def test_memory_usage_tracking(self): """Test memory usage tracking.""" manager = MemoryManager() initial_usage = manager.get_current_usage() assert initial_usage >= 0 # Allocate some memory large_list = [i for i in range(10000)] new_usage = manager.get_current_usage() assert new_usage >= initial_usage def test_memory_limit_check(self): """Test memory limit checking.""" manager = MemoryManager(max_memory_mb=1) # Very low limit # Should detect when approaching limit is_approaching = manager.is_approaching_limit(threshold=0.8) # Result depends on current system memory usage @pytest.mark.unit class TestQueryOptimizer: """Test query optimization utilities.""" def test_query_optimizer_initialization(self): """Test QueryOptimizer initialization.""" optimizer = QueryOptimizer() assert hasattr(optimizer, 'optimize_query') def test_query_optimization_simple(self): """Test simple query optimization.""" optimizer = QueryOptimizer() original_query = "SELECT * FROM users WHERE id = 1" optimized = optimizer.optimize_query(original_query) # Should return optimized version or same query assert isinstance(optimized, str) assert len(optimized) > 0 def test_query_optimization_with_joins(self): """Test query optimization with joins.""" optimizer = QueryOptimizer() complex_query = """ SELECT u.*, p.name FROM users u JOIN profiles p ON u.id = p.user_id WHERE u.active = true """ optimized = optimizer.optimize_query(complex_query) assert isinstance(optimized, str) assert "JOIN" in optimized @pytest.mark.unit class TestPerformanceMonitor: """Test performance monitoring utilities.""" def test_performance_monitor_initialization(self): """Test PerformanceMonitor initialization.""" monitor = PerformanceMonitor() assert hasattr(monitor, 'start_timer') assert hasattr(monitor, 'end_timer') def test_timer_functionality(self): """Test timer start/end functionality.""" monitor = PerformanceMonitor() timer_id = monitor.start_timer("test_operation") assert timer_id is not None # Simulate some work import time time.sleep(0.1) duration = monitor.end_timer(timer_id) assert duration >= 0.1 assert duration < 1.0 # Should be reasonable def test_metrics_collection(self): """Test metrics collection.""" monitor = PerformanceMonitor() monitor.record_metric("test_metric", 42.5) metrics = monitor.get_metrics() assert "test_metric" in metrics assert metrics["test_metric"] == 42.5 def test_performance_summary(self): """Test performance summary generation.""" monitor = PerformanceMonitor() # Record some metrics monitor.record_metric("cpu_usage", 75.0) monitor.record_metric("memory_usage", 60.0) summary = monitor.get_summary() assert isinstance(summary, dict) assert "cpu_usage" in summary assert "memory_usage" in summary @pytest.mark.unit class TestAlertManager: """Test alerting system.""" def test_alert_creation(self): """Test Alert object creation.""" alert = Alert( level=AlertLevel.WARNING, message="Test alert", component="test_component", details={"key": "value"} ) assert alert.level == AlertLevel.WARNING assert alert.message == "Test alert" assert alert.component == "test_component" assert alert.details == {"key": "value"} assert isinstance(alert.timestamp, datetime) def test_alert_manager_initialization(self): """Test AlertManager initialization.""" manager = AlertManager() assert hasattr(manager, 'send_alert') assert hasattr(manager, 'get_alerts') @pytest.mark.asyncio async def test_alert_manager_send_alert(self): """Test sending alerts.""" manager = AlertManager() alert = Alert( level=AlertLevel.ERROR, message="Test error alert", component="test_component" ) result = await manager.send_alert(alert) assert result is True # Assuming successful send def test_alert_manager_get_alerts(self): """Test retrieving alerts.""" manager = AlertManager() # Should return list of alerts alerts = manager.get_alerts(limit=10) assert isinstance(alerts, list) def test_alert_filtering(self): """Test alert filtering by level.""" manager = AlertManager() # Test filtering by alert level error_alerts = manager.get_alerts(level=AlertLevel.ERROR) assert isinstance(error_alerts, list) warning_alerts = manager.get_alerts(level=AlertLevel.WARNING) assert isinstance(warning_alerts, list) if __name__ == "__main__": pytest.main([__file__, "-v"])