File size: 27,759 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
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
"""

Unit tests for the Preprocessing MCP Server.

Tests preprocessing plan creation, application, feature mappings, and validation.

"""

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

# Mock the database module before importing the server
with patch.dict('sys.modules', {'shared.database': MagicMock()}):
    from mcp_servers.preprocessing.server import PreprocessingMCPServer
    from shared.models import UserContext, PreprocessingPlan, FeatureMapping
    from shared.database import DatabaseError, UserIsolationError


@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 preprocessing MCP server instance."""
    return PreprocessingMCPServer()


@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)


@pytest.fixture
def mock_database():
    """Create a mock database manager."""
    db_mock = AsyncMock()
    
    # Mock dataset record
    db_mock.get_dataset.return_value = {
        'id': 'test_dataset_123',
        'name': 'test_dataset.csv',
        'file_path': '/path/to/dataset.csv',
        'metadata': {
            'rows': 100,
            'columns': 6,
            'column_names': ['numeric_col1', 'numeric_col2', 'categorical_col1', 'categorical_col2', 'high_cardinality_col', 'target']
        }
    }
    
    # Mock hypothesis records
    db_mock.get_hypothesis.return_value = {
        'id': 'hyp_123',
        'text': 'Test hypothesis',
        'test_type': 'correlation',
        'variables': ['numeric_col1', 'target'],
        'is_significant': True
    }
    
    # Mock storage operations
    db_mock.store_preprocessing_plan.return_value = 'plan_123'
    db_mock.create_dataset.return_value = 'preprocessed_dataset_123'
    db_mock.store_feature_mappings.return_value = ['mapping_1', 'mapping_2']
    
    return db_mock


class TestPreprocessingPlanCreation:
    """Test preprocessing plan creation functionality."""
    
    @pytest.mark.asyncio
    async def test_create_preprocessing_plan_basic(self, preprocessing_server, user_context, mock_database, sample_dataset_file):
        """Test basic preprocessing plan creation."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                # Setup mock
                sample_df = pd.DataFrame({
                    'numeric_col1': [1, 2, 3, 4, 5],
                    'categorical_col1': ['A', 'B', 'A', 'C', 'B'],
                    'target': [0, 1, 0, 1, 0]
                })
                mock_load.return_value = sample_df
                
                # Test arguments
                arguments = {
                    'dataset_id': 'test_dataset_123',
                    'hypotheses': ['hyp_123'],
                    'target_column': 'target',
                    'task_type': 'classification'
                }
                
                # Call the method
                result = await preprocessing_server._create_preprocessing_plan(user_context, arguments)
                
                # Assertions
                assert 'plan_id' in result
                assert 'plan' in result
                assert 'summary' in result
                
                plan = result['plan']
                assert 'scaling_operations' in plan
                assert 'encoding_operations' in plan
                assert 'feature_selection' in plan
                assert plan['target_column'] == 'target'
                
                # Check that numeric column gets scaling
                scaling_ops = plan['scaling_operations']
                assert len(scaling_ops) == 1
                assert scaling_ops[0]['column'] == 'numeric_col1'
                
                # Check that categorical column gets encoding
                encoding_ops = plan['encoding_operations']
                assert len(encoding_ops) == 1
                assert encoding_ops[0]['column'] == 'categorical_col1'
    
    @pytest.mark.asyncio
    async def test_create_preprocessing_plan_outliers(self, preprocessing_server, user_context, mock_database):
        """Test preprocessing plan creation with outliers."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                # Create data with outliers
                data = np.random.normal(0, 1, 100)
                data[0] = 100  # Add outlier
                sample_df = pd.DataFrame({
                    'numeric_col_with_outliers': data,
                    'target': np.random.choice([0, 1], 100)
                })
                mock_load.return_value = sample_df
                
                arguments = {
                    'dataset_id': 'test_dataset_123',
                    'hypotheses': ['hyp_123'],
                    'target_column': 'target',
                    'task_type': 'classification'
                }
                
                result = await preprocessing_server._create_preprocessing_plan(user_context, arguments)
                
                # Should use robust scaling for data with outliers
                plan = result['plan']
                scaling_ops = plan['scaling_operations']
                assert len(scaling_ops) == 1
                assert scaling_ops[0]['scaler_type'] == 'robust'
    
    @pytest.mark.asyncio
    async def test_create_preprocessing_plan_high_cardinality(self, preprocessing_server, user_context, mock_database):
        """Test preprocessing plan creation with high cardinality categorical data."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                # Create high cardinality categorical data
                sample_df = pd.DataFrame({
                    'high_cardinality_col': [f'cat_{i}' for i in range(50)],  # 50 unique categories
                    'target': np.random.choice([0, 1], 50)
                })
                mock_load.return_value = sample_df
                
                arguments = {
                    'dataset_id': 'test_dataset_123',
                    'hypotheses': ['hyp_123'],
                    'target_column': 'target',
                    'task_type': 'classification'
                }
                
                result = await preprocessing_server._create_preprocessing_plan(user_context, arguments)
                
                # Should use target encoding for high cardinality with target
                plan = result['plan']
                encoding_ops = plan['encoding_operations']
                assert len(encoding_ops) == 1
                assert encoding_ops[0]['encoding_type'] == 'target'
    
    @pytest.mark.asyncio
    async def test_create_preprocessing_plan_feature_selection(self, preprocessing_server, user_context, mock_database):
        """Test preprocessing plan creation with feature selection."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                # Create high-dimensional data
                data = {}
                for i in range(60):  # More than 50 features
                    data[f'feature_{i}'] = np.random.normal(0, 1, 100)
                data['target'] = np.random.choice([0, 1], 100)
                
                sample_df = pd.DataFrame(data)
                mock_load.return_value = sample_df
                
                arguments = {
                    'dataset_id': 'test_dataset_123',
                    'hypotheses': ['hyp_123'],
                    'target_column': 'target',
                    'task_type': 'classification'
                }
                
                result = await preprocessing_server._create_preprocessing_plan(user_context, arguments)
                
                # Should include feature selection for high-dimensional data
                plan = result['plan']
                feature_selection = plan['feature_selection']
                assert len(feature_selection) == 1
                assert feature_selection[0]['method'] == 'selectkbest'
                assert feature_selection[0]['k'] <= 20  # Should limit features


class TestPreprocessingApplication:
    """Test preprocessing application functionality."""
    
    @pytest.mark.asyncio
    async def test_apply_preprocessing_scaling(self, preprocessing_server, user_context, mock_database, sample_dataset_file):
        """Test applying scaling operations."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                sample_df = pd.DataFrame({
                    'numeric_col1': [1, 2, 3, 4, 5],
                    'numeric_col2': [10, 20, 30, 40, 50],
                    'target': [0, 1, 0, 1, 0]
                })
                mock_load.return_value = sample_df
                
                # Create preprocessing plan
                plan = PreprocessingPlan(
                    scaling_operations=[
                        {'column': 'numeric_col1', 'scaler_type': 'standard', 'parameters': {}},
                        {'column': 'numeric_col2', 'scaler_type': 'minmax', 'parameters': {}}
                    ],
                    encoding_operations=[],
                    feature_selection=[],
                    target_column='target'
                )
                
                arguments = {
                    'dataset_id': 'test_dataset_123',
                    'plan': plan.model_dump()
                }
                
                with patch('pandas.DataFrame.to_csv'):  # Mock file saving
                    result = await preprocessing_server._apply_preprocessing(user_context, arguments)
                
                # Assertions
                assert 'preprocessed_dataset_id' in result
                assert 'feature_mappings_count' in result
                assert result['transformations_applied']['scaling_operations'] == 2
    
    @pytest.mark.asyncio
    async def test_apply_preprocessing_encoding(self, preprocessing_server, user_context, mock_database):
        """Test applying encoding operations."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                sample_df = pd.DataFrame({
                    'categorical_col1': ['A', 'B', 'A', 'C', 'B'],
                    'categorical_col2': ['X', 'Y', 'X', 'X', 'Y'],
                    'target': [0, 1, 0, 1, 0]
                })
                mock_load.return_value = sample_df
                
                # Create preprocessing plan with different encoding types
                plan = PreprocessingPlan(
                    scaling_operations=[],
                    encoding_operations=[
                        {'column': 'categorical_col1', 'encoding_type': 'onehot', 'parameters': {'drop_first': True}},
                        {'column': 'categorical_col2', 'encoding_type': 'label', 'parameters': {}}
                    ],
                    feature_selection=[],
                    target_column='target'
                )
                
                arguments = {
                    'dataset_id': 'test_dataset_123',
                    'plan': plan.model_dump()
                }
                
                with patch('pandas.DataFrame.to_csv'):  # Mock file saving
                    with patch('builtins.open', create=True):  # Mock pickle saving
                        result = await preprocessing_server._apply_preprocessing(user_context, arguments)
                
                # Assertions
                assert 'preprocessed_dataset_id' in result
                assert result['transformations_applied']['encoding_operations'] == 2
    
    @pytest.mark.asyncio
    async def test_apply_preprocessing_feature_selection(self, preprocessing_server, user_context, mock_database):
        """Test applying feature selection."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                # Create data with multiple features
                data = {}
                for i in range(10):
                    data[f'feature_{i}'] = np.random.normal(0, 1, 50)
                data['target'] = np.random.choice([0, 1], 50)
                
                sample_df = pd.DataFrame(data)
                mock_load.return_value = sample_df
                
                # Create preprocessing plan with feature selection
                plan = PreprocessingPlan(
                    scaling_operations=[],
                    encoding_operations=[],
                    feature_selection=[
                        {'method': 'selectkbest', 'k': 5, 'score_func': 'f_classif'}
                    ],
                    target_column='target'
                )
                
                arguments = {
                    'dataset_id': 'test_dataset_123',
                    'plan': plan.model_dump()
                }
                
                with patch('pandas.DataFrame.to_csv'):  # Mock file saving
                    with patch('builtins.open', create=True):  # Mock pickle saving
                        result = await preprocessing_server._apply_preprocessing(user_context, arguments)
                
                # Assertions
                assert 'preprocessed_dataset_id' in result
                assert result['transformations_applied']['feature_selection'] == 1


