#!/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)