""" Unit tests for Hypothesis Testing MCP Server. Tests statistical test implementations and hypothesis generation. """ import pytest import pandas as pd import numpy as np from unittest.mock import AsyncMock, MagicMock, patch from uuid import uuid4 from datetime import datetime from mcp_servers.hypothesis_testing.server import HypothesisTestingMCPServer from shared.models import UserContext, Hypothesis, HypothesisResult, TestType @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 sample_dataframe(): """Create a sample dataframe for testing.""" np.random.seed(42) # Create correlated data n = 100 x1 = np.random.normal(0, 1, n) x2 = 0.7 * x1 + 0.3 * np.random.normal(0, 1, n) # Correlated with x1 x3 = np.random.normal(0, 1, n) # Independent # Create categorical data category = np.random.choice(['A', 'B'], n) category2 = np.random.choice(['X', 'Y', 'Z'], n) # Create group differences numeric_with_groups = np.where(category == 'A', np.random.normal(5, 1, n), np.random.normal(3, 1, n)) df = pd.DataFrame({ 'numeric1': x1, 'numeric2': x2, 'numeric3': x3, 'category1': category, 'category2': category2, 'numeric_with_groups': numeric_with_groups }) return df @pytest.fixture def hypothesis_server(): """Create a hypothesis testing server instance.""" return HypothesisTestingMCPServer() class TestHypothesisGeneration: """Test hypothesis generation functionality.""" @pytest.mark.asyncio async def test_generate_hypotheses_correlation(self, hypothesis_server, user_context, sample_dataframe): """Test generation of correlation hypotheses.""" # Mock database operations with patch('mcp_servers.hypothesis_testing.server.get_database') as mock_db: mock_db_instance = AsyncMock() mock_db.return_value = mock_db_instance # Mock dataset retrieval mock_db_instance.get_dataset.return_value = { 'id': 'test_dataset', 'file_path': '/fake/path/test.csv' } # Mock hypothesis creation mock_db_instance.create_hypothesis.side_effect = lambda ctx, hyp: str(hyp.id) # Mock dataframe loading with patch.object(hypothesis_server, '_load_dataframe', return_value=sample_dataframe): arguments = { 'dataset_id': 'test_dataset', 'business_context': 'Test business context', 'max_hypotheses': 5 } result = await hypothesis_server._generate_hypotheses(user_context, arguments) # Verify results assert 'hypotheses_generated' in result assert 'hypotheses' in result assert result['hypotheses_generated'] > 0 assert len(result['hypotheses']) <= 5 # Check that correlation hypotheses were generated correlation_hypotheses = [h for h in result['hypotheses'] if h['test_type'] == 'correlation'] assert len(correlation_hypotheses) > 0 @pytest.mark.asyncio async def test_generate_hypotheses_group_comparison(self, hypothesis_server, user_context, sample_dataframe): """Test generation of group comparison hypotheses.""" with patch('mcp_servers.hypothesis_testing.server.get_database') as mock_db: mock_db_instance = AsyncMock() mock_db.return_value = mock_db_instance mock_db_instance.get_dataset.return_value = { 'id': 'test_dataset', 'file_path': '/fake/path/test.csv' } mock_db_instance.create_hypothesis.side_effect = lambda ctx, hyp: str(hyp.id) with patch.object(hypothesis_server, '_load_dataframe', return_value=sample_dataframe): arguments = { 'dataset_id': 'test_dataset', 'business_context': 'Test business context', 'max_hypotheses': 20 } result = await hypothesis_server._generate_hypotheses(user_context, arguments) # Check that t-test hypotheses were generated t_test_hypotheses = [h for h in result['hypotheses'] if h['test_type'] == 't_test'] assert len(t_test_hypotheses) > 0 # Check that ANOVA hypotheses were generated (or at least some group comparison tests) anova_hypotheses = [h for h in result['hypotheses'] if h['test_type'] == 'anova'] group_comparison_hypotheses = [h for h in result['hypotheses'] if h['test_type'] in ['t_test', 'anova']] # Should have at least some group comparison tests assert len(group_comparison_hypotheses) > 0 class TestStatisticalTests: """Test statistical test implementations.""" @pytest.mark.asyncio async def test_correlation_test(self, hypothesis_server, sample_dataframe): """Test correlation test implementation.""" hypothesis = { 'id': str(uuid4()), 'test_type': 'correlation', 'variables': ['numeric1', 'numeric2'] } result = await hypothesis_server._execute_statistical_test( sample_dataframe, hypothesis, 0.05 ) assert isinstance(result, HypothesisResult) assert str(result.hypothesis_id) == hypothesis['id'] assert 0 <= result.p_value <= 1 assert isinstance(result.is_significant, bool) assert result.effect_size is not None assert result.test_statistic is not None assert len(result.interpretation) > 0 # Since numeric1 and numeric2 are correlated, should be significant assert result.is_significant == True assert result.effect_size > 0.5 # Strong correlation @pytest.mark.asyncio async def test_t_test(self, hypothesis_server, sample_dataframe): """Test t-test implementation.""" hypothesis = { 'id': str(uuid4()), 'test_type': 't_test', 'variables': ['category1', 'numeric_with_groups'] } result = await hypothesis_server._execute_statistical_test( sample_dataframe, hypothesis, 0.05 ) assert isinstance(result, HypothesisResult) assert str(result.hypothesis_id) == hypothesis['id'] assert 0 <= result.p_value <= 1 assert isinstance(result.is_significant, bool) assert result.effect_size is not None assert result.test_statistic is not None # Since we created group differences, should be significant assert result.is_significant == True @pytest.mark.asyncio async def test_anova_test(self, hypothesis_server, sample_dataframe): """Test ANOVA implementation.""" hypothesis = { 'id': str(uuid4()), 'test_type': 'anova', 'variables': ['category2', 'numeric1'] } result = await hypothesis_server._execute_statistical_test( sample_dataframe, hypothesis, 0.05 ) assert isinstance(result, HypothesisResult) assert str(result.hypothesis_id) == hypothesis['id'] assert 0 <= result.p_value <= 1 assert isinstance(result.is_significant, bool) assert result.effect_size is not None assert result.test_statistic is not None @pytest.mark.asyncio async def test_chi_square_test(self, hypothesis_server, sample_dataframe): """Test chi-square test implementation.""" hypothesis = { 'id': str(uuid4()), 'test_type': 'chi_square', 'variables': ['category1', 'category2'] } result = await hypothesis_server._execute_statistical_test( sample_dataframe, hypothesis, 0.05 ) assert isinstance(result, HypothesisResult) assert str(result.hypothesis_id) == hypothesis['id'] assert 0 <= result.p_value <= 1 assert isinstance(result.is_significant, bool) assert result.effect_size is not None assert result.test_statistic is not None class TestHypothesisTestingTools: """Test MCP tool implementations.""" @pytest.mark.asyncio async def test_test_hypothesis_tool(self, hypothesis_server, user_context, sample_dataframe): """Test the test_hypothesis tool.""" with patch('mcp_servers.hypothesis_testing.server.get_database') as mock_db: mock_db_instance = AsyncMock() mock_db.return_value = mock_db_instance # Mock hypothesis retrieval hypothesis_data = { 'id': 'test_hypothesis', 'dataset_id': 'test_dataset', 'test_type': 'correlation', 'variables': ['numeric1', 'numeric2'], 'text': 'Test hypothesis' } mock_db_instance.get_hypothesis.return_value = hypothesis_data # Mock dataset retrieval mock_db_instance.get_dataset.return_value = { 'id': 'test_dataset', 'file_path': '/fake/path/test.csv' } # Mock result creation mock_db_instance.create_hypothesis_result.return_value = 'result_id' with patch.object(hypothesis_server, '_load_dataframe', return_value=sample_dataframe): arguments = { 'hypothesis_id': 'test_hypothesis', 'significance_level': 0.05 } result = await hypothesis_server._test_hypothesis(user_context, arguments) assert 'hypothesis_id' in result assert 'p_value' in result assert 'is_significant' in result assert 'interpretation' in result @pytest.mark.asyncio async def test_get_validated_hypotheses_tool(self, hypothesis_server, user_context): """Test the get_validated_hypotheses tool.""" with patch('mcp_servers.hypothesis_testing.server.get_database') as mock_db: mock_db_instance = AsyncMock() mock_db.return_value = mock_db_instance # Mock validated hypotheses validated_hypotheses = [ { 'id': 'hyp1', 'text': 'Hypothesis 1', 'is_significant': True }, { 'id': 'hyp2', 'text': 'Hypothesis 2', 'is_significant': True } ] mock_db_instance.get_validated_hypotheses.return_value = validated_hypotheses arguments = {'dataset_id': 'test_dataset'} result = await hypothesis_server._get_validated_hypotheses(user_context, arguments) assert 'dataset_id' in result assert 'validated_count' in result assert 'hypotheses' in result assert result['validated_count'] == 2 assert len(result['hypotheses']) == 2 class TestStatisticalTestEdgeCases: """Test edge cases and error handling in statistical tests.""" @pytest.mark.asyncio async def test_correlation_insufficient_data(self, hypothesis_server): """Test correlation with insufficient data.""" # Create dataframe with only 2 rows df = pd.DataFrame({ 'x': [1, 2], 'y': [3, 4] }) hypothesis = { 'id': str(uuid4()), 'test_type': 'correlation', 'variables': ['x', 'y'] } result = await hypothesis_server._execute_statistical_test(df, hypothesis, 0.05) # Should handle gracefully and return non-significant result assert isinstance(result, HypothesisResult) assert not result.is_significant @pytest.mark.asyncio async def test_t_test_wrong_group_count(self, hypothesis_server): """Test t-test with wrong number of groups.""" # Create dataframe with 3 groups instead of 2 df = pd.DataFrame({ 'group': ['A', 'B', 'C'] * 10, 'value': np.random.normal(0, 1, 30) }) hypothesis = { 'id': str(uuid4()), 'test_type': 't_test', 'variables': ['group', 'value'] } result = await hypothesis_server._execute_statistical_test(df, hypothesis, 0.05) # Should handle gracefully and return non-significant result assert isinstance(result, HypothesisResult) assert not result.is_significant @pytest.mark.asyncio async def test_missing_variables(self, hypothesis_server, sample_dataframe): """Test with missing variables.""" hypothesis = { 'id': str(uuid4()), 'test_type': 'correlation', 'variables': ['nonexistent1', 'nonexistent2'] } result = await hypothesis_server._execute_statistical_test( sample_dataframe, hypothesis, 0.05 ) # Should handle gracefully and return non-significant result assert isinstance(result, HypothesisResult) assert not result.is_significant class TestInterpretations: """Test interpretation generation for statistical tests.""" def test_correlation_interpretation_significant(self, hypothesis_server): """Test correlation interpretation for significant result.""" interpretation = hypothesis_server._interpret_correlation_result( correlation=0.8, p_value=0.001, is_significant=True, var1='x', var2='y' ) assert 'significant' in interpretation.lower() assert 'strong' in interpretation.lower() assert 'positive' in interpretation.lower() assert 'x' in interpretation assert 'y' in interpretation def test_correlation_interpretation_not_significant(self, hypothesis_server): """Test correlation interpretation for non-significant result.""" interpretation = hypothesis_server._interpret_correlation_result( correlation=0.1, p_value=0.5, is_significant=False, var1='x', var2='y' ) assert 'no statistically significant' in interpretation.lower() assert 'random variation' in interpretation.lower() def test_t_test_interpretation(self, hypothesis_server): """Test t-test interpretation.""" interpretation = hypothesis_server._interpret_t_test_result( t_stat=3.5, p_value=0.001, is_significant=True, groups=['A', 'B'], mean1=5.0, mean2=3.0, group_var='category', numeric_var='value' ) assert 'significant difference' in interpretation.lower() assert 'category' in interpretation assert 'value' in interpretation assert '5.0' in interpretation or '5.000' in interpretation assert '3.0' in interpretation or '3.000' in interpretation if __name__ == "__main__": pytest.main([__file__])