class TestFeatureMappings:
    """Test feature mapping functionality."""
    
    @pytest.mark.asyncio
    async def test_get_feature_mappings(self, preprocessing_server, user_context, mock_database):
        """Test getting feature mappings for a preprocessed dataset."""
        
        # Mock dataset with preprocessing metadata
        mock_database.get_dataset.return_value = {
            'id': 'preprocessed_dataset_123',
            'name': 'preprocessed_dataset.csv',
            'file_path': '/path/to/preprocessed.csv',
            'metadata': {
                'preprocessing_applied': True,
                'feature_mappings': [
                    {
                        'original_name': 'numeric_col1',
                        'transformed_name': 'numeric_col1',
                        'transformation_type': 'standard_scaling',
                        'parameters': {}
                    }
                ],
                'original_columns': ['numeric_col1', 'categorical_col1', 'target'],
                'column_names': ['numeric_col1', 'categorical_col1_A', 'categorical_col1_B', 'target'],
                'preprocessing_plan': {}
            }
        }
        
        with patch('shared.database.get_database', return_value=mock_database):
            arguments = {
                'preprocessed_dataset_id': 'preprocessed_dataset_123'
            }
            
            result = await preprocessing_server._get_feature_mappings(user_context, arguments)
            
            # Assertions
            assert 'preprocessed_dataset_id' in result
            assert 'feature_mappings' in result
            assert 'original_columns' in result
            assert 'final_columns' in result
            assert len(result['feature_mappings']) == 1
    
    @pytest.mark.asyncio
    async def test_get_feature_mappings_not_preprocessed(self, preprocessing_server, user_context, mock_database):
        """Test error when getting mappings for non-preprocessed dataset."""
        
        # Mock dataset without preprocessing
        mock_database.get_dataset.return_value = {
            'id': 'original_dataset_123',
            'name': 'original_dataset.csv',
            'file_path': '/path/to/original.csv',
            'metadata': {
                'preprocessing_applied': False
            }
        }
        
        with patch('shared.database.get_database', return_value=mock_database):
            arguments = {
                'preprocessed_dataset_id': 'original_dataset_123'
            }
            
            with pytest.raises(ValueError, match="is not a preprocessed dataset"):
                await preprocessing_server._get_feature_mappings(user_context, arguments)


