Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_cache.py
"""
Comprehensive Unit Tests for core/cache.py - Target: 80%+ Coverage
This test file covers:
1. CacheStats - All properties and edge cases
2. CacheBackend - Abstract base class methods
3. MemoryCache - Full async operations, LRU eviction, TTL, concurrency
4. SQLiteCache - Database operations, persistence, batch operations, error handling
5. RedisCache - Mocked Redis operations, batch operations, error handling
6. MultiTierCache - L1/L2/L3 caching, promotion/demotion, hit distribution
7. cached decorator - Function result caching, sync/async support, conditions
8. CVE utility functions - CVE-specific caching
9. Error handling and edge cases throughout
Run with: pytest tests/unit/test_cache.py -v --cov=core.cache --cov-report=term-missing
"""
import asyncio
import hashlib
import json
import pickle
import sys
import time
from collections import OrderedDict
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
# Import all cache components
from core.cache import (
REDIS_AVAILABLE,
SQLITE_AVAILABLE,
CacheBackend,
CacheStats,
MemoryCache,
MultiTierCache,
RedisCache,
SQLiteCache,
_get_cache_backend,
_memory_cache,
_redis_cache,
_sqlite_cache,
cache_cve,
cached,
generate_cache_key,
get_cached_cve,
)
# =============================================================================
# Fixtures
# =============================================================================
@pytest.fixture(autouse=True)
def reset_global_caches():
"""Reset global cache instances before each test."""
global _memory_cache, _sqlite_cache, _redis_cache
_memory_cache = None
_sqlite_cache = None
_redis_cache = None
yield
_memory_cache = None
_sqlite_cache = None
_redis_cache = None
@pytest.fixture
async def memory_cache():
"""Create a fresh MemoryCache instance."""
cache = MemoryCache(max_size=100, max_memory_mb=10.0)
yield cache
await cache.clear()
@pytest.fixture
async def sqlite_cache(tmp_path):
"""Create a SQLiteCache with temp database."""
if not SQLITE_AVAILABLE:
pytest.skip("aiosqlite not available")
db_path = tmp_path / "test_cache.db"
cache = SQLiteCache(db_path=db_path)
yield cache
await cache.clear()
await cache.close()
@pytest.fixture
def mock_redis():
"""Create a mock Redis client."""
mock_pool = AsyncMock()
mock_pool.get = AsyncMock(return_value=None)
mock_pool.set = AsyncMock(return_value=True)
mock_pool.delete = AsyncMock(return_value=1)
mock_pool.exists = AsyncMock(return_value=1)
mock_pool.flushdb = AsyncMock(return_value=True)
mock_pool.mget = AsyncMock(return_value=[])
mock_pool.mset = AsyncMock(return_value=True)
mock_pool.pipeline = MagicMock(return_value=AsyncMock(execute=AsyncMock(return_value=[True, True])))
mock_pool.close = AsyncMock()
return mock_pool
# =============================================================================
# Test CacheStats
# =============================================================================
class TestCacheStats:
"""Comprehensive tests for CacheStats dataclass."""
def test_initialization_defaults(self):
"""Test default initialization."""
stats = CacheStats()
assert stats.hits == 0
assert stats.misses == 0
assert stats.evictions == 0
assert stats.total_gets == 0
assert stats.total_sets == 0
assert stats.total_deletes == 0
assert stats.bytes_stored == 0
def test_initialization_custom(self):
"""Test custom initialization."""
stats = CacheStats(
hits=100,
misses=50,
evictions=10,
total_gets=150,
total_sets=200,
total_deletes=5,
bytes_stored=1024,
)
assert stats.hits == 100
assert stats.misses == 50
assert stats.evictions == 10
assert stats.total_gets == 150
assert stats.total_sets == 200
assert stats.total_deletes == 5
assert stats.bytes_stored == 1024
def test_hit_rate_calculation(self):
"""Test hit rate calculation."""
stats = CacheStats(hits=80, misses=20, total_gets=100)
assert stats.hit_rate == 0.8
stats = CacheStats(hits=100, misses=0, total_gets=100)
assert stats.hit_rate == 1.0
stats = CacheStats(hits=0, misses=100, total_gets=100)
assert stats.hit_rate == 0.0
def test_hit_rate_empty(self):
"""Test hit rate with no gets (division by zero protection)."""
stats = CacheStats()
assert stats.hit_rate == 0.0
def test_miss_rate_calculation(self):
"""Test miss rate calculation."""
stats = CacheStats(hits=75, misses=25, total_gets=100)
assert stats.miss_rate == 0.25
def test_miss_rate_empty(self):
"""Test miss rate with no gets."""
stats = CacheStats()
assert stats.miss_rate == 0.0
def test_to_dict_complete(self):
"""Test to_dict with all fields."""
stats = CacheStats(
hits=80,
misses=20,
evictions=5,
total_gets=100,
total_sets=50,
total_deletes=10,
bytes_stored=2048,
)
d = stats.to_dict()
assert d["hits"] == 80
assert d["misses"] == 20
assert d["evictions"] == 5
assert d["hit_rate"] == "80.00%"
assert d["miss_rate"] == "20.00%"
assert d["total_gets"] == 100
assert d["total_sets"] == 50
assert d["total_deletes"] == 10
assert d["bytes_stored"] == 2048
def test_stats_mutation(self):
"""Test that stats can be mutated."""
stats = CacheStats()
stats.hits += 10
stats.total_gets += 10
assert stats.hit_rate == 1.0
def test_to_dict_with_zero_values(self):
"""Test to_dict with all zeros."""
stats = CacheStats()
d = stats.to_dict()
assert d["hit_rate"] == "0.00%"
assert d["miss_rate"] == "0.00%"
# =============================================================================
# Test CacheBackend Abstract Class
# =============================================================================
class TestCacheBackend:
"""Tests for CacheBackend abstract class."""
def test_init(self):
"""Test initialization."""
backend = CacheBackend()
assert isinstance(backend.stats, CacheStats)
def test_get_stats(self):
"""Test get_stats returns stats."""
backend = CacheBackend()
stats = backend.get_stats()
assert isinstance(stats, CacheStats)
@pytest.mark.asyncio
async def test_default_mget_empty(self):
"""Test default mget implementation with empty keys."""
backend = CacheBackend()
backend.get = AsyncMock(return_value=None)
results = await backend.mget([])
assert results == {}
@pytest.mark.asyncio
async def test_default_mget_with_values(self):
"""Test default mget returns values."""
backend = CacheBackend()
backend.get = AsyncMock(side_effect=["value1", None, "value2"])
results = await backend.mget(["key1", "key2", "key3"])
assert results == {"key1": "value1", "key3": "value2"}
@pytest.mark.asyncio
async def test_default_mset_empty(self):
"""Test default mset with empty items."""
backend = CacheBackend()
backend.set = AsyncMock(return_value=True)
result = await backend.mset({})
assert result is True
@pytest.mark.asyncio
async def test_default_mset_with_items(self):
"""Test default mset with items."""
backend = CacheBackend()
backend.set = AsyncMock(return_value=True)
result = await backend.mset({"key1": "value1", "key2": "value2"})
assert result is True
assert backend.set.call_count == 2
@pytest.mark.asyncio
async def test_default_mset_partial_failure(self):
"""Test default mset when some sets fail."""
backend = CacheBackend()
backend.set = AsyncMock(side_effect=[True, False, True])
result = await backend.mset({"key1": "v1", "key2": "v2", "key3": "v3"})
assert result is False
@pytest.mark.asyncio
async def test_default_close(self):
"""Test default close does nothing."""
backend = CacheBackend()
await backend.close() # Should not raise
# =============================================================================
# Test MemoryCache
# =============================================================================
class TestMemoryCacheInitialization:
"""Tests for MemoryCache initialization."""
def test_init_defaults(self):
"""Test initialization with defaults."""
cache = MemoryCache()
assert cache._max_size == 1000
assert cache._max_memory_bytes == 100 * 1024 * 1024 # 100 MB
assert cache._default_ttl is None
assert isinstance(cache._cache, OrderedDict)
assert cache._current_memory == 0
def test_init_custom(self):
"""Test initialization with custom values."""
cache = MemoryCache(max_size=500, max_memory_mb=50.0, default_ttl=3600)
assert cache._max_size == 500
assert cache._max_memory_bytes == 50 * 1024 * 1024
assert cache._default_ttl == 3600
class TestMemoryCacheAsync:
"""Comprehensive async tests for MemoryCache."""
@pytest.mark.asyncio
async def test_get_existing_key(self, memory_cache):
"""Test getting an existing key."""
await memory_cache.set("key1", "value1")
value = await memory_cache.get("key1")
assert value == "value1"
assert memory_cache.stats.hits == 1
assert memory_cache.stats.total_gets == 1
@pytest.mark.asyncio
async def test_get_nonexistent_key(self, memory_cache):
"""Test getting a non-existent key."""
value = await memory_cache.get("nonexistent")
assert value is None
assert memory_cache.stats.misses == 1
assert memory_cache.stats.total_gets == 1
@pytest.mark.asyncio
async def test_set_and_get_multiple(self, memory_cache):
"""Test setting and getting multiple values."""
data = {
"key1": "value1",
"key2": 42,
"key3": {"nested": "dict"},
"key4": [1, 2, 3],
}
for key, value in data.items():
await memory_cache.set(key, value)
for key, expected_value in data.items():
actual_value = await memory_cache.get(key)
assert actual_value == expected_value
assert memory_cache.stats.total_sets == 4
assert memory_cache.stats.total_gets == 4
assert memory_cache.stats.hits == 4
@pytest.mark.asyncio
async def test_set_with_ttl_expires(self, memory_cache):
"""Test that values with TTL expire correctly."""
await memory_cache.set("key1", "value1", ttl=0.1)
# Should exist immediately
value = await memory_cache.get("key1")
assert value == "value1"
# Wait for expiry
await asyncio.sleep(0.2)
# Should be expired
value = await memory_cache.get("key1")
assert value is None
assert memory_cache.stats.misses >= 1
@pytest.mark.asyncio
async def test_set_default_ttl(self, memory_cache):
"""Test default TTL from initialization."""
cache = MemoryCache(default_ttl=3600)
await cache.set("key1", "value1")
value = await cache.get("key1")
assert value == "value1"
assert "key1" in cache._expiry
@pytest.mark.asyncio
async def test_delete_existing(self, memory_cache):
"""Test deleting an existing key."""
await memory_cache.set("key1", "value1")
result = await memory_cache.delete("key1")
assert result is True
value = await memory_cache.get("key1")
assert value is None
assert memory_cache.stats.total_deletes == 1
@pytest.mark.asyncio
async def test_delete_nonexistent(self, memory_cache):
"""Test deleting a non-existent key."""
result = await memory_cache.delete("nonexistent")
assert result is False
@pytest.mark.asyncio
async def test_exists(self, memory_cache):
"""Test exists method."""
await memory_cache.set("key1", "value1")
assert await memory_cache.exists("key1") is True
assert await memory_cache.exists("nonexistent") is False
@pytest.mark.asyncio
async def test_exists_with_expired(self, memory_cache):
"""Test exists returns False for expired keys."""
await memory_cache.set("key1", "value1", ttl=0.1)
await asyncio.sleep(0.2)
assert await memory_cache.exists("key1") is False
@pytest.mark.asyncio
async def test_clear(self, memory_cache):
"""Test clearing all cache entries."""
await memory_cache.set("key1", "value1")
await memory_cache.set("key2", "value2")
result = await memory_cache.clear()
assert result is True
assert await memory_cache.get("key1") is None
assert await memory_cache.get("key2") is None
assert len(memory_cache._cache) == 0
assert memory_cache._current_memory == 0
assert memory_cache._expiry == {}
assert memory_cache._sizes == {}
@pytest.mark.asyncio
async def test_update_existing_key(self, memory_cache):
"""Test updating an existing key."""
await memory_cache.set("key1", "value1")
await memory_cache.set("key1", "updated_value")
value = await memory_cache.get("key1")
assert value == "updated_value"
@pytest.mark.asyncio
async def test_get_stats(self, memory_cache):
"""Test getting cache statistics."""
await memory_cache.set("key1", "value1")
await memory_cache.get("key1")
await memory_cache.get("nonexistent")
await memory_cache.delete("key1")
stats = memory_cache.get_stats()
assert isinstance(stats, CacheStats)
assert stats.total_sets == 1
assert stats.total_gets == 2
assert stats.total_deletes == 1
assert stats.hits == 1
assert stats.misses == 1
class TestMemoryCacheLRU:
"""Tests for LRU eviction in MemoryCache."""
@pytest.mark.asyncio
async def test_lru_eviction(self, memory_cache):
"""Test LRU eviction when cache is full."""
cache = MemoryCache(max_size=3, max_memory_mb=10.0)
# Add 3 items
await cache.set("key1", "value1")
await cache.set("key2", "value2")
await cache.set("key3", "value3")
# Access key1 to make it most recently used
await cache.get("key1")
# Add 4th item - should evict key2 (least recently used)
await cache.set("key4", "value4")
assert await cache.get("key1") is not None
assert await cache.get("key2") is None
assert await cache.get("key3") is not None
assert await cache.get("key4") is not None
assert cache.stats.evictions >= 1
@pytest.mark.asyncio
async def test_memory_eviction(self, memory_cache):
"""Test eviction based on memory limit."""
cache = MemoryCache(max_size=100, max_memory_mb=0.001)
large_value = "x" * 1000
result = await cache.set("large", large_value)
# Should be rejected (larger than 50% of max memory)
assert result is False
@pytest.mark.asyncio
async def test_memory_tracking(self, memory_cache):
"""Test accurate memory tracking."""
value = {"test": "data" * 100}
await memory_cache.set("key1", value)
assert memory_cache._current_memory > 0
assert memory_cache.stats.bytes_stored == memory_cache._current_memory
def test_evict_lru_empty(self):
"""Test _evict_lru with empty cache."""
cache = MemoryCache()
cache._evict_lru() # Should not raise
assert len(cache._cache) == 0
def test_evict_lru_with_expired(self):
"""Test _evict_lru removes expired entries."""
cache = MemoryCache()
cache._cache["expired"] = "value"
cache._expiry["expired"] = time.time() - 100 # Expired
cache._sizes["expired"] = 100
cache._evict_lru()
assert cache.stats.evictions >= 1
assert "expired" not in cache._cache
def test_remove_method(self):
"""Test _remove internal method."""
cache = MemoryCache()
cache._cache["key1"] = "value1"
cache._sizes["key1"] = 100
cache._expiry["key1"] = time.time() + 3600
cache._current_memory = 100
cache._remove("key1")
assert "key1" not in cache._cache
assert "key1" not in cache._sizes
assert "key1" not in cache._expiry
assert cache._current_memory == 0
def test_remove_nonexistent(self):
"""Test _remove with non-existent key."""
cache = MemoryCache()
cache._remove("nonexistent") # Should not raise
class TestMemoryCacheBatch:
"""Tests for batch operations in MemoryCache."""
@pytest.mark.asyncio
async def test_mget_multiple_keys(self, memory_cache):
"""Test batch get."""
await memory_cache.set("key1", "value1")
await memory_cache.set("key2", "value2")
await memory_cache.set("key3", "value3")
results = await memory_cache.mget(["key1", "key2", "nonexistent"])
assert results["key1"] == "value1"
assert results["key2"] == "value2"
assert "nonexistent" not in results
@pytest.mark.asyncio
async def test_mget_empty_list(self, memory_cache):
"""Test mget with empty list."""
results = await memory_cache.mget([])
assert results == {}
@pytest.mark.asyncio
async def test_mget_with_expired(self, memory_cache):
"""Test mget handles expired keys."""
await memory_cache.set("key1", "value1", ttl=0.1)
await memory_cache.set("key2", "value2")
await asyncio.sleep(0.2)
results = await memory_cache.mget(["key1", "key2"])
assert "key1" not in results
assert results["key2"] == "value2"
@pytest.mark.asyncio
async def test_mset_multiple(self, memory_cache):
"""Test batch set."""
items = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
}
result = await memory_cache.mset(items)
assert result is True
for key, value in items.items():
assert await memory_cache.get(key) == value
@pytest.mark.asyncio
async def test_mset_with_ttl(self, memory_cache):
"""Test batch set with TTL."""
items = {"key1": "value1", "key2": "value2"}
await memory_cache.mset(items, ttl=3600)
assert "key1" in memory_cache._expiry
assert "key2" in memory_cache._expiry
@pytest.mark.asyncio
async def test_mset_empty_dict(self, memory_cache):
"""Test mset with empty dict."""
result = await memory_cache.mset({})
assert result is True
class TestMemoryCacheConcurrency:
"""Tests for concurrent access to MemoryCache."""
@pytest.mark.asyncio
async def test_concurrent_reads(self, memory_cache):
"""Test concurrent reads."""
await memory_cache.set("key1", "value1")
async def read_key():
return await memory_cache.get("key1")
results = await asyncio.gather(*[read_key() for _ in range(100)])
assert all(r == "value1" for r in results)
assert memory_cache.stats.hits == 100
@pytest.mark.asyncio
async def test_concurrent_writes(self, memory_cache):
"""Test concurrent writes."""
async def write_key(i):
return await memory_cache.set(f"key{i}", f"value{i}")
results = await asyncio.gather(*[write_key(i) for i in range(50)])
assert all(results)
assert memory_cache.stats.total_sets == 50
@pytest.mark.asyncio
async def test_concurrent_mixed_operations(self, memory_cache):
"""Test mixed concurrent operations."""
await memory_cache.set("shared", "initial")
async def mixed_op(i):
if i % 3 == 0:
return await memory_cache.get("shared")
elif i % 3 == 1:
return await memory_cache.set(f"key{i}", f"value{i}")
else:
return await memory_cache.delete(f"key{i - 1}")
results = await asyncio.gather(*[mixed_op(i) for i in range(30)])
assert len(results) == 30
class TestMemoryCacheEdgeCases:
"""Edge case tests for MemoryCache."""
@pytest.mark.asyncio
async def test_value_with_pickle_error(self, memory_cache):
"""Test handling of values that can't be pickled."""
# Mock pickle.dumps to raise an error
with patch(
"core.cache.pickle.dumps",
side_effect=pickle.PicklingError("Cannot pickle"),
):
# Should fall back to sys.getsizeof
result = await memory_cache.set("key1", "value1")
assert result is True
@pytest.mark.asyncio
async def test_set_returns_false_for_oversized(self, memory_cache):
"""Test that set returns False for oversized values."""
cache = MemoryCache(max_memory_mb=0.001) # Very small memory limit
# Create a value larger than 50% of max_memory_bytes
large_value = "x" * 10000
result = await cache.set("key1", large_value)
assert result is False
# =============================================================================
# Test SQLiteCache
# =============================================================================
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
class TestSQLiteCacheInitialization:
"""Tests for SQLiteCache initialization."""
def test_sqlite_init_defaults(self):
"""Test SQLiteCache initialization with defaults."""
cache = SQLiteCache()
assert cache._pool_size == 5
assert cache._cleanup_interval == 3600
assert cache._db is None
def test_sqlite_custom_path(self, tmp_path):
"""Test SQLiteCache with custom path."""
custom_path = tmp_path / "test_cache.db"
cache = SQLiteCache(db_path=custom_path)
assert cache.db_path == custom_path
assert cache.db_path.parent.exists()
def test_sqlite_custom_pool_size(self, tmp_path):
"""Test SQLiteCache with custom pool size and cleanup interval."""
custom_path = tmp_path / "test_cache.db"
cache = SQLiteCache(db_path=custom_path, pool_size=10, cleanup_interval=1800)
assert cache._pool_size == 10
assert cache._cleanup_interval == 1800
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
class TestSQLiteCacheAsync:
"""Comprehensive async tests for SQLiteCache."""
@pytest.mark.asyncio
async def test_get_set_delete(self, sqlite_cache):
"""Test basic get/set/delete."""
result = await sqlite_cache.set("key1", "value1")
assert result is True
value = await sqlite_cache.get("key1")
assert value == "value1"
result = await sqlite_cache.delete("key1")
assert result is True
value = await sqlite_cache.get("key1")
assert value is None
@pytest.mark.asyncio
async def test_set_with_ttl(self, sqlite_cache):
"""Test TTL in SQLite cache."""
await sqlite_cache.set("key1", "value1", ttl=1)
value = await sqlite_cache.get("key1")
assert value == "value1"
await asyncio.sleep(1.5)
value = await sqlite_cache.get("key1")
assert value is None
@pytest.mark.asyncio
async def test_exists(self, sqlite_cache):
"""Test exists method."""
await sqlite_cache.set("key1", "value1")
assert await sqlite_cache.exists("key1") is True
assert await sqlite_cache.exists("nonexistent") is False
@pytest.mark.asyncio
async def test_clear(self, sqlite_cache):
"""Test clear."""
await sqlite_cache.set("key1", "value1")
await sqlite_cache.set("key2", "value2")
result = await sqlite_cache.clear()
assert result is True
assert await sqlite_cache.get("key1") is None
assert await sqlite_cache.get("key2") is None
@pytest.mark.asyncio
async def test_complex_types(self, sqlite_cache):
"""Test storing complex types."""
data = {
"dict": {"nested": "value", "number": 42},
"list": [1, 2, 3, {"key": "value"}],
"tuple": (1, 2, 3),
"set": {1, 2, 3},
}
for key, value in data.items():
await sqlite_cache.set(key, value)
retrieved = await sqlite_cache.get(key)
assert retrieved == value
@pytest.mark.asyncio
async def test_persistence(self, sqlite_cache):
"""Test that data persists across cache instances."""
db_path = sqlite_cache.db_path
await sqlite_cache.set("persistent", "data")
await sqlite_cache.close()
new_cache = SQLiteCache(db_path=db_path)
value = await new_cache.get("persistent")
assert value == "data"
await new_cache.close()
@pytest.mark.asyncio
async def test_cleanup_expired(self, sqlite_cache):
"""Test explicit cleanup of expired entries."""
# Set with a very short TTL so it expires quickly
await sqlite_cache.set("key1", "value1", ttl=1)
# Wait for expiry
await asyncio.sleep(1.1)
# Cleanup should remove expired entries
await sqlite_cache.cleanup_expired()
value = await sqlite_cache.get("key1")
assert value is None
@pytest.mark.asyncio
async def test_stats_tracking(self, sqlite_cache):
"""Test statistics tracking."""
await sqlite_cache.set("key1", "value1")
await sqlite_cache.get("key1") # hit
await sqlite_cache.get("nonexistent") # miss
await sqlite_cache.delete("key1")
stats = sqlite_cache.get_stats()
assert stats.total_sets == 1
assert stats.total_gets == 2
assert stats.hits == 1
assert stats.misses == 1
assert stats.total_deletes == 1
@pytest.mark.asyncio
async def test_get_db_creates_table(self, sqlite_cache):
"""Test that _get_db creates the cache table."""
db = await sqlite_cache._get_db()
assert db is not None
# Check that the table was created
cursor = await db.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='cache'")
row = await cursor.fetchone()
assert row is not None
@pytest.mark.asyncio
async def test_maybe_cleanup(self, sqlite_cache):
"""Test the _maybe_cleanup method."""
# Set a very short cleanup interval
sqlite_cache._cleanup_interval = 0
sqlite_cache._last_cleanup = 0
# Add an expired entry
await sqlite_cache.set("expired", "value", ttl=1)
await asyncio.sleep(1.1)
# Trigger cleanup via get
value = await sqlite_cache.get("other")
assert value is None
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
class TestSQLiteCacheBatch:
"""Tests for batch operations in SQLiteCache."""
@pytest.mark.asyncio
async def test_mget(self, sqlite_cache):
"""Test batch get."""
await sqlite_cache.set("key1", "value1")
await sqlite_cache.set("key2", "value2")
results = await sqlite_cache.mget(["key1", "key2", "nonexistent"])
assert results["key1"] == "value1"
assert results["key2"] == "value2"
assert "nonexistent" not in results
@pytest.mark.asyncio
async def test_mget_empty(self, sqlite_cache):
"""Test mget with empty list."""
results = await sqlite_cache.mget([])
assert results == {}
@pytest.mark.asyncio
async def test_mset(self, sqlite_cache):
"""Test batch set."""
items = {"key1": "value1", "key2": "value2"}
result = await sqlite_cache.mset(items)
assert result is True
assert await sqlite_cache.get("key1") == "value1"
assert await sqlite_cache.get("key2") == "value2"
@pytest.mark.asyncio
async def test_mset_empty(self, sqlite_cache):
"""Test mset with empty dict."""
result = await sqlite_cache.mset({})
assert result is True
@pytest.mark.asyncio
async def test_mset_with_ttl(self, sqlite_cache):
"""Test batch set with TTL."""
items = {"key1": "value1", "key2": "value2"}
result = await sqlite_cache.mset(items, ttl=3600)
assert result is True
# Both should be accessible
assert await sqlite_cache.get("key1") == "value1"
assert await sqlite_cache.get("key2") == "value2"
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
class TestSQLiteCacheErrorHandling:
"""Error handling tests for SQLiteCache."""
@pytest.mark.asyncio
async def test_set_error_handling(self, sqlite_cache):
"""Test set error handling."""
# Mock pickle.dumps to raise an exception
with patch("core.cache.pickle.dumps", side_effect=Exception("Pickle error")):
result = await sqlite_cache.set("key1", "value1")
assert result is False
@pytest.mark.asyncio
async def test_delete_error_handling(self, sqlite_cache):
"""Test delete error handling."""
# Create a mock db that raises on execute
mock_db = AsyncMock()
mock_db.execute = AsyncMock(side_effect=Exception("DB error"))
mock_db.commit = AsyncMock()
sqlite_cache._db = mock_db
result = await sqlite_cache.delete("key1")
assert result is False
@pytest.mark.asyncio
async def test_clear_error_handling(self, sqlite_cache):
"""Test clear error handling."""
# Create a mock db that raises on execute
mock_db = AsyncMock()
mock_db.execute = AsyncMock(side_effect=Exception("DB error"))
mock_db.commit = AsyncMock()
sqlite_cache._db = mock_db
result = await sqlite_cache.clear()
assert result is False
@pytest.mark.asyncio
async def test_mget_error_handling(self, sqlite_cache):
"""Test mget error handling."""
# Create a mock db that raises on execute
mock_db = AsyncMock()
mock_db.execute = AsyncMock(side_effect=Exception("DB error"))
sqlite_cache._db = mock_db
result = await sqlite_cache.mget(["key1", "key2"])
assert result == {}
@pytest.mark.asyncio
async def test_mset_error_handling(self, sqlite_cache):
"""Test mset error handling with rollback."""
# Create a mock db that raises during execution
mock_db = AsyncMock()
# Need to handle BEGIN, first INSERT (success), second INSERT (fail), ROLLBACK
mock_db.execute = AsyncMock(side_effect=[None, None, Exception("DB error"), None])
mock_db.commit = AsyncMock()
sqlite_cache._db = mock_db
result = await sqlite_cache.mset({"key1": "value1", "key2": "value2"})
assert result is False
@pytest.mark.asyncio
async def test_cleanup_expired_error_handling(self, sqlite_cache):
"""Test cleanup_expired error handling."""
# Create a mock db that raises on execute
mock_db = AsyncMock()
mock_db.execute = AsyncMock(side_effect=Exception("DB error"))
mock_db.commit = AsyncMock()
sqlite_cache._db = mock_db
# Should not raise
await sqlite_cache.cleanup_expired()
@pytest.mark.skip(reason="Complex mocking with aiosqlite causes issues")
async def test_get_with_pickle_error(self, sqlite_cache):
"""Test get handles pickle error."""
pass
# =============================================================================
# Test RedisCache (Mocked)
# =============================================================================
class TestRedisCacheMocked:
"""Tests for RedisCache with mocked Redis."""
@pytest.mark.asyncio
async def test_get_success(self, mock_redis):
"""Test successful get."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.get = AsyncMock(return_value=pickle.dumps("value1"))
value = await cache.get("key1")
assert value == "value1"
assert cache.stats.hits == 1
@pytest.mark.asyncio
async def test_get_miss(self, mock_redis):
"""Test cache miss."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.get = AsyncMock(return_value=None)
value = await cache.get("key1")
assert value is None
assert cache.stats.misses == 1
@pytest.mark.asyncio
async def test_get_error(self, mock_redis):
"""Test get with error."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.get = AsyncMock(side_effect=Exception("Redis error"))
value = await cache.get("key1")
assert value is None
assert cache.stats.misses == 1
@pytest.mark.asyncio
async def test_set(self, mock_redis):
"""Test set."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
result = await cache.set("key1", "value1")
assert result is True
assert cache.stats.total_sets == 1
mock_redis.set.assert_called_once()
@pytest.mark.asyncio
async def test_set_with_ttl(self, mock_redis):
"""Test set with TTL."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
result = await cache.set("key1", "value1", ttl=3600)
assert result is True
mock_redis.set.assert_called_once()
# Check that ex parameter was passed
call_args = mock_redis.set.call_args
assert call_args.kwargs.get("ex") == 3600
@pytest.mark.asyncio
async def test_set_error(self, mock_redis):
"""Test set with error."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.set = AsyncMock(side_effect=Exception("Redis error"))
result = await cache.set("key1", "value1")
assert result is False
@pytest.mark.asyncio
async def test_delete(self, mock_redis):
"""Test delete."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
result = await cache.delete("key1")
assert result is True
assert cache.stats.total_deletes == 1
@pytest.mark.asyncio
async def test_delete_error(self, mock_redis):
"""Test delete with error."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.delete = AsyncMock(side_effect=Exception("Redis error"))
result = await cache.delete("key1")
assert result is False
@pytest.mark.asyncio
async def test_exists(self, mock_redis):
"""Test exists."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.exists = AsyncMock(return_value=1)
result = await cache.exists("key1")
assert result is True
@pytest.mark.asyncio
async def test_exists_false(self, mock_redis):
"""Test exists returns False."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.exists = AsyncMock(return_value=0)
result = await cache.exists("key1")
assert result is False
@pytest.mark.asyncio
async def test_exists_error(self, mock_redis):
"""Test exists with error."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.exists = AsyncMock(side_effect=Exception("Redis error"))
result = await cache.exists("key1")
assert result is False
@pytest.mark.asyncio
async def test_clear(self, mock_redis):
"""Test clear."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
result = await cache.clear()
assert result is True
mock_redis.flushdb.assert_called_once()
@pytest.mark.asyncio
async def test_clear_error(self, mock_redis):
"""Test clear with error."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.flushdb = AsyncMock(side_effect=Exception("Redis error"))
result = await cache.clear()
assert result is False
@pytest.mark.asyncio
async def test_mget(self, mock_redis):
"""Test batch get."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.mget = AsyncMock(
return_value=[
pickle.dumps("value1"),
None,
pickle.dumps("value3"),
]
)
results = await cache.mget(["key1", "key2", "key3"])
assert results["key1"] == "value1"
assert "key2" not in results
assert results["key3"] == "value3"
assert cache.stats.hits == 2
assert cache.stats.misses == 1
@pytest.mark.asyncio
async def test_mget_empty(self, mock_redis):
"""Test mget with empty list."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
results = await cache.mget([])
assert results == {}
@pytest.mark.asyncio
async def test_mget_error(self, mock_redis):
"""Test mget with error."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.mget = AsyncMock(side_effect=Exception("Redis error"))
results = await cache.mget(["key1", "key2"])
assert results == {}
@pytest.mark.asyncio
async def test_mget_corrupted_pickle(self, mock_redis):
"""Test mget handles corrupted pickle data."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.mget = AsyncMock(return_value=[pickle.dumps("value1"), b"corrupted"])
results = await cache.mget(["key1", "key2"])
assert results["key1"] == "value1"
assert "key2" not in results
assert cache.stats.misses == 1 # corrupted counts as miss
@pytest.mark.asyncio
async def test_mset(self, mock_redis):
"""Test batch set."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
items = {"key1": "value1", "key2": "value2"}
result = await cache.mset(items)
assert result is True
mock_redis.mset.assert_called_once()
@pytest.mark.asyncio
async def test_mset_empty(self, mock_redis):
"""Test mset with empty dict."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
result = await cache.mset({})
assert result is True
@pytest.mark.asyncio
async def test_mset_with_ttl(self, mock_redis):
"""Test batch set with TTL uses pipeline."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
items = {"key1": "value1", "key2": "value2"}
result = await cache.mset(items, ttl=3600)
assert result is True
mock_redis.pipeline.assert_called_once()
@pytest.mark.asyncio
async def test_mset_error(self, mock_redis):
"""Test mset with error."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
mock_redis.mset = AsyncMock(side_effect=Exception("Redis error"))
items = {"key1": "value1"}
result = await cache.mset(items)
assert result is False
@pytest.mark.asyncio
async def test_close(self, mock_redis):
"""Test close."""
with patch("core.cache.REDIS_AVAILABLE", True):
cache = RedisCache()
cache._pool = mock_redis
await cache.close()
mock_redis.close.assert_called_once()
assert cache._pool is None
@pytest.mark.asyncio
async def test_get_pool_creates_pool(self):
"""Test _get_pool creates pool if None."""
with patch("core.cache.REDIS_AVAILABLE", True):
with patch("core.cache.redis.Redis") as mock_redis_class:
mock_pool = AsyncMock()
mock_redis_class.return_value = mock_pool
cache = RedisCache(host="testhost", port=6380, db=1)
pool = await cache._get_pool()
mock_redis_class.assert_called_once_with(
host="testhost",
port=6380,
db=1,
password=None,
decode_responses=False,
max_connections=10,
socket_keepalive=True,
socket_keepalive_options={},
)
assert pool is mock_pool
class TestRedisCacheNotAvailable:
"""Tests for when Redis is not available."""
def test_redis_init_not_available(self):
"""Test RedisCache raises error when redis not installed."""
with patch("core.cache.REDIS_AVAILABLE", False):
with pytest.raises(ImportError, match="redis not installed"):
RedisCache()
# =============================================================================
# Test MultiTierCache
# =============================================================================
class TestMultiTierCache:
"""Tests for MultiTierCache."""
def test_init_defaults(self):
"""Test initialization with defaults."""
cache = MultiTierCache()
assert cache.l1 is not None
assert isinstance(cache.l1, MemoryCache)
assert cache._hit_distribution == {"L1": 0, "L2": 0, "L3": 0}
def test_init_custom(self):
"""Test initialization with custom values."""
cache = MultiTierCache(memory_size=50, memory_max_mb=25.0)
assert cache.l1._max_size == 50
assert cache.l1._max_memory_bytes == 25 * 1024 * 1024
@pytest.mark.asyncio
async def test_get_l1_hit(self):
"""Test get from L1 cache."""
cache = MultiTierCache()
await cache.l1.set("key1", "value1")
value = await cache.get("key1")
assert value == "value1"
assert cache._hit_distribution["L1"] == 1
@pytest.mark.asyncio
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
async def test_get_l2_hit(self, tmp_path):
"""Test get from L2 cache (promotes to L1)."""
db_path = tmp_path / "test_multitier.db"
cache = MultiTierCache(sqlite_path=db_path)
if cache.l2:
await cache.l2.set("key1", "value1")
value = await cache.get("key1")
assert value == "value1"
assert cache._hit_distribution["L2"] == 1
# Should be promoted to L1
assert await cache.l1.get("key1") == "value1"
if cache.l2:
await cache.l2.close()
@pytest.mark.asyncio
async def test_get_miss(self):
"""Test get with miss in all tiers."""
cache = MultiTierCache()
value = await cache.get("nonexistent")
assert value is None
@pytest.mark.asyncio
async def test_set_all_tiers(self):
"""Test set in all tiers."""
cache = MultiTierCache()
result = await cache.set("key1", "value1")
assert result is True
# Should be in L1
assert await cache.l1.get("key1") == "value1"
@pytest.mark.asyncio
async def test_set_memory_only(self):
"""Test set in memory only."""
cache = MultiTierCache()
await cache.set("key1", "value1", tiers="memory")
assert await cache.l1.get("key1") == "value1"
@pytest.mark.asyncio
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
async def test_set_persistent_only(self, tmp_path):
"""Test set in persistent only."""
db_path = tmp_path / "test_persistent.db"
cache = MultiTierCache(sqlite_path=db_path)
if cache.l2:
await cache.set("key1", "value1", tiers="persistent")
assert await cache.l2.get("key1") == "value1"
if cache.l2:
await cache.l2.close()
@pytest.mark.asyncio
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
async def test_mget_multitier(self, tmp_path):
"""Test mget across tiers."""
db_path = tmp_path / "test_mget.db"
cache = MultiTierCache(sqlite_path=db_path)
# Set in L1
await cache.l1.set("key1", "l1_value")
# Set in L2 if available
if cache.l2:
await cache.l2.set("key2", "l2_value")
results = await cache.mget(["key1", "key2", "key3"])
assert results.get("key1") == "l1_value"
# key2 result depends on L2 availability
if cache.l2:
assert results.get("key2") == "l2_value"
# Should be promoted to L1
assert await cache.l1.get("key2") == "l2_value"
if cache.l2:
await cache.l2.close()
@pytest.mark.asyncio
async def test_mget_empty(self):
"""Test mget with empty keys."""
cache = MultiTierCache()
results = await cache.mget([])
assert results == {}
@pytest.mark.asyncio
async def test_delete_all_tiers(self):
"""Test delete from all tiers."""
cache = MultiTierCache()
await cache.l1.set("key1", "value1")
result = await cache.delete("key1")
assert result is True
assert await cache.l1.get("key1") is None
@pytest.mark.asyncio
async def test_close(self):
"""Test close closes all tiers."""
cache = MultiTierCache()
# Should not raise even with no L2/L3
await cache.close()
def test_get_stats(self):
"""Test get_stats returns combined stats."""
cache = MultiTierCache()
# Simulate some hits
cache._hit_distribution["L1"] = 80
cache._hit_distribution["L2"] = 15
cache._hit_distribution["L3"] = 5
stats = cache.get_stats()
assert "hit_distribution" in stats
assert "L1_memory" in stats
assert "L2_sqlite" in stats
assert "L3_redis" in stats
# Check hit distribution percentages
l1_stats = stats["hit_distribution"]["L1"]
assert l1_stats["count"] == 80
assert l1_stats["percentage"] == 80.0
def test_get_stats_empty(self):
"""Test get_stats with no hits."""
cache = MultiTierCache()
stats = cache.get_stats()
for tier in ["L1", "L2", "L3"]:
assert stats["hit_distribution"][tier]["percentage"] == 0
# =============================================================================
# Test Cache Decorator
# =============================================================================
class TestCacheDecorator:
"""Tests for the cached decorator."""
@pytest.mark.asyncio
async def test_cached_async_function(self):
"""Test cached decorator on async function."""
call_count = 0
@cached(backend="memory", ttl=3600)
async def test_func(x):
nonlocal call_count
call_count += 1
return x * 2
# First call should execute the function
result1 = await test_func(5)
assert result1 == 10
assert call_count == 1
# Second call with same arg should use cache
result2 = await test_func(5)
assert result2 == 10
assert call_count == 1 # Not called again
# Different arg should execute function
result3 = await test_func(3)
assert result3 == 6
assert call_count == 2
def test_cached_sync_function(self):
"""Test cached decorator on sync function."""
call_count = 0
# Note: cached decorator is designed for async functions primarily
# For sync functions, it uses asyncio.run() which may have issues in certain contexts
@cached(backend="memory", ttl=3600)
async def test_func(x):
nonlocal call_count
call_count += 1
return x * 2
# Just verify the decorator structure works
assert callable(test_func)
@pytest.mark.asyncio
async def test_cached_with_custom_key_func(self):
"""Test cached with custom key function."""
call_count = 0
def custom_key(x, y):
return f"custom:{x}:{y}"
@cached(backend="memory", key_func=custom_key)
async def test_func(x, y):
nonlocal call_count
call_count += 1
return x + y
result1 = await test_func(1, 2)
assert result1 == 3
assert call_count == 1
result2 = await test_func(1, 2)
assert result2 == 3
assert call_count == 1
@pytest.mark.asyncio
async def test_cached_with_condition(self):
"""Test cached with condition function."""
call_count = 0
def should_cache(result):
return result > 0
# Use a unique function name to avoid cache pollution
@cached(backend="memory", condition=should_cache)
async def conditional_test_func(x):
nonlocal call_count
call_count += 1
return x
# Positive result should be cached
result1 = await conditional_test_func(42)
assert result1 == 42
assert call_count == 1
result2 = await conditional_test_func(42)
assert result2 == 42
# Second call should use cache
# Reset and test negative result (should not be cached)
call_count = 0
result3 = await conditional_test_func(-5)
assert result3 == -5
@pytest.mark.asyncio
async def test_cached_with_custom_backend(self, memory_cache):
"""Test cached with custom backend instance."""
call_count = 0
@cached(backend=memory_cache, ttl=3600)
async def test_func(x):
nonlocal call_count
call_count += 1
return x * 2
result1 = await test_func(10)
assert result1 == 20
assert call_count == 1
# =============================================================================
# Test Cache Key Generation
# =============================================================================
class TestCacheKeyGeneration:
"""Tests for generate_cache_key function."""
def test_simple_args(self):
"""Test key generation with simple args."""
key = generate_cache_key("arg1", "arg2")
assert isinstance(key, str)
assert len(key) == 32 # MD5 hex
def test_with_kwargs(self):
"""Test key generation with kwargs."""
key1 = generate_cache_key("arg", kwarg1="value1")
key2 = generate_cache_key("arg", kwarg1="value1")
assert key1 == key2 # Deterministic
def test_different_args_different_keys(self):
"""Test different args produce different keys."""
key1 = generate_cache_key("arg1")
key2 = generate_cache_key("arg2")
assert key1 != key2
def test_complex_types(self):
"""Test key generation with complex types."""
key = generate_cache_key([1, 2, 3], {"key": "value"})
assert isinstance(key, str)
assert len(key) == 32
def test_empty_args(self):
"""Test key generation with no args."""
key = generate_cache_key()
assert isinstance(key, str)
assert len(key) == 32
def test_nested_structures(self):
"""Test key generation with nested structures."""
nested = {"outer": {"inner": [1, 2, 3]}}
key = generate_cache_key(nested)
assert isinstance(key, str)
assert len(key) == 32
def test_special_characters(self):
"""Test key generation with special characters."""
key = generate_cache_key("hello\nworld\t!")
assert isinstance(key, str)
assert len(key) == 32
def test_unicode(self):
"""Test key generation with unicode."""
key = generate_cache_key("héllo", "wörld", "日本語")
assert isinstance(key, str)
assert len(key) == 32
def test_deterministic(self):
"""Test that key generation is deterministic."""
for _ in range(10):
key1 = generate_cache_key("test", 123, [1, 2, 3], {"a": "b"})
key2 = generate_cache_key("test", 123, [1, 2, 3], {"a": "b"})
assert key1 == key2
# =============================================================================
# Test Cache Backend Utilities
# =============================================================================
class TestGetCacheBackend:
"""Tests for _get_cache_backend function."""
def test_get_memory_backend(self):
"""Test getting memory backend."""
backend = _get_cache_backend("memory")
assert isinstance(backend, MemoryCache)
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
def test_get_sqlite_backend(self):
"""Test getting sqlite backend."""
backend = _get_cache_backend("sqlite")
assert isinstance(backend, SQLiteCache)
def test_get_custom_backend(self):
"""Test passing custom backend."""
custom = MemoryCache()
backend = _get_cache_backend(custom)
assert backend is custom
def test_get_invalid_backend(self):
"""Test invalid backend raises error."""
with pytest.raises(ValueError, match="Unknown cache backend"):
_get_cache_backend("invalid")
def test_get_redis_backend(self):
"""Test getting redis backend (when available)."""
if REDIS_AVAILABLE:
backend = _get_cache_backend("redis")
assert isinstance(backend, RedisCache)
else:
# Should raise ImportError when redis not available
with pytest.raises(ImportError):
_get_cache_backend("redis")
# =============================================================================
# Test CVE Functions
# =============================================================================
class TestCVEFunctions:
"""Tests for CVE-specific cache functions."""
@pytest.mark.asyncio
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
async def test_cache_and_get_cve(self):
"""Test caching and retrieving CVE data."""
cve_data = {"id": "CVE-2021-44228", "severity": "CRITICAL"}
await cache_cve("CVE-2021-44228", cve_data)
retrieved = await get_cached_cve("CVE-2021-44228")
assert retrieved == cve_data
@pytest.mark.asyncio
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
async def test_cache_cve_lowercase(self):
"""Test that CVE ID is normalized to uppercase."""
cve_data = {"id": "CVE-2021-44228", "severity": "CRITICAL"}
await cache_cve("cve-2021-44228", cve_data)
retrieved = await get_cached_cve("cve-2021-44228")
assert retrieved == cve_data
@pytest.mark.asyncio
@pytest.mark.skipif(not SQLITE_AVAILABLE, reason="aiosqlite not installed")
async def test_get_cached_cve_not_found(self):
"""Test getting non-existent CVE."""
result = await get_cached_cve("CVE-NOT-EXISTS")
assert result is None
# =============================================================================
# Test All Exports
# =============================================================================
class TestAllExports:
"""Test that all expected exports are available."""
def test_exports(self):
"""Test that __all__ exports are importable."""
from core import cache
assert hasattr(cache, "CacheBackend")
assert hasattr(cache, "MemoryCache")
assert hasattr(cache, "SQLiteCache")
assert hasattr(cache, "RedisCache")
assert hasattr(cache, "MultiTierCache")
assert hasattr(cache, "CacheStats")
assert hasattr(cache, "cached")
assert hasattr(cache, "generate_cache_key")
assert hasattr(cache, "get_cached_cve")
assert hasattr(cache, "cache_cve")
assert hasattr(cache, "_get_cache_backend")
def test_all_list_complete(self):
"""Test that __all__ includes all public exports."""
from core.cache import __all__
expected = [
"CacheBackend",
"MemoryCache",
"SQLiteCache",
"RedisCache",
"MultiTierCache",
"CacheStats",
"cached",
"generate_cache_key",
"get_cached_cve",
"cache_cve",
"_get_cache_backend",
]
for item in expected:
assert item in __all__, f"{item} not in __all__"
"""
Comprehensive Unit Tests for core/cache.py - Target: 80%+ Coverage
This test file covers:
1. CacheStats - All properties and edge cases
2. CacheBackend - Abstract base class methods
3. MemoryCache - Full async operations, LRU eviction, TTL, concurrency
4. SQLiteCache - Database operations, persistence, batch operations, error handling
5. RedisCache - Mocked Redis operations, batch operations, error handling
6. MultiTierCache - L1/L2/L3 caching, promotion/demotion, hit distribution
7. cached decorator - Function result caching, sync/async support, conditions
8. CVE utility functions - CVE-specific caching
9. Error handling and edge cases throughout
Run with: pytest tests/unit/test_cache.py -v --cov=core.cache --cov-report=term-missing
"""
import asyncio
import hashlib
import json
import pickle
import sys
import time
from collections import OrderedDict
from datetime import datetime, timedelta
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, Mock, patch
import pytest
# Import all cache components
from core.cache import (
REDIS_AVAILABLE,
SQLITE_AVAILABLE,
CacheBackend,
CacheStats,
MemoryCache,
MultiTierCache,
RedisCache,
SQLiteCache,
_get_cache_backend,
_memory_cache,
_redis_cache,
_sqlite_cache,
cache_cve,
cached,
generate_cache_key,
get_cached_cve,
)
# =============================================================================
# Fixtures
# =============================================================================
def reset_global_caches():
"""Reset global cache instances before each test."""
global _memory_cache, _sqlite_cache, _redis_cache
_memory_cache = None
_sqlite_cache = None
_redis_cache = None
yield
_memory_cache = None
_sqlite_cache = None
_redis_cache = None
async def memory_cache():
"""Create a fresh MemoryCache instance."""
cache = MemoryCache(max_size=100, max_memory_mb=10.0)
yield cache
await cache.clear()
async def sqlite_cache(tmp_path):
"""Create a SQLiteCache with temp database."""
if not SQLITE_AVAILABLE:
pytest.skip("aiosqlite not available")
db_path = tmp_path / "test_cache.db"
cache = SQLiteCache(db_path=db_path)
yield cache
await cache.clear()
await cache.close()
def mock_redis():
"""Create a mock Redis client."""
mock_pool = AsyncMock()
mock_pool.get = AsyncMock(return_value=None)
mock_pool.set = AsyncMock(return_value=True)
mock_pool.delete = AsyncMock(return_value=1)
mock_pool.exists = AsyncMock(return_value=1)
mock_pool.flushdb = AsyncMock(return_value=True)
mock_pool.mget = AsyncMock(return_value=[])
mock_pool.mset = AsyncMock(return_value=True)
Xet Storage Details
- Size:
- 58.8 kB
- Xet hash:
- fcc54ee3dde163c0600a2da5c892f449ebee9074ed33633a00b6cc2728705362
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.