File size: 13,277 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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""

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"])