#!/usr/bin/env python3 """ Test cache permission handling. """ import asyncio import sys import tempfile import os from pathlib import Path from unittest.mock import patch # Add project root to path project_root = Path(__file__).parent.parent # Go up from test-integration to backend-py sys.path.insert(0, str(project_root)) from src.services.word_cache import WordCacheManager async def test_permission_denied(): """Test cache handling when permissions are denied.""" print("๐Ÿงช Testing permission denied scenario...") # Mock Path.mkdir to raise PermissionError with patch.object(Path, 'mkdir', side_effect=PermissionError("Permission denied")): try: cache_manager = WordCacheManager(cache_dir="/some/protected/path") await cache_manager.initialize() print(f"โœ… Cache manager created with fallback: {cache_manager.cache_dir}") # Test caching still works (in-memory or temp dir) test_words = [ {"word": "TEST", "clue": "A test word", "similarity": 0.8, "source": "test"} ] success = await cache_manager.cache_words("TestTopic", "medium", test_words) print(f"โœ… Caching {'succeeded' if success else 'failed'}") cached_words = await cache_manager.get_cached_words("TestTopic", "medium", 5) print(f"โœ… Retrieved {len(cached_words)} cached words") return True except Exception as e: print(f"โŒ Permission handling failed: {e}") return False async def test_in_memory_mode(): """Test pure in-memory cache mode.""" print("\n๐Ÿงช Testing in-memory only mode...") # Force in-memory mode by setting cache_dir to None cache_manager = WordCacheManager() cache_manager.cache_dir = None # Force in-memory mode await cache_manager.initialize() # Test that caching still works in memory test_words = [ {"word": "MEMORY", "clue": "Stored in RAM", "similarity": 0.9, "source": "test"} ] success = await cache_manager.cache_words("Memory", "medium", test_words) print(f"โœ… In-memory caching {'succeeded' if success else 'failed'}") cached_words = await cache_manager.get_cached_words("Memory", "medium", 5) print(f"โœ… Retrieved {len(cached_words)} words from memory") stats = cache_manager.get_cache_stats() print(f"๐Ÿ“Š Cache stats: {stats}") return len(cached_words) > 0 async def main(): """Run permission tests.""" print("๐Ÿ” Testing Cache Permission Handling\n") test1 = await test_permission_denied() test2 = await test_in_memory_mode() if test1 and test2: print("\nโœ… All permission tests passed!") print("๐Ÿ“ฆ Cache system gracefully handles permission issues") else: print("\nโŒ Some permission tests failed") if __name__ == "__main__": asyncio.run(main())