ai_data_scientist / tests /test_streamlit_components.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
18.9 kB
"""
UI tests for Streamlit components.
Tests the functionality and behavior of Streamlit dashboard components.
"""
import pytest
import streamlit as st
from unittest.mock import Mock, patch, MagicMock
import pandas as pd
import io
from datetime import datetime
# Import components to test
from streamlit_app.components.file_upload import FileUploadComponent
from streamlit_app.components.business_context import BusinessContextForm
from streamlit_app.components.progress_monitor import ProgressMonitor
from streamlit_app.components.results_viewer import ResultsViewer
from streamlit_app.components.session_manager import SessionManagerComponent
from streamlit_app.components.auth import AuthManager
from streamlit_app.utils.api_client import APIClient
from streamlit_app.utils.sse_client import SSEClient
class TestFileUploadComponent:
"""Test cases for FileUploadComponent."""
def setup_method(self):
"""Set up test fixtures."""
self.component = FileUploadComponent()
def test_init(self):
"""Test component initialization."""
assert self.component.max_size_mb == 100
assert "csv" in self.component.supported_formats
assert "xlsx" in self.component.supported_formats
def test_validate_file_size_limit(self):
"""Test file size validation."""
# Create a mock file that's too large
mock_file = Mock()
mock_file.name = "test.csv"
mock_file.getvalue.return_value = b"x" * (101 * 1024 * 1024) # 101MB
result = self.component._validate_file(mock_file)
assert not result["valid"]
assert "exceeds maximum allowed size" in result["error"]
def test_validate_file_unsupported_format(self):
"""Test validation of unsupported file formats."""
mock_file = Mock()
mock_file.name = "test.txt"
mock_file.getvalue.return_value = b"small file"
result = self.component._validate_file(mock_file)
assert not result["valid"]
assert "Unsupported file format" in result["error"]
@patch('pandas.read_csv')
def test_validate_file_valid_csv(self, mock_read_csv):
"""Test validation of valid CSV file."""
# Mock pandas DataFrame
mock_df = pd.DataFrame({
'col1': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
'col2': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
})
mock_read_csv.return_value = mock_df
mock_file = Mock()
mock_file.name = "test.csv"
mock_file.getvalue.return_value = b"col1,col2\n1,a\n2,b"
mock_file.seek = Mock()
result = self.component._validate_file(mock_file)
assert result["valid"]
assert result["rows"] == 10
assert result["columns"] == 2
@patch('pandas.read_csv')
def test_validate_file_insufficient_data(self, mock_read_csv):
"""Test validation with insufficient data."""
# Mock DataFrame with only 1 column
mock_df = pd.DataFrame({'col1': [1, 2, 3]})
mock_read_csv.return_value = mock_df
mock_file = Mock()
mock_file.name = "test.csv"
mock_file.getvalue.return_value = b"small file"
mock_file.seek = Mock()
result = self.component._validate_file(mock_file)
assert not result["valid"]
assert "must have at least 2 columns" in result["error"]
class TestBusinessContextForm:
"""Test cases for BusinessContextForm."""
def setup_method(self):
"""Set up test fixtures."""
self.component = BusinessContextForm()
def test_init(self):
"""Test component initialization."""
assert "Customer Analytics" in self.component.context_templates
assert "Sales Performance" in self.component.context_templates
assert len(self.component.context_templates) >= 6
def test_validate_responses_insufficient(self):
"""Test validation with insufficient responses."""
responses = {
"question_1": "short",
"question_2": "",
"question_3": "also short"
}
result = self.component._validate_responses(responses)
assert not result
def test_validate_responses_sufficient(self):
"""Test validation with sufficient responses."""
responses = {
"question_1": "This is a detailed response with more than twenty characters",
"question_2": "Another detailed response that meets the minimum length requirement",
"question_3": ""
}
result = self.component._validate_responses(responses)
assert result
def test_compile_context(self):
"""Test context compilation."""
template = "Customer Analytics"
responses = {
"question_1": "We want to understand customer behavior",
"question_2": "Increase customer retention"
}
metadata = {
"industry": "Technology",
"company_size": "Medium (51-200)",
"analysis_urgency": "High - Decision Support",
"data_sensitivity": "Internal",
"success_criteria": "Improve retention by 10%",
"constraints": "Limited budget",
"stakeholders": "Marketing team",
"timeline": "Short-term (1-3 months)"
}
context = self.component._compile_context(template, responses, metadata)
assert "BUSINESS ANALYSIS CONTEXT" in context
assert "Customer Analytics" in context
assert "Technology" in context
assert "We want to understand customer behavior" in context
class TestProgressMonitor:
"""Test cases for ProgressMonitor."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_api_client = Mock(spec=APIClient)
self.mock_sse_client = Mock(spec=SSEClient)
self.component = ProgressMonitor(self.mock_api_client, self.mock_sse_client)
def test_init(self):
"""Test component initialization."""
assert len(self.component.stages) == 6
assert "data_cleaning" in self.component.stages
assert "model_training" in self.component.stages
def test_estimate_remaining_time(self):
"""Test remaining time estimation."""
status = {
"current_stage": "preprocessing",
"stage_progress": {
"data_cleaning": {"status": "completed", "progress": 100},
"hypothesis_testing": {"status": "completed", "progress": 100},
"preprocessing": {"status": "running", "progress": 50}
}
}
remaining = self.component._estimate_remaining_time(status)
# Should include remaining time for current stage + future stages
assert isinstance(remaining, str)
assert "m" in remaining or "s" in remaining
class TestResultsViewer:
"""Test cases for ResultsViewer."""
def setup_method(self):
"""Set up test fixtures."""
self.component = ResultsViewer()
def test_init(self):
"""Test component initialization."""
assert hasattr(self.component, 'chart_colors')
def test_render_with_empty_results(self):
"""Test rendering with empty results."""
with patch('streamlit.error') as mock_error:
self.component.render({})
mock_error.assert_called_once()
def test_render_with_valid_results(self):
"""Test rendering with valid results."""
results = {
"dataset_info": {
"metadata": {"rows": 1000}
},
"model_results": {
"models": [
{
"id": "model_1",
"algorithm": "Random Forest",
"performance": {"accuracy": 0.85}
}
],
"best_model_id": "model_1"
},
"hypothesis_results": [
{
"hypothesis_id": "hyp_1",
"is_significant": True,
"p_value": 0.01
}
],
"recommendations": {
"action_items": [
{"title": "Action 1", "priority": "high"}
]
}
}
# This would normally render in Streamlit context
# For testing, we just verify no exceptions are raised
try:
# Mock streamlit functions that would be called
with patch('streamlit.title'), \
patch('streamlit.metric'), \
patch('streamlit.tabs'), \
patch('streamlit.columns'):
pass # Component methods would be called here in real test
except Exception as e:
pytest.fail(f"Rendering failed with exception: {e}")
class TestSessionManagerComponent:
"""Test cases for SessionManagerComponent."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_api_client = Mock(spec=APIClient)
self.component = SessionManagerComponent(self.mock_api_client)
def test_init(self):
"""Test component initialization."""
assert self.component.api_client == self.mock_api_client
def test_get_user_sessions_success(self):
"""Test successful session retrieval."""
mock_sessions = [
{
"id": "session_1",
"name": "Test Analysis",
"status": "completed",
"created_at": "2024-01-01T10:00:00Z"
}
]
self.mock_api_client.get_user_sessions.return_value = mock_sessions
sessions = self.component._get_user_sessions()
assert len(sessions) == 1
assert sessions[0]["name"] == "Test Analysis"
def test_get_user_sessions_error(self):
"""Test session retrieval with error."""
self.mock_api_client.get_user_sessions.side_effect = Exception("API Error")
with patch('streamlit.error'):
sessions = self.component._get_user_sessions()
assert sessions == []
def test_apply_filters(self):
"""Test session filtering."""
sessions = [
{"id": "1", "status": "completed", "name": "Analysis A"},
{"id": "2", "status": "running", "name": "Analysis B"},
{"id": "3", "status": "failed", "name": "Analysis C"}
]
# Mock session state for filters
with patch('streamlit.session_state', {
"session_status_filter": "completed",
"session_date_filter": "All Time",
"session_sort": "Name (A-Z)"
}):
filtered = self.component._apply_filters(sessions)
# Should only return completed sessions
assert len(filtered) == 1
assert filtered[0]["status"] == "completed"
def test_calculate_duration(self):
"""Test duration calculation."""
session = {
"created_at": "2024-01-01T10:00:00Z",
"completed_at": "2024-01-01T10:05:30Z"
}
duration = self.component._calculate_duration(session)
assert "5m 30s" in duration
class TestAuthManager:
"""Test cases for AuthManager."""
def setup_method(self):
"""Set up test fixtures."""
with patch('streamlit.secrets', {"CLERK_PUBLISHABLE_KEY": "test_key"}):
self.component = AuthManager()
def test_init(self):
"""Test component initialization."""
assert hasattr(self.component, 'clerk_publishable_key')
def test_extract_user_context(self):
"""Test user context extraction."""
token = "mock_jwt_token"
context = self.component._extract_user_context(token)
assert "user_id" in context
assert "email" in context
assert "permissions" in context
@patch('requests.get')
def test_validate_token_success(self, mock_get):
"""Test successful token validation."""
mock_response = Mock()
mock_response.status_code = 200
mock_get.return_value = mock_response
with patch('streamlit.session_state', {}):
result = self.component._validate_token("valid_token")
assert result is True
@patch('requests.get')
def test_validate_token_failure(self, mock_get):
"""Test failed token validation."""
mock_response = Mock()
mock_response.status_code = 401
mock_get.return_value = mock_response
result = self.component._validate_token("invalid_token")
assert result is False
class TestAPIClient:
"""Test cases for APIClient."""
def setup_method(self):
"""Set up test fixtures."""
self.client = APIClient("http://test-api.com")
def test_init(self):
"""Test client initialization."""
assert self.client.base_url == "http://test-api.com"
assert hasattr(self.client, 'session')
def test_get_headers_with_token(self):
"""Test header generation with auth token."""
with patch('streamlit.session_state', {"auth_token": "test_token"}):
headers = self.client._get_headers()
assert headers["Authorization"] == "Bearer test_token"
assert headers["Content-Type"] == "application/json"
def test_get_headers_without_token(self):
"""Test header generation without auth token."""
with patch('streamlit.session_state', {}):
headers = self.client._get_headers()
assert "Authorization" not in headers
assert headers["Content-Type"] == "application/json"
@patch('requests.Session.get')
def test_health_check_success(self, mock_get):
"""Test successful health check."""
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"status": "healthy"}
mock_get.return_value = mock_response
result = self.client.health_check()
assert result["status"] == "healthy"
@patch('requests.Session.get')
def test_health_check_failure(self, mock_get):
"""Test failed health check."""
mock_get.side_effect = Exception("Connection error")
result = self.client.health_check()
assert result["status"] == "unreachable"
assert "Connection error" in result["error"]
class TestSSEClient:
"""Test cases for SSEClient."""
def setup_method(self):
"""Set up test fixtures."""
self.mock_api_client = Mock(spec=APIClient)
self.mock_api_client.base_url = "http://test-api.com"
self.user_context = {"user_id": "test_user"}
with patch('streamlit.session_state', {"sse_updates": {}}):
self.client = SSEClient(self.mock_api_client, self.user_context)
def test_init(self):
"""Test client initialization."""
assert self.client.api_client == self.mock_api_client
assert self.client.user_context == self.user_context
assert not self.client.is_connected
def test_start_monitoring(self):
"""Test starting session monitoring."""
session_id = "test_session"
self.client.start_monitoring(session_id)
assert self.client.monitoring_session == session_id
def test_handle_sse_line_valid_data(self):
"""Test handling valid SSE data."""
line = 'data: {"session_id": "test", "message": "Progress update", "event_type": "info"}'
with patch('streamlit.session_state', {"sse_updates": {}}):
self.client._handle_sse_line(line)
# Verify update was stored (would need to check session state in real test)
def test_handle_sse_line_invalid_data(self):
"""Test handling invalid SSE data."""
line = 'data: invalid json'
# Should not raise exception
try:
self.client._handle_sse_line(line)
except Exception as e:
pytest.fail(f"Should handle invalid JSON gracefully: {e}")
def test_get_updates(self):
"""Test getting updates for session."""
session_id = "test_session"
with patch('streamlit.session_state', {
"sse_updates": {
session_id: [{"message": "test update"}]
}
}):
updates = self.client.get_updates(session_id)
assert len(updates) == 1
assert updates[0]["message"] == "test update"
# Integration test for main dashboard
class TestMainDashboard:
"""Integration tests for main dashboard functionality."""
@patch('streamlit_app.main.APIClient')
@patch('streamlit_app.main.SSEClient')
def test_main_dashboard_flow(self, mock_sse_client, mock_api_client):
"""Test main dashboard initialization and flow."""
# Mock session state
with patch('streamlit.session_state', {
'authenticated': True,
'user_context': {'email': 'test@example.com'},
'current_session': None,
'analysis_results': None,
'sse_client': None
}):
# Mock Streamlit functions
with patch('streamlit.title'), \
patch('streamlit.markdown'), \
patch('streamlit.sidebar'), \
patch('streamlit.selectbox'), \
patch('streamlit.button'), \
patch('streamlit.columns'):
# Import and test main function
from streamlit_app.main import render_main_dashboard
# Should not raise exceptions
try:
render_main_dashboard(mock_api_client.return_value)
except Exception as e:
pytest.fail(f"Main dashboard rendering failed: {e}")
if __name__ == "__main__":
pytest.main([__file__])