CoolFace
Apppublic

findEthics/Atlas

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
test_search_optimizer_refactor.py222 linesDownload Raw Back to unit
1#!/usr/bin/env python32"""3Test script for search_optimizer refactoring functionality.4 5This script tests the refactored search optimization functions to ensure6they work correctly after being moved from app.py to search_optimizer.py.7"""8 9import sys10import traceback11from typing import List, Dict, Any12 13def test_search_decision_functions():14    """Test basic search decision functions without dependencies"""15    16    print("๐Ÿงช Testing Search Decision Functions")17    print("=" * 50)18    19    # Test cases for should_perform_search20    test_cases = [21        {22            "name": "No history - should search",23            "prompt": "Explain artificial intelligence concepts",24            "history": None,25            "expected_search": True26        },27        {28            "name": "Greeting - should not search",29            "prompt": "Hello there!",30            "history": None,31            "expected_search": False32        },33        {34            "name": "Follow-up question - should not search",35            "prompt": "Tell me more about that",36            "history": [{"user": "What is AI?", "assistant": "AI is artificial intelligence..."}],37            "expected_search": False38        },39        {40            "name": "New information request - should search",41            "prompt": "What is the latest news about AI?",42            "history": [{"user": "What is AI?", "assistant": "AI is artificial intelligence..."}],43            "expected_search": True44        }45    ]46    47    try:48        # Import the function for testing49        from search_optimizer import should_perform_search50        51        print("โœ… Function import successful")52        53        # Test each case54        for i, case in enumerate(test_cases, 1):55            print(f"\n๐Ÿ” Test {i}: {case['name']}")56            57            try:58                result = should_perform_search(59                    case["prompt"],60                    case["history"]61                )62                63                actual_search = result["should_search"]64                expected_search = case["expected_search"]65                66                if actual_search == expected_search:67                    print(f"   โœ… PASS - Decision: {actual_search}")68                    print(f"   ๐Ÿ“ Reason: {result['reason']}")69                    print(f"   ๐Ÿ“Š Confidence: {result['confidence']:.2f}")70                else:71                    print(f"   โŒ FAIL - Expected: {expected_search}, Got: {actual_search}")72                    print(f"   ๐Ÿ“ Reason: {result['reason']}")73                    74            except Exception as e:75                print(f"   โŒ ERROR: {e}")76        77    except ImportError as e:78        print(f"โŒ Import failed: {e}")79        return False80    except Exception as e:81        print(f"โŒ Unexpected error: {e}")82        traceback.print_exc()83        return False84    85    return True86 87def test_utility_functions():88    """Test utility functions that don't require heavy dependencies"""89    90    print("\n๐Ÿ› ๏ธ  Testing Utility Functions")91    print("=" * 50)92    93    try:94        from search_optimizer import format_search_context95        96        print("โœ… format_search_context import successful")97        98        # Test format_search_context99        test_results = [100            {101                "source": "Brave",102                "title": "Machine Learning Guide",103                "body": "Machine learning is a subset of artificial intelligence..."104            },105            {106                "source": "DuckDuckGo", 107                "title": "AI Overview",108                "body": "Artificial intelligence involves creating systems that can perform tasks..."109            }110        ]111        112        formatted = format_search_context(test_results)113        114        if formatted and "Machine Learning Guide" in formatted and "AI Overview" in formatted:115            print("โœ… format_search_context works correctly")116            print(f"๐Ÿ“„ Sample output: {formatted[:100]}...")117        else:118            print("โŒ format_search_context failed")119            120    except ImportError as e:121        print(f"โŒ Import failed: {e}")122        return False123    except Exception as e:124        print(f"โŒ Unexpected error: {e}")125        traceback.print_exc()126        return False127        128    return True129 130def test_conversation_history_analysis():131    """Test conversation history analysis function"""132    133    print("\n๐Ÿ“Š Testing Conversation History Analysis")134    print("=" * 50)135    136    try:137        from search_optimizer import has_meaningful_conversation_history138        139        print("โœ… has_meaningful_conversation_history import successful")140        141        # Test cases142        test_cases = [143            {144                "name": "Empty history",145                "history": None,146                "expected": False147            },148            {149                "name": "Meaningful conversation",150                "history": [{"user": "What is machine learning?", "assistant": "Machine learning is a field of artificial intelligence..."}],151                "expected": True152            },153            {154                "name": "Too short entries",155                "history": [{"user": "Hi", "assistant": "Hi"}],156                "expected": False157            }158        ]159        160        for i, case in enumerate(test_cases, 1):161            print(f"\n๐Ÿ” Test {i}: {case['name']}")162            163            try:164                result = has_meaningful_conversation_history(case["history"])165                166                if result == case["expected"]:167                    print(f"   โœ… PASS - Result: {result}")168                else:169                    print(f"   โŒ FAIL - Expected: {case['expected']}, Got: {result}")170                    171            except Exception as e:172                print(f"   โŒ ERROR: {e}")173        174    except ImportError as e:175        print(f"โŒ Import failed: {e}")176        return False177    except Exception as e:178        print(f"โŒ Unexpected error: {e}")179        traceback.print_exc()180        return False181        182    return True183 184def main():185    """Run all functional tests"""186    187    print("๐Ÿš€ Search Optimizer Refactoring Test Suite")188    print("=" * 60)189    print("Testing refactored search optimization functions...")190    print()191    192    # Track test results193    tests_passed = 0194    total_tests = 3195    196    # Run tests197    if test_search_decision_functions():198        tests_passed += 1199        200    if test_utility_functions():201        tests_passed += 1202        203    if test_conversation_history_analysis():204        tests_passed += 1205    206    # Summary207    print("\n" + "=" * 60)208    print("๐Ÿ“‹ TEST SUMMARY")209    print("=" * 60)210    211    if tests_passed == total_tests:212        print(f"โœ… ALL TESTS PASSED ({tests_passed}/{total_tests})")213        print("๐ŸŽ‰ Search optimizer refactoring successful!")214        return True215    else:216        print(f"โŒ SOME TESTS FAILED ({tests_passed}/{total_tests})")217        print("โš ๏ธ  Please check the errors above")218        return False219 220if __name__ == "__main__":221    success = main()222    sys.exit(0 if success else 1)