17
17
"""Tests for the lru_cache module."""
26
"""Test helper to walk the LRU list and assert its consistency"""
27
node = lru._most_recently_used
29
if node.prev is not None:
30
raise AssertionError('the _most_recently_used entry is not'
31
' supposed to have a previous entry'
33
while node is not None:
34
if node.next_key is lru_cache._null_key:
35
if node is not lru._least_recently_used:
36
raise AssertionError('only the last node should have'
37
' no next value: %s' % (node,))
40
node_next = lru._cache[node.next_key]
41
if node_next.prev is not node:
42
raise AssertionError('inconsistency found, node.next.prev'
43
' != node: %s' % (node,))
45
if node is not lru._most_recently_used:
46
raise AssertionError('only the _most_recently_used should'
47
' not have a previous node: %s'
50
if node.prev.next_key != node.key:
51
raise AssertionError('inconsistency found, node.prev.next'
52
' != node: %s' % (node,))
57
25
class TestLRUCache(tests.TestCase):
58
26
"""Test that LRU cache properly keeps track of entries."""
125
92
# This must kick out 'foo' because it was the last accessed
126
93
cache['nub'] = 'in'
128
self.assertFalse('foo' in cache)
95
self.failIf('foo' in cache)
97
def test_cleanup(self):
98
"""Test that we can use a cleanup function."""
100
def cleanup_func(key, val):
101
cleanup_called.append((key, val))
103
cache = lru_cache.LRUCache(max_cache=2)
105
cache.add('baz', '1', cleanup=cleanup_func)
106
cache.add('foo', '2', cleanup=cleanup_func)
107
cache.add('biz', '3', cleanup=cleanup_func)
109
self.assertEqual([('baz', '1')], cleanup_called)
111
# 'foo' is now most recent, so final cleanup will call it last
114
self.assertEqual([('baz', '1'), ('biz', '3'), ('foo', '2')],
117
def test_cleanup_on_replace(self):
118
"""Replacing an object should cleanup the old value."""
120
def cleanup_func(key, val):
121
cleanup_called.append((key, val))
123
cache = lru_cache.LRUCache(max_cache=2)
124
cache.add(1, 10, cleanup=cleanup_func)
125
cache.add(2, 20, cleanup=cleanup_func)
126
cache.add(2, 25, cleanup=cleanup_func)
128
self.assertEqual([(2, 20)], cleanup_called)
129
self.assertEqual(25, cache[2])
131
# Even __setitem__ should make sure cleanup() is called
133
self.assertEqual([(2, 20), (2, 25)], cleanup_called)
135
def test_cleanup_error_maintains_linked_list(self):
137
def cleanup_func(key, val):
138
cleanup_called.append((key, val))
139
raise ValueError('failure during cleanup')
141
cache = lru_cache.LRUCache(max_cache=10)
143
cache.add(i, i, cleanup=cleanup_func)
144
for i in xrange(10, 20):
145
self.assertRaises(ValueError,
146
cache.add, i, i, cleanup=cleanup_func)
148
self.assertEqual([(i, i) for i in xrange(10)], cleanup_called)
150
self.assertEqual(range(19, 9, -1), [n.key for n in cache._walk_lru()])
152
def test_cleanup_during_replace_still_replaces(self):
154
def cleanup_func(key, val):
155
cleanup_called.append((key, val))
156
raise ValueError('failure during cleanup')
158
cache = lru_cache.LRUCache(max_cache=10)
160
cache.add(i, i, cleanup=cleanup_func)
161
self.assertRaises(ValueError,
162
cache.add, 1, 20, cleanup=cleanup_func)
163
# We also still update the recent access to this node
164
self.assertEqual([1, 9, 8, 7, 6, 5, 4, 3, 2, 0],
165
[n.key for n in cache._walk_lru()])
166
self.assertEqual(20, cache[1])
168
self.assertEqual([(1, 1)], cleanup_called)
169
self.assertEqual([1, 9, 8, 7, 6, 5, 4, 3, 2, 0],
170
[n.key for n in cache._walk_lru()])
130
172
def test_len(self):
131
173
cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
200
242
cache = lru_cache.LRUCache(max_cache=5)
202
244
# Add these in order
209
self.assertEqual([5, 4, 3, 2, 1], [n.key for n in walk_lru(cache)])
251
self.assertEqual([5, 4, 3, 2, 1], [n.key for n in cache._walk_lru()])
211
253
# Now access some randomly
216
self.assertEqual([2, 3, 5, 4, 1], [n.key for n in walk_lru(cache)])
258
self.assertEqual([2, 3, 5, 4, 1], [n.key for n in cache._walk_lru()])
218
260
def test_get(self):
219
261
cache = lru_cache.LRUCache(max_cache=5)
223
265
self.assertEqual(20, cache.get(2))
224
266
self.assertIs(None, cache.get(3))
226
268
self.assertIs(obj, cache.get(3, obj))
227
self.assertEqual([2, 1], [n.key for n in walk_lru(cache)])
269
self.assertEqual([2, 1], [n.key for n in cache._walk_lru()])
228
270
self.assertEqual(10, cache.get(1))
229
self.assertEqual([1, 2], [n.key for n in walk_lru(cache)])
271
self.assertEqual([1, 2], [n.key for n in cache._walk_lru()])
231
273
def test_keys(self):
232
274
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5)
285
334
def test_basic_init(self):
286
335
cache = lru_cache.LRUSizeCache()
287
336
self.assertEqual(2048, cache._max_cache)
288
self.assertEqual(int(cache._max_size * 0.8), cache._after_cleanup_size)
337
self.assertEqual(int(cache._max_size*0.8), cache._after_cleanup_size)
289
338
self.assertEqual(0, cache._value_size)
291
340
def test_add__null_key(self):
292
341
cache = lru_cache.LRUSizeCache()
293
self.assertRaises(ValueError,
294
cache.__setitem__, lru_cache._null_key, 1)
342
self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1)
296
344
def test_add_tracks_size(self):
297
345
cache = lru_cache.LRUSizeCache()
298
346
self.assertEqual(0, cache._value_size)
299
cache['my key'] = 'my value text'
347
cache.add('my key', 'my value text')
300
348
self.assertEqual(13, cache._value_size)
302
350
def test_remove_tracks_size(self):
303
351
cache = lru_cache.LRUSizeCache()
304
352
self.assertEqual(0, cache._value_size)
305
cache['my key'] = 'my value text'
353
cache.add('my key', 'my value text')
306
354
self.assertEqual(13, cache._value_size)
307
355
node = cache._cache['my key']
308
356
cache._remove_node(node)
312
360
"""Adding a large value may not be cached at all."""
313
361
cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
314
362
self.assertEqual(0, cache._value_size)
315
self.assertEqual({}, cache.as_dict())
316
cache['test'] = 'key'
317
self.assertEqual(3, cache._value_size)
318
self.assertEqual({'test': 'key'}, cache.as_dict())
319
cache['test2'] = 'key that is too big'
320
self.assertEqual(3, cache._value_size)
321
self.assertEqual({'test': 'key'}, cache.as_dict())
363
self.assertEqual({}, cache.items())
364
cache.add('test', 'key')
365
self.assertEqual(3, cache._value_size)
366
self.assertEqual({'test': 'key'}, cache.items())
367
cache.add('test2', 'key that is too big')
368
self.assertEqual(3, cache._value_size)
369
self.assertEqual({'test':'key'}, cache.items())
322
370
# If we would add a key, only to cleanup and remove all cached entries,
323
371
# then obviously that value should not be stored
324
cache['test3'] = 'bigkey'
325
self.assertEqual(3, cache._value_size)
326
self.assertEqual({'test': 'key'}, cache.as_dict())
328
cache['test4'] = 'bikey'
329
self.assertEqual(3, cache._value_size)
330
self.assertEqual({'test': 'key'}, cache.as_dict())
372
cache.add('test3', 'bigkey')
373
self.assertEqual(3, cache._value_size)
374
self.assertEqual({'test':'key'}, cache.items())
376
cache.add('test4', 'bikey')
377
self.assertEqual(3, cache._value_size)
378
self.assertEqual({'test':'key'}, cache.items())
380
def test_no_add_over_size_cleanup(self):
381
"""If a large value is not cached, we will call cleanup right away."""
383
def cleanup(key, value):
384
cleanup_calls.append((key, value))
386
cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
387
self.assertEqual(0, cache._value_size)
388
self.assertEqual({}, cache.items())
389
cache.add('test', 'key that is too big', cleanup=cleanup)
391
self.assertEqual(0, cache._value_size)
392
self.assertEqual({}, cache.items())
393
# and cleanup was called
394
self.assertEqual([('test', 'key that is too big')], cleanup_calls)
332
396
def test_adding_clears_cache_based_on_size(self):
333
397
"""The cache is cleared in LRU order until small enough"""
334
398
cache = lru_cache.LRUSizeCache(max_size=20)
335
cache['key1'] = 'value' # 5 chars
336
cache['key2'] = 'value2' # 6 chars
337
cache['key3'] = 'value23' # 7 chars
338
self.assertEqual(5 + 6 + 7, cache._value_size)
339
cache['key2'] # reference key2 so it gets a newer reference time
340
cache['key4'] = 'value234' # 8 chars, over limit
399
cache.add('key1', 'value') # 5 chars
400
cache.add('key2', 'value2') # 6 chars
401
cache.add('key3', 'value23') # 7 chars
402
self.assertEqual(5+6+7, cache._value_size)
403
cache['key2'] # reference key2 so it gets a newer reference time
404
cache.add('key4', 'value234') # 8 chars, over limit
341
405
# We have to remove 2 keys to get back under limit
342
self.assertEqual(6 + 8, cache._value_size)
343
self.assertEqual({'key2': 'value2', 'key4': 'value234'},
406
self.assertEqual(6+8, cache._value_size)
407
self.assertEqual({'key2':'value2', 'key4':'value234'},
346
410
def test_adding_clears_to_after_cleanup_size(self):
347
411
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
348
cache['key1'] = 'value' # 5 chars
349
cache['key2'] = 'value2' # 6 chars
350
cache['key3'] = 'value23' # 7 chars
351
self.assertEqual(5 + 6 + 7, cache._value_size)
352
cache['key2'] # reference key2 so it gets a newer reference time
353
cache['key4'] = 'value234' # 8 chars, over limit
412
cache.add('key1', 'value') # 5 chars
413
cache.add('key2', 'value2') # 6 chars
414
cache.add('key3', 'value23') # 7 chars
415
self.assertEqual(5+6+7, cache._value_size)
416
cache['key2'] # reference key2 so it gets a newer reference time
417
cache.add('key4', 'value234') # 8 chars, over limit
354
418
# We have to remove 3 keys to get back under limit
355
419
self.assertEqual(8, cache._value_size)
356
self.assertEqual({'key4': 'value234'}, cache.as_dict())
420
self.assertEqual({'key4':'value234'}, cache.items())
358
422
def test_custom_sizes(self):
359
423
def size_of_list(lst):
361
425
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10,
362
426
compute_size=size_of_list)
364
cache['key1'] = ['val', 'ue'] # 5 chars
365
cache['key2'] = ['val', 'ue2'] # 6 chars
366
cache['key3'] = ['val', 'ue23'] # 7 chars
367
self.assertEqual(5 + 6 + 7, cache._value_size)
368
cache['key2'] # reference key2 so it gets a newer reference time
369
cache['key4'] = ['value', '234'] # 8 chars, over limit
428
cache.add('key1', ['val', 'ue']) # 5 chars
429
cache.add('key2', ['val', 'ue2']) # 6 chars
430
cache.add('key3', ['val', 'ue23']) # 7 chars
431
self.assertEqual(5+6+7, cache._value_size)
432
cache['key2'] # reference key2 so it gets a newer reference time
433
cache.add('key4', ['value', '234']) # 8 chars, over limit
370
434
# We have to remove 3 keys to get back under limit
371
435
self.assertEqual(8, cache._value_size)
372
self.assertEqual({'key4': ['value', '234']}, cache.as_dict())
436
self.assertEqual({'key4':['value', '234']}, cache.items())
374
438
def test_cleanup(self):
375
439
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
377
441
# Add these in order
378
cache['key1'] = 'value' # 5 chars
379
cache['key2'] = 'value2' # 6 chars
380
cache['key3'] = 'value23' # 7 chars
381
self.assertEqual(5 + 6 + 7, cache._value_size)
442
cache.add('key1', 'value') # 5 chars
443
cache.add('key2', 'value2') # 6 chars
444
cache.add('key3', 'value23') # 7 chars
445
self.assertEqual(5+6+7, cache._value_size)
384
448
# Only the most recent fits after cleaning up