Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /test_cache_redis_multitier.py
| """Comprehensive async tests for RedisCache and MultiTierCache. | |
| This module provides async unit tests for the cache backends in core/cache.py. | |
| Targets coverage for: | |
| - RedisCache: lines 414-437 (get, set, delete, exists, mget, mset, clear) | |
| - MultiTierCache: lines 518-543 (tier management, get, set, delete, mget) | |
| """ | |
| import pickle # nosemgrep | |
| import sys | |
| from pathlib import Path | |
| from unittest.mock import AsyncMock, MagicMock, Mock, patch | |
| import pytest | |
| import pytest_asyncio | |
| # Add project root to path | |
| project_root = Path(__file__).parent.parent | |
| sys.path.insert(0, str(project_root)) | |
| from core.cache import ( | |
| REDIS_AVAILABLE, | |
| CacheStats, | |
| MemoryCache, | |
| MultiTierCache, | |
| RedisCache, | |
| _get_cache_backend, | |
| ) | |
| # ============================================================================ | |
| # Fixtures | |
| # ============================================================================ | |
| async def mock_redis_pool(): | |
| """Create a mock Redis connection pool.""" | |
| pool = AsyncMock() | |
| pool.get = AsyncMock(return_value=None) | |
| pool.set = AsyncMock(return_value=True) | |
| pool.delete = AsyncMock(return_value=1) | |
| pool.exists = AsyncMock(return_value=1) | |
| pool.flushdb = AsyncMock(return_value=True) | |
| pool.mget = AsyncMock(return_value=[]) | |
| pool.mset = AsyncMock(return_value=True) | |
| pool.close = AsyncMock(return_value=None) | |
| pool.pipeline = MagicMock(return_value=AsyncMock()) | |
| return pool | |
| async def redis_cache(mock_redis_pool): | |
| """Create a RedisCache instance with mocked pool.""" | |
| with patch("core.cache.REDIS_AVAILABLE", True): | |
| with patch("core.cache.redis.Redis", return_value=mock_redis_pool): | |
| cache = RedisCache( | |
| host="localhost", | |
| port=6379, | |
| db=0, | |
| password=None, | |
| max_connections=10, | |
| ) | |
| # Pre-set the pool to avoid initialization | |
| cache._pool = mock_redis_pool | |
| yield cache | |
| await cache.close() | |
| async def memory_cache(): | |
| """Create a MemoryCache instance.""" | |
| cache = MemoryCache(max_size=100, max_memory_mb=50.0) | |
| yield cache | |
| await cache.clear() | |
| async def multitier_cache(): | |
| """Create a MultiTierCache instance with L1 and L2.""" | |
| cache = MultiTierCache( | |
| memory_size=100, | |
| memory_max_mb=50.0, | |
| sqlite_path=None, | |
| redis_config=None, | |
| ) | |
| yield cache | |
| await cache.close() | |
| async def multitier_cache_with_redis(mock_redis_pool): | |
| """Create a MultiTierCache instance with L1, L2, and mocked L3 (Redis).""" | |
| with patch("core.cache.REDIS_AVAILABLE", True): | |
| with patch("core.cache.redis.Redis", return_value=mock_redis_pool): | |
| cache = MultiTierCache( | |
| memory_size=100, | |
| memory_max_mb=50.0, | |
| sqlite_path=None, | |
| redis_config={"host": "localhost", "port": 6379}, | |
| ) | |
| # Pre-set the L3 pool | |
| if cache.l3: | |
| cache.l3._pool = mock_redis_pool | |
| yield cache | |
| await cache.close() | |
| # ============================================================================ | |
| # RedisCache Tests | |
| # ============================================================================ | |
| class TestRedisCache: | |
| """Test RedisCache async operations.""" | |
| async def test_redis_cache_init(self): | |
| """Test RedisCache initialization.""" | |
| with patch("core.cache.REDIS_AVAILABLE", True): | |
| cache = RedisCache( | |
| host="redis.example.com", | |
| port=6380, | |
| db=1, | |
| password="secret", | |
| max_connections=20, | |
| ) | |
| assert cache.host == "redis.example.com" | |
| assert cache.port == 6380 | |
| assert cache.db == 1 | |
| assert cache.password == "secret" | |
| assert cache.max_connections == 20 | |
| assert cache._pool is None | |
| async def test_redis_cache_init_without_redis(self): | |
| """Test RedisCache initialization when redis is not available.""" | |
| with patch("core.cache.REDIS_AVAILABLE", False): | |
| with pytest.raises(ImportError, match="redis not installed"): | |
| RedisCache() | |
| async def test_redis_cache_get_hit(self, redis_cache, mock_redis_pool): | |
| """Test getting an existing value from Redis.""" | |
| serialized_value = pickle.dumps({"data": "test_value"}) | |
| mock_redis_pool.get = AsyncMock(return_value=serialized_value) | |
| result = await redis_cache.get("test_key") | |
| assert result == {"data": "test_value"} | |
| mock_redis_pool.get.assert_called_once_with("test_key") | |
| assert redis_cache.stats.total_gets == 1 | |
| assert redis_cache.stats.hits == 1 | |
| assert redis_cache.stats.misses == 0 | |
| async def test_redis_cache_get_miss(self, redis_cache, mock_redis_pool): | |
| """Test getting a non-existent key from Redis.""" | |
| mock_redis_pool.get = AsyncMock(return_value=None) | |
| result = await redis_cache.get("missing_key") | |
| assert result is None | |
| mock_redis_pool.get.assert_called_once_with("missing_key") | |
| assert redis_cache.stats.total_gets == 1 | |
| assert redis_cache.stats.hits == 0 | |
| assert redis_cache.stats.misses == 1 | |
| async def test_redis_cache_get_error(self, redis_cache, mock_redis_pool): | |
| """Test get handles Redis errors gracefully.""" | |
| mock_redis_pool.get = AsyncMock(side_effect=Exception("Redis connection error")) | |
| result = await redis_cache.get("test_key") | |
| assert result is None | |
| assert redis_cache.stats.total_gets == 1 | |
| assert redis_cache.stats.misses == 1 | |
| async def test_redis_cache_get_pickle_error(self, redis_cache, mock_redis_pool): | |
| """Test get handles pickle deserialization errors.""" | |
| mock_redis_pool.get = AsyncMock(return_value=b"invalid pickle data") | |
| result = await redis_cache.get("test_key") | |
| assert result is None | |
| assert redis_cache.stats.total_gets == 1 | |
| assert redis_cache.stats.misses == 1 | |
| async def test_redis_cache_set_success(self, redis_cache, mock_redis_pool): | |
| """Test setting a value in Redis.""" | |
| mock_redis_pool.set = AsyncMock(return_value=True) | |
| result = await redis_cache.set("test_key", {"data": "value"}, ttl=300) | |
| assert result is True | |
| mock_redis_pool.set.assert_called_once() | |
| call_args = mock_redis_pool.set.call_args | |
| assert call_args[0][0] == "test_key" # key | |
| # nosemgrep | |
| assert pickle.loads(call_args[0][1]) == {"data": "value"} # nosec B301 # serialized value | |
| assert call_args[1]["ex"] == 300 # ttl | |
| assert redis_cache.stats.total_sets == 1 | |
| async def test_redis_cache_set_no_ttl(self, redis_cache, mock_redis_pool): | |
| """Test setting a value without TTL.""" | |
| mock_redis_pool.set = AsyncMock(return_value=True) | |
| result = await redis_cache.set("test_key", "simple_value", ttl=None) | |
| assert result is True | |
| call_args = mock_redis_pool.set.call_args | |
| assert call_args[1]["ex"] is None | |
| async def test_redis_cache_set_error(self, redis_cache, mock_redis_pool): | |
| """Test set handles Redis errors gracefully.""" | |
| mock_redis_pool.set = AsyncMock(side_effect=Exception("Redis connection error")) | |
| result = await redis_cache.set("test_key", "value") | |
| assert result is False | |
| async def test_redis_cache_delete_success(self, redis_cache, mock_redis_pool): | |
| """Test deleting a key from Redis.""" | |
| mock_redis_pool.delete = AsyncMock(return_value=1) | |
| result = await redis_cache.delete("test_key") | |
| assert result is True | |
| mock_redis_pool.delete.assert_called_once_with("test_key") | |
| assert redis_cache.stats.total_deletes == 1 | |
| async def test_redis_cache_delete_error(self, redis_cache, mock_redis_pool): | |
| """Test delete handles Redis errors gracefully.""" | |
| mock_redis_pool.delete = AsyncMock(side_effect=Exception("Redis connection error")) | |
| result = await redis_cache.delete("test_key") | |
| assert result is False | |
| async def test_redis_cache_exists_true(self, redis_cache, mock_redis_pool): | |
| """Test checking existence of existing key.""" | |
| mock_redis_pool.exists = AsyncMock(return_value=1) | |
| result = await redis_cache.exists("test_key") | |
| assert result is True | |
| mock_redis_pool.exists.assert_called_once_with("test_key") | |
| async def test_redis_cache_exists_false(self, redis_cache, mock_redis_pool): | |
| """Test checking existence of non-existent key.""" | |
| mock_redis_pool.exists = AsyncMock(return_value=0) | |
| result = await redis_cache.exists("missing_key") | |
| assert result is False | |
| async def test_redis_cache_exists_error(self, redis_cache, mock_redis_pool): | |
| """Test exists handles Redis errors gracefully.""" | |
| mock_redis_pool.exists = AsyncMock(side_effect=Exception("Redis connection error")) | |
| result = await redis_cache.exists("test_key") | |
| assert result is False | |
| async def test_redis_cache_clear_success(self, redis_cache, mock_redis_pool): | |
| """Test clearing all keys from Redis.""" | |
| mock_redis_pool.flushdb = AsyncMock(return_value=True) | |
| result = await redis_cache.clear() | |
| assert result is True | |
| mock_redis_pool.flushdb.assert_called_once() | |
| async def test_redis_cache_clear_error(self, redis_cache, mock_redis_pool): | |
| """Test clear handles Redis errors gracefully.""" | |
| mock_redis_pool.flushdb = AsyncMock(side_effect=Exception("Redis connection error")) | |
| result = await redis_cache.clear() | |
| assert result is False | |
| async def test_redis_cache_mget_success(self, redis_cache, mock_redis_pool): | |
| """Test batch get from Redis.""" | |
| value1 = pickle.dumps({"id": 1}) | |
| value2 = pickle.dumps({"id": 2}) | |
| mock_redis_pool.mget = AsyncMock(return_value=[value1, value2]) | |
| result = await redis_cache.mget(["key1", "key2"]) | |
| assert result == {"key1": {"id": 1}, "key2": {"id": 2}} | |
| mock_redis_pool.mget.assert_called_once_with(["key1", "key2"]) | |
| assert redis_cache.stats.total_gets == 2 | |
| assert redis_cache.stats.hits == 2 | |
| async def test_redis_cache_mget_partial(self, redis_cache, mock_redis_pool): | |
| """Test batch get with some missing keys.""" | |
| value1 = pickle.dumps({"id": 1}) | |
| mock_redis_pool.mget = AsyncMock(return_value=[value1, None]) | |
| result = await redis_cache.mget(["key1", "key2"]) | |
| assert result == {"key1": {"id": 1}} | |
| assert redis_cache.stats.hits == 1 | |
| assert redis_cache.stats.misses == 1 | |
| async def test_redis_cache_mget_empty(self, redis_cache, mock_redis_pool): | |
| """Test batch get with empty keys list.""" | |
| result = await redis_cache.mget([]) | |
| assert result == {} | |
| mock_redis_pool.mget.assert_not_called() | |
| async def test_redis_cache_mget_error(self, redis_cache, mock_redis_pool): | |
| """Test mget handles Redis errors gracefully.""" | |
| mock_redis_pool.mget = AsyncMock(side_effect=Exception("Redis connection error")) | |
| result = await redis_cache.mget(["key1", "key2"]) | |
| assert result == {} | |
| async def test_redis_cache_mget_pickle_error(self, redis_cache, mock_redis_pool): | |
| """Test mget handles pickle errors for individual values.""" | |
| value1 = pickle.dumps({"id": 1}) | |
| mock_redis_pool.mget = AsyncMock(return_value=[value1, b"invalid pickle"]) | |
| result = await redis_cache.mget(["key1", "key2"]) | |
| assert result == {"key1": {"id": 1}} | |
| assert redis_cache.stats.hits == 1 | |
| assert redis_cache.stats.misses == 1 | |
| async def test_redis_cache_mset_success(self, redis_cache, mock_redis_pool): | |
| """Test batch set in Redis without TTL.""" | |
| mock_redis_pool.mset = AsyncMock(return_value=True) | |
| items = {"key1": "value1", "key2": "value2"} | |
| result = await redis_cache.mset(items) | |
| assert result is True | |
| mock_redis_pool.mset.assert_called_once() | |
| call_args = mock_redis_pool.mset.call_args[0][0] | |
| # nosemgrep | |
| assert pickle.loads(call_args["key1"]) == "value1" # nosec B301 | |
| # nosemgrep | |
| assert pickle.loads(call_args["key2"]) == "value2" # nosec B301 | |
| assert redis_cache.stats.total_sets == 2 | |
| async def test_redis_cache_mset_with_ttl(self, redis_cache, mock_redis_pool): | |
| """Test batch set in Redis with TTL using pipeline.""" | |
| mock_pipeline = AsyncMock() | |
| mock_pipeline.mset = AsyncMock(return_value=None) | |
| mock_pipeline.expire = AsyncMock(return_value=None) | |
| mock_pipeline.execute = AsyncMock(return_value=[True, True, True]) | |
| mock_redis_pool.pipeline = MagicMock(return_value=mock_pipeline) | |
| items = {"key1": "value1", "key2": "value2"} | |
| result = await redis_cache.mset(items, ttl=300) | |
| assert result is True | |
| mock_pipeline.mset.assert_called_once() | |
| assert mock_pipeline.expire.call_count == 2 | |
| mock_pipeline.execute.assert_called_once() | |
| async def test_redis_cache_mset_empty(self, redis_cache, mock_redis_pool): | |
| """Test batch set with empty items.""" | |
| result = await redis_cache.mset({}) | |
| assert result is True | |
| mock_redis_pool.mset.assert_not_called() | |
| async def test_redis_cache_mset_error(self, redis_cache, mock_redis_pool): | |
| """Test mset handles Redis errors gracefully.""" | |
| mock_redis_pool.mset = AsyncMock(side_effect=Exception("Redis connection error")) | |
| result = await redis_cache.mset({"key1": "value1"}) | |
| assert result is False | |
| async def test_redis_cache_get_pool(self, redis_cache, mock_redis_pool): | |
| """Test _get_pool creates pool lazily.""" | |
| cache = RedisCache(host="localhost", port=6379) | |
| cache._pool = None | |
| with patch("core.cache.redis.Redis", return_value=mock_redis_pool) as mock_redis: | |
| pool = await cache._get_pool() | |
| assert pool is mock_redis_pool | |
| mock_redis.assert_called_once() | |
| async def test_redis_cache_close(self, redis_cache, mock_redis_pool): | |
| """Test closing Redis connection.""" | |
| await redis_cache.close() | |
| mock_redis_pool.close.assert_called_once() | |
| assert redis_cache._pool is None | |
| async def test_redis_cache_close_no_pool(self, redis_cache): | |
| """Test closing when no pool exists.""" | |
| redis_cache._pool = None | |
| # Should not raise | |
| await redis_cache.close() | |
| async def test_redis_cache_get_stats(self, redis_cache): | |
| """Test getting cache statistics.""" | |
| redis_cache.stats.hits = 10 | |
| redis_cache.stats.misses = 5 | |
| redis_cache.stats.total_gets = 15 # Set total_gets to match hits + misses | |
| redis_cache.stats.total_sets = 20 | |
| stats = redis_cache.get_stats() | |
| assert isinstance(stats, CacheStats) | |
| assert stats.hits == 10 | |
| assert stats.misses == 5 | |
| assert stats.total_sets == 20 | |
| assert stats.hit_rate == 10 / 15 # 10 hits out of 15 total gets | |
| # ============================================================================ | |
| # MultiTierCache Tests | |
| # ============================================================================ | |
| class TestMultiTierCache: | |
| """Test MultiTierCache async operations.""" | |
| async def test_multitier_cache_init(self): | |
| """Test MultiTierCache initialization.""" | |
| cache = MultiTierCache( | |
| memory_size=200, | |
| memory_max_mb=100.0, | |
| sqlite_path=None, | |
| redis_config=None, | |
| ) | |
| assert cache.l1 is not None | |
| assert isinstance(cache.l1, MemoryCache) | |
| # L2 may be present if SQLITE_AVAILABLE is True | |
| assert cache.l3 is None | |
| assert cache._hit_distribution == {"L1": 0, "L2": 0, "L3": 0} | |
| await cache.close() | |
| async def test_multitier_cache_get_l1_hit(self, multitier_cache): | |
| """Test get when value is in L1 cache.""" | |
| await multitier_cache.l1.set("test_key", "l1_value") | |
| result = await multitier_cache.get("test_key") | |
| assert result == "l1_value" | |
| assert multitier_cache._hit_distribution["L1"] == 1 | |
| async def test_multitier_cache_get_l2_hit(self, multitier_cache): | |
| """Test get when value is in L2 (SQLite) cache - promotes to L1.""" | |
| # This test depends on SQLite availability | |
| if multitier_cache.l2 is None: | |
| pytest.skip("SQLite not available") | |
| await multitier_cache.l2.set("test_key", "l2_value") | |
| result = await multitier_cache.get("test_key") | |
| assert result == "l2_value" | |
| assert multitier_cache._hit_distribution["L2"] == 1 | |
| # Should be promoted to L1 | |
| l1_value = await multitier_cache.l1.get("test_key") | |
| assert l1_value == "l2_value" | |
| async def test_multitier_cache_get_l3_hit(self, multitier_cache_with_redis, mock_redis_pool): | |
| """Test get when value is in L3 (Redis) cache - promotes to L1/L2.""" | |
| cache = multitier_cache_with_redis | |
| if cache.l3 is None: | |
| pytest.skip("Redis not available") | |
| # Clear L1/L2 to ensure we hit L3 | |
| await cache.l1.clear() | |
| if cache.l2: | |
| await cache.l2.clear() | |
| serialized = pickle.dumps("l3_value") | |
| mock_redis_pool.get = AsyncMock(return_value=serialized) | |
| result = await cache.get("test_key") | |
| assert result == "l3_value" | |
| assert cache._hit_distribution["L3"] == 1 | |
| async def test_multitier_cache_get_miss(self, multitier_cache): | |
| """Test get when value is not in any tier.""" | |
| result = await multitier_cache.get("missing_key") | |
| assert result is None | |
| assert sum(multitier_cache._hit_distribution.values()) == 0 | |
| async def test_multitier_cache_set_all_tiers(self, multitier_cache_with_redis, mock_redis_pool): | |
| """Test set with tiers='all' sets in all available tiers.""" | |
| cache = multitier_cache_with_redis | |
| result = await cache.set("test_key", "test_value", tiers="all") | |
| assert result is True | |
| # Check L1 | |
| l1_value = await cache.l1.get("test_key") | |
| assert l1_value == "test_value" | |
| # L3 (Redis) should have been called | |
| if cache.l3: | |
| mock_redis_pool.set.assert_called_once() | |
| async def test_multitier_cache_set_memory_tier(self, multitier_cache_with_redis, mock_redis_pool): | |
| """Test set with tiers='memory' only sets in L1.""" | |
| cache = multitier_cache_with_redis | |
| result = await cache.set("test_key", "test_value", tiers="memory") | |
| assert result is True | |
| l1_value = await cache.l1.get("test_key") | |
| assert l1_value == "test_value" | |
| # L3 should NOT have been called | |
| if cache.l3: | |
| mock_redis_pool.set.assert_not_called() | |
| async def test_multitier_cache_set_persistent_tier(self, multitier_cache): | |
| """Test set with tiers='persistent' only sets in L2.""" | |
| if multitier_cache.l2 is None: | |
| pytest.skip("SQLite not available") | |
| result = await multitier_cache.set("test_key", "test_value", tiers="persistent") | |
| assert result is True | |
| # L2 should have the value | |
| l2_value = await multitier_cache.l2.get("test_key") | |
| assert l2_value == "test_value" | |
| # L1 should NOT have the value | |
| l1_value = await multitier_cache.l1.get("test_key") | |
| assert l1_value is None | |
| async def test_multitier_cache_delete(self, multitier_cache_with_redis, mock_redis_pool): | |
| """Test delete removes from all tiers.""" | |
| cache = multitier_cache_with_redis | |
| # Set in L1 | |
| await cache.l1.set("test_key", "l1_value") | |
| mock_redis_pool.delete = AsyncMock(return_value=1) | |
| result = await cache.delete("test_key") | |
| assert result is True | |
| # Should be deleted from L1 | |
| l1_value = await cache.l1.get("test_key") | |
| assert l1_value is None | |
| # Should be deleted from L3 | |
| if cache.l3: | |
| mock_redis_pool.delete.assert_called_once_with("test_key") | |
| async def test_multitier_cache_mget_all_l1(self, multitier_cache): | |
| """Test mget when all keys are in L1.""" | |
| await multitier_cache.l1.set("key1", "value1") | |
| await multitier_cache.l1.set("key2", "value2") | |
| result = await multitier_cache.mget(["key1", "key2"]) | |
| assert result == {"key1": "value1", "key2": "value2"} | |
| assert multitier_cache._hit_distribution["L1"] == 2 | |
| async def test_multitier_cache_mget_partial_l1(self, multitier_cache): | |
| """Test mget when some keys are in L1.""" | |
| await multitier_cache.l1.set("key1", "value1") | |
| result = await multitier_cache.mget(["key1", "key2"]) | |
| assert result == {"key1": "value1"} | |
| assert multitier_cache._hit_distribution["L1"] == 1 | |
| async def test_multitier_cache_mget_with_l2(self, multitier_cache): | |
| """Test mget promotes L2 hits to L1.""" | |
| if multitier_cache.l2 is None: | |
| pytest.skip("SQLite not available") | |
| await multitier_cache.l2.set("key1", "l2_value") | |
| result = await multitier_cache.mget(["key1"]) | |
| assert result == {"key1": "l2_value"} | |
| assert multitier_cache._hit_distribution["L2"] == 1 | |
| # Should be promoted to L1 | |
| l1_value = await multitier_cache.l1.get("key1") | |
| assert l1_value == "l2_value" | |
| async def test_multitier_cache_mget_with_l3(self, multitier_cache_with_redis, mock_redis_pool): | |
| """Test mget promotes L3 hits to L1/L2.""" | |
| cache = multitier_cache_with_redis | |
| if cache.l3 is None: | |
| pytest.skip("Redis not available") | |
| # Clear L1/L2 to ensure we hit L3 | |
| await cache.l1.clear() | |
| if cache.l2: | |
| await cache.l2.clear() | |
| serialized1 = pickle.dumps("l3_value1") | |
| mock_redis_pool.mget = AsyncMock(return_value=[serialized1]) | |
| result = await cache.mget(["key1"]) | |
| assert result == {"key1": "l3_value1"} | |
| assert cache._hit_distribution["L3"] == 1 | |
| async def test_multitier_cache_mget_empty(self, multitier_cache): | |
| """Test mget with empty keys list.""" | |
| result = await multitier_cache.mget([]) | |
| assert result == {} | |
| async def test_multitier_cache_close(self, multitier_cache_with_redis, mock_redis_pool): | |
| """Test close closes all tiers.""" | |
| cache = multitier_cache_with_redis | |
| await cache.close() | |
| # L3 (Redis) should be closed | |
| if cache.l3: | |
| mock_redis_pool.close.assert_called_once() | |
| async def test_multitier_cache_get_stats(self, multitier_cache): | |
| """Test getting combined statistics from all tiers.""" | |
| # Add some hits | |
| await multitier_cache.l1.set("key1", "value1") | |
| await multitier_cache.get("key1") # L1 hit | |
| stats = multitier_cache.get_stats() | |
| assert "hit_distribution" in stats | |
| assert "L1_memory" in stats | |
| assert stats["hit_distribution"]["L1"]["count"] == 1 | |
| assert stats["hit_distribution"]["L1"]["percentage"] == 100.0 | |
| async def test_multitier_cache_get_stats_empty(self, multitier_cache): | |
| """Test getting stats with no hits.""" | |
| stats = multitier_cache.get_stats() | |
| assert stats["hit_distribution"]["L1"]["percentage"] == 0 | |
| assert stats["hit_distribution"]["L2"]["percentage"] == 0 | |
| assert stats["hit_distribution"]["L3"]["percentage"] == 0 | |
| # ============================================================================ | |
| # Integration Tests | |
| # ============================================================================ | |
| class TestCacheIntegration: | |
| """Integration tests for cache operations.""" | |
| async def test_redis_cache_full_lifecycle(self, mock_redis_pool): | |
| """Test complete RedisCache lifecycle.""" | |
| with patch("core.cache.REDIS_AVAILABLE", True): | |
| cache = RedisCache() | |
| cache._pool = mock_redis_pool | |
| # Set values | |
| mock_redis_pool.set = AsyncMock(return_value=True) | |
| await cache.set("key1", "value1", ttl=300) | |
| await cache.set("key2", "value2", ttl=300) | |
| # Get values | |
| mock_redis_pool.get = AsyncMock(return_value=pickle.dumps("value1")) | |
| result1 = await cache.get("key1") | |
| assert result1 == "value1" | |
| # Check exists | |
| mock_redis_pool.exists = AsyncMock(return_value=1) | |
| exists = await cache.exists("key2") | |
| assert exists is True | |
| # Delete | |
| mock_redis_pool.delete = AsyncMock(return_value=1) | |
| deleted = await cache.delete("key1") | |
| assert deleted is True | |
| # Clear | |
| mock_redis_pool.flushdb = AsyncMock(return_value=True) | |
| cleared = await cache.clear() | |
| assert cleared is True | |
| await cache.close() | |
| async def test_multitier_cache_promotion(self): | |
| """Test value promotion between tiers.""" | |
| cache = MultiTierCache(memory_size=100, sqlite_path=None, redis_config=None) | |
| # Start with value in L1 | |
| await cache.l1.set("key1", "value1") | |
| # Get should hit L1 | |
| result = await cache.get("key1") | |
| assert result == "value1" | |
| assert cache._hit_distribution["L1"] == 1 | |
| # Stats should show 100% L1 hits | |
| stats = cache.get_stats() | |
| assert stats["hit_distribution"]["L1"]["percentage"] == 100.0 | |
| await cache.close() | |
| async def test_multitier_cache_with_redis_config(self, mock_redis_pool): | |
| """Test MultiTierCache with Redis configuration.""" | |
| with patch("core.cache.REDIS_AVAILABLE", True): | |
| with patch("core.cache.redis.Redis", return_value=mock_redis_pool): | |
| cache = MultiTierCache( | |
| memory_size=100, | |
| redis_config={"host": "localhost", "port": 6379, "db": 0}, | |
| ) | |
| # L3 should be initialized | |
| assert cache.l3 is not None | |
| assert isinstance(cache.l3, RedisCache) | |
| await cache.close() | |
| async def test_multitier_cache_redis_init_failure(self): | |
| """Test MultiTierCache handles Redis initialization failure.""" | |
| with patch("core.cache.REDIS_AVAILABLE", True): | |
| with patch("core.cache.RedisCache") as MockRedisCache: | |
| MockRedisCache.side_effect = Exception("Connection refused") | |
| # Should not raise, just log warning | |
| cache = MultiTierCache( | |
| memory_size=100, | |
| redis_config={"host": "localhost", "port": 6379}, | |
| ) | |
| # L3 should be None due to failure (exception caught in __init__) | |
| assert cache.l3 is None | |
| await cache.close() | |
| # ============================================================================ | |
| # Cache Backend Factory Tests | |
| # ============================================================================ | |
| class TestCacheBackendFactory: | |
| """Test _get_cache_backend factory function.""" | |
| async def test_get_cache_backend_memory(self): | |
| """Test getting memory cache backend.""" | |
| # Reset global instance | |
| import core.cache as cache_module | |
| cache_module._memory_cache = None | |
| cache = _get_cache_backend("memory") | |
| assert isinstance(cache, MemoryCache) | |
| async def test_get_cache_backend_redis(self): | |
| """Test getting Redis cache backend.""" | |
| with patch("core.cache.REDIS_AVAILABLE", True): | |
| with patch("core.cache.redis.Redis", return_value=AsyncMock()): | |
| import core.cache as cache_module | |
| cache_module._redis_cache = None | |
| cache = _get_cache_backend("redis") | |
| assert isinstance(cache, RedisCache) | |
| async def test_get_cache_backend_instance(self, memory_cache): | |
| """Test passing through existing cache instance.""" | |
| result = _get_cache_backend(memory_cache) | |
| assert result is memory_cache | |
| async def test_get_cache_backend_invalid(self): | |
| """Test getting invalid backend raises error.""" | |
| with pytest.raises(ValueError, match="Unknown cache backend"): | |
| _get_cache_backend("invalid_backend") | |
| # ============================================================================ | |
| # Error Handling Tests | |
| # ============================================================================ | |
| class TestCacheErrorHandling: | |
| """Test error handling scenarios.""" | |
| async def test_redis_cache_get_connection_error(self, redis_cache, mock_redis_pool): | |
| """Test handling connection error on get.""" | |
| mock_redis_pool.get = AsyncMock(side_effect=ConnectionError("Connection refused")) | |
| result = await redis_cache.get("key") | |
| assert result is None | |
| async def test_redis_cache_set_timeout_error(self, redis_cache, mock_redis_pool): | |
| """Test handling timeout error on set.""" | |
| mock_redis_pool.set = AsyncMock(side_effect=TimeoutError("Operation timed out")) | |
| result = await redis_cache.set("key", "value") | |
| assert result is False | |
| async def test_redis_cache_mget_partial_failure(self, redis_cache, mock_redis_pool): | |
| """Test mget with mixed success/failure.""" | |
| value1 = pickle.dumps("value1") | |
| mock_redis_pool.mget = AsyncMock(return_value=[value1, None]) | |
| result = await redis_cache.mget(["key1", "key2"]) | |
| assert result == {"key1": "value1"} | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v"]) | |
Xet Storage Details
- Size:
- 30.3 kB
- Xet hash:
- 6266e7c11d3f38f84688f620fb0d692908b2bdbb26c7630f30af9cff15404e16
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.