Spaces:
Paused
Paused
Download tests/test_feature_engineering_integration.py from VAH6002/ai_data_scientist: direct link, hf CLI and curl.
- Browser
- Download file 24 kB
-
https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/tests/test_feature_engineering_integration.py
- Command line
-
hf download hf://spaces/VAH6002/ai_data_scientist/tests/test_feature_engineering_integration.py
-
curl -L -o test_feature_engineering_integration.py https://huggingface.co/spaces/VAH6002/ai_data_scientist/resolve/main/tests/test_feature_engineering_integration.py
24 kB
| """ | |
| Integration tests for Feature Engineering MCP Server. | |
| Tests the complete feature engineering pipeline with real data flows. | |
| """ | |
| import pytest | |
| import pandas as pd | |
| import numpy as np | |
| import tempfile | |
| import os | |
| import asyncio | |
| from unittest.mock import patch, AsyncMock | |
| from uuid import uuid4 | |
| from mcp_servers.feature_engineering.server import FeatureEngineeringMCPServer | |
| from shared.models import UserContext, FeatureSet | |
| from shared.database import SupabaseManager | |
| class TestFeatureEngineeringIntegration: | |
| """Integration tests for feature engineering workflows.""" | |
| def sample_dataset(self): | |
| """Create a realistic sample dataset for testing.""" | |
| np.random.seed(42) | |
| n_samples = 1000 | |
| # Create correlated features | |
| x1 = np.random.normal(100, 15, n_samples) | |
| x2 = 0.7 * x1 + np.random.normal(0, 5, n_samples) # Correlated with x1 | |
| x3 = np.random.exponential(2, n_samples) | |
| # Create categorical features | |
| categories = np.random.choice(['Low', 'Medium', 'High'], n_samples, p=[0.3, 0.4, 0.3]) | |
| binary_cat = np.random.choice(['Yes', 'No'], n_samples) | |
| # Create target with some relationship to features | |
| target = (0.3 * x1 + 0.2 * x2 + 0.1 * x3 + | |
| np.where(categories == 'High', 20, 0) + | |
| np.random.normal(0, 10, n_samples)) | |
| target = (target > target.median()).astype(int) | |
| return pd.DataFrame({ | |
| 'sales_amount': x1, | |
| 'marketing_spend': x2, | |
| 'customer_age': x3, | |
| 'product_category': categories, | |
| 'premium_customer': binary_cat, | |
| 'target': target | |
| }) | |
| def sample_hypotheses(self): | |
| """Create realistic hypotheses based on business scenarios.""" | |
| return [ | |
| { | |
| "id": str(uuid4()), | |
| "text": "There is a significant correlation between sales_amount and marketing_spend", | |
| "test_type": "correlation", | |
| "variables": ["sales_amount", "marketing_spend"], | |
| "expected_outcome": "Positive correlation exists", | |
| "business_relevance": "Understanding marketing ROI", | |
| "is_significant": True, | |
| "p_value": 0.001 | |
| }, | |
| { | |
| "id": str(uuid4()), | |
| "text": "There are significant differences in sales_amount across product_category groups", | |
| "test_type": "anova", | |
| "variables": ["product_category", "sales_amount"], | |
| "expected_outcome": "Significant differences across categories", | |
| "business_relevance": "Product performance analysis", | |
| "is_significant": True, | |
| "p_value": 0.01 | |
| }, | |
| { | |
| "id": str(uuid4()), | |
| "text": "There is a significant difference in customer_age between premium_customer groups", | |
| "test_type": "t_test", | |
| "variables": ["premium_customer", "customer_age"], | |
| "expected_outcome": "Age difference between premium and regular customers", | |
| "business_relevance": "Customer segmentation insights", | |
| "is_significant": True, | |
| "p_value": 0.02 | |
| } | |
| ] | |
| def temp_dataset_file(self, sample_dataset): | |
| """Create a temporary dataset file.""" | |
| 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) | |
| def mock_database(self, temp_dataset_file): | |
| """Create a comprehensive mock database.""" | |
| db = AsyncMock() | |
| # Mock dataset retrieval | |
| db.get_dataset.return_value = { | |
| "id": "dataset-123", | |
| "name": "sales_data.csv", | |
| "file_path": temp_dataset_file, | |
| "metadata": { | |
| "rows": 1000, | |
| "columns": 6, | |
| "column_names": ["sales_amount", "marketing_spend", "customer_age", | |
| "product_category", "premium_customer", "target"] | |
| } | |
| } | |
| # Mock database operations | |
| db.store_feature_engineering_plan.return_value = "plan-123" | |
| db.create_dataset.return_value = "engineered-dataset-123" | |
| db.store_engineered_features.return_value = ["feature-1", "feature-2"] | |
| db.store_feature_complexity_metrics.return_value = "metrics-123" | |
| db.store_feature_validation.return_value = "validation-123" | |
| return db | |
| def server(self): | |
| """Create server instance.""" | |
| return FeatureEngineeringMCPServer() | |
| def user_context(self): | |
| """Create user context.""" | |
| return UserContext(user_id="integration_test_user", email="test@example.com") | |
| async def test_complete_feature_engineering_pipeline( | |
| self, server, user_context, sample_hypotheses, mock_database | |
| ): | |
| """Test the complete feature engineering pipeline from hypothesis to validation.""" | |
| with patch('shared.database.get_database', return_value=mock_database): | |
| # Step 1: Generate features based on hypotheses | |
| generation_result = await server._generate_features( | |
| user_context, | |
| { | |
| "dataset_id": "dataset-123", | |
| "hypotheses": sample_hypotheses, | |
| "max_features": 20, | |
| "complexity_threshold": 0.7 | |
| } | |
| ) | |
| # Verify feature generation results | |
| assert "plan_id" in generation_result | |
| assert "feature_set" in generation_result | |
| assert "features_generated" in generation_result | |
| assert generation_result["features_generated"] > 0 | |
| feature_set = generation_result["feature_set"] | |
| assert "interaction_features" in feature_set | |
| assert "transformation_features" in feature_set | |
| assert "aggregation_features" in feature_set | |
| # Verify we have different types of features | |
| breakdown = generation_result["breakdown"] | |
| assert breakdown["interaction_features"] > 0 # Should have correlation-based interactions | |
| assert breakdown["transformation_features"] > 0 # Should have log/square transforms | |
| assert breakdown["aggregation_features"] > 0 # Should have group-based features | |
| # Step 2: Apply feature engineering | |
| with patch.object(server, '_load_dataframe') as mock_load: | |
| # Load the actual dataset for feature engineering | |
| original_df = pd.read_csv(mock_database.get_dataset.return_value["file_path"]) | |
| mock_load.return_value = original_df | |
| engineering_result = await server._apply_feature_engineering( | |
| user_context, | |
| { | |
| "dataset_id": "dataset-123", | |
| "feature_set": feature_set | |
| } | |
| ) | |
| # Verify engineering results | |
| assert "engineered_dataset_id" in engineering_result | |
| assert "features_created" in engineering_result | |
| assert "final_shape" in engineering_result | |
| assert "complexity_metrics" in engineering_result | |
| # Should have created new features | |
| assert engineering_result["features_created"] > 0 | |
| # Final dataset should have more columns than original | |
| final_shape = engineering_result["final_shape"] | |
| assert final_shape["columns"] > len(original_df.columns) | |
| # Step 3: Validate features for data leakage | |
| mock_database.get_engineered_features.return_value = [ | |
| { | |
| "feature_name": "sales_amount_x_marketing_spend", | |
| "feature_type": "interaction", | |
| "source_columns": ["sales_amount", "marketing_spend"], | |
| "formula": "sales_amount * marketing_spend", | |
| "hypothesis_basis": "Correlation hypothesis" | |
| } | |
| ] | |
| # Mock loading both original and engineered datasets | |
| engineered_df = original_df.copy() | |
| engineered_df["sales_amount_x_marketing_spend"] = ( | |
| engineered_df["sales_amount"] * engineered_df["marketing_spend"] | |
| ) | |
| mock_load.side_effect = [original_df, engineered_df] | |
| validation_result = await server._validate_features( | |
| user_context, | |
| { | |
| "original_dataset_id": "dataset-123", | |
| "engineered_dataset_id": engineering_result["engineered_dataset_id"], | |
| "target_column": "target" | |
| } | |
| ) | |
| # Verify validation results | |
| assert "has_data_leakage" in validation_result | |
| assert "leakage_warnings" in validation_result | |
| assert "validation_errors" in validation_result | |
| assert "validation_passed" in validation_result | |
| # Should pass validation (no direct target leakage) | |
| assert validation_result["validation_passed"] is True | |
| async def test_feature_explanation_generation( | |
| self, server, user_context, mock_database | |
| ): | |
| """Test feature explanation generation.""" | |
| # Mock engineered features with detailed information | |
| mock_database.get_engineered_features.return_value = [ | |
| { | |
| "feature_name": "sales_marketing_interaction", | |
| "feature_type": "interaction", | |
| "source_columns": ["sales_amount", "marketing_spend"], | |
| "formula": "sales_amount * marketing_spend", | |
| "hypothesis_basis": "Strong correlation between sales and marketing indicates multiplicative effect", | |
| "description": "Interaction between sales amount and marketing spend to capture synergistic effects", | |
| "importance_score": 0.85 | |
| }, | |
| { | |
| "feature_name": "customer_age_log", | |
| "feature_type": "transformation", | |
| "source_columns": ["customer_age"], | |
| "formula": "log(customer_age)", | |
| "hypothesis_basis": "Age distribution is right-skewed, log transformation normalizes", | |
| "description": "Log transformation of customer age for better model performance", | |
| "importance_score": 0.62 | |
| }, | |
| { | |
| "feature_name": "sales_mean_by_category", | |
| "feature_type": "aggregation", | |
| "source_columns": ["product_category", "sales_amount"], | |
| "formula": "mean(sales_amount) grouped by product_category", | |
| "hypothesis_basis": "ANOVA test showed significant differences across product categories", | |
| "description": "Average sales amount for each product category", | |
| "importance_score": 0.73 | |
| } | |
| ] | |
| mock_database.get_dataset.return_value = { | |
| "metadata": {"feature_engineering_applied": True} | |
| } | |
| with patch('shared.database.get_database', return_value=mock_database): | |
| result = await server._explain_features( | |
| user_context, | |
| {"engineered_dataset_id": "engineered-123"} | |
| ) | |
| # Verify explanation results | |
| assert "engineered_dataset_id" in result | |
| assert "total_features" in result | |
| assert "feature_explanations" in result | |
| assert "feature_breakdown" in result | |
| assert result["total_features"] == 3 | |
| explanations = result["feature_explanations"] | |
| assert len(explanations) == 3 | |
| # Verify each explanation has required fields | |
| for explanation in explanations: | |
| assert "feature_name" in explanation | |
| assert "description" in explanation | |
| assert "hypothesis_basis" in explanation | |
| assert "importance_score" in explanation | |
| # Verify feature breakdown | |
| breakdown = result["feature_breakdown"] | |
| assert breakdown["interaction"] == 1 | |
| assert breakdown["transformation"] == 1 | |
| assert breakdown["aggregation"] == 1 | |
| async def test_complexity_metrics_tracking( | |
| self, server, user_context, mock_database | |
| ): | |
| """Test complexity metrics calculation and tracking.""" | |
| # Mock complexity metrics | |
| mock_database.get_feature_complexity_metrics.return_value = { | |
| "total_features": 45, | |
| "original_features": 6, | |
| "engineered_features": 39, | |
| "interaction_features": 15, | |
| "transformation_features": 12, | |
| "aggregation_features": 12, | |
| "complexity_score": 0.45, | |
| "dimensionality_reduction_applied": False | |
| } | |
| with patch('shared.database.get_database', return_value=mock_database): | |
| result = await server._get_complexity_metrics( | |
| user_context, | |
| {"engineered_dataset_id": "engineered-123"} | |
| ) | |
| # Verify complexity metrics | |
| assert "engineered_dataset_id" in result | |
| assert "complexity_metrics" in result | |
| assert "recommendations" in result | |
| metrics = result["complexity_metrics"] | |
| assert metrics["total_features"] == 45 | |
| assert metrics["original_features"] == 6 | |
| assert metrics["engineered_features"] == 39 | |
| assert metrics["complexity_score"] == 0.45 | |
| # Should have recommendations for this complexity level | |
| recommendations = result["recommendations"] | |
| assert isinstance(recommendations, list) | |
| async def test_data_leakage_detection_scenarios( | |
| self, server, user_context, mock_database, sample_dataset | |
| ): | |
| """Test various data leakage detection scenarios.""" | |
| # Create datasets with different leakage scenarios | |
| original_df = sample_dataset.copy() | |
| # Scenario 1: Direct target leakage | |
| leaky_df = original_df.copy() | |
| leaky_df["target_copy"] = leaky_df["target"] # Perfect correlation | |
| # Scenario 2: Future information leakage (group stats including target) | |
| future_leak_df = original_df.copy() | |
| future_leak_df["target_mean_by_category"] = future_leak_df.groupby("product_category")["target"].transform("mean") | |
| # Scenario 3: Legitimate feature (no leakage) | |
| clean_df = original_df.copy() | |
| clean_df["sales_marketing_ratio"] = clean_df["sales_amount"] / (clean_df["marketing_spend"] + 1e-8) | |
| test_scenarios = [ | |
| ("direct_leakage", leaky_df, True), | |
| ("future_leakage", future_leak_df, True), | |
| ("clean_features", clean_df, False) | |
| ] | |
| for scenario_name, test_df, should_have_leakage in test_scenarios: | |
| # Create temporary file for test dataset | |
| with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f: | |
| test_df.to_csv(f.name, index=False) | |
| temp_file = f.name | |
| try: | |
| # Mock engineered features based on scenario | |
| if scenario_name == "direct_leakage": | |
| mock_features = [ | |
| { | |
| "feature_name": "target_copy", | |
| "feature_type": "interaction", | |
| "source_columns": ["target"], | |
| "formula": "target" | |
| } | |
| ] | |
| elif scenario_name == "future_leakage": | |
| mock_features = [ | |
| { | |
| "feature_name": "target_mean_by_category", | |
| "feature_type": "aggregation", | |
| "source_columns": ["product_category", "target"], | |
| "formula": "mean(target) grouped by product_category" | |
| } | |
| ] | |
| else: | |
| mock_features = [ | |
| { | |
| "feature_name": "sales_marketing_ratio", | |
| "feature_type": "interaction", | |
| "source_columns": ["sales_amount", "marketing_spend"], | |
| "formula": "sales_amount / marketing_spend" | |
| } | |
| ] | |
| mock_database.get_engineered_features.return_value = mock_features | |
| 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, test_df] | |
| result = await server._validate_features( | |
| user_context, | |
| { | |
| "original_dataset_id": "original-123", | |
| "engineered_dataset_id": "engineered-123", | |
| "target_column": "target" | |
| } | |
| ) | |
| # Verify leakage detection | |
| if should_have_leakage: | |
| assert result["has_data_leakage"] is True or len(result["leakage_warnings"]) > 0 | |
| else: | |
| assert result["has_data_leakage"] is False | |
| assert result["validation_passed"] is True | |
| finally: | |
| os.unlink(temp_file) | |
| async def test_dimensionality_reduction_integration( | |
| self, server, user_context, mock_database, sample_dataset | |
| ): | |
| """Test dimensionality reduction when feature count is high.""" | |
| # Create a dataset with many features to trigger dimensionality reduction | |
| high_dim_df = sample_dataset.copy() | |
| # Add many random features to trigger dimensionality reduction | |
| np.random.seed(42) | |
| for i in range(100): | |
| high_dim_df[f"random_feature_{i}"] = np.random.normal(0, 1, len(sample_dataset)) | |
| # Create feature set with many features | |
| feature_set = FeatureSet( | |
| interaction_features=[ | |
| { | |
| "name": f"interaction_{i}", | |
| "type": "multiplication", | |
| "variables": ["sales_amount", "marketing_spend"], | |
| "formula": "sales_amount * marketing_spend", | |
| "hypothesis_basis": "Test interaction", | |
| "description": f"Test interaction feature {i}" | |
| } | |
| for i in range(30) | |
| ], | |
| transformation_features=[ | |
| { | |
| "name": f"transform_{i}", | |
| "type": "square_transform", | |
| "variables": ["sales_amount"], | |
| "formula": "sales_amount^2", | |
| "hypothesis_basis": "Test transformation", | |
| "description": f"Test transformation feature {i}" | |
| } | |
| for i in range(30) | |
| ], | |
| aggregation_features=[] | |
| ) | |
| with patch('shared.database.get_database', return_value=mock_database): | |
| with patch.object(server, '_load_dataframe') as mock_load: | |
| mock_load.return_value = high_dim_df | |
| result = await server._apply_feature_engineering( | |
| user_context, | |
| { | |
| "dataset_id": "dataset-123", | |
| "feature_set": feature_set.model_dump() | |
| } | |
| ) | |
| # Should trigger dimensionality reduction | |
| assert result["dimensionality_reduction_applied"] is True | |
| # Final feature count should be reduced | |
| complexity_metrics = result["complexity_metrics"] | |
| assert complexity_metrics["dimensionality_reduction_applied"] is True | |
| # Should have reasonable number of final features | |
| final_columns = result["final_shape"]["columns"] | |
| assert final_columns < len(high_dim_df.columns) + 60 # Original + all new features | |
| async def test_error_handling_and_recovery( | |
| self, server, user_context, mock_database | |
| ): | |
| """Test error handling and recovery mechanisms.""" | |
| # Test missing dataset error | |
| 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": [] | |
| } | |
| ) | |
| # Test invalid feature set error | |
| mock_database.get_dataset.return_value = { | |
| "file_path": "/nonexistent/file.csv" | |
| } | |
| with patch('shared.database.get_database', return_value=mock_database): | |
| with pytest.raises(ValueError, match="Failed to load dataset"): | |
| await server._apply_feature_engineering( | |
| user_context, | |
| { | |
| "dataset_id": "dataset-123", | |
| "feature_set": {"interaction_features": [], "transformation_features": [], "aggregation_features": []} | |
| } | |
| ) | |
| # Test validation with non-engineered dataset | |
| mock_database.get_dataset.return_value = { | |
| "metadata": {"feature_engineering_applied": False} | |
| } | |
| with patch('shared.database.get_database', return_value=mock_database): | |
| with pytest.raises(ValueError, match="not an engineered dataset"): | |
| await server._explain_features( | |
| user_context, | |
| {"engineered_dataset_id": "not-engineered-123"} | |
| ) | |
| if __name__ == "__main__": | |
| pytest.main([__file__]) |