File size: 3,021 Bytes
38c016b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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())