class TestPreprocessingValidation:
    """Test preprocessing validation functionality."""
    
    @pytest.mark.asyncio
    async def test_validate_preprocessing_success(self, preprocessing_server, user_context, mock_database):
        """Test successful preprocessing validation."""
        
        # Mock original dataset
        original_df = pd.DataFrame({
            'numeric_col1': [1, 2, 3, 4, 5],
            'categorical_col1': ['A', 'B', 'A', 'C', 'B'],
            'target': [0, 1, 0, 1, 0]
        })
        
        # Mock preprocessed dataset
        preprocessed_df = pd.DataFrame({
            'numeric_col1': [-1.5, -0.5, 0.0, 0.5, 1.5],  # Scaled values
            'categorical_col1_A': [1, 0, 1, 0, 0],  # One-hot encoded
            'categorical_col1_B': [0, 1, 0, 0, 1],
            'target': [0, 1, 0, 1, 0]
        })
        
        def mock_get_dataset(user_context, dataset_id):
            if dataset_id == 'original_123':
                return {
                    'id': 'original_123',
                    'file_path': '/path/to/original.csv',
                    'metadata': {}
                }
            else:
                return {
                    'id': 'preprocessed_123',
                    'file_path': '/path/to/preprocessed.csv',
                    'metadata': {
                        'preprocessing_plan': {
                            'scaling_operations': [{'column': 'numeric_col1', 'scaler_type': 'standard'}],
                            'encoding_operations': [{'column': 'categorical_col1', 'encoding_type': 'onehot'}],
                            'target_column': 'target'
                        }
                    }
                }
        
        mock_database.get_dataset.side_effect = mock_get_dataset
        
        def mock_load_dataframe(file_path):
            if 'original' in file_path:
                return original_df
            else:
                return preprocessed_df
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe', side_effect=mock_load_dataframe):
                arguments = {
                    'original_dataset_id': 'original_123',
                    'preprocessed_dataset_id': 'preprocessed_123'
                }
                
                result = await preprocessing_server._validate_preprocessing(user_context, arguments)
                
                # Assertions
                assert 'is_valid' in result
                assert 'warnings' in result
                assert 'errors' in result
                assert 'statistics' in result
                assert result['is_valid'] is True
    
    @pytest.mark.asyncio
    async def test_validate_preprocessing_target_leakage(self, preprocessing_server, user_context, mock_database):
        """Test validation detects target column leakage."""
        
        original_df = pd.DataFrame({
            'feature1': [1, 2, 3, 4, 5],
            'target': [0, 1, 0, 1, 0]
        })
        
        preprocessed_df = pd.DataFrame({
            'feature1': [-1.5, -0.5, 0.0, 0.5, 1.5],
            'target': [-1.0, 1.0, -1.0, 1.0, -1.0]  # Target was scaled - leakage!
        })
        
        def mock_get_dataset(user_context, dataset_id):
            if dataset_id == 'original_123':
                return {
                    'id': 'original_123',
                    'file_path': '/path/to/original.csv',
                    'metadata': {}
                }
            else:
                return {
                    'id': 'preprocessed_123',
                    'file_path': '/path/to/preprocessed.csv',
                    'metadata': {
                        'preprocessing_plan': {
                            'scaling_operations': [
                                {'column': 'feature1', 'scaler_type': 'standard'},
                                {'column': 'target', 'scaler_type': 'standard'}  # This is leakage!
                            ],
                            'encoding_operations': [],
                            'target_column': 'target'
                        }
                    }
                }
        
        mock_database.get_dataset.side_effect = mock_get_dataset
        
        def mock_load_dataframe(file_path):
            if 'original' in file_path:
                return original_df
            else:
                return preprocessed_df
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe', side_effect=mock_load_dataframe):
                arguments = {
                    'original_dataset_id': 'original_123',
                    'preprocessed_dataset_id': 'preprocessed_123'
                }
                
                result = await preprocessing_server._validate_preprocessing(user_context, arguments)
                
                # Should detect target column scaling as error
                assert result['is_valid'] is False
                assert len(result['errors']) > 0
                assert any('target column' in error.lower() for error in result['errors'])


