1
# Copyright (C) 2006, 2008, 2009 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
"""Tests for the lru_cache module."""
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,))
58
class TestLRUCache(tests.TestCase):
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())
71
def test_missing(self):
72
cache = lru_cache.LRUCache(max_cache=10)
74
self.assertFalse('foo' in cache)
75
self.assertRaises(KeyError, cache.__getitem__, 'foo')
78
self.assertEqual('bar', cache['foo'])
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)
104
def test_overflow(self):
105
"""Adding extra entries will pop out old ones."""
106
cache = lru_cache.LRUCache(max_cache=1, after_cleanup_count=1)
109
# With a max cache of 1, adding 'baz' should pop out 'foo'
112
self.assertFalse('foo' in cache)
113
self.assertTrue('baz' in cache)
115
self.assertEqual('biz', cache['baz'])
117
def test_by_usage(self):
118
"""Accessing entries bumps them up in priority."""
119
cache = lru_cache.LRUCache(max_cache=2)
124
self.assertEqual('biz', cache['baz'])
126
# This must kick out 'foo' because it was the last accessed
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)
139
cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
146
self.assertEqual(4, len(cache))
153
self.assertEqual(8, len(cache))
155
cache[1] = 15 # replacement
157
self.assertEqual(8, len(cache))
164
self.assertEqual(10, len(cache))
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)
177
self.assertEqual(5, len(cache))
178
# This will bump us over the max, which causes us to shrink down to
179
# after_cleanup_cache size
181
self.assertEqual(3, len(cache))
183
def test_after_cleanup_larger_than_max(self):
184
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=10)
185
self.assertEqual(5, cache._after_cleanup_count)
187
def test_after_cleanup_none(self):
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)
192
def test_cleanup(self):
193
cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2)
202
self.assertEqual(5, len(cache))
205
self.assertEqual(2, len(cache))
207
def test_preserve_last_access_order(self):
208
cache = lru_cache.LRUCache(max_cache=5)
217
self.assertEqual([5, 4, 3, 2, 1], [n.key for n in walk_lru(cache)])
219
# Now access some randomly
224
self.assertEqual([2, 3, 5, 4, 1], [n.key for n in walk_lru(cache)])
227
cache = lru_cache.LRUCache(max_cache=5)
231
self.assertEqual(20, cache.get(2))
232
self.assertIs(None, cache.get(3))
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()))
291
class TestLRUSizeCache(tests.TestCase):
293
def test_basic_init(self):
294
cache = lru_cache.LRUSizeCache()
295
self.assertEqual(2048, cache._max_cache)
296
self.assertEqual(int(cache._max_size*0.8), cache._after_cleanup_size)
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)
304
def test_add_tracks_size(self):
305
cache = lru_cache.LRUSizeCache()
306
self.assertEqual(0, cache._value_size)
307
cache['my key'] = 'my value text'
308
self.assertEqual(13, cache._value_size)
310
def test_remove_tracks_size(self):
311
cache = lru_cache.LRUSizeCache()
312
self.assertEqual(0, cache._value_size)
313
cache['my key'] = 'my value text'
314
self.assertEqual(13, cache._value_size)
315
node = cache._cache['my key']
316
cache._remove_node(node)
317
self.assertEqual(0, cache._value_size)
319
def test_no_add_over_size(self):
320
"""Adding a large value may not be cached at all."""
321
cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
322
self.assertEqual(0, cache._value_size)
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())
330
# If we would add a key, only to cleanup and remove all cached entries,
331
# then obviously that value should not be stored
332
cache['test3'] = 'bigkey'
333
self.assertEqual(3, cache._value_size)
334
self.assertEqual({'test':'key'}, cache.as_dict())
336
cache['test4'] = 'bikey'
337
self.assertEqual(3, cache._value_size)
338
self.assertEqual({'test':'key'}, cache.as_dict())
340
def test_adding_clears_cache_based_on_size(self):
341
"""The cache is cleared in LRU order until small enough"""
342
cache = lru_cache.LRUSizeCache(max_size=20)
343
cache['key1'] = 'value' # 5 chars
344
cache['key2'] = 'value2' # 6 chars
345
cache['key3'] = 'value23' # 7 chars
346
self.assertEqual(5+6+7, cache._value_size)
347
cache['key2'] # reference key2 so it gets a newer reference time
348
cache['key4'] = 'value234' # 8 chars, over limit
349
# We have to remove 2 keys to get back under limit
350
self.assertEqual(6+8, cache._value_size)
351
self.assertEqual({'key2':'value2', 'key4':'value234'},
354
def test_adding_clears_to_after_cleanup_size(self):
355
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
356
cache['key1'] = 'value' # 5 chars
357
cache['key2'] = 'value2' # 6 chars
358
cache['key3'] = 'value23' # 7 chars
359
self.assertEqual(5+6+7, cache._value_size)
360
cache['key2'] # reference key2 so it gets a newer reference time
361
cache['key4'] = 'value234' # 8 chars, over limit
362
# We have to remove 3 keys to get back under limit
363
self.assertEqual(8, cache._value_size)
364
self.assertEqual({'key4':'value234'}, cache.as_dict())
366
def test_custom_sizes(self):
367
def size_of_list(lst):
368
return sum(len(x) for x in lst)
369
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10,
370
compute_size=size_of_list)
372
cache['key1'] = ['val', 'ue'] # 5 chars
373
cache['key2'] = ['val', 'ue2'] # 6 chars
374
cache['key3'] = ['val', 'ue23'] # 7 chars
375
self.assertEqual(5+6+7, cache._value_size)
376
cache['key2'] # reference key2 so it gets a newer reference time
377
cache['key4'] = ['value', '234'] # 8 chars, over limit
378
# We have to remove 3 keys to get back under limit
379
self.assertEqual(8, cache._value_size)
380
self.assertEqual({'key4':['value', '234']}, cache.as_dict())
382
def test_cleanup(self):
383
cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
386
cache['key1'] = 'value' # 5 chars
387
cache['key2'] = 'value2' # 6 chars
388
cache['key3'] = 'value23' # 7 chars
389
self.assertEqual(5+6+7, cache._value_size)
392
# Only the most recent fits after cleaning up
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()))