File size: 14,874 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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
#!/usr/bin/env python3
"""
Regression testing for search optimizer refactoring.

This script validates that the refactored functions behave exactly the same
as they did before the refactoring, ensuring no behavioral changes.
"""

import sys
from typing import List, Dict, Any, Optional

def test_search_decision_consistency():
    """Test that search decisions are consistent and logical"""
    
    print("πŸ”„ Regression Testing: Search Decision Consistency")
    print("=" * 60)
    
    try:
        from search_optimizer import should_perform_search
        
        # Test cases with expected behaviors that should remain consistent
        test_cases = [
            {
                "name": "Greeting detection",
                "prompt": "Hello there!",
                "history": None,
                "expected_decision": False,
                "expected_reason_contains": "greeting"
            },
            {
                "name": "New information request",
                "prompt": "What is the latest news about artificial intelligence?",
                "history": None,
                "expected_decision": True,
                "expected_reason_contains": ["information", "history", "No conversation"]
            },
            {
                "name": "Follow-up elaboration",
                "prompt": "Tell me more about that",
                "history": [{"user": "What is AI?", "assistant": "AI is artificial intelligence used to create smart systems..."}],
                "expected_decision": False,
                "expected_reason_contains": "Follow-up"
            },
            {
                "name": "Referential question",
                "prompt": "Can you explain that concept better?",
                "history": [{"user": "What is ML?", "assistant": "Machine learning is a subset of AI that enables systems to learn..."}],
                "expected_decision": False,
                "expected_reason_contains": "question"
            },
            {
                "name": "Continuation request",
                "prompt": "What else should I know?",
                "history": [{"user": "Basics of AI?", "assistant": "AI involves creating intelligent systems..."}],
                "expected_decision": True,
                "expected_reason_contains": ["topic", "patterns", "insufficient"]
            },
            {
                "name": "Fresh topic change",
                "prompt": "How does quantum computing work?",
                "history": [{"user": "What is AI?", "assistant": "AI is artificial intelligence..."}],
                "expected_decision": True,
                "expected_reason_contains": ["information", "topic"]
            }
        ]
        
        passed_tests = 0
        total_tests = len(test_cases)
        
        for i, case in enumerate(test_cases, 1):
            print(f"\nπŸ” Test {i}: {case['name']}")
            
            result = should_perform_search(
                case["prompt"],
                case["history"]
            )
            
            # Check decision consistency
            decision_correct = result["should_search"] == case["expected_decision"]
            
            # Check reason consistency
            reason_correct = False
            expected_reasons = case["expected_reason_contains"]
            if isinstance(expected_reasons, str):
                expected_reasons = [expected_reasons]
            
            for expected_reason in expected_reasons:
                if expected_reason.lower() in result["reason"].lower():
                    reason_correct = True
                    break
            
            print(f"   πŸ“ Decision: {result['should_search']} (expected: {case['expected_decision']})")
            print(f"   πŸ“ Reason: {result['reason']}")
            print(f"   πŸ“Š Confidence: {result['confidence']:.2f}")
            
            if decision_correct and reason_correct:
                print("   βœ… PASS - Behavior consistent")
                passed_tests += 1
            else:
                print("   ❌ FAIL - Behavior inconsistent")
                if not decision_correct:
                    print("      πŸ”Έ Decision mismatch")
                if not reason_correct:
                    print("      πŸ”Έ Reason doesn't match expected pattern")
        
        print(f"\nπŸ“Š Search Decision Tests: {passed_tests}/{total_tests} passed")
        return passed_tests == total_tests
        
    except Exception as e:
        print(f"❌ Search decision regression test error: {e}")
        return False

