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."""
41
cache = lru_cache.LRUCache(max_cache=1)
106
cache = lru_cache.LRUCache(max_cache=1, after_cleanup_count=1)
43
108
cache['foo'] = 'bar'
44
109
# With a max cache of 1, adding 'baz' should pop out 'foo'
45
110
cache['baz'] = 'biz'
47
self.failIf('foo' in cache)
48
self.failUnless('baz' in cache)
112
self.assertFalse('foo' in cache)
113
self.assertTrue('baz' in cache)
50
115
self.assertEqual('biz', cache['baz'])
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
cache = lru_cache.LRUCache(max_cache=10)
139
cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
141
164
self.assertEqual(10, len(cache))
143
def test_cleanup_shrinks_to_after_clean_size(self):
144
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_size=3)
165
self.assertEqual([11, 10, 9, 1, 8, 7, 6, 5, 4, 3],
166
[n.key for n in walk_lru(cache)])
168
def test_cleanup_shrinks_to_after_clean_count(self):
169
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=3)
152
177
self.assertEqual(5, len(cache))
153
178
# This will bump us over the max, which causes us to shrink down to
154
179
# after_cleanup_cache size
156
181
self.assertEqual(3, len(cache))
158
183
def test_after_cleanup_larger_than_max(self):
159
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_size=10)
160
self.assertEqual(5, cache._after_cleanup_size)
184
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=10)
185
self.assertEqual(5, cache._after_cleanup_count)
162
187
def test_after_cleanup_none(self):
163
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_size=None)
164
self.assertEqual(5, cache._after_cleanup_size)
188
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=None)
189
# By default _after_cleanup_size is 80% of the normal size
190
self.assertEqual(4, cache._after_cleanup_count)
166
192
def test_cleanup(self):
167
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_size=2)
193
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2)
169
195
# Add these in order
176
202
self.assertEqual(5, len(cache))
177
203
# Force a compaction
179
205
self.assertEqual(2, len(cache))
181
def test_compact_preserves_last_access_order(self):
207
def test_preserve_last_access_order(self):
182
208
cache = lru_cache.LRUCache(max_cache=5)
184
210
# Add these in order
191
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)])
193
219
# Now access some randomly
198
self.assertEqual([1, 2, 3, 4, 5, 2, 5, 3, 2], list(cache._queue))
199
self.assertEqual({1:1, 2:3, 3:2, 4:1, 5:2}, cache._refcount)
201
# Compacting should save the last position
202
cache._compact_queue()
203
self.assertEqual([1, 4, 5, 3, 2], list(cache._queue))
204
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)])
206
226
def test_get(self):
207
227
cache = lru_cache.LRUCache(max_cache=5)
211
231
self.assertEqual(20, cache.get(2))
212
232
self.assertIs(None, cache.get(3))
214
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)])
240
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5)
245
self.assertEqual([1, 2, 3], sorted(cache.keys()))
249
self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
251
def test_resize_smaller(self):
252
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
258
self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
260
self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
261
# Now resize to something smaller, which triggers a cleanup
262
cache.resize(max_cache=3, after_cleanup_count=2)
263
self.assertEqual([5, 6], sorted(cache.keys()))
264
# Adding something will use the new size
266
self.assertEqual([5, 6, 7], sorted(cache.keys()))
268
self.assertEqual([7, 8], sorted(cache.keys()))
270
def test_resize_larger(self):
271
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
277
self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
279
self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
280
cache.resize(max_cache=8, after_cleanup_count=6)
281
self.assertEqual([3, 4, 5, 6], sorted(cache.keys()))
286
self.assertEqual([3, 4, 5, 6, 7, 8, 9, 10], sorted(cache.keys()))
287
cache[11] = 12 # triggers cleanup back to new after_cleanup_count
288
self.assertEqual([6, 7, 8, 9, 10, 11], sorted(cache.keys()))
217
291
class TestLRUSizeCache(tests.TestCase):
219
293
def test_basic_init(self):
220
294
cache = lru_cache.LRUSizeCache()
221
295
self.assertEqual(2048, cache._max_cache)
222
self.assertEqual(4*2048, cache._compact_queue_length)
223
self.assertEqual(cache._max_size, cache._after_cleanup_size)
296
self.assertEqual(int(cache._max_size*0.8), cache._after_cleanup_size)
224
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)
226
304
def test_add_tracks_size(self):
227
305
cache = lru_cache.LRUSizeCache()
228
306
self.assertEqual(0, cache._value_size)
229
cache.add('my key', 'my value text')
307
cache['my key'] = 'my value text'
230
308
self.assertEqual(13, cache._value_size)
232
310
def test_remove_tracks_size(self):
233
311
cache = lru_cache.LRUSizeCache()
234
312
self.assertEqual(0, cache._value_size)
235
cache.add('my key', 'my value text')
313
cache['my key'] = 'my value text'
236
314
self.assertEqual(13, cache._value_size)
237
cache._remove('my key')
315
node = cache._cache['my key']
316
cache._remove_node(node)
238
317
self.assertEqual(0, cache._value_size)
240
319
def test_no_add_over_size(self):
241
320
"""Adding a large value may not be cached at all."""
242
321
cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
243
322
self.assertEqual(0, cache._value_size)
244
self.assertEqual({}, cache._cache)
245
cache.add('test', 'key')
246
self.assertEqual(3, cache._value_size)
247
self.assertEqual({'test':'key'}, cache._cache)
248
cache.add('test2', 'key that is too big')
249
self.assertEqual(3, cache._value_size)
250
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())
251
330
# If we would add a key, only to cleanup and remove all cached entries,
252
331
# then obviously that value should not be stored
253
cache.add('test3', 'bigkey')
332
cache['test3'] = 'bigkey'
254
333
self.assertEqual(3, cache._value_size)
255
self.assertEqual({'test':'key'}, cache._cache)
334
self.assertEqual({'test':'key'}, cache.as_dict())
257
cache.add('test4', 'bikey')
336
cache['test4'] = 'bikey'
258
337
self.assertEqual(3, cache._value_size)
259
self.assertEqual({'test':'key'}, cache._cache)
338
self.assertEqual({'test':'key'}, cache.as_dict())
261
340
def test_adding_clears_cache_based_on_size(self):
262
341
"""The cache is cleared in LRU order until small enough"""
263
342
cache = lru_cache.LRUSizeCache(max_size=20)
264
cache.add('key1', 'value') # 5 chars
265
cache.add('key2', 'value2') # 6 chars
266
cache.add('key3', 'value23') # 7 chars
343
cache['key1'] = 'value' # 5 chars
344
cache['key2'] = 'value2' # 6 chars
345
cache['key3'] = 'value23' # 7 chars
267
346
self.assertEqual(5+6+7, cache._value_size)
268
347
cache['key2'] # reference key2 so it gets a newer reference time
269
cache.add('key4', 'value234') # 8 chars, over limit
348
cache['key4'] = 'value234' # 8 chars, over limit
270
349
# We have to remove 2 keys to get back under limit
271
350
self.assertEqual(6+8, cache._value_size)
272
351
self.assertEqual({'key2':'value2', 'key4':'value234'},
275
354
def test_adding_clears_to_after_cleanup_size(self):
276
355
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
277
cache.add('key1', 'value') # 5 chars
278
cache.add('key2', 'value2') # 6 chars
279
cache.add('key3', 'value23') # 7 chars
356
cache['key1'] = 'value' # 5 chars
357
cache['key2'] = 'value2' # 6 chars
358
cache['key3'] = 'value23' # 7 chars
280
359
self.assertEqual(5+6+7, cache._value_size)
281
360
cache['key2'] # reference key2 so it gets a newer reference time
282
cache.add('key4', 'value234') # 8 chars, over limit
361
cache['key4'] = 'value234' # 8 chars, over limit
283
362
# We have to remove 3 keys to get back under limit
284
363
self.assertEqual(8, cache._value_size)
285
self.assertEqual({'key4':'value234'}, cache._cache)
364
self.assertEqual({'key4':'value234'}, cache.as_dict())
287
366
def test_custom_sizes(self):
288
367
def size_of_list(lst):
290
369
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10,
291
370
compute_size=size_of_list)
293
cache.add('key1', ['val', 'ue']) # 5 chars
294
cache.add('key2', ['val', 'ue2']) # 6 chars
295
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
296
375
self.assertEqual(5+6+7, cache._value_size)
297
376
cache['key2'] # reference key2 so it gets a newer reference time
298
cache.add('key4', ['value', '234']) # 8 chars, over limit
377
cache['key4'] = ['value', '234'] # 8 chars, over limit
299
378
# We have to remove 3 keys to get back under limit
300
379
self.assertEqual(8, cache._value_size)
301
self.assertEqual({'key4':['value', '234']}, cache._cache)
380
self.assertEqual({'key4':['value', '234']}, cache.as_dict())
303
382
def test_cleanup(self):
304
383
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
306
385
# Add these in order
307
cache.add('key1', 'value') # 5 chars
308
cache.add('key2', 'value2') # 6 chars
309
cache.add('key3', 'value23') # 7 chars
386
cache['key1'] = 'value' # 5 chars
387
cache['key2'] = 'value2' # 6 chars
388
cache['key3'] = 'value23' # 7 chars
310
389
self.assertEqual(5+6+7, cache._value_size)
313
392
# Only the most recent fits after cleaning up
314
393
self.assertEqual(7, cache._value_size)
396
cache = lru_cache.LRUSizeCache(max_size=10)
401
self.assertEqual([1, 2, 3], sorted(cache.keys()))
403
def test_resize_smaller(self):
404
cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
410
self.assertEqual([2, 3, 4], sorted(cache.keys()))
411
# Resize should also cleanup again
412
cache.resize(max_size=6, after_cleanup_size=4)
413
self.assertEqual([4], sorted(cache.keys()))
414
# Adding should use the new max size
416
self.assertEqual([4, 5], sorted(cache.keys()))
418
self.assertEqual([6], sorted(cache.keys()))
420
def test_resize_larger(self):
421
cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
427
self.assertEqual([2, 3, 4], sorted(cache.keys()))
428
cache.resize(max_size=15, after_cleanup_size=12)
429
self.assertEqual([2, 3, 4], sorted(cache.keys()))
432
self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
434
self.assertEqual([4, 5, 6, 7], sorted(cache.keys()))