""" Integration tests for the Preprocessing MCP Server. Tests end-to-end preprocessing workflows with real data and database interactions. """ import pytest import asyncio import pandas as pd import numpy as np import os import tempfile import json from uuid import uuid4 from unittest.mock import patch, AsyncMock from mcp_servers.preprocessing.server import PreprocessingMCPServer from shared.models import UserContext, DatasetInfo, Hypothesis, PreprocessingPlan from shared.database import get_database @pytest.fixture def user_context(): """Create a test user context.""" return UserContext( user_id="integration_test_user", email="integration@example.com", permissions=["read", "write"] ) @pytest.fixture def preprocessing_server(): """Create a preprocessing MCP server instance.""" return PreprocessingMCPServer() @pytest.fixture def sample_ecommerce_dataset(): """Create a realistic e-commerce dataset for testing.""" np.random.seed(42) n_samples = 1000 # Generate realistic e-commerce data data = { 'customer_age': np.random.randint(18, 80, n_samples), 'annual_income': np.random.lognormal(10, 0.5, n_samples), 'purchase_amount': np.random.gamma(2, 50, n_samples), 'days_since_last_purchase': np.random.exponential(30, n_samples), 'customer_segment': np.random.choice(['Premium', 'Standard', 'Basic'], n_samples, p=[0.2, 0.5, 0.3]), 'product_category': np.random.choice(['Electronics', 'Clothing', 'Books', 'Home', 'Sports'], n_samples), 'payment_method': np.random.choice(['Credit Card', 'Debit Card', 'PayPal', 'Cash'], n_samples), 'region': np.random.choice(['North', 'South', 'East', 'West'], n_samples), 'is_weekend_purchase': np.random.choice([0, 1], n_samples, p=[0.7, 0.3]), 'has_discount': np.random.choice([0, 1], n_samples, p=[0.6, 0.4]) } # Create target variable (will_purchase_again) based on features purchase_probability = ( 0.3 + 0.2 * (data['customer_age'] > 40) + 0.15 * (data['annual_income'] > np.median(data['annual_income'])) + 0.1 * (data['purchase_amount'] > np.median(data['purchase_amount'])) + 0.15 * (data['days_since_last_purchase'] < 30) + 0.1 * data['has_discount'] ) data['will_purchase_again'] = np.random.binomial(1, purchase_probability, n_samples) return pd.DataFrame(data) @pytest.fixture def sample_dataset_file(sample_ecommerce_dataset): """Create a temporary CSV file with the sample dataset.""" with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: sample_ecommerce_dataset.to_csv(f.name, index=False) yield f.name os.unlink(f.name) @pytest.fixture def mock_hypotheses(): """Create mock validated hypotheses for the e-commerce dataset.""" return [ { 'id': 'hyp_age_income', 'text': 'Customer age is positively correlated with annual income', 'test_type': 'correlation', 'variables': ['customer_age', 'annual_income'], 'is_significant': True, 'business_relevance': 'Older customers tend to have higher income' }, { 'id': 'hyp_segment_purchase', 'text': 'Premium customers have higher purchase amounts', 'test_type': 'anova', 'variables': ['customer_segment', 'purchase_amount'], 'is_significant': True, 'business_relevance': 'Customer segment affects purchase behavior' }, { 'id': 'hyp_discount_retention', 'text': 'Customers with discounts are more likely to purchase again', 'test_type': 'chi_square', 'variables': ['has_discount', 'will_purchase_again'], 'is_significant': True, 'business_relevance': 'Discounts improve customer retention' } ] class TestEndToEndPreprocessingWorkflow: """Test complete preprocessing workflow from plan creation to validation.""" @pytest.mark.asyncio async def test_complete_preprocessing_workflow(self, preprocessing_server, user_context, sample_dataset_file, mock_hypotheses): """Test the complete preprocessing workflow end-to-end.""" # Mock database operations mock_db = AsyncMock() # Mock dataset record dataset_id = str(uuid4()) mock_db.get_dataset.return_value = { 'id': dataset_id, 'name': 'ecommerce_dataset.csv', 'file_path': sample_dataset_file, 'metadata': { 'rows': 1000, 'columns': 11, 'column_names': ['customer_age', 'annual_income', 'purchase_amount', 'days_since_last_purchase', 'customer_segment', 'product_category', 'payment_method', 'region', 'is_weekend_purchase', 'has_discount', 'will_purchase_again'] } } # Mock hypothesis records def mock_get_hypothesis(user_context, hypothesis_id): for hyp in mock_hypotheses: if hyp['id'] == hypothesis_id: return hyp return None mock_db.get_hypothesis.side_effect = mock_get_hypothesis mock_db.store_preprocessing_plan.return_value = 'plan_123' mock_db.create_dataset.return_value = 'preprocessed_dataset_123' mock_db.store_feature_mappings.return_value = ['mapping_1', 'mapping_2'] with patch('shared.database.get_database', return_value=mock_db): # Step 1: Create preprocessing plan plan_arguments = { 'dataset_id': dataset_id, 'hypotheses': [hyp['id'] for hyp in mock_hypotheses], 'target_column': 'will_purchase_again', 'task_type': 'classification' } plan_result = await preprocessing_server._create_preprocessing_plan(user_context, plan_arguments) # Verify plan creation assert 'plan_id' in plan_result assert 'plan' in plan_result assert 'summary' in plan_result plan = plan_result['plan'] assert plan['target_column'] == 'will_purchase_again' assert len(plan['scaling_operations']) > 0 # Should have numeric columns to scale assert len(plan['encoding_operations']) > 0 # Should have categorical columns to encode # Step 2: Apply preprocessing with patch('pandas.DataFrame.to_csv'): # Mock file saving with patch('builtins.open', create=True): # Mock pickle saving preprocess_arguments = { 'dataset_id': dataset_id, 'plan': plan } preprocess_result = await preprocessing_server._apply_preprocessing(user_context, preprocess_arguments) # Verify preprocessing application assert 'preprocessed_dataset_id' in preprocess_result assert 'feature_mappings_count' in preprocess_result assert 'final_shape' in preprocess_result assert 'transformations_applied' in preprocess_result # Step 3: Get feature mappings preprocessed_dataset_id = preprocess_result['preprocessed_dataset_id'] # Mock preprocessed dataset record mock_db.get_dataset.return_value = { 'id': preprocessed_dataset_id, 'name': 'preprocessed_ecommerce_dataset.csv', 'file_path': '/path/to/preprocessed.csv', 'metadata': { 'preprocessing_applied': True, 'feature_mappings': [ { 'original_name': 'customer_age', 'transformed_name': 'customer_age', 'transformation_type': 'standard_scaling', 'parameters': {} } ], 'original_columns': list(plan_arguments.keys()), 'column_names': ['transformed_col1', 'transformed_col2'], 'preprocessing_plan': plan } } mappings_arguments = { 'preprocessed_dataset_id': preprocessed_dataset_id } mappings_result = await preprocessing_server._get_feature_mappings(user_context, mappings_arguments) # Verify feature mappings assert 'preprocessed_dataset_id' in mappings_result assert 'feature_mappings' in mappings_result assert 'original_columns' in mappings_result assert 'final_columns' in mappings_result @pytest.mark.asyncio async def test_preprocessing_with_different_data_types(self, preprocessing_server, user_context): """Test preprocessing with various data types and edge cases.""" # Create dataset with various data types and edge cases data = { 'int_column': [1, 2, 3, 4, 5], 'float_column': [1.1, 2.2, 3.3, 4.4, 5.5], 'binary_categorical': ['Yes', 'No', 'Yes', 'No', 'Yes'], 'multi_categorical': ['A', 'B', 'C', 'A', 'B'], 'high_cardinality': ['cat_1', 'cat_2', 'cat_3', 'cat_4', 'cat_5'], 'missing_values': [1.0, np.nan, 3.0, np.nan, 5.0], 'outlier_column': [1, 2, 3, 4, 100], # 100 is an outlier 'target': [0, 1, 0, 1, 0] } df = pd.DataFrame(data) # Create temporary file with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: df.to_csv(f.name, index=False) temp_file = f.name try: # Mock database operations mock_db = AsyncMock() dataset_id = str(uuid4()) mock_db.get_dataset.return_value = { 'id': dataset_id, 'name': 'mixed_types_dataset.csv', 'file_path': temp_file, 'metadata': {'rows': 5, 'columns': 8} } mock_db.get_hypothesis.return_value = { 'id': 'hyp_test', 'text': 'Test hypothesis', 'variables': ['int_column', 'target'], 'is_significant': True } mock_db.store_preprocessing_plan.return_value = 'plan_123' mock_db.create_dataset.return_value = 'preprocessed_123' mock_db.store_feature_mappings.return_value = ['mapping_1'] with patch('shared.database.get_database', return_value=mock_db): # Create preprocessing plan plan_arguments = { 'dataset_id': dataset_id, 'hypotheses': ['hyp_test'], 'target_column': 'target', 'task_type': 'classification' } plan_result = await preprocessing_server._create_preprocessing_plan(user_context, plan_arguments) # Verify plan handles different data types appropriately plan = plan_result['plan'] # Should have scaling operations for numeric columns scaling_ops = plan['scaling_operations'] numeric_columns = ['int_column', 'float_column', 'missing_values', 'outlier_column'] scaled_columns = [op['column'] for op in scaling_ops] # Check that numeric columns are included (excluding target) for col in numeric_columns: if col != 'target': assert col in scaled_columns or col == 'missing_values' # Missing values might be skipped # Should have encoding operations for categorical columns encoding_ops = plan['encoding_operations'] categorical_columns = ['binary_categorical', 'multi_categorical', 'high_cardinality'] encoded_columns = [op['column'] for op in encoding_ops] for col in categorical_columns: assert col in encoded_columns # Check encoding types are appropriate for op in encoding_ops: if op['column'] == 'binary_categorical': assert op['encoding_type'] == 'label' # Binary should use label encoding elif op['column'] == 'multi_categorical': assert op['encoding_type'] == 'onehot' # Low cardinality should use one-hot elif op['column'] == 'high_cardinality': assert op['encoding_type'] in ['target', 'label'] # High cardinality with target finally: # Clean up temporary file os.unlink(temp_file) @pytest.mark.asyncio async def test_preprocessing_validation_workflow(self, preprocessing_server, user_context): """Test the preprocessing validation workflow.""" # Create original and preprocessed datasets original_data = { 'feature1': [1, 2, 3, 4, 5], 'feature2': ['A', 'B', 'A', 'C', 'B'], 'target': [0, 1, 0, 1, 0] } preprocessed_data = { 'feature1': [-1.5, -0.5, 0.0, 0.5, 1.5], # Standardized 'feature2_A': [1, 0, 1, 0, 0], # One-hot encoded 'feature2_B': [0, 1, 0, 0, 1], 'target': [0, 1, 0, 1, 0] # Target unchanged } original_df = pd.DataFrame(original_data) preprocessed_df = pd.DataFrame(preprocessed_data) # Create temporary files with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: original_df.to_csv(f.name, index=False) original_file = f.name with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: preprocessed_df.to_csv(f.name, index=False) preprocessed_file = f.name try: # Mock database operations mock_db = AsyncMock() def mock_get_dataset(user_context, dataset_id): if dataset_id == 'original_123': return { 'id': 'original_123', 'file_path': original_file, 'metadata': {} } else: return { 'id': 'preprocessed_123', 'file_path': preprocessed_file, 'metadata': { 'preprocessing_plan': { 'scaling_operations': [{'column': 'feature1', 'scaler_type': 'standard'}], 'encoding_operations': [{'column': 'feature2', 'encoding_type': 'onehot'}], 'target_column': 'target' } } } mock_db.get_dataset.side_effect = mock_get_dataset with patch('shared.database.get_database', return_value=mock_db): validation_arguments = { 'original_dataset_id': 'original_123', 'preprocessed_dataset_id': 'preprocessed_123' } validation_result = await preprocessing_server._validate_preprocessing(user_context, validation_arguments) # Verify validation results assert 'is_valid' in validation_result assert 'warnings' in validation_result assert 'errors' in validation_result assert 'statistics' in validation_result # Should be valid since no data leakage assert validation_result['is_valid'] is True # Check statistics stats = validation_result['statistics'] assert 'original_shape' in stats assert 'preprocessed_shape' in stats assert 'original_missing_values' in stats assert 'preprocessed_missing_values' in stats finally: # Clean up temporary files os.unlink(original_file) os.unlink(preprocessed_file) class TestPreprocessingPerformance: """Test preprocessing performance with larger datasets.""" @pytest.mark.asyncio async def test_large_dataset_preprocessing(self, preprocessing_server, user_context): """Test preprocessing performance with a larger dataset.""" # Create a larger dataset (10,000 rows, 50 features) np.random.seed(42) n_samples = 10000 n_features = 50 data = {} # Add numeric features for i in range(30): data[f'numeric_feature_{i}'] = np.random.normal(0, 1, n_samples) # Add categorical features for i in range(15): cardinality = np.random.randint(2, 20) # Random cardinality categories = [f'cat_{j}' for j in range(cardinality)] data[f'categorical_feature_{i}'] = np.random.choice(categories, n_samples) # Add target data['target'] = np.random.choice([0, 1], n_samples) df = pd.DataFrame(data) # Create temporary file with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: df.to_csv(f.name, index=False) temp_file = f.name try: # Mock database operations mock_db = AsyncMock() dataset_id = str(uuid4()) mock_db.get_dataset.return_value = { 'id': dataset_id, 'name': 'large_dataset.csv', 'file_path': temp_file, 'metadata': {'rows': n_samples, 'columns': len(data)} } mock_db.get_hypothesis.return_value = { 'id': 'hyp_large', 'text': 'Large dataset hypothesis', 'variables': ['numeric_feature_0', 'target'], 'is_significant': True } mock_db.store_preprocessing_plan.return_value = 'plan_large' mock_db.create_dataset.return_value = 'preprocessed_large' mock_db.store_feature_mappings.return_value = ['mapping_large'] with patch('shared.database.get_database', return_value=mock_db): # Measure preprocessing plan creation time import time start_time = time.time() plan_arguments = { 'dataset_id': dataset_id, 'hypotheses': ['hyp_large'], 'target_column': 'target', 'task_type': 'classification' } plan_result = await preprocessing_server._create_preprocessing_plan(user_context, plan_arguments) plan_time = time.time() - start_time # Verify plan was created successfully assert 'plan_id' in plan_result assert 'plan' in plan_result plan = plan_result['plan'] # Should apply feature selection for high-dimensional data assert len(plan['feature_selection']) > 0 feature_selection = plan['feature_selection'][0] assert feature_selection['method'] == 'selectkbest' assert feature_selection['k'] <= 20 # Should limit features # Performance check - should complete within reasonable time assert plan_time < 30.0 # Should complete within 30 seconds print(f"Large dataset preprocessing plan creation took {plan_time:.2f} seconds") finally: # Clean up temporary file os.unlink(temp_file) class TestPreprocessingEdgeCases: """Test preprocessing with edge cases and error conditions.""" @pytest.mark.asyncio async def test_empty_dataset_handling(self, preprocessing_server, user_context): """Test handling of empty datasets.""" # Create empty dataset df = pd.DataFrame() with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: df.to_csv(f.name, index=False) temp_file = f.name try: mock_db = AsyncMock() dataset_id = str(uuid4()) mock_db.get_dataset.return_value = { 'id': dataset_id, 'name': 'empty_dataset.csv', 'file_path': temp_file, 'metadata': {'rows': 0, 'columns': 0} } with patch('shared.database.get_database', return_value=mock_db): plan_arguments = { 'dataset_id': dataset_id, 'hypotheses': [], 'target_column': None, 'task_type': None } # Should handle empty dataset gracefully with pytest.raises(ValueError, match="Dataset is empty"): await preprocessing_server._create_preprocessing_plan(user_context, plan_arguments) finally: os.unlink(temp_file) @pytest.mark.asyncio async def test_all_missing_values_column(self, preprocessing_server, user_context): """Test handling of columns with all missing values.""" data = { 'good_column': [1, 2, 3, 4, 5], 'all_missing': [np.nan, np.nan, np.nan, np.nan, np.nan], 'target': [0, 1, 0, 1, 0] } df = pd.DataFrame(data) with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: df.to_csv(f.name, index=False) temp_file = f.name try: mock_db = AsyncMock() dataset_id = str(uuid4()) mock_db.get_dataset.return_value = { 'id': dataset_id, 'name': 'missing_values_dataset.csv', 'file_path': temp_file, 'metadata': {'rows': 5, 'columns': 3} } mock_db.get_hypothesis.return_value = { 'id': 'hyp_missing', 'text': 'Missing values hypothesis', 'variables': ['good_column', 'target'], 'is_significant': True } mock_db.store_preprocessing_plan.return_value = 'plan_missing' with patch('shared.database.get_database', return_value=mock_db): plan_arguments = { 'dataset_id': dataset_id, 'hypotheses': ['hyp_missing'], 'target_column': 'target', 'task_type': 'classification' } # Should handle columns with all missing values plan_result = await preprocessing_server._create_preprocessing_plan(user_context, plan_arguments) # Should create plan but skip all-missing columns assert 'plan_id' in plan_result plan = plan_result['plan'] # Should only include scaling for good_column, not all_missing scaling_ops = plan['scaling_operations'] scaled_columns = [op['column'] for op in scaling_ops] assert 'good_column' in scaled_columns assert 'all_missing' not in scaled_columns finally: os.unlink(temp_file) if __name__ == "__main__": pytest.main([__file__])