def test_conversation_history_consistency():
    """Test conversation history analysis consistency"""
    
    print("\nπŸ“Š Regression Testing: Conversation History Analysis")
    print("=" * 60)
    
    try:
        from search_optimizer import has_meaningful_conversation_history
        
        # Test cases with expected behaviors
        test_cases = [
            {
                "name": "None history",
                "history": None,
                "expected": False
            },
            {
                "name": "Empty history",
                "history": [],
                "expected": False
            },
            {
                "name": "Too short entries (role format)",
                "history": [{"role": "user", "content": "Hi"}, {"role": "assistant", "content": "Hi"}],
                "expected": False
            },
            {
                "name": "Too short entries (user/assistant format)",
                "history": [{"user": "Hi", "assistant": "Hi"}],
                "expected": False
            },
            {
                "name": "Meaningful conversation (role format)",
                "history": [{"role": "user", "content": "What is machine learning?"}, {"role": "assistant", "content": "Machine learning is a subset of artificial intelligence..."}],
                "expected": True
            },
            {
                "name": "Meaningful conversation (user/assistant format)",
                "history": [{"user": "Explain neural networks", "assistant": "Neural networks are computing systems inspired by biological neural networks..."}],
                "expected": True
            },
            {
                "name": "Mixed meaningful and short entries",
                "history": [
                    {"user": "Hi", "assistant": "Hello"},
                    {"user": "What is deep learning?", "assistant": "Deep learning is a subset of machine learning that uses neural networks with multiple layers..."}
                ],
                "expected": True
            },
        ]
        
        passed_tests = 0
        total_tests = len(test_cases)
        
        for i, case in enumerate(test_cases, 1):
            print(f"\nπŸ” Test {i}: {case['name']}")
            
            result = has_meaningful_conversation_history(case["history"])
            
            print(f"   πŸ“ Result: {result} (expected: {case['expected']})")
            
            if result == case["expected"]:
                print("   βœ… PASS - Behavior consistent")
                passed_tests += 1
            else:
                print("   ❌ FAIL - Behavior inconsistent")
        
        print(f"\nπŸ“Š History Analysis Tests: {passed_tests}/{total_tests} passed")
        return passed_tests == total_tests
        
    except Exception as e:
        print(f"❌ History analysis regression test error: {e}")
        return False

def test_utility_functions_consistency():
    """Test utility functions consistency"""
    
    print("\nπŸ› οΈ  Regression Testing: Utility Functions")
    print("=" * 60)
    
    try:
        from search_optimizer import format_search_context
        
        # Test format_search_context with various inputs
        test_cases = [
            {
                "name": "Empty results list",
                "results": [],
                "expected_empty": True
            },
            {
                "name": "Single result",
                "results": [{"source": "Brave", "title": "Test Title", "body": "Test body content"}],
                "expected_contains": ["[Brave]", "Test Title", "Test body content"]
            },
            {
                "name": "Multiple results",
                "results": [
                    {"source": "Brave", "title": "Title 1", "body": "Body 1"},
                    {"source": "DuckDuckGo", "title": "Title 2", "body": "Body 2"}
                ],
                "expected_contains": ["[Brave]", "[DuckDuckGo]", "Title 1", "Title 2"]
            },
            {
                "name": "Results with missing fields",
                "results": [{"title": "Only Title"}, {"source": "Only Source"}],
                "expected_contains": ["Only Title", "Only Source"]
            },
            {
                "name": "Very long body content (truncation test)",
                "results": [{"source": "Test", "title": "Long Content", "body": "x" * 2000}],
                "expected_contains": ["[Test]", "Long Content"],
                "expected_truncated": True
            }
        ]
        
        passed_tests = 0
        total_tests = len(test_cases)
        
        for i, case in enumerate(test_cases, 1):
            print(f"\nπŸ” Test {i}: {case['name']}")
            
            result = format_search_context(case["results"])
            
            # Check if result is empty as expected
            if case.get("expected_empty", False):
                if not result:
                    print("   βœ… PASS - Empty result as expected")
                    passed_tests += 1
                else:
                    print("   ❌ FAIL - Expected empty result")
                continue
            
            # Check expected content
            contains_all = True
            for expected_content in case.get("expected_contains", []):
                if expected_content not in result:
                    contains_all = False
                    print(f"      πŸ”Έ Missing expected content: {expected_content}")
            
            # Check truncation if expected
            if case.get("expected_truncated", False):
                if len(result) < 2000:  # Should be truncated from original 2000+ chars
                    print("   πŸ“ Content appropriately truncated")
                else:
                    print("   ⚠️  Content may not be truncated as expected")
            
            if contains_all:
                print("   βœ… PASS - Content formatting consistent")
                passed_tests += 1
            else:
                print("   ❌ FAIL - Content formatting issue")
        
        print(f"\nπŸ“Š Utility Function Tests: {passed_tests}/{total_tests} passed")
        return passed_tests == total_tests
        
    except Exception as e:
        print(f"❌ Utility function regression test error: {e}")
        return False

