ai_data_scientist / tests /test_feature_engineering_unit.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
22 kB
"""
Unit tests for Feature Engineering MCP Server functionality.
Tests feature generation algorithms, transformations, and validation logic.
"""
import pytest
import pandas as pd
import numpy as np
from unittest.mock import AsyncMock, MagicMock, patch
from uuid import uuid4
import tempfile
import os
from mcp_servers.feature_engineering.server import FeatureEngineeringMCPServer
from shared.models import UserContext, FeatureSet
class TestFeatureEngineeringAlgorithms:
"""Test feature engineering algorithms and transformations."""
@pytest.fixture
def sample_dataframe(self):
"""Create a sample dataframe for testing."""
np.random.seed(42)
return pd.DataFrame({
'numeric1': np.random.normal(100, 15, 1000),
'numeric2': np.random.normal(50, 10, 1000),
'numeric3': np.random.exponential(2, 1000),
'category1': np.random.choice(['A', 'B', 'C'], 1000),
'category2': np.random.choice(['X', 'Y'], 1000),
'target': np.random.choice([0, 1], 1000)
})
@pytest.fixture
def sample_hypotheses(self):
"""Create sample hypotheses for testing."""
return [
{
"id": str(uuid4()),
"text": "There is a significant correlation between numeric1 and numeric2",
"test_type": "correlation",
"variables": ["numeric1", "numeric2"],
"is_significant": True
},
{
"id": str(uuid4()),
"text": "There is a significant difference in numeric1 between category1 groups",
"test_type": "anova",
"variables": ["category1", "numeric1"],
"is_significant": True
},
{
"id": str(uuid4()),
"text": "There is a significant difference in numeric2 between category2 groups",
"test_type": "t_test",
"variables": ["category2", "numeric2"],
"is_significant": True
}
]
def test_interaction_feature_generation(self, sample_dataframe, sample_hypotheses):
"""Test generation of interaction features."""
server = FeatureEngineeringMCPServer()
# Test multiplicative interaction
correlation_hypothesis = sample_hypotheses[0]
var1, var2 = correlation_hypothesis["variables"]
# Create multiplicative interaction
result = sample_dataframe[var1] * sample_dataframe[var2]
assert len(result) == len(sample_dataframe)
assert not result.isna().all()
# Test ratio interaction
ratio_result = sample_dataframe[var1] / (sample_dataframe[var2] + 1e-8)
assert len(ratio_result) == len(sample_dataframe)
assert not np.isinf(ratio_result).any() # Should not have infinite values
def test_transformation_features(self, sample_dataframe):
"""Test mathematical transformation features."""
server = FeatureEngineeringMCPServer()
# Test log transformation
positive_col = sample_dataframe['numeric3'] # Exponential distribution, always positive
log_transform = np.log(positive_col)
assert len(log_transform) == len(sample_dataframe)
assert not np.isinf(log_transform).any()
assert not log_transform.isna().any()
# Test square transformation
square_transform = sample_dataframe['numeric1'] ** 2
assert len(square_transform) == len(sample_dataframe)
assert (square_transform >= 0).all() # Squares are always non-negative
# Test square root transformation
abs_values = np.abs(sample_dataframe['numeric1'])
sqrt_transform = np.sqrt(abs_values)
assert len(sqrt_transform) == len(sample_dataframe)
assert (sqrt_transform >= 0).all()
assert not sqrt_transform.isna().any()
def test_aggregation_features(self, sample_dataframe):
"""Test group-based aggregation features."""
server = FeatureEngineeringMCPServer()
# Test group mean
group_means = sample_dataframe.groupby('category1')['numeric1'].transform('mean')
assert len(group_means) == len(sample_dataframe)
assert not group_means.isna().any()
# Verify that all rows in the same group have the same mean
for category in sample_dataframe['category1'].unique():
mask = sample_dataframe['category1'] == category
group_mean_values = group_means[mask]
assert len(group_mean_values.unique()) == 1 # All values should be the same
# Test group standard deviation
group_stds = sample_dataframe.groupby('category1')['numeric1'].transform('std')
assert len(group_stds) == len(sample_dataframe)
# Fill NaN values (which can occur for single-item groups)
group_stds = group_stds.fillna(0)
assert (group_stds >= 0).all() # Standard deviations are non-negative
def test_polynomial_features(self, sample_dataframe):
"""Test polynomial feature generation."""
from sklearn.preprocessing import PolynomialFeatures
# Select two numeric columns
variables = ['numeric1', 'numeric2']
data = sample_dataframe[variables]
# Create polynomial features
poly = PolynomialFeatures(degree=2, include_bias=False, interaction_only=False)
poly_data = poly.fit_transform(data)
# Should have more features than original
assert poly_data.shape[1] >= len(variables)
assert poly_data.shape[0] == len(sample_dataframe)
# Check feature names
feature_names = poly.get_feature_names_out(variables)
assert len(feature_names) == poly_data.shape[1]
def test_data_leakage_detection(self, sample_dataframe):
"""Test data leakage detection algorithms."""
server = FeatureEngineeringMCPServer()
# Create a feature that perfectly correlates with target (data leakage)
leaky_feature = sample_dataframe['target'] + np.random.normal(0, 0.01, len(sample_dataframe))
# Calculate correlation
correlation = abs(sample_dataframe['target'].corr(leaky_feature))
# Should detect high correlation (>0.95 threshold)
assert correlation > 0.95
# Create a legitimate feature (low correlation)
legitimate_feature = pd.Series(np.random.normal(0, 1, len(sample_dataframe)))
correlation_legit = abs(sample_dataframe['target'].corr(legitimate_feature))
# Should have low correlation
assert correlation_legit < 0.1
def test_dimensionality_reduction_trigger(self, sample_dataframe):
"""Test when dimensionality reduction should be triggered."""
server = FeatureEngineeringMCPServer()
# Create a dataset with many features
many_features_df = sample_dataframe.copy()
# Add many random features
for i in range(100):
many_features_df[f'random_feature_{i}'] = np.random.normal(0, 1, len(sample_dataframe))
total_features = len(many_features_df.columns)
# Should trigger dimensionality reduction
assert total_features > 100
# Test PCA application
from sklearn.decomposition import PCA
numeric_cols = many_features_df.select_dtypes(include=[np.number]).columns
if len(numeric_cols) > 20:
n_components = min(20, len(numeric_cols), len(many_features_df) - 1)
pca = PCA(n_components=n_components)
pca_data = pca.fit_transform(many_features_df[numeric_cols])
assert pca_data.shape[1] == n_components
assert pca_data.shape[0] == len(many_features_df)
assert len(pca.explained_variance_ratio_) == n_components
def test_complexity_score_calculation(self):
"""Test complexity score calculation."""
server = FeatureEngineeringMCPServer()
# Test complexity score normalization
test_cases = [
(10, 0.1), # 10 features -> 0.1 complexity
(50, 0.5), # 50 features -> 0.5 complexity
(100, 1.0), # 100 features -> 1.0 complexity
(150, 1.0), # 150 features -> 1.0 (capped at 1.0)
]
for feature_count, expected_complexity in test_cases:
complexity_score = min(1.0, feature_count / 100.0)
assert complexity_score == expected_complexity
def test_feature_validation_edge_cases(self, sample_dataframe):
"""Test feature validation with edge cases."""
server = FeatureEngineeringMCPServer()
# Test with infinite values
df_with_inf = sample_dataframe.copy()
df_with_inf['inf_feature'] = np.inf
# Should detect infinite values
assert np.isinf(df_with_inf['inf_feature']).any()
# Test with extreme outliers
df_with_outliers = sample_dataframe.copy()
mean_val = df_with_outliers['numeric1'].mean()
std_val = df_with_outliers['numeric1'].std()
df_with_outliers.loc[0, 'numeric1'] = mean_val + 10 * std_val # 10 standard deviations
# Calculate z-scores
z_scores = np.abs((df_with_outliers['numeric1'] - mean_val) / std_val)
# Should detect extreme outliers
assert (z_scores > 5).any()
def test_missing_value_handling(self, sample_dataframe):
"""Test handling of missing values in feature engineering."""
server = FeatureEngineeringMCPServer()
# Introduce missing values
df_with_na = sample_dataframe.copy()
df_with_na.loc[0:10, 'numeric1'] = np.nan
df_with_na.loc[5:15, 'numeric2'] = np.nan
# Test interaction feature with missing values
interaction = df_with_na['numeric1'] * df_with_na['numeric2']
# Should have NaN where either input is NaN
assert interaction.isna().sum() > 0
# Test filling with median
median_val = df_with_na['numeric1'].median()
filled_values = df_with_na['numeric1'].fillna(median_val)
# Should have no missing values after filling
assert not filled_values.isna().any()
assert filled_values.isna().sum() == 0
class TestFeatureEngineeringMCPServer:
"""Test the Feature Engineering MCP Server class."""
@pytest.fixture
def server(self):
"""Create a server instance for testing."""
return FeatureEngineeringMCPServer()
@pytest.fixture
def user_context(self):
"""Create a user context for testing."""
return UserContext(user_id="test_user_123", email="test@example.com")
@pytest.fixture
def temp_csv_file(self):
"""Create a temporary CSV file for testing."""
df = pd.DataFrame({
'numeric1': [1, 2, 3, 4, 5],
'numeric2': [10, 20, 30, 40, 50],
'category': ['A', 'B', 'A', 'B', 'A'],
'target': [0, 1, 0, 1, 0]
})
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
df.to_csv(f.name, index=False)
yield f.name
# Cleanup
os.unlink(f.name)
def test_server_initialization(self, server):
"""Test server initialization."""
assert server.server_name == "feature_engineering"
assert server.port == 3004 # Default port from config
assert hasattr(server, 'feature_engineering_dir')
@pytest.mark.asyncio
async def test_load_dataframe_csv(self, server, temp_csv_file):
"""Test loading CSV dataframe."""
df = await server._load_dataframe(temp_csv_file)
assert isinstance(df, pd.DataFrame)
assert len(df) == 5
assert 'numeric1' in df.columns
assert 'numeric2' in df.columns
assert 'category' in df.columns
assert 'target' in df.columns
@pytest.mark.asyncio
async def test_load_dataframe_invalid_format(self, server):
"""Test loading dataframe with invalid format."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
f.write("invalid content")
temp_file = f.name
try:
with pytest.raises(ValueError, match="Unsupported file format"):
await server._load_dataframe(temp_file)
finally:
os.unlink(temp_file)
@pytest.mark.asyncio
async def test_load_dataframe_empty_file(self, server):
"""Test loading empty dataframe."""
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
# Write only headers, no data
f.write("col1,col2\n")
temp_file = f.name
try:
with pytest.raises(ValueError, match="Dataset is empty"):
await server._load_dataframe(temp_file)
finally:
os.unlink(temp_file)
def test_generate_complexity_recommendations(self, server):
"""Test complexity recommendation generation."""
# Test high feature count
metrics_high_features = {
"total_features": 150,
"complexity_score": 0.9,
"dimensionality_reduction_applied": False,
"original_features": 10,
"engineered_features": 140
}
recommendations = server._generate_complexity_recommendations(metrics_high_features)
assert len(recommendations) > 0
assert any("dimensionality reduction" in rec.lower() for rec in recommendations)
assert any("overfitting" in rec.lower() for rec in recommendations)
# Test normal feature count
metrics_normal = {
"total_features": 20,
"complexity_score": 0.3,
"dimensionality_reduction_applied": False,
"original_features": 15,
"engineered_features": 5
}
recommendations_normal = server._generate_complexity_recommendations(metrics_normal)
# Should have fewer or no recommendations
assert len(recommendations_normal) <= len(recommendations)
@pytest.mark.asyncio
async def test_tool_registration(self, server):
"""Test that all required tools are registered."""
await server.register_server_tools()
expected_tools = [
"generate_features",
"apply_feature_engineering",
"explain_features",
"validate_features",
"get_complexity_metrics"
]
registered_tools = list(server.tools.keys())
for tool in expected_tools:
assert tool in registered_tools
def test_validate_required_params(self, server):
"""Test parameter validation."""
# Test with valid parameters
arguments = {"dataset_id": "123", "hypotheses": []}
server.validate_required_params(arguments, ["dataset_id", "hypotheses"])
# Test with missing parameters
with pytest.raises(Exception, match="Missing required parameter"):
server.validate_required_params(arguments, ["dataset_id", "missing_param"])
def test_sanitize_input(self, server):
"""Test input sanitization."""
# Test normal string
clean_input = server.sanitize_input("normal text")
assert clean_input == "normal text"
# Test with potential SQL injection
malicious_input = "'; DROP TABLE users; --"
sanitized = server.sanitize_input(malicious_input)
assert sanitized == malicious_input # Should be returned as-is for logging
class TestFeatureEngineeringIntegration:
"""Integration tests for feature engineering workflows."""
@pytest.fixture
def mock_database(self):
"""Create a mock database for testing."""
db = AsyncMock()
# Mock dataset record
db.get_dataset.return_value = {
"id": "dataset-123",
"name": "test_dataset.csv",
"file_path": "/tmp/test_dataset.csv",
"metadata": {}
}
# Mock hypotheses
db.get_validated_hypotheses.return_value = [
{
"id": "hyp-1",
"text": "Correlation between var1 and var2",
"test_type": "correlation",
"variables": ["numeric1", "numeric2"]
}
]
return db
@pytest.mark.asyncio
async def test_feature_engineering_workflow(self, mock_database):
"""Test complete feature engineering workflow."""
server = FeatureEngineeringMCPServer()
user_context = UserContext(user_id="test_user")
# Mock the database
with patch('shared.database.get_database', return_value=mock_database):
# Mock file loading
with patch.object(server, '_load_dataframe') as mock_load:
mock_load.return_value = pd.DataFrame({
'numeric1': [1, 2, 3, 4, 5],
'numeric2': [10, 20, 30, 40, 50],
'category': ['A', 'B', 'A', 'B', 'A']
})
# Test feature generation
hypotheses = [
{
"id": "hyp-1",
"text": "Correlation test",
"test_type": "correlation",
"variables": ["numeric1", "numeric2"]
}
]
# Mock database operations
mock_database.store_feature_engineering_plan.return_value = "plan-123"
result = await server._generate_features(
user_context,
{
"dataset_id": "dataset-123",
"hypotheses": hypotheses,
"max_features": 10
}
)
assert "plan_id" in result
assert "feature_set" in result
assert "features_generated" in result
assert result["features_generated"] > 0
@pytest.mark.asyncio
async def test_error_handling_missing_dataset(self, mock_database):
"""Test error handling for missing dataset."""
server = FeatureEngineeringMCPServer()
user_context = UserContext(user_id="test_user")
# Mock database to return None (dataset not found)
mock_database.get_dataset.return_value = None
with patch('shared.database.get_database', return_value=mock_database):
with pytest.raises(ValueError, match="Dataset not found"):
await server._generate_features(
user_context,
{
"dataset_id": "nonexistent-dataset",
"hypotheses": []
}
)
@pytest.mark.asyncio
async def test_feature_validation_workflow(self, mock_database):
"""Test feature validation workflow."""
server = FeatureEngineeringMCPServer()
user_context = UserContext(user_id="test_user")
# Mock datasets
original_df = pd.DataFrame({
'numeric1': [1, 2, 3, 4, 5],
'target': [0, 1, 0, 1, 0]
})
engineered_df = pd.DataFrame({
'numeric1': [1, 2, 3, 4, 5],
'target': [0, 1, 0, 1, 0],
'engineered_feature': [10, 20, 30, 40, 50]
})
with patch('shared.database.get_database', return_value=mock_database):
with patch.object(server, '_load_dataframe') as mock_load:
mock_load.side_effect = [original_df, engineered_df]
# Mock engineered features info
mock_database.get_engineered_features.return_value = [
{
"feature_name": "engineered_feature",
"feature_type": "interaction",
"source_columns": ["numeric1"],
"formula": "numeric1 * 10"
}
]
mock_database.store_feature_validation.return_value = "validation-123"
result = await server._validate_features(
user_context,
{
"original_dataset_id": "original-123",
"engineered_dataset_id": "engineered-123",
"target_column": "target"
}
)
assert "has_data_leakage" in result
assert "leakage_warnings" in result
assert "validation_errors" in result
assert "validation_passed" in result
if __name__ == "__main__":
pytest.main([__file__])