ai_data_scientist / tests /validate_streamlit_setup.py
VAH6002's picture
Upload 264 files
56c063a verified
Raw History Blame Contribute Delete
11 kB
"""
Validation script for Streamlit dashboard setup.
Checks that all components can be imported and basic functionality works.
"""
import sys
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
def test_imports():
"""Test that all Streamlit components can be imported."""
print("πŸ” Testing component imports...")
try:
from streamlit_app.components.file_upload import FileUploadComponent
print("βœ… FileUploadComponent imported successfully")
except ImportError as e:
print(f"❌ Failed to import FileUploadComponent: {e}")
return False
try:
from streamlit_app.components.business_context import BusinessContextForm
print("βœ… BusinessContextForm imported successfully")
except ImportError as e:
print(f"❌ Failed to import BusinessContextForm: {e}")
return False
try:
from streamlit_app.components.progress_monitor import ProgressMonitor
print("βœ… ProgressMonitor imported successfully")
except ImportError as e:
print(f"❌ Failed to import ProgressMonitor: {e}")
return False
try:
from streamlit_app.components.results_viewer import ResultsViewer
print("βœ… ResultsViewer imported successfully")
except ImportError as e:
print(f"❌ Failed to import ResultsViewer: {e}")
return False
try:
from streamlit_app.components.session_manager import SessionManagerComponent
print("βœ… SessionManagerComponent imported successfully")
except ImportError as e:
print(f"❌ Failed to import SessionManagerComponent: {e}")
return False
try:
from streamlit_app.components.auth import AuthManager
print("βœ… AuthManager imported successfully")
except ImportError as e:
print(f"❌ Failed to import AuthManager: {e}")
return False
try:
from streamlit_app.utils.api_client import APIClient
print("βœ… APIClient imported successfully")
except ImportError as e:
print(f"❌ Failed to import APIClient: {e}")
return False
try:
from streamlit_app.utils.sse_client import SSEClient
print("βœ… SSEClient imported successfully")
except ImportError as e:
print(f"❌ Failed to import SSEClient: {e}")
return False
return True
def test_component_initialization():
"""Test that components can be initialized."""
print("\nπŸ”§ Testing component initialization...")
try:
from streamlit_app.components.file_upload import FileUploadComponent
component = FileUploadComponent()
assert hasattr(component, 'supported_formats')
assert hasattr(component, 'max_size_mb')
print("βœ… FileUploadComponent initializes correctly")
except Exception as e:
print(f"❌ FileUploadComponent initialization failed: {e}")
return False
try:
from streamlit_app.components.business_context import BusinessContextForm
component = BusinessContextForm()
assert hasattr(component, 'context_templates')
assert len(component.context_templates) > 0
print("βœ… BusinessContextForm initializes correctly")
except Exception as e:
print(f"❌ BusinessContextForm initialization failed: {e}")
return False
try:
from streamlit_app.components.results_viewer import ResultsViewer
component = ResultsViewer()
assert hasattr(component, 'chart_colors')
print("βœ… ResultsViewer initializes correctly")
except Exception as e:
print(f"❌ ResultsViewer initialization failed: {e}")
return False
try:
from streamlit_app.utils.api_client import APIClient
client = APIClient("http://test.com")
assert client.base_url == "http://test.com"
assert hasattr(client, 'session')
print("βœ… APIClient initializes correctly")
except Exception as e:
print(f"❌ APIClient initialization failed: {e}")
return False
return True
def test_component_methods():
"""Test that key component methods work."""
print("\nβš™οΈ Testing component methods...")
try:
from streamlit_app.components.file_upload import FileUploadComponent
from unittest.mock import Mock
component = FileUploadComponent()
# Test file validation with mock file
mock_file = Mock()
mock_file.name = "test.txt" # Unsupported format
mock_file.getvalue.return_value = b"small file"
result = component._validate_file(mock_file)
assert not result["valid"]
assert "Unsupported file format" in result["error"]
print("βœ… FileUploadComponent validation works")
except Exception as e:
print(f"❌ FileUploadComponent method test failed: {e}")
return False
try:
from streamlit_app.components.business_context import BusinessContextForm
component = BusinessContextForm()
# Test response validation
insufficient_responses = {"question_1": "short", "question_2": ""}
result = component._validate_responses(insufficient_responses)
assert not result
sufficient_responses = {
"question_1": "This is a long enough response for validation",
"question_2": "Another sufficiently long response for testing"
}
result = component._validate_responses(sufficient_responses)
assert result
print("βœ… BusinessContextForm validation works")
except Exception as e:
print(f"❌ BusinessContextForm method test failed: {e}")
return False
try:
from streamlit_app.utils.api_client import APIClient
from unittest.mock import patch
client = APIClient("http://test.com")
# Test header generation (without Streamlit context)
headers = client._get_headers()
assert "Content-Type" in headers
assert headers["Content-Type"] == "application/json"
print("βœ… APIClient methods work")
except Exception as e:
print(f"❌ APIClient method test failed: {e}")
return False
return True
def test_requirements_compliance():
"""Test that implementation meets the specified requirements."""
print("\nπŸ“‹ Testing requirements compliance...")
# Requirement 10.1: Intuitive Streamlit-based dashboard
try:
from streamlit_app.main import main, render_main_dashboard
print("βœ… Main dashboard functions exist")
except ImportError:
print("❌ Main dashboard functions missing")
return False
# Requirement 10.2: Upload progress and validation in real-time
try:
from streamlit_app.components.file_upload import FileUploadComponent
component = FileUploadComponent()
assert hasattr(component, '_validate_file')
assert hasattr(component, '_display_file_info')
print("βœ… File upload with validation implemented")
except Exception as e:
print(f"❌ File upload validation missing: {e}")
return False
# Requirement 10.3: Progress indicators and intermediate results
try:
from streamlit_app.components.progress_monitor import ProgressMonitor
from unittest.mock import Mock
monitor = ProgressMonitor(Mock(), Mock())
assert hasattr(monitor, 'stages')
assert len(monitor.stages) > 0
print("βœ… Progress monitoring implemented")
except Exception as e:
print(f"❌ Progress monitoring missing: {e}")
return False
# Requirement 10.4: Clear visualization of insights and recommendations
try:
from streamlit_app.components.results_viewer import ResultsViewer
viewer = ResultsViewer()
assert hasattr(viewer, '_render_business_insights')
assert hasattr(viewer, '_render_model_performance')
print("βœ… Results visualization implemented")
except Exception as e:
print(f"❌ Results visualization missing: {e}")
return False
# Requirement 10.5: Interactive controls for customization
try:
# Check that enhanced parameter controls exist in main.py
with open(project_root / "streamlit_app" / "main.py", "r", encoding="utf-8") as f:
content = f.read()
interactive_controls = [
"st.slider",
"st.selectbox",
"st.multiselect",
"st.checkbox",
"st.number_input"
]
controls_found = sum(1 for control in interactive_controls if control in content)
assert controls_found >= 3, f"Only {controls_found} interactive controls found"
print("βœ… Interactive parameter controls implemented")
except Exception as e:
print(f"❌ Interactive controls missing: {e}")
return False
return True
def main():
"""Run all validation tests."""
print("πŸ§ͺ Streamlit Dashboard Validation")
print("=" * 50)
tests = [
("Component Imports", test_imports),
("Component Initialization", test_component_initialization),
("Component Methods", test_component_methods),
("Requirements Compliance", test_requirements_compliance)
]
results = []
for test_name, test_func in tests:
print(f"\nπŸ” Running {test_name}...")
try:
success = test_func()
results.append((test_name, success))
except Exception as e:
print(f"❌ {test_name} failed with exception: {e}")
results.append((test_name, False))
# Summary
print("\n" + "=" * 50)
print("πŸ“Š Validation Results:")
all_passed = True
for test_name, success in results:
status = "βœ… PASSED" if success else "❌ FAILED"
print(f" {test_name}: {status}")
if not success:
all_passed = False
print(f"\n🎯 Overall Result: {'βœ… ALL TESTS PASSED' if all_passed else '❌ SOME TESTS FAILED'}")
if all_passed:
print("\nπŸŽ‰ Streamlit dashboard is ready for use!")
print("πŸ“ To run the dashboard: streamlit run streamlit_app/main.py")
else:
print("\n⚠️ Please fix the failing tests before using the dashboard.")
return all_passed
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)