Atlas / tests /integration /test_integration_basic.py
findEthics
feat: add comprehensive search optimization and ChromaDB caching system
4b28fb0
Raw
History Blame Contribute Delete
7.19 kB
#!/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)