class TestErrorHandling:
    """Test error handling in preprocessing operations."""
    
    @pytest.mark.asyncio
    async def test_missing_dataset_error(self, preprocessing_server, user_context, mock_database):
        """Test error handling for missing dataset."""
        
        mock_database.get_dataset.return_value = None
        
        with patch('shared.database.get_database', return_value=mock_database):
            arguments = {
                'dataset_id': 'nonexistent_dataset',
                'hypotheses': ['hyp_123']
            }
            
            with pytest.raises(ValueError, match="Dataset not found"):
                await preprocessing_server._create_preprocessing_plan(user_context, arguments)
    
    @pytest.mark.asyncio
    async def test_database_error_handling(self, preprocessing_server, user_context):
        """Test database error handling."""
        
        mock_database = AsyncMock()
        mock_database.get_dataset.side_effect = DatabaseError("Database connection failed")
        
        with patch('shared.database.get_database', return_value=mock_database):
            arguments = {
                'dataset_id': 'test_dataset_123',
                'hypotheses': ['hyp_123']
            }
            
            with pytest.raises(DatabaseError):
                await preprocessing_server._create_preprocessing_plan(user_context, arguments)
    
    @pytest.mark.asyncio
    async def test_invalid_file_format_error(self, preprocessing_server, user_context, mock_database):
        """Test error handling for invalid file formats."""
        
        mock_database.get_dataset.return_value = {
            'id': 'test_dataset_123',
            'file_path': '/path/to/invalid.xyz',  # Unsupported format
            'metadata': {}
        }
        
        with patch('shared.database.get_database', return_value=mock_database):
            arguments = {
                'dataset_id': 'test_dataset_123',
                'hypotheses': ['hyp_123']
            }
            
            with pytest.raises(ValueError, match="Unsupported file format"):
                await preprocessing_server._create_preprocessing_plan(user_context, arguments)


