""" Unit tests for Streamlit components. Tests individual Streamlit functions and classes in isolation. """ import pytest from unittest.mock import Mock, patch, MagicMock import pandas as pd import json from datetime import datetime import streamlit as st # Import Streamlit components from streamlit_app.components.file_uploader import FileUploader, validate_uploaded_file from streamlit_app.components.progress_monitor import ProgressMonitor, ProgressDisplay from streamlit_app.components.results_viewer import ResultsViewer, format_results from streamlit_app.components.business_context import BusinessContextForm from streamlit_app.utils.api_client import APIClient, APIError from streamlit_app.utils.data_formatter import DataFormatter from streamlit_app.utils.chart_generator import ChartGenerator @pytest.mark.unit class TestFileUploader: """Test FileUploader component.""" def test_file_uploader_initialization(self): """Test FileUploader initialization.""" uploader = FileUploader() assert hasattr(uploader, 'allowed_extensions') assert hasattr(uploader, 'max_file_size') def test_validate_uploaded_file_success(self): """Test successful file validation.""" # Mock uploaded file mock_file = Mock() mock_file.name = "test.csv" mock_file.size = 1024 * 1024 # 1MB mock_file.read.return_value = b"col1,col2\n1,2\n3,4" result = validate_uploaded_file(mock_file) assert result['valid'] is True assert result['file_type'] == 'csv' assert result['size'] == 1024 * 1024 def test_validate_uploaded_file_invalid_extension(self): """Test file validation with invalid extension.""" mock_file = Mock() mock_file.name = "test.txt" mock_file.size = 1024 result = validate_uploaded_file(mock_file) assert result['valid'] is False assert 'extension' in result['error'].lower() def test_validate_uploaded_file_too_large(self): """Test file validation with file too large.""" mock_file = Mock() mock_file.name = "test.csv" mock_file.size = 200 * 1024 * 1024 # 200MB result = validate_uploaded_file(mock_file) assert result['valid'] is False assert 'size' in result['error'].lower() @patch('streamlit.file_uploader') def test_render_file_uploader(self, mock_st_uploader): """Test rendering file uploader component.""" mock_st_uploader.return_value = None uploader = FileUploader() result = uploader.render() mock_st_uploader.assert_called_once() assert result is None # No file uploaded @patch('streamlit.file_uploader') def test_render_file_uploader_with_file(self, mock_st_uploader): """Test rendering file uploader with uploaded file.""" mock_file = Mock() mock_file.name = "test.csv" mock_file.size = 1024 mock_file.read.return_value = b"col1,col2\n1,2\n3,4" mock_st_uploader.return_value = mock_file uploader = FileUploader() result = uploader.render() assert result is not None assert result['file'] == mock_file @pytest.mark.unit class TestProgressMonitor: """Test ProgressMonitor component.""" def test_progress_monitor_initialization(self): """Test ProgressMonitor initialization.""" monitor = ProgressMonitor() assert hasattr(monitor, 'current_stage') assert hasattr(monitor, 'progress_value') def test_progress_display_creation(self): """Test ProgressDisplay creation.""" display = ProgressDisplay( stage="data_cleaning", progress=50.0, message="Cleaning data...", timestamp=datetime.now() ) assert display.stage == "data_cleaning" assert display.progress == 50.0 assert display.message == "Cleaning data..." assert isinstance(display.timestamp, datetime) @patch('streamlit.progress') @patch('streamlit.text') def test_render_progress_monitor(self, mock_st_text, mock_st_progress): """Test rendering progress monitor.""" monitor = ProgressMonitor() progress_data = ProgressDisplay( stage="preprocessing", progress=75.0, message="Preprocessing data..." ) monitor.render(progress_data) mock_st_progress.assert_called_once_with(0.75) mock_st_text.assert_called() def test_update_progress(self): """Test updating progress.""" monitor = ProgressMonitor() monitor.update_progress("feature_engineering", 60.0, "Engineering features...") assert monitor.current_stage == "feature_engineering" assert monitor.progress_value == 60.0 def test_stage_name_formatting(self): """Test stage name formatting.""" monitor = ProgressMonitor() formatted = monitor.format_stage_name("data_cleaning") assert formatted == "Data Cleaning" formatted = monitor.format_stage_name("hypothesis_testing") assert formatted == "Hypothesis Testing" @pytest.mark.unit class TestResultsViewer: """Test ResultsViewer component.""" def test_results_viewer_initialization(self): """Test ResultsViewer initialization.""" viewer = ResultsViewer() assert hasattr(viewer, 'render_results') assert hasattr(viewer, 'format_insights') def test_format_results_success(self): """Test formatting successful results.""" raw_results = { "status": "completed", "insights": [ {"text": "Key insight 1", "confidence": 0.9}, {"text": "Key insight 2", "confidence": 0.8} ], "recommendations": [ {"action": "Increase marketing budget", "impact": "high"}, {"action": "Optimize pricing", "impact": "medium"} ], "model_performance": { "accuracy": 0.85, "precision": 0.82, "recall": 0.88 } } formatted = format_results(raw_results) assert formatted['status'] == 'completed' assert len(formatted['insights']) == 2 assert len(formatted['recommendations']) == 2 assert 'model_performance' in formatted def test_format_results_error(self): """Test formatting error results.""" raw_results = { "status": "error", "error_message": "Analysis failed", "error_code": "PROCESSING_ERROR" } formatted = format_results(raw_results) assert formatted['status'] == 'error' assert formatted['error_message'] == "Analysis failed" @patch('streamlit.subheader') @patch('streamlit.write') def test_render_insights(self, mock_st_write, mock_st_subheader): """Test rendering insights section.""" viewer = ResultsViewer() insights = [ {"text": "Revenue increased by 15%", "confidence": 0.9}, {"text": "Customer satisfaction improved", "confidence": 0.8} ] viewer.render_insights(insights) mock_st_subheader.assert_called_with("🔍 Key Insights") assert mock_st_write.call_count >= len(insights) @patch('streamlit.subheader') @patch('streamlit.write') def test_render_recommendations(self, mock_st_write, mock_st_subheader): """Test rendering recommendations section.""" viewer = ResultsViewer() recommendations = [ {"action": "Increase marketing spend", "impact": "high", "timeline": "Q1"}, {"action": "Optimize pricing strategy", "impact": "medium", "timeline": "Q2"} ] viewer.render_recommendations(recommendations) mock_st_subheader.assert_called_with("💡 Recommendations") assert mock_st_write.call_count >= len(recommendations) @pytest.mark.unit class TestBusinessContextForm: """Test BusinessContextForm component.""" def test_business_context_form_initialization(self): """Test BusinessContextForm initialization.""" form = BusinessContextForm() assert hasattr(form, 'render_form') assert hasattr(form, 'validate_context') @patch('streamlit.text_area') @patch('streamlit.selectbox') @patch('streamlit.multiselect') def test_render_form(self, mock_multiselect, mock_selectbox, mock_text_area): """Test rendering business context form.""" mock_text_area.return_value = "Test business context" mock_selectbox.return_value = "retail" mock_multiselect.return_value = ["revenue", "customer_satisfaction"] form = BusinessContextForm() result = form.render_form() assert result['context'] == "Test business context" assert result['industry'] == "retail" assert result['kpis'] == ["revenue", "customer_satisfaction"] def test_validate_context_success(self): """Test successful context validation.""" form = BusinessContextForm() context_data = { 'context': 'We want to improve customer retention', 'industry': 'retail', 'kpis': ['retention_rate', 'customer_lifetime_value'] } result = form.validate_context(context_data) assert result['valid'] is True assert 'error' not in result def test_validate_context_missing_data(self): """Test context validation with missing data.""" form = BusinessContextForm() context_data = { 'context': '', # Empty context 'industry': 'retail', 'kpis': [] } result = form.validate_context(context_data) assert result['valid'] is False assert 'error' in result @pytest.mark.unit class TestAPIClient: """Test APIClient utility.""" def test_api_client_initialization(self): """Test APIClient initialization.""" client = APIClient(base_url="http://localhost:8000") assert client.base_url == "http://localhost:8000" assert hasattr(client, 'session') @patch('requests.Session.post') def test_start_analysis_success(self, mock_post): """Test successful analysis start.""" mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = { "session_id": "test_session_123", "status": "started" } mock_post.return_value = mock_response client = APIClient() result = client.start_analysis( file_data=b"test,data\n1,2", filename="test.csv", business_context="Test context" ) assert result['session_id'] == "test_session_123" assert result['status'] == "started" @patch('requests.Session.post') def test_start_analysis_error(self, mock_post): """Test analysis start with error.""" mock_response = Mock() mock_response.status_code = 400 mock_response.json.return_value = {"error": "Invalid file format"} mock_post.return_value = mock_response client = APIClient() with pytest.raises(APIError): client.start_analysis( file_data=b"invalid data", filename="test.txt", business_context="Test context" ) @patch('requests.Session.get') def test_get_analysis_status(self, mock_get): """Test getting analysis status.""" mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = { "session_id": "test_session_123", "status": "running", "progress": 50.0, "current_stage": "preprocessing" } mock_get.return_value = mock_response client = APIClient() result = client.get_analysis_status("test_session_123") assert result['status'] == "running" assert result['progress'] == 50.0 @pytest.mark.unit class TestDataFormatter: """Test DataFormatter utility.""" def test_data_formatter_initialization(self): """Test DataFormatter initialization.""" formatter = DataFormatter() assert hasattr(formatter, 'format_dataframe') assert hasattr(formatter, 'format_metrics') def test_format_dataframe(self): """Test DataFrame formatting.""" df = pd.DataFrame({ 'column1': [1, 2, 3], 'column2': ['A', 'B', 'C'], 'column3': [1.234, 2.567, 3.890] }) formatter = DataFormatter() formatted = formatter.format_dataframe(df) assert isinstance(formatted, pd.DataFrame) assert len(formatted) == 3 assert len(formatted.columns) == 3 def test_format_metrics(self): """Test metrics formatting.""" metrics = { 'accuracy': 0.8567, 'precision': 0.7834, 'recall': 0.9123, 'f1_score': 0.8421 } formatter = DataFormatter() formatted = formatter.format_metrics(metrics) assert isinstance(formatted, dict) assert all(isinstance(v, str) for v in formatted.values()) assert '85.67%' in formatted['accuracy'] def test_format_currency(self): """Test currency formatting.""" formatter = DataFormatter() formatted = formatter.format_currency(1234.56) assert formatted == "$1,234.56" formatted = formatter.format_currency(1000000) assert formatted == "$1,000,000.00" def test_format_percentage(self): """Test percentage formatting.""" formatter = DataFormatter() formatted = formatter.format_percentage(0.1234) assert formatted == "12.34%" formatted = formatter.format_percentage(0.5) assert formatted == "50.00%" @pytest.mark.unit class TestChartGenerator: """Test ChartGenerator utility.""" def test_chart_generator_initialization(self): """Test ChartGenerator initialization.""" generator = ChartGenerator() assert hasattr(generator, 'create_bar_chart') assert hasattr(generator, 'create_line_chart') def test_create_bar_chart(self): """Test bar chart creation.""" data = pd.DataFrame({ 'category': ['A', 'B', 'C', 'D'], 'value': [10, 20, 15, 25] }) generator = ChartGenerator() chart = generator.create_bar_chart(data, x='category', y='value') # Chart should be a valid Altair chart object assert hasattr(chart, 'mark_bar') def test_create_line_chart(self): """Test line chart creation.""" data = pd.DataFrame({ 'date': pd.date_range('2023-01-01', periods=10), 'value': [i * 2 for i in range(10)] }) generator = ChartGenerator() chart = generator.create_line_chart(data, x='date', y='value') # Chart should be a valid Altair chart object assert hasattr(chart, 'mark_line') def test_create_scatter_plot(self): """Test scatter plot creation.""" data = pd.DataFrame({ 'x': [1, 2, 3, 4, 5], 'y': [2, 4, 1, 5, 3] }) generator = ChartGenerator() chart = generator.create_scatter_plot(data, x='x', y='y') # Chart should be a valid Altair chart object assert hasattr(chart, 'mark_circle') def test_create_histogram(self): """Test histogram creation.""" data = pd.DataFrame({ 'values': [1, 2, 2, 3, 3, 3, 4, 4, 5] }) generator = ChartGenerator() chart = generator.create_histogram(data, column='values') # Chart should be a valid Altair chart object assert hasattr(chart, 'mark_bar') if __name__ == "__main__": pytest.main([__file__, "-v"])