#!/usr/bin/env python3 """ Redis Connection Test Verifies that Redis is available and working for the cached API key service """ import asyncio import aioredis import time async def test_redis_connection(): """Test Redis connection and basic operations""" try: print("šŸ”Œ Testing Redis connection...") # Connect to Redis redis = aioredis.from_url( "redis://localhost:6379", encoding="utf-8", decode_responses=True, socket_connect_timeout=5, socket_timeout=5 ) # Test basic operations test_key = "test:connection" test_value = f"test_value_{int(time.time())}" # Set a value await redis.set(test_key, test_value, ex=60) print("āœ… Successfully wrote to Redis") # Get the value retrieved_value = await redis.get(test_key) if retrieved_value == test_value: print("āœ… Successfully read from Redis") else: print("āŒ Redis read/write mismatch") return False # Test expiration ttl = await redis.ttl(test_key) if 0 < ttl <= 60: print(f"āœ… TTL working correctly: {ttl} seconds") else: print(f"āš ļø TTL may not be working: {ttl}") # Clean up await redis.delete(test_key) print("āœ… Cleanup successful") # Test Redis info info = await redis.info() print(f"āœ… Redis version: {info.get('redis_version', 'unknown')}") print(f"āœ… Redis memory usage: {info.get('used_memory_human', 'unknown')}") await redis.close() print("āœ… Redis connection test passed!") return True except ConnectionError as e: print(f"āŒ Redis connection failed: {e}") print("šŸ’” Make sure Redis is running: docker compose up -d") return False except Exception as e: print(f"āŒ Redis test failed: {e}") return False async def test_api_key_cache_operations(): """Test the specific cache operations used by the API key service""" try: print("\nšŸ”‘ Testing API key cache operations...") redis = aioredis.from_url("redis://localhost:6379", encoding="utf-8", decode_responses=True) # Test API key data caching test_prefix = "ce_test123" cache_key = f"api_key:data:{test_prefix}" test_data = { "user_id": 1, "api_key_id": 123, "permissions": ["read", "write"], "cached_at": time.time() } # Cache data import json await redis.setex(cache_key, 300, json.dumps(test_data)) print("āœ… API key data cached successfully") # Retrieve data cached_data = await redis.get(cache_key) if cached_data: parsed_data = json.loads(cached_data) if parsed_data["user_id"] == 1: print("āœ… API key data retrieved successfully") else: print("āŒ API key data corrupted") # Test verification cache verification_key = f"api_key:verified:{test_prefix}:abcd1234" await redis.setex(verification_key, 3600, "valid") verification_result = await redis.get(verification_key) if verification_result == "valid": print("āœ… Verification cache working") else: print("āŒ Verification cache failed") # Test pattern-based deletion pattern = f"api_key:verified:{test_prefix}:*" keys = await redis.keys(pattern) if keys: await redis.delete(*keys) print("āœ… Pattern-based cache invalidation working") # Cleanup await redis.delete(cache_key) await redis.close() print("āœ… API key cache operations test passed!") return True except Exception as e: print(f"āŒ API key cache test failed: {e}") return False async def main(): """Main test function""" print("=" * 60) print("Redis Connection and Cache Test") print("=" * 60) # Test basic Redis connection basic_test = await test_redis_connection() if not basic_test: print("\nāŒ Basic Redis test failed. Cannot proceed with cache tests.") return False # Test API key specific operations cache_test = await test_api_key_cache_operations() if basic_test and cache_test: print("\nšŸŽ‰ All Redis tests passed! The cached API key service should work correctly.") return True else: print("\nāŒ Some tests failed. Check your Redis configuration.") return False if __name__ == "__main__": success = asyncio.run(main()) exit(0 if success else 1)