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

Unit tests for the Preprocessing MCP Server core functionality.

Tests preprocessing logic without database dependencies.

"""

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

from shared.models import UserContext, PreprocessingPlan, FeatureMapping


class MockPreprocessingServer:
    """Mock preprocessing server for testing core functionality."""
    
    def __init__(self):
        self.preprocessed_dir = "/tmp/preprocessed"
    
    def validate_required_params(self, arguments, required):
        """Validate that required parameters are present."""
        missing = [param for param in required if param not in arguments]
        if missing:
            raise ValueError(f"Missing required parameters: {missing}")
    
    def sanitize_input(self, value, param_type="string"):
        """Sanitize input parameters."""
        if value is None:
            return None
        
        if param_type == "string":
            return str(value).strip()
        elif param_type == "integer":
            return int(value)
        elif param_type == "float":
            return float(value)
        elif param_type == "boolean":
            return bool(value)
        else:
            return value
    
    async def _load_dataframe(self, file_path):
        """Load dataframe from file path."""
        from pathlib import Path
        file_ext = Path(file_path).suffix.lower()
        
        try:
            if file_ext == '.csv':
                df = pd.read_csv(file_path)
            elif file_ext == '.xlsx':
                df = pd.read_excel(file_path, engine='openpyxl')
            elif file_ext == '.xls':
                df = pd.read_excel(file_path, engine='xlrd')
            elif file_ext == '.json':
                df = pd.read_json(file_path)
            elif file_ext == '.parquet':
                df = pd.read_parquet(file_path)
            else:
                raise ValueError(f"Unsupported file format: {file_ext}")
            
            if df.empty:
                raise ValueError("Dataset is empty")
            
            return df
            
        except Exception as e:
            raise ValueError(f"Failed to load dataset: {str(e)}")
    
    def _analyze_dataset_characteristics(self, df, target_column=None):
        """Analyze dataset characteristics for preprocessing plan."""
        numeric_columns = df.select_dtypes(include=[np.number]).columns.tolist()
        categorical_columns = df.select_dtypes(include=['object', 'category']).columns.tolist()
        
        # Remove target column from features if specified
        if target_column:
            if target_column in numeric_columns:
                numeric_columns.remove(target_column)
            if target_column in categorical_columns:
                categorical_columns.remove(target_column)
        
        return numeric_columns, categorical_columns
    
    def _create_scaling_operations(self, df, numeric_columns):
        """Create scaling operations based on data characteristics."""
        scaling_operations = []
        
        for col in numeric_columns:
            col_data = df[col].dropna()
            
            if len(col_data) == 0:
                continue
            
            # Check for outliers
            Q1 = col_data.quantile(0.25)
            Q3 = col_data.quantile(0.75)
            IQR = Q3 - Q1
            outlier_ratio = ((col_data < (Q1 - 1.5 * IQR)) | (col_data > (Q3 + 1.5 * IQR))).sum() / len(col_data)
            
            # Choose scaler based on data characteristics
            if outlier_ratio > 0.1:  # High outlier ratio
                scaler_type = "robust"
            elif col_data.min() >= 0 and col_data.max() <= 1:  # Already normalized
                scaler_type = "none"
            elif (col_data >= 0).all():  # All positive values
                scaler_type = "minmax"
            else:  # General case
                scaler_type = "standard"
            
            if scaler_type != "none":
                scaling_operations.append({
                    "column": col,
                    "scaler_type": scaler_type,
                    "parameters": {}
                })
        
        return scaling_operations
    
    def _create_encoding_operations(self, df, categorical_columns, target_column=None, task_type=None):
        """Create encoding operations based on categorical data characteristics."""
        encoding_operations = []
        
        for col in categorical_columns:
            unique_count = df[col].nunique()
            
            # Choose encoding strategy based on cardinality and task type
            if unique_count <= 2:
                # Binary categorical - use label encoding
                encoding_operations.append({
                    "column": col,
                    "encoding_type": "label",
                    "parameters": {}
                })
            elif unique_count <= 10:
                # Low cardinality - use one-hot encoding
                encoding_operations.append({
                    "column": col,
                    "encoding_type": "onehot",
                    "parameters": {"drop_first": True}
                })
            elif target_column and task_type:
                # High cardinality with target - use target encoding
                encoding_operations.append({
                    "column": col,
                    "encoding_type": "target",
                    "parameters": {"target_column": target_column}
                })
            else:
                # High cardinality without target - use label encoding
                encoding_operations.append({
                    "column": col,
                    "encoding_type": "label",
                    "parameters": {}
                })
        
        return encoding_operations
    
    def _create_feature_selection_operations(self, numeric_columns, categorical_columns, target_column=None):
        """Create feature selection operations for high-dimensional data."""
        feature_selection = []
        total_features = len(numeric_columns + categorical_columns)
        
        if target_column and total_features > 50:
            # Apply feature selection for high-dimensional data
            max_features = min(20, total_features // 2)
            feature_selection.append({
                "method": "selectkbest",
                "k": max_features,
                "score_func": "f_classif"  # Default, can be overridden
            })
        
        return feature_selection


@pytest.fixture
def user_context():
    """Create a test user context."""
    return UserContext(
        user_id="test_user_123",
        email="test@example.com",
        permissions=["read", "write"]
    )


@pytest.fixture
def preprocessing_server():
    """Create a mock preprocessing server instance."""
    return MockPreprocessingServer()


@pytest.fixture
def sample_dataset():
    """Create a sample dataset for testing."""
    np.random.seed(42)
    data = {
        'numeric_col1': np.random.normal(0, 1, 100),
        'numeric_col2': np.random.uniform(0, 100, 100),
        'categorical_col1': np.random.choice(['A', 'B', 'C'], 100),
        'categorical_col2': np.random.choice(['X', 'Y'], 100),
        'high_cardinality_col': [f'cat_{i%25}' for i in range(100)],
        'target': np.random.choice([0, 1], 100)
    }
    return pd.DataFrame(data)


@pytest.fixture
def sample_dataset_file(sample_dataset):
    """Create a temporary CSV file with sample dataset."""
    with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
        sample_dataset.to_csv(f.name, index=False)
        yield f.name
    os.unlink(f.name)


class TestDatasetCharacteristics:
    """Test dataset characteristic analysis."""
    
    def test_analyze_dataset_characteristics_basic(self, preprocessing_server, sample_dataset):
        """Test basic dataset characteristic analysis."""
        numeric_cols, categorical_cols = preprocessing_server._analyze_dataset_characteristics(
            sample_dataset, target_column='target'
        )
        
        # Should identify numeric columns (excluding target)
        expected_numeric = ['numeric_col1', 'numeric_col2']
        assert set(numeric_cols) == set(expected_numeric)
        
        # Should identify categorical columns
        expected_categorical = ['categorical_col1', 'categorical_col2', 'high_cardinality_col']
        assert set(categorical_cols) == set(expected_categorical)
    
    def test_analyze_dataset_characteristics_no_target(self, preprocessing_server, sample_dataset):
        """Test dataset analysis without target column."""
        numeric_cols, categorical_cols = preprocessing_server._analyze_dataset_characteristics(
            sample_dataset
        )
        
        # Should include target in numeric columns when no target specified
        expected_numeric = ['numeric_col1', 'numeric_col2', 'target']
        assert set(numeric_cols) == set(expected_numeric)


class TestScalingOperations:
    """Test scaling operation creation."""
    
    def test_create_scaling_operations_normal_data(self, preprocessing_server):
        """Test scaling operations for normal distributed data."""
        # Create normal distributed data
        df = pd.DataFrame({
            'normal_col': np.random.normal(0, 1, 100),
            'target': np.random.choice([0, 1], 100)
        })
        
        scaling_ops = preprocessing_server._create_scaling_operations(df, ['normal_col'])
        
        assert len(scaling_ops) == 1
        assert scaling_ops[0]['column'] == 'normal_col'
        assert scaling_ops[0]['scaler_type'] == 'standard'
    
    def test_create_scaling_operations_with_outliers(self, preprocessing_server):
        """Test scaling operations for data with outliers."""
        # Create data with outliers
        data = np.random.normal(0, 1, 100)
        data[:15] = 100  # Add 15% outliers
        
        df = pd.DataFrame({
            'outlier_col': data,
            'target': np.random.choice([0, 1], 100)
        })
        
        scaling_ops = preprocessing_server._create_scaling_operations(df, ['outlier_col'])
        
        assert len(scaling_ops) == 1
        assert scaling_ops[0]['column'] == 'outlier_col'
        assert scaling_ops[0]['scaler_type'] == 'robust'
    
    def test_create_scaling_operations_positive_data(self, preprocessing_server):
        """Test scaling operations for positive data."""
        # Create positive data
        df = pd.DataFrame({
            'positive_col': np.random.uniform(10, 100, 100),
            'target': np.random.choice([0, 1], 100)
        })
        
        scaling_ops = preprocessing_server._create_scaling_operations(df, ['positive_col'])
        
        assert len(scaling_ops) == 1
        assert scaling_ops[0]['column'] == 'positive_col'
        assert scaling_ops[0]['scaler_type'] == 'minmax'
    
    def test_create_scaling_operations_normalized_data(self, preprocessing_server):
        """Test scaling operations for already normalized data."""
        # Create normalized data (0-1 range)
        df = pd.DataFrame({
            'normalized_col': np.random.uniform(0, 1, 100),
            'target': np.random.choice([0, 1], 100)
        })
        
        scaling_ops = preprocessing_server._create_scaling_operations(df, ['normalized_col'])
        
        # Should not create scaling operation for already normalized data
        assert len(scaling_ops) == 0


class TestEncodingOperations:
    """Test encoding operation creation."""
    
    def test_create_encoding_operations_binary(self, preprocessing_server):
        """Test encoding operations for binary categorical data."""
        df = pd.DataFrame({
            'binary_col': ['Yes', 'No', 'Yes', 'No', 'Yes'],
            'target': [0, 1, 0, 1, 0]
        })
        
        encoding_ops = preprocessing_server._create_encoding_operations(
            df, ['binary_col'], target_column='target', task_type='classification'
        )
        
        assert len(encoding_ops) == 1
        assert encoding_ops[0]['column'] == 'binary_col'
        assert encoding_ops[0]['encoding_type'] == 'label'
    
    def test_create_encoding_operations_low_cardinality(self, preprocessing_server):
        """Test encoding operations for low cardinality categorical data."""
        df = pd.DataFrame({
            'low_cardinality_col': ['A', 'B', 'C', 'A', 'B'],
            'target': [0, 1, 0, 1, 0]
        })
        
        encoding_ops = preprocessing_server._create_encoding_operations(
            df, ['low_cardinality_col'], target_column='target', task_type='classification'
        )
        
        assert len(encoding_ops) == 1
        assert encoding_ops[0]['column'] == 'low_cardinality_col'
        assert encoding_ops[0]['encoding_type'] == 'onehot'
        assert encoding_ops[0]['parameters']['drop_first'] is True
    
    def test_create_encoding_operations_high_cardinality_with_target(self, preprocessing_server):
        """Test encoding operations for high cardinality categorical data with target."""
        # Create high cardinality data (>10 unique values)
        df = pd.DataFrame({
            'high_cardinality_col': [f'cat_{i}' for i in range(50)],
            'target': np.random.choice([0, 1], 50)
        })
        
        encoding_ops = preprocessing_server._create_encoding_operations(
            df, ['high_cardinality_col'], target_column='target', task_type='classification'
        )
        
        assert len(encoding_ops) == 1
        assert encoding_ops[0]['column'] == 'high_cardinality_col'
        assert encoding_ops[0]['encoding_type'] == 'target'
        assert encoding_ops[0]['parameters']['target_column'] == 'target'
    
    def test_create_encoding_operations_high_cardinality_no_target(self, preprocessing_server):
        """Test encoding operations for high cardinality categorical data without target."""
        # Create high cardinality data (>10 unique values)
        df = pd.DataFrame({
            'high_cardinality_col': [f'cat_{i}' for i in range(50)]
        })
        
        encoding_ops = preprocessing_server._create_encoding_operations(
            df, ['high_cardinality_col'], target_column=None, task_type=None
        )
        
        assert len(encoding_ops) == 1
        assert encoding_ops[0]['column'] == 'high_cardinality_col'
        assert encoding_ops[0]['encoding_type'] == 'label'


class TestFeatureSelection:
    """Test feature selection operation creation."""
    
    def test_create_feature_selection_high_dimensional(self, preprocessing_server):
        """Test feature selection for high-dimensional data."""
        # Create lists representing many features
        numeric_columns = [f'numeric_{i}' for i in range(40)]
        categorical_columns = [f'categorical_{i}' for i in range(20)]
        
        feature_selection = preprocessing_server._create_feature_selection_operations(
            numeric_columns, categorical_columns, target_column='target'
        )
        
        assert len(feature_selection) == 1
        assert feature_selection[0]['method'] == 'selectkbest'
        assert feature_selection[0]['k'] <= 20
        assert feature_selection[0]['k'] <= len(numeric_columns + categorical_columns) // 2
    
    def test_create_feature_selection_low_dimensional(self, preprocessing_server):
        """Test no feature selection for low-dimensional data."""
        # Create lists representing few features
        numeric_columns = ['numeric_1', 'numeric_2']
        categorical_columns = ['categorical_1']
        
        feature_selection = preprocessing_server._create_feature_selection_operations(
            numeric_columns, categorical_columns, target_column='target'
        )
        
        # Should not apply feature selection for low-dimensional data
        assert len(feature_selection) == 0
    
    def test_create_feature_selection_no_target(self, preprocessing_server):
        """Test no feature selection without target column."""
        # Create lists representing many features
        numeric_columns = [f'numeric_{i}' for i in range(40)]
        categorical_columns = [f'categorical_{i}' for i in range(20)]
        
        feature_selection = preprocessing_server._create_feature_selection_operations(
            numeric_columns, categorical_columns, target_column=None
        )
        
        # Should not apply feature selection without target
        assert len(feature_selection) == 0


class TestParameterValidation:
    """Test parameter validation functionality."""
    
    def test_validate_required_parameters_success(self, preprocessing_server):
        """Test successful parameter validation."""
        arguments = {
            'dataset_id': 'test_123',
            'hypotheses': ['hyp_1', 'hyp_2'],
            'target_column': 'target'
        }
        
        required = ['dataset_id', 'hypotheses']
        
        # Should not raise exception
        preprocessing_server.validate_required_params(arguments, required)
    
    def test_validate_required_parameters_missing(self, preprocessing_server):
        """Test parameter validation with missing parameters."""
        arguments = {
            'dataset_id': 'test_123'
            # Missing 'hypotheses'
        }
        
        required = ['dataset_id', 'hypotheses']
        
        with pytest.raises(ValueError, match="Missing required parameters"):
            preprocessing_server.validate_required_params(arguments, required)
    
    def test_sanitize_input_string(self, preprocessing_server):
        """Test input sanitization for strings."""
        # Test with whitespace
        result = preprocessing_server.sanitize_input("  test_value  ", "string")
        assert result == "test_value"
        
        # Test with None
        result = preprocessing_server.sanitize_input(None, "string")
        assert result is None
    
    def test_sanitize_input_numeric(self, preprocessing_server):
        """Test input sanitization for numeric values."""
        # Test integer
        result = preprocessing_server.sanitize_input("123", "integer")
        assert result == 123
        
        # Test float
        result = preprocessing_server.sanitize_input("123.45", "float")
        assert result == 123.45
        
        # Test boolean
        result = preprocessing_server.sanitize_input("true", "boolean")
        assert result is True


class TestFileLoading:
    """Test file loading functionality."""
    
    @pytest.mark.asyncio
    async def test_load_dataframe_csv(self, preprocessing_server, sample_dataset_file):
        """Test loading CSV files."""
        df = await preprocessing_server._load_dataframe(sample_dataset_file)
        
        assert isinstance(df, pd.DataFrame)
        assert not df.empty
        assert len(df.columns) == 6  # Expected number of columns
    
    @pytest.mark.asyncio
    async def test_load_dataframe_unsupported_format(self, preprocessing_server):
        """Test error handling for unsupported file formats."""
        with pytest.raises(ValueError, match="Unsupported file format"):
            await preprocessing_server._load_dataframe("/path/to/file.xyz")
    
    @pytest.mark.asyncio
    async def test_load_dataframe_nonexistent_file(self, preprocessing_server):
        """Test error handling for nonexistent files."""
        with pytest.raises(ValueError, match="Failed to load dataset"):
            await preprocessing_server._load_dataframe("/path/to/nonexistent.csv")


class TestPreprocessingPlanIntegration:
    """Test integration of preprocessing plan components."""
    
    def test_complete_preprocessing_plan_creation(self, preprocessing_server, sample_dataset):
        """Test complete preprocessing plan creation workflow."""
        # Analyze dataset characteristics
        numeric_cols, categorical_cols = preprocessing_server._analyze_dataset_characteristics(
            sample_dataset, target_column='target'
        )
        
        # Create scaling operations
        scaling_ops = preprocessing_server._create_scaling_operations(sample_dataset, numeric_cols)
        
        # Create encoding operations
        encoding_ops = preprocessing_server._create_encoding_operations(
            sample_dataset, categorical_cols, target_column='target', task_type='classification'
        )
        
        # Create feature selection operations
        feature_selection = preprocessing_server._create_feature_selection_operations(
            numeric_cols, categorical_cols, target_column='target'
        )
        
        # Verify all components are created
        assert len(scaling_ops) > 0  # Should have scaling operations for numeric columns
        assert len(encoding_ops) > 0  # Should have encoding operations for categorical columns
        assert len(feature_selection) == 0  # Should not have feature selection for this dataset size
        
        # Verify scaling operations
        scaled_columns = [op['column'] for op in scaling_ops]
        for col in numeric_cols:
            assert col in scaled_columns
        
        # Verify encoding operations
        encoded_columns = [op['column'] for op in encoding_ops]
        for col in categorical_cols:
            assert col in encoded_columns
        
        # Verify encoding types are appropriate
        for op in encoding_ops:
            if sample_dataset[op['column']].nunique() <= 2:
                assert op['encoding_type'] == 'label'
            elif sample_dataset[op['column']].nunique() <= 10:
                assert op['encoding_type'] == 'onehot'
            else:
                assert op['encoding_type'] == 'target'


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