13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
"""Tests for the lru_cache module."""
19
19
from bzrlib import (
27
"""Test helper to walk the LRU list and assert its consistency"""
28
node = lru._most_recently_used
30
if node.prev is not None:
31
raise AssertionError('the _most_recently_used entry is not'
32
' supposed to have a previous entry'
34
while node is not None:
35
if node.next_key is lru_cache._null_key:
36
if node is not lru._least_recently_used:
37
raise AssertionError('only the last node should have'
38
' no next value: %s' % (node,))
41
node_next = lru._cache[node.next_key]
42
if node_next.prev is not node:
43
raise AssertionError('inconsistency found, node.next.prev'
44
' != node: %s' % (node,))
46
if node is not lru._most_recently_used:
47
raise AssertionError('only the _most_recently_used should'
48
' not have a previous node: %s'
51
if node.prev.next_key != node.key:
52
raise AssertionError('inconsistency found, node.prev.next'
53
' != node: %s' % (node,))
25
58
class TestLRUCache(tests.TestCase):
26
59
"""Test that LRU cache properly keeps track of entries."""
61
def test_cache_size(self):
62
cache = lru_cache.LRUCache(max_cache=10)
63
self.assertEqual(10, cache.cache_size())
65
cache = lru_cache.LRUCache(max_cache=256)
66
self.assertEqual(256, cache.cache_size())
69
self.assertEqual(512, cache.cache_size())
28
71
def test_missing(self):
29
72
cache = lru_cache.LRUCache(max_cache=10)
31
self.failIf('foo' in cache)
74
self.assertFalse('foo' in cache)
32
75
self.assertRaises(KeyError, cache.__getitem__, 'foo')
34
77
cache['foo'] = 'bar'
35
78
self.assertEqual('bar', cache['foo'])
36
self.failUnless('foo' in cache)
37
self.failIf('bar' in cache)
79
self.assertTrue('foo' in cache)
80
self.assertFalse('bar' in cache)
82
def test_map_None(self):
83
# Make sure that we can properly map None as a key.
84
cache = lru_cache.LRUCache(max_cache=10)
85
self.assertFalse(None in cache)
87
self.assertEqual(1, cache[None])
89
self.assertEqual(2, cache[None])
90
# Test the various code paths of __getitem__, to make sure that we can
91
# handle when None is the key for the LRU and the MRU
97
self.assertEqual([None, 1], [n.key for n in walk_lru(cache)])
99
def test_add__null_key(self):
100
cache = lru_cache.LRUCache(max_cache=10)
101
self.assertRaises(ValueError,
102
cache.__setitem__, lru_cache._null_key, 1)
39
104
def test_overflow(self):
40
105
"""Adding extra entries will pop out old ones."""
61
126
# This must kick out 'foo' because it was the last accessed
62
127
cache['nub'] = 'in'
64
self.failIf('foo' in cache)
66
def test_queue_stays_bounded(self):
67
"""Lots of accesses does not cause the queue to grow without bound."""
68
cache = lru_cache.LRUCache(max_cache=10)
73
for i in xrange(1000):
76
self.failUnless(len(cache._queue) < 40)
78
def test_cleanup(self):
79
"""Test that we can use a cleanup function."""
81
def cleanup_func(key, val):
82
cleanup_called.append((key, val))
84
cache = lru_cache.LRUCache(max_cache=2)
86
cache.add('baz', '1', cleanup=cleanup_func)
87
cache.add('foo', '2', cleanup=cleanup_func)
88
cache.add('biz', '3', cleanup=cleanup_func)
90
self.assertEqual([('baz', '1')], cleanup_called)
92
# 'foo' is now most recent, so final cleanup will call it last
95
self.assertEqual([('baz', '1'), ('biz', '3'), ('foo', '2')], cleanup_called)
97
def test_cleanup_on_replace(self):
98
"""Replacing an object should cleanup the old value."""
100
def cleanup_func(key, val):
101
cleanup_called.append((key, val))
103
cache = lru_cache.LRUCache(max_cache=2)
104
cache.add(1, 10, cleanup=cleanup_func)
105
cache.add(2, 20, cleanup=cleanup_func)
106
cache.add(2, 25, cleanup=cleanup_func)
108
self.assertEqual([(2, 20)], cleanup_called)
109
self.assertEqual(25, cache[2])
111
# Even __setitem__ should make sure cleanup() is called
113
self.assertEqual([(2, 20), (2, 25)], cleanup_called)
129
self.assertFalse('foo' in cache)
131
def test_cleanup_function_deprecated(self):
132
"""Test that per-node cleanup functions are no longer allowed"""
133
cache = lru_cache.LRUCache()
134
self.assertRaises(ValueError, self.applyDeprecated,
135
symbol_versioning.deprecated_in((2, 5, 0)),
136
cache.add, "key", 1, cleanup=lambda: None)
115
138
def test_len(self):
116
139
cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
168
193
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2)
170
195
# Add these in order
177
202
self.assertEqual(5, len(cache))
178
203
# Force a compaction
180
205
self.assertEqual(2, len(cache))
182
def test_compact_preserves_last_access_order(self):
207
def test_preserve_last_access_order(self):
183
208
cache = lru_cache.LRUCache(max_cache=5)
185
210
# Add these in order
192
self.assertEqual([1, 2, 3, 4, 5], list(cache._queue))
217
self.assertEqual([5, 4, 3, 2, 1], [n.key for n in walk_lru(cache)])
194
219
# Now access some randomly
199
self.assertEqual([1, 2, 3, 4, 5, 2, 5, 3, 2], list(cache._queue))
200
self.assertEqual({1:1, 2:3, 3:2, 4:1, 5:2}, cache._refcount)
202
# Compacting should save the last position
203
cache._compact_queue()
204
self.assertEqual([1, 4, 5, 3, 2], list(cache._queue))
205
self.assertEqual({1:1, 2:1, 3:1, 4:1, 5:1}, cache._refcount)
224
self.assertEqual([2, 3, 5, 4, 1], [n.key for n in walk_lru(cache)])
207
226
def test_get(self):
208
227
cache = lru_cache.LRUCache(max_cache=5)
212
231
self.assertEqual(20, cache.get(2))
213
232
self.assertIs(None, cache.get(3))
215
234
self.assertIs(obj, cache.get(3, obj))
235
self.assertEqual([2, 1], [n.key for n in walk_lru(cache)])
236
self.assertEqual(10, cache.get(1))
237
self.assertEqual([1, 2], [n.key for n in walk_lru(cache)])
217
239
def test_keys(self):
218
240
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5)
278
293
def test_basic_init(self):
279
294
cache = lru_cache.LRUSizeCache()
280
295
self.assertEqual(2048, cache._max_cache)
281
self.assertEqual(4*2048, cache._compact_queue_length)
282
296
self.assertEqual(int(cache._max_size*0.8), cache._after_cleanup_size)
283
297
self.assertEqual(0, cache._value_size)
299
def test_add__null_key(self):
300
cache = lru_cache.LRUSizeCache()
301
self.assertRaises(ValueError,
302
cache.__setitem__, lru_cache._null_key, 1)
285
304
def test_add_tracks_size(self):
286
305
cache = lru_cache.LRUSizeCache()
287
306
self.assertEqual(0, cache._value_size)
288
cache.add('my key', 'my value text')
307
cache['my key'] = 'my value text'
289
308
self.assertEqual(13, cache._value_size)
291
310
def test_remove_tracks_size(self):
292
311
cache = lru_cache.LRUSizeCache()
293
312
self.assertEqual(0, cache._value_size)
294
cache.add('my key', 'my value text')
313
cache['my key'] = 'my value text'
295
314
self.assertEqual(13, cache._value_size)
296
cache._remove('my key')
315
node = cache._cache['my key']
316
cache._remove_node(node)
297
317
self.assertEqual(0, cache._value_size)
299
319
def test_no_add_over_size(self):
300
320
"""Adding a large value may not be cached at all."""
301
321
cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
302
322
self.assertEqual(0, cache._value_size)
303
self.assertEqual({}, cache._cache)
304
cache.add('test', 'key')
305
self.assertEqual(3, cache._value_size)
306
self.assertEqual({'test':'key'}, cache._cache)
307
cache.add('test2', 'key that is too big')
308
self.assertEqual(3, cache._value_size)
309
self.assertEqual({'test':'key'}, cache._cache)
323
self.assertEqual({}, cache.as_dict())
324
cache['test'] = 'key'
325
self.assertEqual(3, cache._value_size)
326
self.assertEqual({'test': 'key'}, cache.as_dict())
327
cache['test2'] = 'key that is too big'
328
self.assertEqual(3, cache._value_size)
329
self.assertEqual({'test':'key'}, cache.as_dict())
310
330
# If we would add a key, only to cleanup and remove all cached entries,
311
331
# then obviously that value should not be stored
312
cache.add('test3', 'bigkey')
332
cache['test3'] = 'bigkey'
313
333
self.assertEqual(3, cache._value_size)
314
self.assertEqual({'test':'key'}, cache._cache)
334
self.assertEqual({'test':'key'}, cache.as_dict())
316
cache.add('test4', 'bikey')
336
cache['test4'] = 'bikey'
317
337
self.assertEqual(3, cache._value_size)
318
self.assertEqual({'test':'key'}, cache._cache)
338
self.assertEqual({'test':'key'}, cache.as_dict())
320
340
def test_adding_clears_cache_based_on_size(self):
321
341
"""The cache is cleared in LRU order until small enough"""
322
342
cache = lru_cache.LRUSizeCache(max_size=20)
323
cache.add('key1', 'value') # 5 chars
324
cache.add('key2', 'value2') # 6 chars
325
cache.add('key3', 'value23') # 7 chars
343
cache['key1'] = 'value' # 5 chars
344
cache['key2'] = 'value2' # 6 chars
345
cache['key3'] = 'value23' # 7 chars
326
346
self.assertEqual(5+6+7, cache._value_size)
327
347
cache['key2'] # reference key2 so it gets a newer reference time
328
cache.add('key4', 'value234') # 8 chars, over limit
348
cache['key4'] = 'value234' # 8 chars, over limit
329
349
# We have to remove 2 keys to get back under limit
330
350
self.assertEqual(6+8, cache._value_size)
331
351
self.assertEqual({'key2':'value2', 'key4':'value234'},
334
354
def test_adding_clears_to_after_cleanup_size(self):
335
355
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
336
cache.add('key1', 'value') # 5 chars
337
cache.add('key2', 'value2') # 6 chars
338
cache.add('key3', 'value23') # 7 chars
356
cache['key1'] = 'value' # 5 chars
357
cache['key2'] = 'value2' # 6 chars
358
cache['key3'] = 'value23' # 7 chars
339
359
self.assertEqual(5+6+7, cache._value_size)
340
360
cache['key2'] # reference key2 so it gets a newer reference time
341
cache.add('key4', 'value234') # 8 chars, over limit
361
cache['key4'] = 'value234' # 8 chars, over limit
342
362
# We have to remove 3 keys to get back under limit
343
363
self.assertEqual(8, cache._value_size)
344
self.assertEqual({'key4':'value234'}, cache._cache)
364
self.assertEqual({'key4':'value234'}, cache.as_dict())
346
366
def test_custom_sizes(self):
347
367
def size_of_list(lst):
349
369
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10,
350
370
compute_size=size_of_list)
352
cache.add('key1', ['val', 'ue']) # 5 chars
353
cache.add('key2', ['val', 'ue2']) # 6 chars
354
cache.add('key3', ['val', 'ue23']) # 7 chars
372
cache['key1'] = ['val', 'ue'] # 5 chars
373
cache['key2'] = ['val', 'ue2'] # 6 chars
374
cache['key3'] = ['val', 'ue23'] # 7 chars
355
375
self.assertEqual(5+6+7, cache._value_size)
356
376
cache['key2'] # reference key2 so it gets a newer reference time
357
cache.add('key4', ['value', '234']) # 8 chars, over limit
377
cache['key4'] = ['value', '234'] # 8 chars, over limit
358
378
# We have to remove 3 keys to get back under limit
359
379
self.assertEqual(8, cache._value_size)
360
self.assertEqual({'key4':['value', '234']}, cache._cache)
380
self.assertEqual({'key4':['value', '234']}, cache.as_dict())
362
382
def test_cleanup(self):
363
383
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
365
385
# Add these in order
366
cache.add('key1', 'value') # 5 chars
367
cache.add('key2', 'value2') # 6 chars
368
cache.add('key3', 'value23') # 7 chars
386
cache['key1'] = 'value' # 5 chars
387
cache['key2'] = 'value2' # 6 chars
388
cache['key3'] = 'value23' # 7 chars
369
389
self.assertEqual(5+6+7, cache._value_size)