Spaces:
Sleeping
Sleeping
| #!/usr/bin/env python3 | |
| """ | |
| Basic integration test for refactored search optimizer with chat endpoint. | |
| This test validates that the refactored search optimization functions | |
| integrate correctly with the FastAPI chat endpoint. | |
| """ | |
| import asyncio | |
| import json | |
| import sys | |
| import time | |
| from typing import Dict, Any | |
| def test_app_startup(): | |
| """Test that the app can start with refactored imports""" | |
| print("π Testing App Startup with Refactored Code") | |
| print("=" * 50) | |
| try: | |
| # Test that app.py imports work correctly | |
| print("π¦ Testing app.py imports...") | |
| # Import key components to verify dependencies | |
| import app | |
| print("β app.py imported successfully") | |
| # Test that search optimizer functions are available | |
| from search_optimizer import ( | |
| should_perform_search, | |
| has_meaningful_conversation_history, | |
| format_search_context, | |
| extract_search_terms | |
| ) | |
| print("β Search optimizer functions imported successfully") | |
| # Test that FastAPI app is created | |
| assert hasattr(app, 'app'), "FastAPI app not found" | |
| print("β FastAPI app created successfully") | |
| # Test that required global variables exist | |
| assert hasattr(app, 'nlp'), "NLP model not found" | |
| assert hasattr(app, 'rake'), "RAKE instance not found" | |
| assert hasattr(app, 'model'), "Gemini model not found" | |
| print("β Required global dependencies available") | |
| return True | |
| except ImportError as e: | |
| print(f"β Import error: {e}") | |
| return False | |
| except Exception as e: | |
| print(f"β Unexpected error: {e}") | |
| return False | |
| def test_search_decision_integration(): | |
| """Test search decision functions with app dependencies""" | |
| print("\nπ§ Testing Search Decision Integration") | |
| print("=" * 50) | |
| try: | |
| # Import app to get dependencies | |
| import app | |
| from search_optimizer import should_perform_search, has_meaningful_conversation_history | |
| # Test should_perform_search with different scenarios | |
| test_cases = [ | |
| { | |
| "name": "Simple question - should search", | |
| "prompt": "What is quantum computing?", | |
| "history": None, | |
| "expected_search": True | |
| }, | |
| { | |
| "name": "Follow-up question - should not search", | |
| "prompt": "Tell me more about that topic", | |
| "history": [{"user": "What is AI?", "assistant": "AI stands for artificial intelligence..."}], | |
| "expected_search": False | |
| } | |
| ] | |
| for i, case in enumerate(test_cases, 1): | |
| print(f"\nπ Test {i}: {case['name']}") | |
| result = should_perform_search( | |
| case["prompt"], | |
| case["history"] | |
| ) | |
| print(f" π Decision: {result['should_search']}") | |
| print(f" π Reason: {result['reason']}") | |
| print(f" π Confidence: {result['confidence']:.2f}") | |
| if result["should_search"] == case["expected_search"]: | |
| print(" β Expected result achieved") | |
| else: | |
| print(f" β οΈ Unexpected result (expected: {case['expected_search']})") | |
| # Test has_meaningful_conversation_history | |
| print(f"\nπ Testing conversation history analysis...") | |
| empty_result = has_meaningful_conversation_history(None) | |
| meaningful_result = has_meaningful_conversation_history([ | |
| {"user": "What is machine learning?", "assistant": "Machine learning is a branch of AI..."} | |
| ]) | |
| print(f" π Empty history: {empty_result}") | |
| print(f" π Meaningful history: {meaningful_result}") | |
| if not empty_result and meaningful_result: | |
| print(" β History analysis working correctly") | |
| else: | |
| print(" β History analysis issue") | |
| return True | |
| except Exception as e: | |
| print(f"β Integration test error: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| return False | |
| def test_format_utilities(): | |
| """Test format utilities with realistic data""" | |
| print("\nπ οΈ Testing Format Utilities") | |
| print("=" * 50) | |
| try: | |
| from search_optimizer import format_search_context | |
| # Test with realistic search results | |
| mock_results = [ | |
| { | |
| "source": "Brave", | |
| "title": "Machine Learning Fundamentals", | |
| "body": "Machine learning is a method of data analysis that automates analytical model building. It is a branch of artificial intelligence (AI) based on the idea that systems can learn from data, identify patterns and make decisions with minimal human intervention." | |
| }, | |
| { | |
| "source": "DuckDuckGo", | |
| "title": "Deep Learning vs Machine Learning", | |
| "body": "Deep learning is a subset of machine learning that uses neural networks with multiple layers. While machine learning can work with smaller datasets and simpler algorithms, deep learning requires large amounts of data and computational power." | |
| } | |
| ] | |
| formatted_context = format_search_context(mock_results) | |
| print("π Formatted search context preview:") | |
| print(" " + formatted_context[:200] + "...") | |
| # Validate formatting | |
| if "[Brave]" in formatted_context and "[DuckDuckGo]" in formatted_context: | |
| print("β Search context formatting works correctly") | |
| return True | |
| else: | |
| print("β Search context formatting issue") | |
| return False | |
| except Exception as e: | |
| print(f"β Format utilities test error: {e}") | |
| return False | |
| def main(): | |
| """Run basic integration tests""" | |
| print("π§ͺ Search Optimizer Integration Test Suite") | |
| print("=" * 60) | |
| print("Testing integration of refactored search optimizer with app...") | |
| print() | |
| tests_passed = 0 | |
| total_tests = 3 | |
| # Run tests | |
| if test_app_startup(): | |
| tests_passed += 1 | |
| if test_search_decision_integration(): | |
| tests_passed += 1 | |
| if test_format_utilities(): | |
| tests_passed += 1 | |
| # Summary | |
| print("\n" + "=" * 60) | |
| print("π INTEGRATION TEST SUMMARY") | |
| print("=" * 60) | |
| if tests_passed == total_tests: | |
| print(f"β ALL INTEGRATION TESTS PASSED ({tests_passed}/{total_tests})") | |
| print("π Search optimizer integration successful!") | |
| print("π The refactored code is ready for production!") | |
| return True | |
| else: | |
| print(f"β SOME INTEGRATION TESTS FAILED ({tests_passed}/{total_tests})") | |
| print("β οΈ Please check the errors above") | |
| return False | |
| if __name__ == "__main__": | |
| success = main() | |
| sys.exit(0 if success else 1) |