Atlas / tests /unit /test_search_optimizer_refactor.py
findEthics
feat: add comprehensive search optimization and ChromaDB caching system
4b28fb0
Raw
History Blame Contribute Delete
7.15 kB
#!/usr/bin/env python3
"""
Test script for search_optimizer refactoring functionality.
This script tests the refactored search optimization functions to ensure
they work correctly after being moved from app.py to search_optimizer.py.
"""
import sys
import traceback
from typing import List, Dict, Any
def test_search_decision_functions():
"""Test basic search decision functions without dependencies"""
print("πŸ§ͺ Testing Search Decision Functions")
print("=" * 50)
# Test cases for should_perform_search
test_cases = [
{
"name": "No history - should search",
"prompt": "Explain artificial intelligence concepts",
"history": None,
"expected_search": True
},
{
"name": "Greeting - should not search",
"prompt": "Hello there!",
"history": None,
"expected_search": False
},
{
"name": "Follow-up question - should not search",
"prompt": "Tell me more about that",
"history": [{"user": "What is AI?", "assistant": "AI is artificial intelligence..."}],
"expected_search": False
},
{
"name": "New information request - should search",
"prompt": "What is the latest news about AI?",
"history": [{"user": "What is AI?", "assistant": "AI is artificial intelligence..."}],
"expected_search": True
}
]
try:
# Import the function for testing
from search_optimizer import should_perform_search
print("βœ… Function import successful")
# Test each case
for i, case in enumerate(test_cases, 1):
print(f"\nπŸ” Test {i}: {case['name']}")
try:
result = should_perform_search(
case["prompt"],
case["history"]
)
actual_search = result["should_search"]
expected_search = case["expected_search"]
if actual_search == expected_search:
print(f" βœ… PASS - Decision: {actual_search}")
print(f" πŸ“ Reason: {result['reason']}")
print(f" πŸ“Š Confidence: {result['confidence']:.2f}")
else:
print(f" ❌ FAIL - Expected: {expected_search}, Got: {actual_search}")
print(f" πŸ“ Reason: {result['reason']}")
except Exception as e:
print(f" ❌ ERROR: {e}")
except ImportError as e:
print(f"❌ Import failed: {e}")
return False
except Exception as e:
print(f"❌ Unexpected error: {e}")
traceback.print_exc()
return False
return True
def test_utility_functions():
"""Test utility functions that don't require heavy dependencies"""
print("\nπŸ› οΈ Testing Utility Functions")
print("=" * 50)
try:
from search_optimizer import format_search_context
print("βœ… format_search_context import successful")
# Test format_search_context
test_results = [
{
"source": "Brave",
"title": "Machine Learning Guide",
"body": "Machine learning is a subset of artificial intelligence..."
},
{
"source": "DuckDuckGo",
"title": "AI Overview",
"body": "Artificial intelligence involves creating systems that can perform tasks..."
}
]
formatted = format_search_context(test_results)
if formatted and "Machine Learning Guide" in formatted and "AI Overview" in formatted:
print("βœ… format_search_context works correctly")
print(f"πŸ“„ Sample output: {formatted[:100]}...")
else:
print("❌ format_search_context failed")
except ImportError as e:
print(f"❌ Import failed: {e}")
return False
except Exception as e:
print(f"❌ Unexpected error: {e}")
traceback.print_exc()
return False
return True
def test_conversation_history_analysis():
"""Test conversation history analysis function"""
print("\nπŸ“Š Testing Conversation History Analysis")
print("=" * 50)
try:
from search_optimizer import has_meaningful_conversation_history
print("βœ… has_meaningful_conversation_history import successful")
# Test cases
test_cases = [
{
"name": "Empty history",
"history": None,
"expected": False
},
{
"name": "Meaningful conversation",
"history": [{"user": "What is machine learning?", "assistant": "Machine learning is a field of artificial intelligence..."}],
"expected": True
},
{
"name": "Too short entries",
"history": [{"user": "Hi", "assistant": "Hi"}],
"expected": False
}
]
for i, case in enumerate(test_cases, 1):
print(f"\nπŸ” Test {i}: {case['name']}")
try:
result = has_meaningful_conversation_history(case["history"])
if result == case["expected"]:
print(f" βœ… PASS - Result: {result}")
else:
print(f" ❌ FAIL - Expected: {case['expected']}, Got: {result}")
except Exception as e:
print(f" ❌ ERROR: {e}")
except ImportError as e:
print(f"❌ Import failed: {e}")
return False
except Exception as e:
print(f"❌ Unexpected error: {e}")
traceback.print_exc()
return False
return True
def main():
"""Run all functional tests"""
print("πŸš€ Search Optimizer Refactoring Test Suite")
print("=" * 60)
print("Testing refactored search optimization functions...")
print()
# Track test results
tests_passed = 0
total_tests = 3
# Run tests
if test_search_decision_functions():
tests_passed += 1
if test_utility_functions():
tests_passed += 1
if test_conversation_history_analysis():
tests_passed += 1
# Summary
print("\n" + "=" * 60)
print("πŸ“‹ TEST SUMMARY")
print("=" * 60)
if tests_passed == total_tests:
print(f"βœ… ALL TESTS PASSED ({tests_passed}/{total_tests})")
print("πŸŽ‰ Search optimizer refactoring successful!")
return True
else:
print(f"❌ SOME 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)