test_cache.sh
1 #!/bin/bash 2 # Test caching functionality 3 4 # shellcheck disable=SC1091 5 # Source the completion script 6 source contrib/bar_complete 7 8 # Enable debug mode to see cache messages 9 export BAR_COMPLETE_DEBUG=1 10 11 echo "Testing completion caching..." 12 13 # Initialize registry 14 __bar_init_completion_registry 15 16 # Create a simple test to trigger caching 17 # We'll simulate a completion scenario where the same completer is called multiple times 18 19 # Mock a simple scenario by calling the main completion function 20 # Set up mock COMP variables 21 COMP_WORDS=(bar test) 22 COMP_CWORD=1 23 24 # Run completion first time 25 echo "First completion run (should NOT use cache):" 26 output1=$(_bar_complete 2>&1) 27 echo "$output1" | grep -q "Using cached results" && echo "✗ FAIL: Cache used on first run" || echo "✓ PASS: No cache on first run" 28 29 # Now test that subsequent calls within the same completion session would use cache 30 # This is harder to test directly, so we'll test the cache mechanism more directly 31 32 # Direct test of cache behavior 33 echo "" 34 echo "Testing cache array behavior:" 35 36 # Create a mock cache array and test the caching logic 37 declare -a test_cache=() 38 test_completer="__bar_comp_file" 39 test_cur="test" 40 cache_key="${test_completer}:${test_cur}" 41 42 # First, populate the cache 43 test_results=("result1" "result2" "result3") 44 cache_value="${cache_key}:$(printf '%s\n' "${test_results[@]}")" 45 test_cache+=("$cache_value") 46 47 echo "Cache populated with key: $cache_key" 48 49 # Now search for it 50 use_cache=false 51 cache_idx=0 52 for ((cache_idx=0; cache_idx<${#test_cache[@]}; cache_idx++)); do 53 if [[ "${test_cache[$cache_idx]}" == "$cache_key"* ]]; then 54 use_cache=true 55 break 56 fi 57 done 58 59 if [[ $use_cache == true ]]; then 60 echo "✓ PASS: Cache lookup successful" 61 62 # Extract cached results 63 cached_results="${test_cache[$cache_idx]#*:}" 64 cached_results="${cached_results#*:}" # Skip the second colon 65 66 IFS=$'\n' read -rd '' -a cached_comps <<< "$cached_results" || true 67 68 if [[ ${#cached_comps[@]} -eq 3 ]]; then 69 echo "✓ PASS: Cached results retrieved correctly (${#cached_comps[@]} items)" 70 else 71 echo "✗ FAIL: Expected 3 cached items, got ${#cached_comps[@]}" 72 fi 73 else 74 echo "✗ FAIL: Cache lookup failed" 75 fi 76 77 # Test with different key (should not find in cache) 78 different_key="__bar_comp_directory:other" 79 use_cache=false 80 for ((cache_idx=0; cache_idx<${#test_cache[@]}; cache_idx++)); do 81 if [[ "${test_cache[$cache_idx]}" == "$different_key"* ]]; then 82 use_cache=true 83 break 84 fi 85 done 86 87 if [[ $use_cache == false ]]; then 88 echo "✓ PASS: Different key not found in cache (as expected)" 89 else 90 echo "✗ FAIL: Different key incorrectly found in cache" 91 fi 92 93 echo "" 94 echo "Cache tests complete" 95 96 # Disable debug mode 97 unset BAR_COMPLETE_DEBUG