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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
"""

Unit tests for Feature Engineering MCP Server functionality.

Tests feature generation algorithms, transformations, and validation logic.

"""

import pytest
import pandas as pd
import numpy as np
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
import tempfile
import os

from mcp_servers.feature_engineering.server import FeatureEngineeringMCPServer
from shared.models import UserContext, FeatureSet


class TestFeatureEngineeringAlgorithms:
    """Test feature engineering algorithms and transformations."""
    
    @pytest.fixture
    def sample_dataframe(self):
        """Create a sample dataframe for testing."""
        np.random.seed(42)
        return pd.DataFrame({
            'numeric1': np.random.normal(100, 15, 1000),
            'numeric2': np.random.normal(50, 10, 1000),
            'numeric3': np.random.exponential(2, 1000),
            'category1': np.random.choice(['A', 'B', 'C'], 1000),
            'category2': np.random.choice(['X', 'Y'], 1000),
            'target': np.random.choice([0, 1], 1000)
        })
    
    @pytest.fixture
    def sample_hypotheses(self):
        """Create sample hypotheses for testing."""
        return [
            {
                "id": str(uuid4()),
                "text": "There is a significant correlation between numeric1 and numeric2",
                "test_type": "correlation",
                "variables": ["numeric1", "numeric2"],
                "is_significant": True
            },
            {
                "id": str(uuid4()),
                "text": "There is a significant difference in numeric1 between category1 groups",
                "test_type": "anova",
                "variables": ["category1", "numeric1"],
                "is_significant": True
            },
            {
                "id": str(uuid4()),
                "text": "There is a significant difference in numeric2 between category2 groups",
                "test_type": "t_test",
                "variables": ["category2", "numeric2"],
                "is_significant": True
            }
        ]
    
    def test_interaction_feature_generation(self, sample_dataframe, sample_hypotheses):
        """Test generation of interaction features."""
        server = FeatureEngineeringMCPServer()
        
        # Test multiplicative interaction
        correlation_hypothesis = sample_hypotheses[0]
        var1, var2 = correlation_hypothesis["variables"]
        
        # Create multiplicative interaction
        result = sample_dataframe[var1] * sample_dataframe[var2]
        
        assert len(result) == len(sample_dataframe)
        assert not result.isna().all()
        
        # Test ratio interaction
        ratio_result = sample_dataframe[var1] / (sample_dataframe[var2] + 1e-8)
        
        assert len(ratio_result) == len(sample_dataframe)
        assert not np.isinf(ratio_result).any()  # Should not have infinite values
    
    def test_transformation_features(self, sample_dataframe):
        """Test mathematical transformation features."""
        server = FeatureEngineeringMCPServer()
        
        # Test log transformation
        positive_col = sample_dataframe['numeric3']  # Exponential distribution, always positive
        log_transform = np.log(positive_col)
        
        assert len(log_transform) == len(sample_dataframe)
        assert not np.isinf(log_transform).any()
        assert not log_transform.isna().any()
        
        # Test square transformation
        square_transform = sample_dataframe['numeric1'] ** 2
        
        assert len(square_transform) == len(sample_dataframe)
        assert (square_transform >= 0).all()  # Squares are always non-negative
        
        # Test square root transformation
        abs_values = np.abs(sample_dataframe['numeric1'])
        sqrt_transform = np.sqrt(abs_values)
        
        assert len(sqrt_transform) == len(sample_dataframe)
        assert (sqrt_transform >= 0).all()
        assert not sqrt_transform.isna().any()
    
    def test_aggregation_features(self, sample_dataframe):
        """Test group-based aggregation features."""
        server = FeatureEngineeringMCPServer()
        
        # Test group mean
        group_means = sample_dataframe.groupby('category1')['numeric1'].transform('mean')
        
        assert len(group_means) == len(sample_dataframe)
        assert not group_means.isna().any()
        
        # Verify that all rows in the same group have the same mean
        for category in sample_dataframe['category1'].unique():
            mask = sample_dataframe['category1'] == category
            group_mean_values = group_means[mask]
            assert len(group_mean_values.unique()) == 1  # All values should be the same
        
        # Test group standard deviation
        group_stds = sample_dataframe.groupby('category1')['numeric1'].transform('std')
        
        assert len(group_stds) == len(sample_dataframe)
        # Fill NaN values (which can occur for single-item groups)
        group_stds = group_stds.fillna(0)
        assert (group_stds >= 0).all()  # Standard deviations are non-negative
    
    def test_polynomial_features(self, sample_dataframe):
        """Test polynomial feature generation."""
        from sklearn.preprocessing import PolynomialFeatures
        
        # Select two numeric columns
        variables = ['numeric1', 'numeric2']
        data = sample_dataframe[variables]
        
        # Create polynomial features
        poly = PolynomialFeatures(degree=2, include_bias=False, interaction_only=False)
        poly_data = poly.fit_transform(data)
        
        # Should have more features than original
        assert poly_data.shape[1] >= len(variables)
        assert poly_data.shape[0] == len(sample_dataframe)
        
        # Check feature names
        feature_names = poly.get_feature_names_out(variables)
        assert len(feature_names) == poly_data.shape[1]
    
    def test_data_leakage_detection(self, sample_dataframe):
        """Test data leakage detection algorithms."""
        server = FeatureEngineeringMCPServer()
        
        # Create a feature that perfectly correlates with target (data leakage)
        leaky_feature = sample_dataframe['target'] + np.random.normal(0, 0.01, len(sample_dataframe))
        
        # Calculate correlation
        correlation = abs(sample_dataframe['target'].corr(leaky_feature))
        
        # Should detect high correlation (>0.95 threshold)
        assert correlation > 0.95
        
        # Create a legitimate feature (low correlation)
        legitimate_feature = pd.Series(np.random.normal(0, 1, len(sample_dataframe)))
        correlation_legit = abs(sample_dataframe['target'].corr(legitimate_feature))
        
        # Should have low correlation
        assert correlation_legit < 0.1
    
    def test_dimensionality_reduction_trigger(self, sample_dataframe):
        """Test when dimensionality reduction should be triggered."""
        server = FeatureEngineeringMCPServer()
        
        # Create a dataset with many features
        many_features_df = sample_dataframe.copy()
        
        # Add many random features
        for i in range(100):
            many_features_df[f'random_feature_{i}'] = np.random.normal(0, 1, len(sample_dataframe))
        
        total_features = len(many_features_df.columns)
        
        # Should trigger dimensionality reduction
        assert total_features > 100
        
        # Test PCA application
        from sklearn.decomposition import PCA
        
        numeric_cols = many_features_df.select_dtypes(include=[np.number]).columns
        if len(numeric_cols) > 20:
            n_components = min(20, len(numeric_cols), len(many_features_df) - 1)
            pca = PCA(n_components=n_components)
            
            pca_data = pca.fit_transform(many_features_df[numeric_cols])
            
            assert pca_data.shape[1] == n_components
            assert pca_data.shape[0] == len(many_features_df)
            assert len(pca.explained_variance_ratio_) == n_components
    
    def test_complexity_score_calculation(self):
        """Test complexity score calculation."""
        server = FeatureEngineeringMCPServer()
        
        # Test complexity score normalization
        test_cases = [
            (10, 0.1),   # 10 features -> 0.1 complexity
            (50, 0.5),   # 50 features -> 0.5 complexity
            (100, 1.0),  # 100 features -> 1.0 complexity
            (150, 1.0),  # 150 features -> 1.0 (capped at 1.0)
        ]
        
        for feature_count, expected_complexity in test_cases:
            complexity_score = min(1.0, feature_count / 100.0)
            assert complexity_score == expected_complexity
    
    def test_feature_validation_edge_cases(self, sample_dataframe):
        """Test feature validation with edge cases."""
        server = FeatureEngineeringMCPServer()
        
        # Test with infinite values
        df_with_inf = sample_dataframe.copy()
        df_with_inf['inf_feature'] = np.inf
        
        # Should detect infinite values
        assert np.isinf(df_with_inf['inf_feature']).any()
        
        # Test with extreme outliers
        df_with_outliers = sample_dataframe.copy()
        mean_val = df_with_outliers['numeric1'].mean()
        std_val = df_with_outliers['numeric1'].std()
        df_with_outliers.loc[0, 'numeric1'] = mean_val + 10 * std_val  # 10 standard deviations
        
        # Calculate z-scores
        z_scores = np.abs((df_with_outliers['numeric1'] - mean_val) / std_val)
        
        # Should detect extreme outliers
        assert (z_scores > 5).any()
    
    def test_missing_value_handling(self, sample_dataframe):
        """Test handling of missing values in feature engineering."""
        server = FeatureEngineeringMCPServer()
        
        # Introduce missing values
        df_with_na = sample_dataframe.copy()
        df_with_na.loc[0:10, 'numeric1'] = np.nan
        df_with_na.loc[5:15, 'numeric2'] = np.nan
        
        # Test interaction feature with missing values
        interaction = df_with_na['numeric1'] * df_with_na['numeric2']
        
        # Should have NaN where either input is NaN
        assert interaction.isna().sum() > 0
        
        # Test filling with median
        median_val = df_with_na['numeric1'].median()
        filled_values = df_with_na['numeric1'].fillna(median_val)
        
        # Should have no missing values after filling
        assert not filled_values.isna().any()
        assert filled_values.isna().sum() == 0


