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)