forked from arthurcolle/claude-code-sdk-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cache.py
More file actions
522 lines (401 loc) · 16.8 KB
/
Copy pathtest_cache.py
File metadata and controls
522 lines (401 loc) · 16.8 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
"""Tests for caching functionality."""
import pytest
import tempfile
import shutil
from unittest.mock import AsyncMock, MagicMock, patch
from pathlib import Path
import json
import sqlite3
import time
from claude_code_sdk import ClaudeCodeOptions
from claude_code_sdk.types import (
AssistantMessage, UserMessage, ResultMessage, SystemMessage,
TextBlock, ToolUseBlock, ToolResultBlock
)
from claude_code_sdk.cache import (
CacheManager, CacheConfig, CacheBackend, CacheStrategy,
MemoryCacheBackend, FileCacheBackend, SQLiteCacheBackend,
query_with_cache, get_global_cache
)
@pytest.fixture
def temp_dir():
"""Create a temporary directory for file-based tests."""
temp_dir = tempfile.mkdtemp()
yield temp_dir
shutil.rmtree(temp_dir)
@pytest.fixture
def mock_messages():
"""Create mock messages for testing."""
return [
AssistantMessage(content=[TextBlock(text="Test response")]),
ResultMessage(
subtype="success",
cost_usd=0.01,
duration_ms=500,
session_id="test-session",
total_cost_usd=0.01
)
]
@pytest.fixture
def mock_query(mock_messages):
"""Create a mock query function."""
call_count = 0
async def _mock_query(prompt: str, options: ClaudeCodeOptions | None = None):
nonlocal call_count
call_count += 1
for msg in mock_messages:
yield msg
_mock_query.call_count = lambda: call_count
return _mock_query
class TestMemoryCacheBackend:
"""Test memory cache backend."""
@pytest.mark.asyncio
async def test_get_set(self):
"""Test basic get/set operations."""
backend = MemoryCacheBackend()
# Test set and get
await backend.set("key1", "value1", ttl=60)
assert await backend.get("key1") == "value1"
# Test missing key
assert await backend.get("missing") is None
@pytest.mark.asyncio
async def test_delete(self):
"""Test delete operation."""
backend = MemoryCacheBackend()
await backend.set("key1", "value1")
assert await backend.get("key1") == "value1"
await backend.delete("key1")
assert await backend.get("key1") is None
@pytest.mark.asyncio
async def test_clear(self):
"""Test clear operation."""
backend = MemoryCacheBackend()
await backend.set("key1", "value1")
await backend.set("key2", "value2")
await backend.clear()
assert await backend.get("key1") is None
assert await backend.get("key2") is None
@pytest.mark.asyncio
async def test_ttl_expiration(self):
"""Test TTL expiration."""
backend = MemoryCacheBackend()
# Set with very short TTL
await backend.set("key1", "value1", ttl=0.01)
assert await backend.get("key1") == "value1"
# Wait for expiration
await asyncio.sleep(0.02)
assert await backend.get("key1") is None
@pytest.mark.asyncio
async def test_max_size(self):
"""Test max size limit."""
backend = MemoryCacheBackend(max_size=2)
await backend.set("key1", "value1")
await backend.set("key2", "value2")
await backend.set("key3", "value3") # Should evict key1
assert await backend.get("key1") is None
assert await backend.get("key2") == "value2"
assert await backend.get("key3") == "value3"
class TestFileCacheBackend:
"""Test file cache backend."""
@pytest.mark.asyncio
async def test_get_set(self, temp_dir):
"""Test basic get/set operations."""
backend = FileCacheBackend(cache_dir=temp_dir)
await backend.set("key1", {"data": "value1"})
assert await backend.get("key1") == {"data": "value1"}
@pytest.mark.asyncio
async def test_delete(self, temp_dir):
"""Test delete operation."""
backend = FileCacheBackend(cache_dir=temp_dir)
await backend.set("key1", "value1")
await backend.delete("key1")
assert await backend.get("key1") is None
@pytest.mark.asyncio
async def test_clear(self, temp_dir):
"""Test clear operation."""
backend = FileCacheBackend(cache_dir=temp_dir)
await backend.set("key1", "value1")
await backend.set("key2", "value2")
await backend.clear()
assert await backend.get("key1") is None
assert await backend.get("key2") is None
@pytest.mark.asyncio
async def test_ttl_expiration(self, temp_dir):
"""Test TTL expiration."""
backend = FileCacheBackend(cache_dir=temp_dir)
await backend.set("key1", "value1", ttl=0.01)
assert await backend.get("key1") == "value1"
await asyncio.sleep(0.02)
assert await backend.get("key1") is None
@pytest.mark.asyncio
async def test_safe_key_conversion(self, temp_dir):
"""Test safe key conversion for filesystem."""
backend = FileCacheBackend(cache_dir=temp_dir)
# Test key with special characters
key = "test/key:with*special|chars"
await backend.set(key, "value")
assert await backend.get(key) == "value"
class TestSQLiteCacheBackend:
"""Test SQLite cache backend."""
@pytest.mark.asyncio
async def test_get_set(self, temp_dir):
"""Test basic get/set operations."""
db_path = Path(temp_dir) / "cache.db"
backend = SQLiteCacheBackend(db_path=str(db_path))
await backend.set("key1", {"data": "value1"})
assert await backend.get("key1") == {"data": "value1"}
@pytest.mark.asyncio
async def test_delete(self, temp_dir):
"""Test delete operation."""
db_path = Path(temp_dir) / "cache.db"
backend = SQLiteCacheBackend(db_path=str(db_path))
await backend.set("key1", "value1")
await backend.delete("key1")
assert await backend.get("key1") is None
@pytest.mark.asyncio
async def test_clear(self, temp_dir):
"""Test clear operation."""
db_path = Path(temp_dir) / "cache.db"
backend = SQLiteCacheBackend(db_path=str(db_path))
await backend.set("key1", "value1")
await backend.set("key2", "value2")
await backend.clear()
assert await backend.get("key1") is None
assert await backend.get("key2") is None
@pytest.mark.asyncio
async def test_ttl_expiration(self, temp_dir):
"""Test TTL expiration and cleanup."""
db_path = Path(temp_dir) / "cache.db"
backend = SQLiteCacheBackend(db_path=str(db_path))
await backend.set("key1", "value1", ttl=0.01)
assert await backend.get("key1") == "value1"
await asyncio.sleep(0.02)
assert await backend.get("key1") is None
@pytest.mark.asyncio
async def test_max_size(self, temp_dir):
"""Test max size limit."""
db_path = Path(temp_dir) / "cache.db"
backend = SQLiteCacheBackend(db_path=str(db_path), max_size=2)
await backend.set("key1", "value1")
await backend.set("key2", "value2")
await backend.set("key3", "value3") # Should trigger cleanup
# One of the first two should be evicted
remaining_count = 0
if await backend.get("key1"):
remaining_count += 1
if await backend.get("key2"):
remaining_count += 1
assert remaining_count == 1
assert await backend.get("key3") == "value3"
class TestCacheManager:
"""Test cache manager."""
@pytest.mark.asyncio
async def test_cache_hit(self, mock_query, mock_messages):
"""Test cache hit scenario."""
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(backend=backend))
# First query - cache miss
messages1 = []
async for msg in manager.query_with_cache("test prompt", query_func=mock_query):
messages1.append(msg)
assert len(messages1) == len(mock_messages)
assert mock_query.call_count() == 1
# Second query - cache hit
messages2 = []
async for msg in manager.query_with_cache("test prompt", query_func=mock_query):
messages2.append(msg)
assert len(messages2) == len(mock_messages)
assert mock_query.call_count() == 1 # Should not increase
@pytest.mark.asyncio
async def test_cache_key_with_options(self, mock_query):
"""Test cache key generation with options."""
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(backend=backend))
options1 = ClaudeCodeOptions(allowed_tools=["Read"])
options2 = ClaudeCodeOptions(allowed_tools=["Write"])
# Query with options1
async for _ in manager.query_with_cache("test", options=options1, query_func=mock_query):
pass
assert mock_query.call_count() == 1
# Query with options2 - should be cache miss
async for _ in manager.query_with_cache("test", options=options2, query_func=mock_query):
pass
assert mock_query.call_count() == 2
@pytest.mark.asyncio
async def test_ttl_configuration(self, mock_query):
"""Test TTL configuration."""
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(
backend=backend,
ttl_seconds=0.01
))
# First query
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
assert mock_query.call_count() == 1
# Wait for TTL to expire
await asyncio.sleep(0.02)
# Second query - should be cache miss
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
assert mock_query.call_count() == 2
@pytest.mark.asyncio
async def test_disabled_cache(self, mock_query):
"""Test disabled cache."""
manager = CacheManager(CacheConfig(enabled=False))
# Multiple queries should all hit the actual function
for _ in range(3):
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
assert mock_query.call_count() == 3
@pytest.mark.asyncio
async def test_cache_strategies(self, mock_query):
"""Test different cache strategies."""
# Test ALWAYS strategy (default)
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(
backend=backend,
strategy=CacheStrategy.ALWAYS
))
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
assert mock_query.call_count() == 1
# Test NEVER strategy
manager = CacheManager(CacheConfig(
backend=backend,
strategy=CacheStrategy.NEVER
))
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
assert mock_query.call_count() == 2
@pytest.mark.asyncio
async def test_error_handling(self):
"""Test error handling in cache operations."""
# Create a faulty backend
class FaultyBackend:
async def get(self, key: str):
raise Exception("Backend error")
async def set(self, key: str, value, ttl=None):
raise Exception("Backend error")
manager = CacheManager(CacheConfig(backend=FaultyBackend()))
async def simple_query(prompt, options=None):
yield AssistantMessage(content=[TextBlock(text="Response")])
# Should still work despite backend errors
messages = []
async for msg in manager.query_with_cache("test", query_func=simple_query):
messages.append(msg)
assert len(messages) == 1
@pytest.mark.asyncio
async def test_cache_stats(self, mock_query):
"""Test cache statistics."""
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(backend=backend))
# Generate some hits and misses
async for _ in manager.query_with_cache("prompt1", query_func=mock_query):
pass
async for _ in manager.query_with_cache("prompt1", query_func=mock_query):
pass
async for _ in manager.query_with_cache("prompt2", query_func=mock_query):
pass
stats = manager.get_stats()
assert stats["hits"] == 1
assert stats["misses"] == 2
assert stats["hit_rate"] == 1/3
@pytest.mark.asyncio
async def test_invalidate_cache(self, mock_query):
"""Test cache invalidation."""
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(backend=backend))
# Cache a query
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
assert mock_query.call_count() == 1
# Invalidate specific key
await manager.invalidate("test")
# Should be cache miss
async for _ in manager.query_with_cache("test", query_func=mock_query):
pass
assert mock_query.call_count() == 2
@pytest.mark.asyncio
async def test_clear_cache(self, mock_query):
"""Test clearing entire cache."""
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(backend=backend))
# Cache multiple queries
async for _ in manager.query_with_cache("test1", query_func=mock_query):
pass
async for _ in manager.query_with_cache("test2", query_func=mock_query):
pass
# Clear cache
await manager.clear()
# Both should be cache misses
call_count_before = mock_query.call_count()
async for _ in manager.query_with_cache("test1", query_func=mock_query):
pass
async for _ in manager.query_with_cache("test2", query_func=mock_query):
pass
assert mock_query.call_count() == call_count_before + 2
@pytest.mark.asyncio
async def test_query_with_cache_function(mock_query):
"""Test the convenience query_with_cache function."""
# Set up global cache
cache = get_global_cache()
cache._config.backend = MemoryCacheBackend()
cache._config.enabled = True
with patch("claude_code_sdk.cache.query", mock_query):
# First call - cache miss
messages1 = []
async for msg in query_with_cache(prompt="test"):
messages1.append(msg)
# Second call - cache hit
messages2 = []
async for msg in query_with_cache(prompt="test"):
messages2.append(msg)
assert len(messages1) == len(messages2)
assert mock_query.call_count() == 1
@pytest.mark.asyncio
async def test_global_cache_singleton():
"""Test global cache singleton pattern."""
cache1 = get_global_cache()
cache2 = get_global_cache()
assert cache1 is cache2
@pytest.mark.asyncio
async def test_cache_with_complex_messages():
"""Test caching with complex message types."""
backend = MemoryCacheBackend()
manager = CacheManager(CacheConfig(backend=backend))
complex_messages = [
AssistantMessage(content=[
TextBlock(text="Hello"),
ToolUseBlock(id="tool1", name="Read", input={"file": "test.py"}),
ToolResultBlock(tool_use_id="tool1", content="File contents"),
]),
SystemMessage(subtype="info", data={"info": "Processing"}),
ResultMessage(
subtype="success",
cost_usd=0.02,
duration_ms=1000,
session_id="complex-session",
total_cost_usd=0.02,
usage={"input_tokens": 50, "output_tokens": 100}
)
]
async def complex_query(prompt, options=None):
for msg in complex_messages:
yield msg
# Cache the complex messages
messages1 = []
async for msg in manager.query_with_cache("complex", query_func=complex_query):
messages1.append(msg)
# Retrieve from cache
messages2 = []
async for msg in manager.query_with_cache("complex", query_func=complex_query):
messages2.append(msg)
# Verify all message types are properly cached
assert len(messages1) == len(messages2) == len(complex_messages)
for m1, m2 in zip(messages1, messages2):
assert type(m1) == type(m2)
assert m1 == m2
import asyncio # Add missing import