class TestFeatureEngineeringMCPServer:
    """Test the Feature Engineering MCP Server class."""
    
    @pytest.fixture
    def server(self):
        """Create a server instance for testing."""
        return FeatureEngineeringMCPServer()
    
    @pytest.fixture
    def user_context(self):
        """Create a user context for testing."""
        return UserContext(user_id="test_user_123", email="test@example.com")
    
    @pytest.fixture
    def temp_csv_file(self):
        """Create a temporary CSV file for testing."""
        df = pd.DataFrame({
            'numeric1': [1, 2, 3, 4, 5],
            'numeric2': [10, 20, 30, 40, 50],
            'category': ['A', 'B', 'A', 'B', 'A'],
            'target': [0, 1, 0, 1, 0]
        })
        
        with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
            df.to_csv(f.name, index=False)
            yield f.name
        
        # Cleanup
        os.unlink(f.name)
    
    def test_server_initialization(self, server):
        """Test server initialization."""
        assert server.server_name == "feature_engineering"
        assert server.port == 3004  # Default port from config
        assert hasattr(server, 'feature_engineering_dir')
    
    @pytest.mark.asyncio
    async def test_load_dataframe_csv(self, server, temp_csv_file):
        """Test loading CSV dataframe."""
        df = await server._load_dataframe(temp_csv_file)
        
        assert isinstance(df, pd.DataFrame)
        assert len(df) == 5
        assert 'numeric1' in df.columns
        assert 'numeric2' in df.columns
        assert 'category' in df.columns
        assert 'target' in df.columns
    
    @pytest.mark.asyncio
    async def test_load_dataframe_invalid_format(self, server):
        """Test loading dataframe with invalid format."""
        with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
            f.write("invalid content")
            temp_file = f.name
        
        try:
            with pytest.raises(ValueError, match="Unsupported file format"):
                await server._load_dataframe(temp_file)
        finally:
            os.unlink(temp_file)
    
    @pytest.mark.asyncio
    async def test_load_dataframe_empty_file(self, server):
        """Test loading empty dataframe."""
        with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
            # Write only headers, no data
            f.write("col1,col2\n")
            temp_file = f.name
        
        try:
            with pytest.raises(ValueError, match="Dataset is empty"):
                await server._load_dataframe(temp_file)
        finally:
            os.unlink(temp_file)
    
    def test_generate_complexity_recommendations(self, server):
        """Test complexity recommendation generation."""
        # Test high feature count
        metrics_high_features = {
            "total_features": 150,
            "complexity_score": 0.9,
            "dimensionality_reduction_applied": False,
            "original_features": 10,
            "engineered_features": 140
        }
        
        recommendations = server._generate_complexity_recommendations(metrics_high_features)
        
        assert len(recommendations) > 0
        assert any("dimensionality reduction" in rec.lower() for rec in recommendations)
        assert any("overfitting" in rec.lower() for rec in recommendations)
        
        # Test normal feature count
        metrics_normal = {
            "total_features": 20,
            "complexity_score": 0.3,
            "dimensionality_reduction_applied": False,
            "original_features": 15,
            "engineered_features": 5
        }
        
        recommendations_normal = server._generate_complexity_recommendations(metrics_normal)
        
        # Should have fewer or no recommendations
        assert len(recommendations_normal) <= len(recommendations)
    
    @pytest.mark.asyncio
    async def test_tool_registration(self, server):
        """Test that all required tools are registered."""
        await server.register_server_tools()
        
        expected_tools = [
            "generate_features",
            "apply_feature_engineering", 
            "explain_features",
            "validate_features",
            "get_complexity_metrics"
        ]
        
        registered_tools = list(server.tools.keys())
        
        for tool in expected_tools:
            assert tool in registered_tools
    
    def test_validate_required_params(self, server):
        """Test parameter validation."""
        # Test with valid parameters
        arguments = {"dataset_id": "123", "hypotheses": []}
        server.validate_required_params(arguments, ["dataset_id", "hypotheses"])
        
        # Test with missing parameters
        with pytest.raises(Exception, match="Missing required parameter"):
            server.validate_required_params(arguments, ["dataset_id", "missing_param"])
    
    def test_sanitize_input(self, server):
        """Test input sanitization."""
        # Test normal string
        clean_input = server.sanitize_input("normal text")
        assert clean_input == "normal text"
        
        # Test with potential SQL injection
        malicious_input = "'; DROP TABLE users; --"
        sanitized = server.sanitize_input(malicious_input)
        assert sanitized == malicious_input  # Should be returned as-is for logging