def test_error_handling_consistency():
    """Test that error handling behaves consistently"""
    
    print("\nπŸ›‘οΈ  Regression Testing: Error Handling")
    print("=" * 60)
    
    try:
        from search_optimizer import should_perform_search, has_meaningful_conversation_history, format_search_context
        
        print("πŸ” Testing graceful error handling...")
        
        # Test functions with malformed inputs
        error_tests_passed = 0
        total_error_tests = 0
        
        # Test should_perform_search with malformed history
        print("\n   πŸ“ Testing should_perform_search with malformed history")
        total_error_tests += 1
        try:
            result = should_perform_search("test prompt", [{"malformed": "entry"}])
            if isinstance(result, dict) and "should_search" in result:
                print("      βœ… Handled malformed history gracefully")
                error_tests_passed += 1
            else:
                print("      ❌ Unexpected result format")
        except Exception as e:
            print(f"      ❌ Unexpected exception: {e}")
        
        # Test has_meaningful_conversation_history with malformed data
        print("\n   πŸ“ Testing has_meaningful_conversation_history with malformed data")
        total_error_tests += 1
        try:
            result = has_meaningful_conversation_history([{"invalid": "format"}, "not_a_dict"])
            if isinstance(result, bool):
                print("      βœ… Handled malformed data gracefully")
                error_tests_passed += 1
            else:
                print("      ❌ Unexpected result type")
        except Exception as e:
            print(f"      ❌ Unexpected exception: {e}")
        
        # Test format_search_context with malformed results
        print("\n   πŸ“ Testing format_search_context with malformed results")
        total_error_tests += 1
        try:
            result = format_search_context([{"missing_keys": True}, None, "not_a_dict"])
            if isinstance(result, str):
                print("      βœ… Handled malformed results gracefully")
                error_tests_passed += 1
            else:
                print("      ❌ Unexpected result type")
        except Exception as e:
            print(f"      ❌ Unexpected exception: {e}")
        
        print(f"\nπŸ“Š Error Handling Tests: {error_tests_passed}/{total_error_tests} passed")
        return error_tests_passed == total_error_tests
        
    except Exception as e:
        print(f"❌ Error handling regression test error: {e}")
        return False

def main():
    """Run regression validation suite"""
    
    print("πŸ”„ Search Optimizer Regression Validation Suite")
    print("=" * 70)
    print("Validating behavioral consistency after refactoring...")
    print()
    
    tests_passed = 0
    total_tests = 4
    
    # Run regression tests
    if test_search_decision_consistency():
        tests_passed += 1
        
    if test_conversation_history_consistency():
        tests_passed += 1
        
    if test_utility_functions_consistency():
        tests_passed += 1
        
    if test_error_handling_consistency():
        tests_passed += 1
    
    # Summary
    print("\n" + "=" * 70)
    print("πŸ“‹ REGRESSION VALIDATION SUMMARY")
    print("=" * 70)
    
    if tests_passed == total_tests:
        print(f"βœ… ALL REGRESSION TESTS PASSED ({tests_passed}/{total_tests})")
        print("πŸŽ‰ Behavioral consistency maintained after refactoring!")
        print("πŸš€ The refactored code behaves exactly as expected!")
        return True
    else:
        print(f"❌ SOME REGRESSION TESTS FAILED ({tests_passed}/{total_tests})")
        print("⚠️  Behavioral changes detected - review required")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)