File size: 7,148 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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/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)