ai_data_scientist / tests /test_model_training_unit.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
19.9 kB
"""
Unit tests for Model Training MCP Server functionality.
Tests individual components and methods in isolation.
"""
import pytest
import pandas as pd
import numpy as np
from unittest.mock import Mock, AsyncMock, patch, MagicMock
from uuid import uuid4
import tempfile
import os
import pickle
from mcp_servers.model_training.server import ModelTrainingMCPServer
from shared.models import UserContext, TaskType, ModelPerformance, TrainedModel
class TestModelTrainingMCPServer:
"""Test cases for ModelTrainingMCPServer class."""
@pytest.fixture
def server(self):
"""Create a ModelTrainingMCPServer instance for testing."""
return ModelTrainingMCPServer()
@pytest.fixture
def user_context(self):
"""Create a test user context."""
return UserContext(
user_id="test_user_123",
email="test@example.com",
permissions=["read", "write"]
)
@pytest.fixture
def sample_classification_data(self):
"""Create sample classification dataset."""
np.random.seed(42)
n_samples = 100
data = {
'feature1': np.random.normal(0, 1, n_samples),
'feature2': np.random.normal(0, 1, n_samples),
'feature3': np.random.choice(['A', 'B', 'C'], n_samples),
'target': np.random.choice([0, 1], n_samples)
}
return pd.DataFrame(data)
@pytest.fixture
def sample_regression_data(self):
"""Create sample regression dataset."""
np.random.seed(42)
n_samples = 100
data = {
'feature1': np.random.normal(0, 1, n_samples),
'feature2': np.random.normal(0, 1, n_samples),
'feature3': np.random.choice(['X', 'Y', 'Z'], n_samples),
'target': np.random.normal(50, 10, n_samples)
}
return pd.DataFrame(data)
@pytest.mark.asyncio
async def test_detect_task_type_classification_binary(self, server, sample_classification_data):
"""Test automatic detection of binary classification task."""
task_type = await server._detect_task_type(sample_classification_data, 'target')
assert task_type == TaskType.CLASSIFICATION
@pytest.mark.asyncio
async def test_detect_task_type_classification_categorical(self, server):
"""Test automatic detection of categorical classification task."""
data = pd.DataFrame({
'feature1': [1, 2, 3, 4, 5],
'target': ['cat', 'dog', 'bird', 'cat', 'dog']
})
task_type = await server._detect_task_type(data, 'target')
assert task_type == TaskType.CLASSIFICATION
@pytest.mark.asyncio
async def test_detect_task_type_regression(self, server, sample_regression_data):
"""Test automatic detection of regression task."""
task_type = await server._detect_task_type(sample_regression_data, 'target')
assert task_type == TaskType.REGRESSION
@pytest.mark.asyncio
async def test_detect_task_type_missing_column(self, server, sample_classification_data):
"""Test error handling for missing target column."""
with pytest.raises(ValueError, match="Target column 'nonexistent' not found"):
await server._detect_task_type(sample_classification_data, 'nonexistent')
@pytest.mark.asyncio
async def test_detect_task_type_all_nan(self, server):
"""Test error handling for target column with all NaN values."""
data = pd.DataFrame({
'feature1': [1, 2, 3, 4, 5],
'target': [np.nan, np.nan, np.nan, np.nan, np.nan]
})
with pytest.raises(ValueError, match="Target column 'target' contains only NaN values"):
await server._detect_task_type(data, 'target')
def test_get_algorithms_for_task_classification(self, server):
"""Test getting algorithms for classification task."""
algorithms = server._get_algorithms_for_task(TaskType.CLASSIFICATION)
expected_algorithms = [
'random_forest', 'logistic_regression', 'svm', 'decision_tree',
'knn', 'naive_bayes', 'gradient_boosting'
]
for algo in expected_algorithms:
assert algo in algorithms
# Check that all algorithms are classifiers
from sklearn.base import ClassifierMixin
for algo_name, algo_instance in algorithms.items():
if not algo_name.startswith(('xgboost', 'lightgbm')): # Skip optional libraries
assert isinstance(algo_instance, ClassifierMixin)
def test_get_algorithms_for_task_regression(self, server):
"""Test getting algorithms for regression task."""
algorithms = server._get_algorithms_for_task(TaskType.REGRESSION)
expected_algorithms = [
'random_forest', 'linear_regression', 'ridge', 'lasso',
'svr', 'decision_tree', 'knn', 'gradient_boosting'
]
for algo in expected_algorithms:
assert algo in algorithms
# Check that all algorithms are regressors
from sklearn.base import RegressorMixin
for algo_name, algo_instance in algorithms.items():
if not algo_name.startswith(('xgboost', 'lightgbm')): # Skip optional libraries
assert isinstance(algo_instance, RegressorMixin)
def test_calculate_performance_metrics_classification(self, server):
"""Test performance metrics calculation for classification."""
y_true = np.array([0, 1, 0, 1, 0, 1])
y_pred = np.array([0, 1, 1, 1, 0, 0])
y_pred_proba = np.array([[0.8, 0.2], [0.3, 0.7], [0.4, 0.6],
[0.2, 0.8], [0.9, 0.1], [0.6, 0.4]])
performance = server._calculate_performance_metrics(
y_true, y_pred, TaskType.CLASSIFICATION, y_pred_proba
)
assert isinstance(performance, ModelPerformance)
assert performance.accuracy is not None
assert performance.precision is not None
assert performance.recall is not None
assert performance.f1_score is not None
assert performance.roc_auc is not None
# Check that values are reasonable
assert 0 <= performance.accuracy <= 1
assert 0 <= performance.precision <= 1
assert 0 <= performance.recall <= 1
assert 0 <= performance.f1_score <= 1
assert 0 <= performance.roc_auc <= 1
def test_calculate_performance_metrics_regression(self, server):
"""Test performance metrics calculation for regression."""
y_true = np.array([1.0, 2.0, 3.0, 4.0, 5.0])
y_pred = np.array([1.1, 2.2, 2.8, 4.1, 4.9])
performance = server._calculate_performance_metrics(
y_true, y_pred, TaskType.REGRESSION
)
assert isinstance(performance, ModelPerformance)
assert performance.rmse is not None
assert performance.mae is not None
assert performance.r2_score is not None
# Check that values are reasonable
assert performance.rmse >= 0
assert performance.mae >= 0
assert performance.r2_score <= 1 # R² can be negative for very bad models
@pytest.mark.asyncio
async def test_prepare_data_classification(self, server, sample_classification_data):
"""Test data preparation for classification."""
X, y, feature_names = await server._prepare_data(
sample_classification_data, 'target', TaskType.CLASSIFICATION
)
assert isinstance(X, np.ndarray)
assert isinstance(y, np.ndarray)
assert isinstance(feature_names, list)
# Check dimensions
assert X.shape[0] == len(y)
assert X.shape[1] == len(feature_names)
assert len(feature_names) == 3 # feature1, feature2, feature3
# Check that categorical features are encoded
assert np.issubdtype(X.dtype, np.number)
assert np.issubdtype(y.dtype, np.number)
@pytest.mark.asyncio
async def test_prepare_data_regression(self, server, sample_regression_data):
"""Test data preparation for regression."""
X, y, feature_names = await server._prepare_data(
sample_regression_data, 'target', TaskType.REGRESSION
)
assert isinstance(X, np.ndarray)
assert isinstance(y, np.ndarray)
assert isinstance(feature_names, list)
# Check dimensions
assert X.shape[0] == len(y)
assert X.shape[1] == len(feature_names)
assert len(feature_names) == 3 # feature1, feature2, feature3
# Check that all data is numeric
assert np.issubdtype(X.dtype, np.number)
assert np.issubdtype(y.dtype, np.number)
@pytest.mark.asyncio
async def test_prepare_data_missing_values(self, server):
"""Test data preparation with missing values."""
data = pd.DataFrame({
'feature1': [1.0, 2.0, np.nan, 4.0, 5.0],
'feature2': [1.0, np.nan, 3.0, 4.0, 5.0],
'target': [0, 1, np.nan, 1, 0]
})
X, y, feature_names = await server._prepare_data(
data, 'target', TaskType.CLASSIFICATION
)
# Should remove rows with missing target values
assert len(y) == 4 # One row removed due to missing target
assert X.shape[0] == 4
# Should fill missing feature values
assert not np.isnan(X).any()
assert not np.isnan(y).any()
@pytest.mark.asyncio
async def test_load_dataframe_csv(self, server):
"""Test loading CSV files."""
# Create temporary CSV file
data = pd.DataFrame({
'col1': [1, 2, 3],
'col2': ['a', 'b', 'c']
})
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
data.to_csv(f.name, index=False)
temp_path = f.name
try:
loaded_df = await server._load_dataframe(temp_path)
pd.testing.assert_frame_equal(loaded_df, data)
finally:
os.unlink(temp_path)
@pytest.mark.asyncio
async def test_load_dataframe_excel(self, server):
"""Test loading Excel files."""
# Create temporary Excel file
data = pd.DataFrame({
'col1': [1, 2, 3],
'col2': ['a', 'b', 'c']
})
with tempfile.NamedTemporaryFile(suffix='.xlsx', delete=False) as f:
data.to_excel(f.name, index=False)
temp_path = f.name
try:
loaded_df = await server._load_dataframe(temp_path)
pd.testing.assert_frame_equal(loaded_df, data)
finally:
os.unlink(temp_path)
@pytest.mark.asyncio
async def test_load_dataframe_unsupported_format(self, server):
"""Test error handling for unsupported file formats."""
with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:
f.write(b"some text content")
temp_path = f.name
try:
with pytest.raises(ValueError, match="Unsupported file format"):
await server._load_dataframe(temp_path)
finally:
os.unlink(temp_path)
@pytest.mark.asyncio
async def test_load_dataframe_nonexistent_file(self, server):
"""Test error handling for nonexistent files."""
with pytest.raises(ValueError, match="File not found"):
await server._load_dataframe("/nonexistent/path/file.csv")
def test_validate_required_params(self, server):
"""Test parameter validation."""
arguments = {
'param1': 'value1',
'param2': 'value2'
}
# Should not raise for existing parameters
server.validate_required_params(arguments, ['param1', 'param2'])
# Should raise for missing parameters
with pytest.raises(Exception): # MCPToolError
server.validate_required_params(arguments, ['param1', 'param3'])
def test_sanitize_input(self, server):
"""Test input sanitization."""
# String sanitization
assert server.sanitize_input(" test ", "string") == "test"
assert server.sanitize_input(123, "string") == "123"
# Integer sanitization
assert server.sanitize_input("42", "integer") == 42
assert server.sanitize_input(42.7, "integer") == 42
# Float sanitization
assert server.sanitize_input("3.14", "float") == 3.14
assert server.sanitize_input(42, "float") == 42.0
# Boolean sanitization
assert server.sanitize_input("true", "boolean") is True
assert server.sanitize_input(1, "boolean") is True
assert server.sanitize_input(0, "boolean") is False
# None handling
assert server.sanitize_input(None, "string") is None
class TestModelTrainingIntegration:
"""Integration tests for model training functionality."""
@pytest.fixture
def mock_database(self):
"""Create a mock database for testing."""
db = AsyncMock()
db.get_dataset.return_value = {
'id': 'dataset123',
'name': 'test_dataset.csv',
'file_path': '/tmp/test_dataset.csv',
'metadata': {}
}
return db
@pytest.fixture
def user_context(self):
"""Create a test user context."""
return UserContext(
user_id="test_user_123",
email="test@example.com",
permissions=["read", "write"]
)
@pytest.mark.asyncio
async def test_train_models_integration(self, mock_database, user_context):
"""Test the complete model training workflow."""
server = ModelTrainingMCPServer()
# Create sample data file
data = pd.DataFrame({
'feature1': np.random.normal(0, 1, 50),
'feature2': np.random.normal(0, 1, 50),
'target': np.random.choice([0, 1], 50)
})
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
data.to_csv(f.name, index=False)
temp_path = f.name
try:
# Mock database responses
mock_database.get_dataset.return_value = {
'id': 'dataset123',
'name': 'test_dataset.csv',
'file_path': temp_path,
'metadata': {}
}
# Mock database operations
mock_database.execute_query = AsyncMock()
with patch('mcp_servers.model_training.server.get_database', return_value=mock_database):
arguments = {
'dataset_id': 'dataset123',
'target_column': 'target',
'task_type': 'auto',
'algorithms': ['random_forest', 'logistic_regression'],
'test_size': 0.3,
'cv_folds': 3
}
result = await server._train_models(user_context, arguments)
# Verify results
assert 'session_id' in result
assert 'task_type' in result
assert 'models_trained' in result
assert 'best_model_id' in result
assert result['task_type'] == 'classification'
assert result['models_trained'] >= 1
# Verify database calls
assert mock_database.execute_query.call_count >= 2 # Session creation + model storage
finally:
os.unlink(temp_path)
@pytest.mark.asyncio
async def test_explain_predictions_integration(self, mock_database, user_context):
"""Test the prediction explanation workflow."""
server = ModelTrainingMCPServer()
# Create sample model file
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10, random_state=42)
X_sample = np.random.random((20, 3))
y_sample = np.random.choice([0, 1], 20)
model.fit(X_sample, y_sample)
model_data = {
'model': model,
'feature_names': ['feature1', 'feature2', 'feature3'],
'task_type': 'classification',
'target_column': 'target',
'label_encoders': {}
}
with tempfile.NamedTemporaryFile(suffix='.pkl', delete=False) as f:
pickle.dump(model_data, f)
model_path = f.name
# Create sample dataset
data = pd.DataFrame({
'feature1': np.random.normal(0, 1, 20),
'feature2': np.random.normal(0, 1, 20),
'feature3': np.random.normal(0, 1, 20),
'target': np.random.choice([0, 1], 20)
})
with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as f:
data.to_csv(f.name, index=False)
data_path = f.name
try:
# Mock database responses
mock_database.fetch_one.return_value = {
'id': 'model123',
'algorithm': 'random_forest',
'task_type': 'classification',
'target_column': 'target',
'model_file_path': model_path,
'dataset_id': 'dataset123',
'feature_importance': '{"feature1": 0.4, "feature2": 0.3, "feature3": 0.3}'
}
mock_database.get_dataset.return_value = {
'id': 'dataset123',
'name': 'test_dataset.csv',
'file_path': data_path,
'metadata': {}
}
mock_database.execute_query = AsyncMock()
with patch('mcp_servers.model_training.server.get_database', return_value=mock_database):
arguments = {
'model_id': 'model123',
'sample_indices': [0, 1, 2],
'max_samples': 5
}
result = await server._explain_predictions(user_context, arguments)
# Verify results
assert 'model_id' in result
assert 'explanations' in result
assert 'total_explanations' in result
assert result['model_id'] == 'model123'
assert len(result['explanations']) == 3
# Verify explanation structure
for explanation in result['explanations']:
assert 'sample_index' in explanation
assert 'prediction' in explanation
assert 'feature_contributions' in explanation
assert 'explanation_text' in explanation
finally:
os.unlink(model_path)
os.unlink(data_path)
if __name__ == "__main__":
pytest.main([__file__])