class TestParameterValidation:
    """Test parameter validation."""
    
    @pytest.mark.asyncio
    async def test_missing_required_parameters(self, preprocessing_server, user_context):
        """Test validation of required parameters."""
        
        # Missing dataset_id
        arguments = {
            'hypotheses': ['hyp_123']
        }
        
        with pytest.raises(Exception):  # Should raise validation error
            await preprocessing_server._create_preprocessing_plan(user_context, arguments)
        
        # Missing hypotheses
        arguments = {
            'dataset_id': 'test_dataset_123'
        }
        
        with pytest.raises(Exception):  # Should raise validation error
            await preprocessing_server._create_preprocessing_plan(user_context, arguments)
    
    @pytest.mark.asyncio
    async def test_parameter_sanitization(self, preprocessing_server, user_context, mock_database):
        """Test parameter sanitization."""
        
        with patch('shared.database.get_database', return_value=mock_database):
            with patch.object(preprocessing_server, '_load_dataframe') as mock_load:
                sample_df = pd.DataFrame({
                    'col1': [1, 2, 3],
                    'target': [0, 1, 0]
                })
                mock_load.return_value = sample_df
                
                # Test with extra whitespace in parameters
                arguments = {
                    'dataset_id': '  test_dataset_123  ',  # Extra whitespace
                    'hypotheses': ['hyp_123'],
                    'target_column': '  target  ',
                    'task_type': '  classification  '
                }
                
                # Should not raise error and should handle sanitization
                result = await preprocessing_server._create_preprocessing_plan(user_context, arguments)
                assert 'plan_id' in result


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