def test_key_is_none(self): cache = Cache("LRU", 4) self.assertRaises(ValueError, cache.put, None, 1) cache = Cache("MRU", 4) self.assertRaises(ValueError, cache.put, None, 1) cache = Cache("SF", 4) self.assertRaises(ValueError, cache.put, None, 1)
def test_smallest_first_system_str_input(self): cache = Cache("SF", 3) cache.put("a", 1) cache.put("b", 2) cache.put("c", 3) self.assertEqual(cache.get("a"), 1) self.assertEqual(cache.get("b"), 2) cache.put("d", 4) self.assertEqual(cache.get("a"), None) # evicted ("a",1) self.assertEqual(cache.get("d"), 4)
def test_lru_system_int_input(self): cache = Cache("LRU", 3) cache.put(1, 1) cache.put(2, 2) cache.put(3, 3) self.assertEqual(cache.get(1), 1) cache.put(4, 4) self.assertEqual(cache.get(2), None) # evicted (2,2) self.assertEqual(cache.get(4), 4)
def __init__(self, eviction_strategy, num_caches, cache_size, key_type, value_type): """ Smallest First strategy implemented as custom strategy. :param eviction_strategy: One of ["LRU", "MRU", "SF"] by default. :param num_caches: Number of caches. :param cache_size: Size of each cache. :param key_type: Type of keys. Once chosen, every key has to be of this type. :param value_type: Type of values. Once chose, every value has to be of this type. """ self.eviction_strategy = eviction_strategy self.num_caches = num_caches self.cache_size = cache_size self.check_key_type_immutable(key_type) self.key_type = key_type self.value_type = value_type self.caches = [ Cache(eviction_strategy, cache_size) for _ in range(num_caches) ]
def test_mru_system_tuple_input(self): cache = Cache("MRU", 3) cache.put((1, 2), 1) cache.put((1, 1), 2) cache.put((2, 5), 3) self.assertEqual(cache.get((1,1)), 2) cache.put((5, 6), 4) self.assertEqual(cache.get((1, 1)), None) # evicted ((1,1), 2) self.assertEqual(cache.get((0, 0)), None) # never added self.assertEqual(cache.get((5, 6)), 4)
def test_smallest_first_system_int_input(self): cache = Cache("SF", 3) cache.put(1, 1) cache.put(2, 2) cache.put(3, 3) self.assertEqual(cache.get(1), 1) self.assertEqual(cache.get(2), 2) cache.put(4, 4) self.assertEqual(cache.get(1), None) # evicted (1,1) self.assertEqual(cache.get(4), 4) cache.put(4, 5) self.assertEqual(cache.get(4), 5) # update key 4
def test_evicts_smallest(self): cache = Cache("SF", 2) cache.put((1, 1), 1) cache.put((1, 2), 2) cache.put((1, 3), 3) self.assertEqual(cache.get((1, 1)), None)