Spaces:
Paused
Paused
File size: 25,192 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 | """
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__]) |