""" Tests for cache_manager module. """ import unittest import time from cache_manager import LRUCache class TestCacheManager(unittest.TestCase): """Test cases for cache management.""" def setUp(self): """Set up test fixtures.""" self.cache = LRUCache(max_size=5, ttl_seconds=1) def test_cache_set_get(self): """Test basic cache set and get operations.""" self.cache.set("key1", "value1") value = self.cache.get("key1") self.assertEqual(value, "value1") def test_cache_miss(self): """Test cache miss scenario.""" value = self.cache.get("nonexistent") self.assertIsNone(value) def test_cache_size_limit(self): """Test that cache respects size limits.""" # Fill cache beyond max_size for i in range(10): self.cache.set(f"key{i}", f"value{i}") # Oldest entries should be evicted self.assertIsNone(self.cache.get("key0")) self.assertIsNotNone(self.cache.get("key9")) def test_cache_lru_eviction(self): """Test LRU eviction policy.""" # Fill cache for i in range(5): self.cache.set(f"key{i}", f"value{i}") # Access key0 to make it recently used self.cache.get("key0") # Add new entry - should evict least recently used (key1) self.cache.set("key5", "value5") self.assertIsNotNone(self.cache.get("key0")) # Still in cache self.assertIsNone(self.cache.get("key1")) # Evicted def test_cache_ttl_expiration(self): """Test cache TTL expiration.""" self.cache.set("key1", "value1") # Value should be available immediately self.assertIsNotNone(self.cache.get("key1")) # Wait for expiration time.sleep(1.1) # Value should be expired self.assertIsNone(self.cache.get("key1")) def test_cache_clear(self): """Test cache clear operation.""" self.cache.set("key1", "value1") self.cache.set("key2", "value2") self.assertEqual(self.cache.size(), 2) self.cache.clear() self.assertEqual(self.cache.size(), 0) self.assertIsNone(self.cache.get("key1")) def test_cache_stats(self): """Test cache statistics.""" self.cache.set("key1", "value1") stats = self.cache.stats() self.assertIn("size", stats) self.assertIn("max_size", stats) self.assertIn("ttl_seconds", stats) self.assertIn("usage_percent", stats) self.assertEqual(stats["size"], 1) if __name__ == '__main__': unittest.main()