class TestFeatureEngineeringIntegration:
    """Integration tests for feature engineering workflows."""
    
    @pytest.fixture
    def mock_database(self):
        """Create a mock database for testing."""
        db = AsyncMock()
        
        # Mock dataset record
        db.get_dataset.return_value = {
            "id": "dataset-123",
            "name": "test_dataset.csv",
            "file_path": "/tmp/test_dataset.csv",
            "metadata": {}
        }
        
        # Mock hypotheses
        db.get_validated_hypotheses.return_value = [
            {
                "id": "hyp-1",
                "text": "Correlation between var1 and var2",
                "test_type": "correlation",
                "variables": ["numeric1", "numeric2"]
            }
        ]
        
        return db
    
    @pytest.mark.asyncio
    async def test_feature_engineering_workflow(self, mock_database):
        """Test complete feature engineering workflow."""
        server = FeatureEngineeringMCPServer()
        user_context = UserContext(user_id="test_user")
        
        # Mock the database
        with patch('shared.database.get_database', return_value=mock_database):
            # Mock file loading
            with patch.object(server, '_load_dataframe') as mock_load:
                mock_load.return_value = pd.DataFrame({
                    'numeric1': [1, 2, 3, 4, 5],
                    'numeric2': [10, 20, 30, 40, 50],
                    'category': ['A', 'B', 'A', 'B', 'A']
                })
                
                # Test feature generation
                hypotheses = [
                    {
                        "id": "hyp-1",
                        "text": "Correlation test",
                        "test_type": "correlation",
                        "variables": ["numeric1", "numeric2"]
                    }
                ]
                
                # Mock database operations
                mock_database.store_feature_engineering_plan.return_value = "plan-123"
                
                result = await server._generate_features(
                    user_context,
                    {
                        "dataset_id": "dataset-123",
                        "hypotheses": hypotheses,
                        "max_features": 10
                    }
                )
                
                assert "plan_id" in result
                assert "feature_set" in result
                assert "features_generated" in result
                assert result["features_generated"] > 0
    
    @pytest.mark.asyncio
    async def test_error_handling_missing_dataset(self, mock_database):
        """Test error handling for missing dataset."""
        server = FeatureEngineeringMCPServer()
        user_context = UserContext(user_id="test_user")
        
        # Mock database to return None (dataset not found)
        mock_database.get_dataset.return_value = None
        
        with patch('shared.database.get_database', return_value=mock_database):
            with pytest.raises(ValueError, match="Dataset not found"):
                await server._generate_features(
                    user_context,
                    {
                        "dataset_id": "nonexistent-dataset",
                        "hypotheses": []
                    }
                )
    
    @pytest.mark.asyncio
    async def test_feature_validation_workflow(self, mock_database):
        """Test feature validation workflow."""
        server = FeatureEngineeringMCPServer()
        user_context = UserContext(user_id="test_user")
        
        # Mock datasets
        original_df = pd.DataFrame({
            'numeric1': [1, 2, 3, 4, 5],
            'target': [0, 1, 0, 1, 0]
        })
        
        engineered_df = pd.DataFrame({
            'numeric1': [1, 2, 3, 4, 5],
            'target': [0, 1, 0, 1, 0],
            'engineered_feature': [10, 20, 30, 40, 50]
        })
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(server, '_load_dataframe') as mock_load:
                mock_load.side_effect = [original_df, engineered_df]
                
                # Mock engineered features info
                mock_database.get_engineered_features.return_value = [
                    {
                        "feature_name": "engineered_feature",
                        "feature_type": "interaction",
                        "source_columns": ["numeric1"],
                        "formula": "numeric1 * 10"
                    }
                ]
                
                mock_database.store_feature_validation.return_value = "validation-123"
                
                result = await server._validate_features(
                    user_context,
                    {
                        "original_dataset_id": "original-123",
                        "engineered_dataset_id": "engineered-123",
                        "target_column": "target"
                    }
                )
                
                assert "has_data_leakage" in result
                assert "leakage_warnings" in result
                assert "validation_errors" in result
                assert "validation_passed" in result


if __name__ == "__main__":
    pytest.main([__file__])