ai_data_scientist / tests /test_models.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
17.8 kB
"""
Unit tests for shared data models and validation schemas.
"""
import pytest
from datetime import datetime
from uuid import UUID, uuid4
from pydantic import ValidationError
from shared.models import (
AnalysisStatus, TaskType, TestType, UserContext, DatasetInfo,
DataQualityReport, CleaningOperation, CleaningSummary, Hypothesis,
HypothesisResult, PreprocessingPlan, FeatureMapping, FeatureSet,
FeatureExplanation, ModelPerformance, TrainedModel, ModelResults,
PredictionExplanation, KeyInsight, ActionItem, KPIRecommendation,
BusinessRecommendations, ExecutiveSummary, AnalysisSession,
AnalysisResult, SSEEvent, MCPToolResult, MCPServerHealth
)
class TestEnums:
"""Test enum definitions."""
def test_analysis_status_enum(self):
"""Test AnalysisStatus enum values."""
assert AnalysisStatus.PENDING == "pending"
assert AnalysisStatus.RUNNING == "running"
assert AnalysisStatus.COMPLETED == "completed"
assert AnalysisStatus.FAILED == "failed"
assert AnalysisStatus.CANCELLED == "cancelled"
def test_task_type_enum(self):
"""Test TaskType enum values."""
assert TaskType.CLASSIFICATION == "classification"
assert TaskType.REGRESSION == "regression"
def test_test_type_enum(self):
"""Test TestType enum values."""
assert TestType.CHI_SQUARE == "chi_square"
assert TestType.T_TEST == "t_test"
assert TestType.ANOVA == "anova"
assert TestType.CORRELATION == "correlation"
class TestUserContext:
"""Test UserContext model."""
def test_user_context_creation(self):
"""Test creating a UserContext."""
context = UserContext(
user_id="test_user_123",
email="test@example.com",
permissions=["read", "write"]
)
assert context.user_id == "test_user_123"
assert context.email == "test@example.com"
assert context.permissions == ["read", "write"]
def test_user_context_minimal(self):
"""Test creating UserContext with minimal data."""
context = UserContext(user_id="test_user_123")
assert context.user_id == "test_user_123"
assert context.email is None
assert context.permissions == []
def test_user_context_validation_error(self):
"""Test UserContext validation error."""
with pytest.raises(ValidationError):
UserContext() # Missing required user_id
class TestDatasetInfo:
"""Test DatasetInfo model."""
def test_dataset_info_creation(self):
"""Test creating a DatasetInfo."""
dataset_id = uuid4()
created_at = datetime.utcnow()
dataset = DatasetInfo(
id=dataset_id,
user_id="test_user_123",
name="test_dataset.csv",
file_path="/uploads/test_dataset.csv",
metadata={"rows": 1000, "columns": 10},
created_at=created_at
)
assert dataset.id == dataset_id
assert dataset.user_id == "test_user_123"
assert dataset.name == "test_dataset.csv"
assert dataset.file_path == "/uploads/test_dataset.csv"
assert dataset.metadata == {"rows": 1000, "columns": 10}
assert dataset.created_at == created_at
def test_dataset_info_defaults(self):
"""Test DatasetInfo with default values."""
dataset = DatasetInfo(
user_id="test_user_123",
name="test_dataset.csv",
file_path="/uploads/test_dataset.csv"
)
assert isinstance(dataset.id, UUID)
assert dataset.metadata == {}
assert isinstance(dataset.created_at, datetime)
def test_dataset_info_json_encoding(self):
"""Test DatasetInfo JSON encoding."""
dataset = DatasetInfo(
user_id="test_user_123",
name="test_dataset.csv",
file_path="/uploads/test_dataset.csv"
)
json_data = dataset.dict()
assert isinstance(json_data["id"], UUID)
assert isinstance(json_data["created_at"], datetime)
class TestDataQualityReport:
"""Test DataQualityReport model."""
def test_data_quality_report_creation(self):
"""Test creating a DataQualityReport."""
report = DataQualityReport(
missing_values={"col1": 5, "col2": 0},
outliers={"col1": [1.5, 2.8], "col2": []},
data_types={"col1": "float64", "col2": "object"},
statistics={"mean_col1": 10.5},
recommendations=["Remove outliers", "Impute missing values"],
total_rows=1000,
total_columns=10
)
assert report.missing_values == {"col1": 5, "col2": 0}
assert report.outliers == {"col1": [1.5, 2.8], "col2": []}
assert report.total_rows == 1000
assert report.total_columns == 10
assert len(report.recommendations) == 2
def test_data_quality_report_defaults(self):
"""Test DataQualityReport with default values."""
report = DataQualityReport()
assert report.missing_values == {}
assert report.outliers == {}
assert report.data_types == {}
assert report.statistics == {}
assert report.recommendations == []
assert report.total_rows == 0
assert report.total_columns == 0
class TestHypothesis:
"""Test Hypothesis model."""
def test_hypothesis_creation(self):
"""Test creating a Hypothesis."""
hypothesis_id = uuid4()
dataset_id = uuid4()
hypothesis = Hypothesis(
id=hypothesis_id,
text="Age is correlated with income",
test_type=TestType.CORRELATION,
variables=["age", "income"],
expected_outcome="Positive correlation",
python_code="correlation_test(age, income)",
business_relevance="High",
dataset_id=dataset_id
)
assert hypothesis.id == hypothesis_id
assert hypothesis.text == "Age is correlated with income"
assert hypothesis.test_type == TestType.CORRELATION
assert hypothesis.variables == ["age", "income"]
assert hypothesis.dataset_id == dataset_id
def test_hypothesis_defaults(self):
"""Test Hypothesis with default values."""
dataset_id = uuid4()
hypothesis = Hypothesis(
text="Test hypothesis",
test_type=TestType.T_TEST,
variables=["var1"],
expected_outcome="Significant difference",
business_relevance="Medium",
dataset_id=dataset_id
)
assert isinstance(hypothesis.id, UUID)
assert hypothesis.python_code is None
class TestHypothesisResult:
"""Test HypothesisResult model."""
def test_hypothesis_result_creation(self):
"""Test creating a HypothesisResult."""
hypothesis_id = uuid4()
result = HypothesisResult(
hypothesis_id=hypothesis_id,
p_value=0.025,
is_significant=True,
confidence_interval=(0.1, 0.8),
effect_size=0.5,
interpretation="Statistically significant positive correlation",
test_statistic=2.45
)
assert result.hypothesis_id == hypothesis_id
assert result.p_value == 0.025
assert result.is_significant is True
assert result.confidence_interval == (0.1, 0.8)
assert result.effect_size == 0.5
assert result.test_statistic == 2.45
def test_hypothesis_result_minimal(self):
"""Test HypothesisResult with minimal data."""
hypothesis_id = uuid4()
result = HypothesisResult(
hypothesis_id=hypothesis_id,
p_value=0.15,
is_significant=False,
interpretation="Not statistically significant"
)
assert result.confidence_interval is None
assert result.effect_size is None
assert result.test_statistic is None
class TestModelPerformance:
"""Test ModelPerformance model."""
def test_model_performance_classification(self):
"""Test ModelPerformance for classification."""
performance = ModelPerformance(
accuracy=0.85,
precision=0.82,
recall=0.88,
f1_score=0.85,
roc_auc=0.90,
cross_val_scores=[0.83, 0.87, 0.84, 0.86, 0.85]
)
assert performance.accuracy == 0.85
assert performance.precision == 0.82
assert performance.recall == 0.88
assert performance.f1_score == 0.85
assert performance.roc_auc == 0.90
assert len(performance.cross_val_scores) == 5
# Regression metrics should be None
assert performance.rmse is None
assert performance.mae is None
assert performance.r2_score is None
def test_model_performance_regression(self):
"""Test ModelPerformance for regression."""
performance = ModelPerformance(
rmse=2.5,
mae=1.8,
r2_score=0.75,
cross_val_scores=[0.72, 0.78, 0.74, 0.76, 0.75]
)
assert performance.rmse == 2.5
assert performance.mae == 1.8
assert performance.r2_score == 0.75
# Classification metrics should be None
assert performance.accuracy is None
assert performance.precision is None
assert performance.recall is None
class TestTrainedModel:
"""Test TrainedModel model."""
def test_trained_model_creation(self):
"""Test creating a TrainedModel."""
model_id = uuid4()
performance = ModelPerformance(accuracy=0.85, f1_score=0.83)
model = TrainedModel(
id=model_id,
algorithm="RandomForest",
hyperparameters={"n_estimators": 100, "max_depth": 10},
performance=performance,
feature_importance={"feature1": 0.3, "feature2": 0.7},
training_time_seconds=45.2
)
assert model.id == model_id
assert model.algorithm == "RandomForest"
assert model.hyperparameters["n_estimators"] == 100
assert model.performance == performance
assert model.feature_importance["feature2"] == 0.7
assert model.training_time_seconds == 45.2
def test_trained_model_defaults(self):
"""Test TrainedModel with default values."""
performance = ModelPerformance(accuracy=0.85)
model = TrainedModel(
algorithm="LogisticRegression",
performance=performance,
training_time_seconds=12.5
)
assert isinstance(model.id, UUID)
assert model.hyperparameters == {}
assert model.feature_importance == {}
class TestBusinessRecommendations:
"""Test BusinessRecommendations model."""
def test_business_recommendations_creation(self):
"""Test creating BusinessRecommendations."""
insights = [
KeyInsight(
title="Customer Segmentation",
description="Three distinct customer segments identified",
confidence_score=0.85,
supporting_evidence=["Statistical analysis", "Domain expertise"]
)
]
actions = [
ActionItem(
title="Implement targeted marketing",
description="Create segment-specific campaigns",
priority="high",
estimated_impact="20% increase in conversion",
implementation_timeline="2-3 months",
required_resources=["Marketing team", "Data analyst"]
)
]
kpis = [
KPIRecommendation(
kpi_name="Conversion Rate",
current_value=0.05,
target_value=0.06,
improvement_strategy="Targeted campaigns",
measurement_method="A/B testing"
)
]
recommendations = BusinessRecommendations(
key_insights=insights,
action_items=actions,
kpi_recommendations=kpis,
timeline="3 months",
confidence_score=0.82
)
assert len(recommendations.key_insights) == 1
assert len(recommendations.action_items) == 1
assert len(recommendations.kpi_recommendations) == 1
assert recommendations.timeline == "3 months"
assert recommendations.confidence_score == 0.82
class TestAnalysisSession:
"""Test AnalysisSession model."""
def test_analysis_session_creation(self):
"""Test creating an AnalysisSession."""
session_id = uuid4()
started_at = datetime.utcnow()
session = AnalysisSession(
id=session_id,
user_id="test_user_123",
name="Customer Analysis",
business_context="Analyze customer behavior patterns",
status=AnalysisStatus.RUNNING,
started_at=started_at
)
assert session.id == session_id
assert session.user_id == "test_user_123"
assert session.name == "Customer Analysis"
assert session.status == AnalysisStatus.RUNNING
assert session.started_at == started_at
assert session.completed_at is None
assert session.error_message is None
def test_analysis_session_defaults(self):
"""Test AnalysisSession with default values."""
session = AnalysisSession(
user_id="test_user_123",
name="Test Analysis",
business_context="Test context"
)
assert isinstance(session.id, UUID)
assert session.status == AnalysisStatus.PENDING
assert isinstance(session.started_at, datetime)
class TestMCPToolResult:
"""Test MCPToolResult model."""
def test_mcp_tool_result_success(self):
"""Test successful MCPToolResult."""
result = MCPToolResult(
success=True,
data={"result": "success", "value": 42},
execution_time_ms=150.5
)
assert result.success is True
assert result.data == {"result": "success", "value": 42}
assert result.error_message is None
assert result.execution_time_ms == 150.5
def test_mcp_tool_result_error(self):
"""Test error MCPToolResult."""
result = MCPToolResult(
success=False,
error_message="Tool execution failed",
execution_time_ms=75.2
)
assert result.success is False
assert result.data is None
assert result.error_message == "Tool execution failed"
assert result.execution_time_ms == 75.2
class TestMCPServerHealth:
"""Test MCPServerHealth model."""
def test_mcp_server_health_healthy(self):
"""Test healthy MCPServerHealth."""
last_check = datetime.utcnow()
health = MCPServerHealth(
server_name="data_cleaning_mcp",
is_healthy=True,
response_time_ms=25.5,
last_check=last_check
)
assert health.server_name == "data_cleaning_mcp"
assert health.is_healthy is True
assert health.response_time_ms == 25.5
assert health.last_check == last_check
assert health.error_message is None
def test_mcp_server_health_unhealthy(self):
"""Test unhealthy MCPServerHealth."""
health = MCPServerHealth(
server_name="model_training_mcp",
is_healthy=False,
response_time_ms=1000.0,
error_message="Database connection timeout"
)
assert health.server_name == "model_training_mcp"
assert health.is_healthy is False
assert health.response_time_ms == 1000.0
assert health.error_message == "Database connection timeout"
assert isinstance(health.last_check, datetime)
class TestSSEEvent:
"""Test SSEEvent model."""
def test_sse_event_creation(self):
"""Test creating an SSEEvent."""
timestamp = datetime.utcnow()
event = SSEEvent(
event_type="analysis_progress",
data={"stage": "data_cleaning", "progress": 0.5},
timestamp=timestamp
)
assert event.event_type == "analysis_progress"
assert event.data == {"stage": "data_cleaning", "progress": 0.5}
assert event.timestamp == timestamp
def test_sse_event_defaults(self):
"""Test SSEEvent with default timestamp."""
event = SSEEvent(
event_type="error",
data={"message": "Processing failed"}
)
assert event.event_type == "error"
assert event.data == {"message": "Processing failed"}
assert isinstance(event.timestamp, datetime)
if __name__ == "__main__":
pytest.main([__file__])