ai_data_scientist / tests /test_streamlit_runner.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
13.7 kB
"""
Test runner for Streamlit UI components.
Provides utilities for running and managing Streamlit component tests.
"""
import pytest
import sys
import os
from pathlib import Path
import subprocess
import tempfile
import shutil
from unittest.mock import patch, Mock
import streamlit as st
# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
class StreamlitTestRunner:
"""Test runner for Streamlit components with mocking utilities."""
def __init__(self):
self.temp_dir = None
self.mock_patches = []
def setup_test_environment(self):
"""Set up test environment with necessary mocks."""
# Create temporary directory for test files
self.temp_dir = tempfile.mkdtemp()
# Mock Streamlit session state
self.mock_session_state = {}
# Common Streamlit function mocks
self.streamlit_mocks = {
'title': Mock(),
'header': Mock(),
'subheader': Mock(),
'markdown': Mock(),
'text': Mock(),
'write': Mock(),
'columns': Mock(return_value=[Mock(), Mock(), Mock()]),
'container': Mock(),
'expander': Mock(),
'tabs': Mock(return_value=[Mock(), Mock(), Mock()]),
'sidebar': Mock(),
'selectbox': Mock(return_value="default"),
'multiselect': Mock(return_value=[]),
'text_input': Mock(return_value=""),
'text_area': Mock(return_value=""),
'number_input': Mock(return_value=0),
'slider': Mock(return_value=0.5),
'checkbox': Mock(return_value=False),
'radio': Mock(return_value="option1"),
'button': Mock(return_value=False),
'file_uploader': Mock(return_value=None),
'dataframe': Mock(),
'table': Mock(),
'metric': Mock(),
'progress': Mock(),
'spinner': Mock(),
'empty': Mock(),
'placeholder': Mock(),
'success': Mock(),
'info': Mock(),
'warning': Mock(),
'error': Mock(),
'exception': Mock(),
'plotly_chart': Mock(),
'pyplot': Mock(),
'image': Mock(),
'video': Mock(),
'audio': Mock(),
'download_button': Mock(),
'form': Mock(),
'form_submit_button': Mock(),
'rerun': Mock(),
'stop': Mock(),
'json': Mock(),
'code': Mock(),
'latex': Mock(),
'divider': Mock(),
'caption': Mock(),
'set_page_config': Mock(),
'secrets': {},
'session_state': self.mock_session_state
}
# Apply patches
for func_name, mock_func in self.streamlit_mocks.items():
if func_name == 'session_state':
# Special handling for session_state
patch_obj = patch('streamlit.session_state', self.mock_session_state)
elif func_name == 'secrets':
patch_obj = patch('streamlit.secrets', {})
else:
patch_obj = patch(f'streamlit.{func_name}', mock_func)
self.mock_patches.append(patch_obj)
patch_obj.start()
def teardown_test_environment(self):
"""Clean up test environment."""
# Stop all patches
for patch_obj in self.mock_patches:
patch_obj.stop()
# Clean up temporary directory
if self.temp_dir and os.path.exists(self.temp_dir):
shutil.rmtree(self.temp_dir)
def run_component_tests(self, test_pattern="test_streamlit*.py"):
"""Run Streamlit component tests."""
self.setup_test_environment()
try:
# Run pytest with specific pattern
test_dir = Path(__file__).parent
result = pytest.main([
str(test_dir / test_pattern),
"-v",
"--tb=short",
"--disable-warnings"
])
return result == 0
finally:
self.teardown_test_environment()
def run_integration_tests(self):
"""Run integration tests for Streamlit components."""
self.setup_test_environment()
try:
# Run integration tests
result = pytest.main([
str(Path(__file__).parent / "test_streamlit_components.py::TestMainDashboard"),
"-v",
"--tb=short"
])
return result == 0
finally:
self.teardown_test_environment()
def create_mock_uploaded_file(self, filename="test.csv", content=b"col1,col2\n1,a\n2,b"):
"""Create a mock uploaded file for testing."""
mock_file = Mock()
mock_file.name = filename
mock_file.type = "text/csv"
mock_file.getvalue.return_value = content
mock_file.seek = Mock()
return mock_file
def create_mock_analysis_results(self):
"""Create mock analysis results for testing."""
return {
"session_id": "test_session_123",
"dataset_info": {
"metadata": {
"rows": 1000,
"columns": 15
}
},
"quality_report": {
"missing_values": {
"column1": 5,
"column2": 0
},
"data_types": {
"column1": "int64",
"column2": "object"
},
"recommendations": [
"Handle missing values in column1",
"Consider encoding categorical variables"
]
},
"hypothesis_results": [
{
"hypothesis_id": "hyp_1",
"p_value": 0.023,
"is_significant": True,
"interpretation": "Significant correlation found between variables"
},
{
"hypothesis_id": "hyp_2",
"p_value": 0.156,
"is_significant": False,
"interpretation": "No significant relationship detected"
}
],
"model_results": {
"models": [
{
"id": "model_rf",
"algorithm": "Random Forest",
"performance": {
"accuracy": 0.856,
"precision": 0.834,
"recall": 0.878,
"f1_score": 0.855
},
"training_time_seconds": 45.2,
"hyperparameters": {
"n_estimators": 100,
"max_depth": 10
}
},
{
"id": "model_xgb",
"algorithm": "XGBoost",
"performance": {
"accuracy": 0.871,
"precision": 0.849,
"recall": 0.892,
"f1_score": 0.870
},
"training_time_seconds": 62.8,
"hyperparameters": {
"n_estimators": 150,
"learning_rate": 0.1
}
}
],
"best_model_id": "model_xgb",
"feature_importance": {
"feature_1": 0.234,
"feature_2": 0.187,
"feature_3": 0.156,
"feature_4": 0.123,
"feature_5": 0.098
}
},
"recommendations": {
"key_insights": [
{
"title": "Customer Segmentation Opportunity",
"description": "Analysis reveals distinct customer segments with different behaviors",
"confidence_score": 0.87,
"supporting_evidence": [
"Significant clustering in customer data",
"Different purchase patterns identified"
]
}
],
"action_items": [
{
"title": "Implement Customer Segmentation",
"description": "Create targeted marketing campaigns for each segment",
"priority": "high",
"estimated_impact": "15-20% increase in conversion",
"implementation_timeline": "2-3 months",
"required_resources": ["Marketing team", "Data analyst"]
}
],
"kpi_recommendations": [
{
"kpi_name": "Customer Lifetime Value",
"current_value": "$450",
"target_value": "$520",
"improvement_strategy": "Focus on high-value customer segments",
"measurement_method": "Monthly cohort analysis"
}
]
},
"executive_summary": {
"title": "Customer Analysis Results",
"overview": "Analysis of customer data reveals significant opportunities for segmentation and targeting.",
"key_findings": [
"Three distinct customer segments identified",
"High-value segment shows 40% higher lifetime value",
"Seasonal patterns detected in purchase behavior"
],
"recommendations": [
"Implement targeted marketing for each segment",
"Develop retention programs for high-value customers",
"Optimize inventory based on seasonal patterns"
],
"next_steps": [
"Present findings to marketing team",
"Develop implementation roadmap",
"Set up monitoring dashboards"
]
}
}
def run_all_streamlit_tests():
"""Run all Streamlit component tests."""
runner = StreamlitTestRunner()
print("πŸ§ͺ Running Streamlit Component Tests...")
print("=" * 50)
# Run component tests
print("\nπŸ“‹ Running Component Tests...")
component_success = runner.run_component_tests("test_streamlit_components.py")
print("\n🎨 Running UI Feature Tests...")
feature_success = runner.run_component_tests("test_streamlit_ui_features.py")
print("\nπŸ”— Running Integration Tests...")
integration_success = runner.run_integration_tests()
# Summary
print("\n" + "=" * 50)
print("πŸ“Š Test Results Summary:")
print(f" Component Tests: {'βœ… PASSED' if component_success else '❌ FAILED'}")
print(f" UI Feature Tests: {'βœ… PASSED' if feature_success else '❌ FAILED'}")
print(f" Integration Tests: {'βœ… PASSED' if integration_success else '❌ FAILED'}")
overall_success = component_success and feature_success and integration_success
print(f"\n🎯 Overall Result: {'βœ… ALL TESTS PASSED' if overall_success else '❌ SOME TESTS FAILED'}")
return overall_success
def run_specific_test(test_class=None, test_method=None):
"""Run a specific test class or method."""
runner = StreamlitTestRunner()
runner.setup_test_environment()
try:
if test_class and test_method:
test_path = f"test_streamlit_components.py::{test_class}::{test_method}"
elif test_class:
test_path = f"test_streamlit_components.py::{test_class}"
else:
test_path = "test_streamlit_components.py"
result = pytest.main([
str(Path(__file__).parent / test_path),
"-v",
"--tb=long"
])
return result == 0
finally:
runner.teardown_test_environment()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Run Streamlit component tests")
parser.add_argument("--class", dest="test_class", help="Specific test class to run")
parser.add_argument("--method", dest="test_method", help="Specific test method to run")
parser.add_argument("--all", action="store_true", help="Run all tests")
args = parser.parse_args()
if args.all or (not args.test_class and not args.test_method):
success = run_all_streamlit_tests()
else:
success = run_specific_test(args.test_class, args.test_method)
sys.exit(0 if success else 1)