Spaces:
Sleeping
Sleeping
File size: 7,192 Bytes
4b28fb0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | #!/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) |