ai_data_scientist / tests /test_preprocessing_unit.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
22.5 kB
"""
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__])