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