anderson-ufrj commited on
Commit
4230b3c
·
1 Parent(s): 66f9c89

test(cache): add comprehensive tests for cache service

Browse files

- Add unit tests for all cache operations
- Add integration tests with real Redis instance
- Test compression, TTL expiration, and stampede protection
- Test chat response, session, and investigation caching
- Add concurrent operation tests
- Test cache statistics and monitoring
- Add missing json import to cache_service.py

src/services/cache_service.py CHANGED
@@ -9,6 +9,7 @@ This service provides:
9
  """
10
 
11
  import hashlib
 
12
  from typing import Optional, Any, Dict, List
13
  from datetime import datetime, timedelta
14
  import asyncio
 
9
  """
10
 
11
  import hashlib
12
+ import json
13
  from typing import Optional, Any, Dict, List
14
  from datetime import datetime, timedelta
15
  import asyncio
tests/integration/test_cache_service_integration.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Integration tests for cache service with real Redis"""
2
+
3
+ import pytest
4
+ import asyncio
5
+ from datetime import datetime
6
+ import time
7
+ import os
8
+
9
+ from src.services.cache_service import CacheService, cache_result
10
+
11
+ # Skip these tests if Redis is not available
12
+ redis_available = os.getenv("REDIS_URL") is not None
13
+
14
+ @pytest.mark.skipif(not redis_available, reason="Redis not available")
15
+ class TestCacheServiceIntegration:
16
+ """Integration tests with real Redis instance"""
17
+
18
+ @pytest.fixture
19
+ async def cache_service(self):
20
+ """Create real cache service instance"""
21
+ service = CacheService()
22
+ await service.initialize()
23
+ yield service
24
+ # Cleanup
25
+ await service.redis.flushdb()
26
+ await service.close()
27
+
28
+ @pytest.mark.asyncio
29
+ async def test_basic_operations(self, cache_service):
30
+ """Test basic get/set/delete operations"""
31
+ # Set value
32
+ assert await cache_service.set("test_key", {"data": "value"}, ttl=10)
33
+
34
+ # Get value
35
+ result = await cache_service.get("test_key")
36
+ assert result == {"data": "value"}
37
+
38
+ # Delete value
39
+ assert await cache_service.delete("test_key")
40
+
41
+ # Verify deleted
42
+ result = await cache_service.get("test_key")
43
+ assert result is None
44
+
45
+ @pytest.mark.asyncio
46
+ async def test_ttl_expiration(self, cache_service):
47
+ """Test TTL expiration"""
48
+ # Set with 1 second TTL
49
+ await cache_service.set("expire_key", "value", ttl=1)
50
+
51
+ # Should exist immediately
52
+ assert await cache_service.get("expire_key") == "value"
53
+
54
+ # Wait for expiration
55
+ await asyncio.sleep(1.5)
56
+
57
+ # Should be expired
58
+ assert await cache_service.get("expire_key") is None
59
+
60
+ @pytest.mark.asyncio
61
+ async def test_compression(self, cache_service):
62
+ """Test compression for large values"""
63
+ large_data = {"data": "x" * 10000} # ~10KB
64
+
65
+ # Set with compression
66
+ await cache_service.set("compressed_key", large_data, compress=True)
67
+
68
+ # Get with decompression
69
+ result = await cache_service.get("compressed_key", decompress=True)
70
+ assert result == large_data
71
+
72
+ @pytest.mark.asyncio
73
+ async def test_chat_response_caching(self, cache_service):
74
+ """Test chat response caching workflow"""
75
+ response = {
76
+ "message": "This is a test response",
77
+ "confidence": 0.95,
78
+ "agent": "test_agent"
79
+ }
80
+
81
+ # Cache response
82
+ assert await cache_service.cache_chat_response("Hello world", response, "greeting")
83
+
84
+ # Get cached response
85
+ cached = await cache_service.get_cached_chat_response("Hello world", "greeting")
86
+ assert cached == response
87
+
88
+ # Case insensitive and trimmed
89
+ cached2 = await cache_service.get_cached_chat_response(" hello WORLD ", "greeting")
90
+ assert cached2 == response
91
+
92
+ @pytest.mark.asyncio
93
+ async def test_session_management(self, cache_service):
94
+ """Test session state management"""
95
+ session_id = "test_session_123"
96
+ initial_state = {
97
+ "user_id": "user_456",
98
+ "started_at": datetime.utcnow().isoformat(),
99
+ "context": {"intent": "help"}
100
+ }
101
+
102
+ # Save session
103
+ assert await cache_service.save_session_state(session_id, initial_state)
104
+
105
+ # Get session
106
+ state = await cache_service.get_session_state(session_id)
107
+ assert state["user_id"] == "user_456"
108
+ assert state["context"]["intent"] == "help"
109
+ assert "last_updated" in state
110
+
111
+ # Update field
112
+ assert await cache_service.update_session_field(session_id, "messages_count", 5)
113
+
114
+ # Verify update
115
+ state = await cache_service.get_session_state(session_id)
116
+ assert state["messages_count"] == 5
117
+ assert state["user_id"] == "user_456" # Original fields preserved
118
+
119
+ @pytest.mark.asyncio
120
+ async def test_investigation_caching(self, cache_service):
121
+ """Test investigation result caching"""
122
+ investigation_id = "inv_789"
123
+ results = {
124
+ "anomalies_found": 3,
125
+ "contracts_analyzed": 150,
126
+ "findings": [
127
+ {"type": "price_anomaly", "severity": "high"},
128
+ {"type": "vendor_concentration", "severity": "medium"}
129
+ ]
130
+ }
131
+
132
+ # Cache investigation
133
+ assert await cache_service.cache_investigation_result(investigation_id, results)
134
+
135
+ # Retrieve investigation
136
+ cached = await cache_service.get_cached_investigation(investigation_id)
137
+ assert cached == results
138
+
139
+ @pytest.mark.asyncio
140
+ async def test_search_results_caching(self, cache_service):
141
+ """Test search results caching with filters"""
142
+ query = "contratos suspeitos"
143
+ filters = {"year": 2024, "min_value": 100000, "status": "active"}
144
+ results = [
145
+ {"id": "1", "title": "Contrato A", "value": 150000},
146
+ {"id": "2", "title": "Contrato B", "value": 200000}
147
+ ]
148
+
149
+ # Cache search results
150
+ assert await cache_service.cache_search_results(query, filters, results)
151
+
152
+ # Get cached results
153
+ cached = await cache_service.get_cached_search_results(query, filters)
154
+ assert cached == results
155
+
156
+ # Different filters should not hit cache
157
+ different_filters = {"year": 2023, "min_value": 100000, "status": "active"}
158
+ cached2 = await cache_service.get_cached_search_results(query, different_filters)
159
+ assert cached2 is None
160
+
161
+ @pytest.mark.asyncio
162
+ async def test_agent_context_management(self, cache_service):
163
+ """Test agent context storage"""
164
+ agent_id = "zumbi"
165
+ session_id = "session_123"
166
+ context = {
167
+ "investigation_id": "inv_456",
168
+ "findings": ["anomaly1", "anomaly2"],
169
+ "confidence": 0.85
170
+ }
171
+
172
+ # Save context
173
+ assert await cache_service.save_agent_context(agent_id, session_id, context)
174
+
175
+ # Get context
176
+ retrieved = await cache_service.get_agent_context(agent_id, session_id)
177
+ assert retrieved == context
178
+
179
+ @pytest.mark.asyncio
180
+ async def test_concurrent_operations(self, cache_service):
181
+ """Test concurrent cache operations"""
182
+ async def set_value(key, value):
183
+ await cache_service.set(key, value)
184
+
185
+ async def get_value(key):
186
+ return await cache_service.get(key)
187
+
188
+ # Create many concurrent operations
189
+ tasks = []
190
+ for i in range(50):
191
+ tasks.append(set_value(f"concurrent_{i}", f"value_{i}"))
192
+
193
+ await asyncio.gather(*tasks)
194
+
195
+ # Verify all values
196
+ get_tasks = []
197
+ for i in range(50):
198
+ get_tasks.append(get_value(f"concurrent_{i}"))
199
+
200
+ results = await asyncio.gather(*get_tasks)
201
+
202
+ for i, result in enumerate(results):
203
+ assert result == f"value_{i}"
204
+
205
+ @pytest.mark.asyncio
206
+ async def test_cache_stats(self, cache_service):
207
+ """Test cache statistics"""
208
+ # Add some data
209
+ await cache_service.cache_chat_response("test1", {"msg": "response1"})
210
+ await cache_service.save_session_state("session1", {"data": "test"})
211
+ await cache_service.cache_investigation_result("inv1", {"results": "data"})
212
+
213
+ # Get stats
214
+ stats = await cache_service.get_cache_stats()
215
+
216
+ assert stats["connected"] is True
217
+ assert stats["total_keys"] >= 3
218
+ assert "memory_used" in stats
219
+ assert "hit_rate" in stats
220
+ assert stats["keys_by_type"]["chat"] >= 1
221
+ assert stats["keys_by_type"]["session"] >= 1
222
+ assert stats["keys_by_type"]["investigation"] >= 1
223
+
224
+ @pytest.mark.asyncio
225
+ async def test_stampede_protection(self, cache_service):
226
+ """Test cache stampede protection"""
227
+ refresh_count = 0
228
+
229
+ async def slow_refresh():
230
+ nonlocal refresh_count
231
+ refresh_count += 1
232
+ await asyncio.sleep(0.1)
233
+ return {"refreshed": refresh_count}
234
+
235
+ # Set initial value with short TTL
236
+ await cache_service.set("stampede_key", {"initial": "value"}, ttl=2)
237
+
238
+ # Multiple concurrent requests near expiration
239
+ await asyncio.sleep(1.5) # Close to expiration
240
+
241
+ tasks = []
242
+ for _ in range(10):
243
+ tasks.append(
244
+ cache_service.get_with_stampede_protection(
245
+ "stampede_key",
246
+ 10,
247
+ slow_refresh
248
+ )
249
+ )
250
+
251
+ results = await asyncio.gather(*tasks)
252
+
253
+ # All should get same value
254
+ assert all(r == results[0] for r in results)
255
+
256
+ # Refresh should be called only once or twice (not 10 times)
257
+ assert refresh_count <= 2
258
+
259
+
260
+ @pytest.mark.skipif(not redis_available, reason="Redis not available")
261
+ class TestCacheDecoratorIntegration:
262
+ """Integration tests for cache decorator"""
263
+
264
+ @pytest.fixture
265
+ async def cleanup_redis(self):
266
+ """Clean Redis after tests"""
267
+ yield
268
+ service = CacheService()
269
+ await service.initialize()
270
+ await service.redis.flushdb()
271
+ await service.close()
272
+
273
+ @pytest.mark.asyncio
274
+ async def test_decorator_caching(self, cleanup_redis):
275
+ """Test function caching with decorator"""
276
+ call_count = 0
277
+
278
+ @cache_result("expensive", ttl=5)
279
+ async def expensive_function(param1, param2):
280
+ nonlocal call_count
281
+ call_count += 1
282
+ await asyncio.sleep(0.1) # Simulate expensive operation
283
+ return {"result": f"{param1}-{param2}", "count": call_count}
284
+
285
+ # First call - should execute
286
+ result1 = await expensive_function("test", "123")
287
+ assert result1["count"] == 1
288
+
289
+ # Second call - should use cache
290
+ result2 = await expensive_function("test", "123")
291
+ assert result2["count"] == 1 # Same count, not executed again
292
+
293
+ # Different parameters - should execute
294
+ result3 = await expensive_function("test", "456")
295
+ assert result3["count"] == 2
296
+
297
+ # Original parameters again - should use cache
298
+ result4 = await expensive_function("test", "123")
299
+ assert result4["count"] == 1
tests/unit/test_cache_service.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Unit tests for cache service"""
2
+
3
+ import pytest
4
+ import asyncio
5
+ from unittest.mock import AsyncMock, MagicMock, patch
6
+ from datetime import datetime
7
+ import zlib
8
+
9
+ from src.services.cache_service import CacheService, cache_result
10
+ from src.core.exceptions import CacheError
11
+
12
+
13
+ class TestCacheService:
14
+ """Test CacheService functionality"""
15
+
16
+ @pytest.fixture
17
+ async def cache_service(self):
18
+ """Create cache service instance"""
19
+ service = CacheService()
20
+ # Mock Redis
21
+ service.redis = AsyncMock()
22
+ service._initialized = True
23
+ yield service
24
+
25
+ @pytest.fixture
26
+ async def uninitialized_cache(self):
27
+ """Create uninitialized cache service"""
28
+ service = CacheService()
29
+ yield service
30
+
31
+ def test_generate_key_short(self, cache_service):
32
+ """Test key generation for short inputs"""
33
+ key = cache_service._generate_key("test", "arg1", "arg2")
34
+ assert key == "cidadao:test:arg1:arg2"
35
+
36
+ def test_generate_key_long(self, cache_service):
37
+ """Test key generation for long inputs (should hash)"""
38
+ long_arg = "a" * 200
39
+ key = cache_service._generate_key("test", long_arg)
40
+ assert key.startswith("cidadao:test:")
41
+ assert len(key) < 100 # Should be hashed
42
+
43
+ @pytest.mark.asyncio
44
+ async def test_initialize_success(self):
45
+ """Test successful initialization"""
46
+ service = CacheService()
47
+
48
+ with patch('redis.asyncio.ConnectionPool.from_url') as mock_pool:
49
+ with patch('redis.asyncio.Redis') as mock_redis:
50
+ mock_redis_instance = AsyncMock()
51
+ mock_redis_instance.ping = AsyncMock(return_value=True)
52
+ mock_redis.return_value = mock_redis_instance
53
+
54
+ await service.initialize()
55
+
56
+ assert service._initialized is True
57
+ mock_redis_instance.ping.assert_called_once()
58
+
59
+ @pytest.mark.asyncio
60
+ async def test_initialize_failure(self):
61
+ """Test initialization failure"""
62
+ service = CacheService()
63
+
64
+ with patch('redis.asyncio.ConnectionPool.from_url') as mock_pool:
65
+ mock_pool.side_effect = Exception("Connection failed")
66
+
67
+ with pytest.raises(CacheError):
68
+ await service.initialize()
69
+
70
+ @pytest.mark.asyncio
71
+ async def test_get_success(self, cache_service):
72
+ """Test successful get operation"""
73
+ cache_service.redis.get.return_value = '{"key": "value"}'
74
+
75
+ result = await cache_service.get("test_key")
76
+ assert result == {"key": "value"}
77
+ cache_service.redis.get.assert_called_once_with("test_key")
78
+
79
+ @pytest.mark.asyncio
80
+ async def test_get_compressed(self, cache_service):
81
+ """Test get with decompression"""
82
+ original = '{"key": "value"}'
83
+ compressed = zlib.compress(original.encode())
84
+ cache_service.redis.get.return_value = compressed
85
+
86
+ result = await cache_service.get("test_key", decompress=True)
87
+ assert result == {"key": "value"}
88
+
89
+ @pytest.mark.asyncio
90
+ async def test_get_not_found(self, cache_service):
91
+ """Test get when key doesn't exist"""
92
+ cache_service.redis.get.return_value = None
93
+
94
+ result = await cache_service.get("test_key")
95
+ assert result is None
96
+
97
+ @pytest.mark.asyncio
98
+ async def test_get_redis_error(self, cache_service):
99
+ """Test get with Redis error"""
100
+ cache_service.redis.get.side_effect = Exception("Redis error")
101
+
102
+ result = await cache_service.get("test_key")
103
+ assert result is None
104
+
105
+ @pytest.mark.asyncio
106
+ async def test_set_success_with_ttl(self, cache_service):
107
+ """Test successful set operation with TTL"""
108
+ cache_service.redis.setex = AsyncMock(return_value=True)
109
+
110
+ result = await cache_service.set("test_key", {"data": "value"}, ttl=300)
111
+ assert result is True
112
+ cache_service.redis.setex.assert_called_once()
113
+
114
+ @pytest.mark.asyncio
115
+ async def test_set_success_without_ttl(self, cache_service):
116
+ """Test successful set operation without TTL"""
117
+ cache_service.redis.set = AsyncMock(return_value=True)
118
+
119
+ result = await cache_service.set("test_key", {"data": "value"})
120
+ assert result is True
121
+ cache_service.redis.set.assert_called_once()
122
+
123
+ @pytest.mark.asyncio
124
+ async def test_set_with_compression(self, cache_service):
125
+ """Test set with compression for large values"""
126
+ large_value = {"data": "x" * 2000} # Large enough to trigger compression
127
+ cache_service.redis.setex = AsyncMock(return_value=True)
128
+
129
+ result = await cache_service.set("test_key", large_value, ttl=300, compress=True)
130
+ assert result is True
131
+
132
+ # Verify compression was applied
133
+ call_args = cache_service.redis.setex.call_args[0]
134
+ compressed_value = call_args[2]
135
+ # Should be compressed (smaller than original JSON)
136
+ assert len(compressed_value) < len(str(large_value))
137
+
138
+ @pytest.mark.asyncio
139
+ async def test_delete_success(self, cache_service):
140
+ """Test successful delete operation"""
141
+ cache_service.redis.delete.return_value = 1
142
+
143
+ result = await cache_service.delete("test_key")
144
+ assert result is True
145
+ cache_service.redis.delete.assert_called_once_with("test_key")
146
+
147
+ @pytest.mark.asyncio
148
+ async def test_delete_key_not_found(self, cache_service):
149
+ """Test delete when key doesn't exist"""
150
+ cache_service.redis.delete.return_value = 0
151
+
152
+ result = await cache_service.delete("test_key")
153
+ assert result is False
154
+
155
+ @pytest.mark.asyncio
156
+ async def test_cache_chat_response(self, cache_service):
157
+ """Test caching chat response"""
158
+ cache_service.redis.setex = AsyncMock(return_value=True)
159
+
160
+ response = {"message": "Test response"}
161
+ result = await cache_service.cache_chat_response("Hello", response, "greeting")
162
+
163
+ assert result is True
164
+ cache_service.redis.setex.assert_called_once()
165
+
166
+ # Check TTL is correct
167
+ call_args = cache_service.redis.setex.call_args[0]
168
+ assert call_args[1] == 300 # TTL_CHAT_RESPONSE
169
+
170
+ @pytest.mark.asyncio
171
+ async def test_get_cached_chat_response(self, cache_service):
172
+ """Test getting cached chat response"""
173
+ cached_data = {
174
+ "response": {"message": "Cached response"},
175
+ "cached_at": datetime.utcnow().isoformat(),
176
+ "hit_count": 5
177
+ }
178
+ cache_service.redis.get.return_value = str(cached_data)
179
+ cache_service.redis.setex = AsyncMock(return_value=True)
180
+
181
+ # Mock loads to return the cached data
182
+ with patch('src.services.cache_service.loads', return_value=cached_data):
183
+ result = await cache_service.get_cached_chat_response("Hello", "greeting")
184
+
185
+ assert result == {"message": "Cached response"}
186
+ # Should increment hit count
187
+ assert cache_service.redis.setex.called
188
+
189
+ @pytest.mark.asyncio
190
+ async def test_save_session_state(self, cache_service):
191
+ """Test saving session state"""
192
+ cache_service.redis.setex = AsyncMock(return_value=True)
193
+
194
+ state = {"user_id": "123", "context": "test"}
195
+ result = await cache_service.save_session_state("session_123", state)
196
+
197
+ assert result is True
198
+ cache_service.redis.setex.assert_called_once()
199
+
200
+ # Check TTL
201
+ call_args = cache_service.redis.setex.call_args[0]
202
+ assert call_args[1] == 86400 # TTL_SESSION
203
+
204
+ @pytest.mark.asyncio
205
+ async def test_get_session_state(self, cache_service):
206
+ """Test getting session state"""
207
+ state = {"user_id": "123", "context": "test"}
208
+ cache_service.redis.get.return_value = str(state)
209
+
210
+ with patch('src.services.cache_service.loads', return_value=state):
211
+ result = await cache_service.get_session_state("session_123")
212
+
213
+ assert result == state
214
+
215
+ @pytest.mark.asyncio
216
+ async def test_update_session_field(self, cache_service):
217
+ """Test updating session field"""
218
+ existing_state = {"user_id": "123", "context": "test"}
219
+ cache_service.redis.get.return_value = str(existing_state)
220
+ cache_service.redis.setex = AsyncMock(return_value=True)
221
+
222
+ with patch('src.services.cache_service.loads', return_value=existing_state):
223
+ result = await cache_service.update_session_field("session_123", "new_field", "value")
224
+
225
+ assert result is True
226
+ # Verify the updated state was saved
227
+ cache_service.redis.setex.assert_called_once()
228
+
229
+ @pytest.mark.asyncio
230
+ async def test_cache_investigation_result(self, cache_service):
231
+ """Test caching investigation result"""
232
+ cache_service.redis.setex = AsyncMock(return_value=True)
233
+
234
+ result_data = {"findings": ["anomaly1", "anomaly2"]}
235
+ result = await cache_service.cache_investigation_result("inv_123", result_data)
236
+
237
+ assert result is True
238
+ call_args = cache_service.redis.setex.call_args[0]
239
+ assert call_args[1] == 3600 # TTL_INVESTIGATION
240
+
241
+ @pytest.mark.asyncio
242
+ async def test_get_cache_stats(self, cache_service):
243
+ """Test getting cache statistics"""
244
+ cache_service.redis.info = AsyncMock()
245
+ cache_service.redis.info.side_effect = [
246
+ {"keyspace_hit_ratio": 0.85, "total_connections_received": 100},
247
+ {"used_memory_human": "10M"}
248
+ ]
249
+ cache_service.redis.dbsize = AsyncMock(return_value=1000)
250
+ cache_service.redis.scan_iter = AsyncMock()
251
+ cache_service.redis.scan_iter.return_value.__aiter__.return_value = iter(["key1", "key2"])
252
+
253
+ stats = await cache_service.get_cache_stats()
254
+
255
+ assert stats["connected"] is True
256
+ assert stats["total_keys"] == 1000
257
+ assert stats["memory_used"] == "10M"
258
+ assert "hit_rate" in stats
259
+
260
+ @pytest.mark.asyncio
261
+ async def test_cache_stampede_protection(self, cache_service):
262
+ """Test cache stampede protection mechanism"""
263
+ # Mock pipeline
264
+ pipeline = AsyncMock()
265
+ pipeline.execute.return_value = ['{"value": "test"}', 5] # value, TTL
266
+ cache_service.redis.pipeline.return_value = pipeline
267
+
268
+ refresh_called = False
269
+ async def refresh_callback():
270
+ nonlocal refresh_called
271
+ refresh_called = True
272
+ return {"value": "refreshed"}
273
+
274
+ with patch('src.services.cache_service.loads', return_value={"value": "test"}):
275
+ result = await cache_service.get_with_stampede_protection(
276
+ "test_key",
277
+ 300,
278
+ refresh_callback
279
+ )
280
+
281
+ assert result == {"value": "test"}
282
+ # Refresh might be called based on random factor
283
+
284
+ @pytest.mark.asyncio
285
+ async def test_auto_initialization(self, uninitialized_cache):
286
+ """Test automatic initialization on first operation"""
287
+ with patch.object(uninitialized_cache, 'initialize') as mock_init:
288
+ mock_init.return_value = None
289
+ uninitialized_cache._initialized = True
290
+ uninitialized_cache.redis = AsyncMock()
291
+ uninitialized_cache.redis.get.return_value = None
292
+
293
+ await uninitialized_cache.get("test_key")
294
+ mock_init.assert_called_once()
295
+
296
+
297
+ class TestCacheDecorator:
298
+ """Test cache_result decorator"""
299
+
300
+ @pytest.mark.asyncio
301
+ async def test_cache_decorator_hit(self):
302
+ """Test cache decorator with cache hit"""
303
+ mock_cache = AsyncMock()
304
+ mock_cache._generate_key.return_value = "test_key"
305
+ mock_cache.get.return_value = {"cached": "result"}
306
+
307
+ with patch('src.services.cache_service.CacheService', return_value=mock_cache):
308
+ @cache_result("test", ttl=60)
309
+ async def test_function(arg1, arg2):
310
+ return {"result": f"{arg1}-{arg2}"}
311
+
312
+ result = await test_function("a", "b")
313
+
314
+ assert result == {"cached": "result"}
315
+ mock_cache.get.assert_called_once()
316
+ mock_cache.set.assert_not_called()
317
+
318
+ @pytest.mark.asyncio
319
+ async def test_cache_decorator_miss(self):
320
+ """Test cache decorator with cache miss"""
321
+ mock_cache = AsyncMock()
322
+ mock_cache._generate_key.return_value = "test_key"
323
+ mock_cache.get.return_value = None
324
+ mock_cache.set.return_value = True
325
+
326
+ with patch('src.services.cache_service.CacheService', return_value=mock_cache):
327
+ @cache_result("test", ttl=60)
328
+ async def test_function(arg1, arg2):
329
+ return {"result": f"{arg1}-{arg2}"}
330
+
331
+ result = await test_function("a", "b")
332
+
333
+ assert result == {"result": "a-b"}
334
+ mock_cache.get.assert_called_once()
335
+ mock_cache.set.assert_called_once_with("test_key", {"result": "a-b"}, 60)