~debian-bazaar/debian/sid/bzr/experimental

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_lru_cache.py

  • Committer: Jelmer Vernooij
  • Date: 2019-02-23 22:23:54 UTC
  • Revision ID: jelmer@jelmer.uk-20190223222354-np2qpunfi10llrex
Add transitional packages to brz.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2008, 2009 Canonical Ltd
2
 
#
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.
7
 
#
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.
12
 
#
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
16
 
 
17
 
"""Tests for the lru_cache module."""
18
 
 
19
 
from bzrlib import (
20
 
    lru_cache,
21
 
    symbol_versioning,
22
 
    tests,
23
 
    )
24
 
 
25
 
 
26
 
def walk_lru(lru):
27
 
    """Test helper to walk the LRU list and assert its consistency"""
28
 
    node = lru._most_recently_used
29
 
    if node is not None:
30
 
        if node.prev is not None:
31
 
            raise AssertionError('the _most_recently_used entry is not'
32
 
                                 ' supposed to have a previous entry'
33
 
                                 ' %s' % (node,))
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,))
39
 
            node_next = None
40
 
        else:
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,))
45
 
        if node.prev is None:
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'
49
 
                                     % (node,))
50
 
        else:
51
 
            if node.prev.next_key != node.key:
52
 
                raise AssertionError('inconsistency found, node.prev.next'
53
 
                                     ' != node: %s' % (node,))
54
 
        yield node
55
 
        node = node_next
56
 
 
57
 
 
58
 
class TestLRUCache(tests.TestCase):
59
 
    """Test that LRU cache properly keeps track of entries."""
60
 
 
61
 
    def test_cache_size(self):
62
 
        cache = lru_cache.LRUCache(max_cache=10)
63
 
        self.assertEqual(10, cache.cache_size())
64
 
 
65
 
        cache = lru_cache.LRUCache(max_cache=256)
66
 
        self.assertEqual(256, cache.cache_size())
67
 
 
68
 
        cache.resize(512)
69
 
        self.assertEqual(512, cache.cache_size())
70
 
 
71
 
    def test_missing(self):
72
 
        cache = lru_cache.LRUCache(max_cache=10)
73
 
 
74
 
        self.assertFalse('foo' in cache)
75
 
        self.assertRaises(KeyError, cache.__getitem__, 'foo')
76
 
 
77
 
        cache['foo'] = 'bar'
78
 
        self.assertEqual('bar', cache['foo'])
79
 
        self.assertTrue('foo' in cache)
80
 
        self.assertFalse('bar' in cache)
81
 
 
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)
86
 
        cache[None] = 1
87
 
        self.assertEqual(1, cache[None])
88
 
        cache[None] = 2
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
92
 
        cache[1] = 3
93
 
        cache[None] = 1
94
 
        cache[None]
95
 
        cache[1]
96
 
        cache[None]
97
 
        self.assertEqual([None, 1], [n.key for n in walk_lru(cache)])
98
 
 
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)
103
 
 
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)
107
 
 
108
 
        cache['foo'] = 'bar'
109
 
        # With a max cache of 1, adding 'baz' should pop out 'foo'
110
 
        cache['baz'] = 'biz'
111
 
 
112
 
        self.assertFalse('foo' in cache)
113
 
        self.assertTrue('baz' in cache)
114
 
 
115
 
        self.assertEqual('biz', cache['baz'])
116
 
 
117
 
    def test_by_usage(self):
118
 
        """Accessing entries bumps them up in priority."""
119
 
        cache = lru_cache.LRUCache(max_cache=2)
120
 
 
121
 
        cache['baz'] = 'biz'
122
 
        cache['foo'] = 'bar'
123
 
 
124
 
        self.assertEqual('biz', cache['baz'])
125
 
 
126
 
        # This must kick out 'foo' because it was the last accessed
127
 
        cache['nub'] = 'in'
128
 
 
129
 
        self.assertFalse('foo' in cache)
130
 
 
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)
137
 
 
138
 
    def test_len(self):
139
 
        cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
140
 
 
141
 
        cache[1] = 10
142
 
        cache[2] = 20
143
 
        cache[3] = 30
144
 
        cache[4] = 40
145
 
 
146
 
        self.assertEqual(4, len(cache))
147
 
 
148
 
        cache[5] = 50
149
 
        cache[6] = 60
150
 
        cache[7] = 70
151
 
        cache[8] = 80
152
 
 
153
 
        self.assertEqual(8, len(cache))
154
 
 
155
 
        cache[1] = 15 # replacement
156
 
 
157
 
        self.assertEqual(8, len(cache))
158
 
 
159
 
        cache[9] = 90
160
 
        cache[10] = 100
161
 
        cache[11] = 110
162
 
 
163
 
        # We hit the max
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)])
167
 
 
168
 
    def test_cleanup_shrinks_to_after_clean_count(self):
169
 
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=3)
170
 
 
171
 
        cache[1] = 10
172
 
        cache[2] = 20
173
 
        cache[3] = 25
174
 
        cache[4] = 30
175
 
        cache[5] = 35
176
 
 
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
180
 
        cache[6] = 40
181
 
        self.assertEqual(3, len(cache))
182
 
 
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)
186
 
 
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)
191
 
 
192
 
    def test_cleanup(self):
193
 
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2)
194
 
 
195
 
        # Add these in order
196
 
        cache[1] = 10
197
 
        cache[2] = 20
198
 
        cache[3] = 25
199
 
        cache[4] = 30
200
 
        cache[5] = 35
201
 
 
202
 
        self.assertEqual(5, len(cache))
203
 
        # Force a compaction
204
 
        cache.cleanup()
205
 
        self.assertEqual(2, len(cache))
206
 
 
207
 
    def test_preserve_last_access_order(self):
208
 
        cache = lru_cache.LRUCache(max_cache=5)
209
 
 
210
 
        # Add these in order
211
 
        cache[1] = 10
212
 
        cache[2] = 20
213
 
        cache[3] = 25
214
 
        cache[4] = 30
215
 
        cache[5] = 35
216
 
 
217
 
        self.assertEqual([5, 4, 3, 2, 1], [n.key for n in walk_lru(cache)])
218
 
 
219
 
        # Now access some randomly
220
 
        cache[2]
221
 
        cache[5]
222
 
        cache[3]
223
 
        cache[2]
224
 
        self.assertEqual([2, 3, 5, 4, 1], [n.key for n in walk_lru(cache)])
225
 
 
226
 
    def test_get(self):
227
 
        cache = lru_cache.LRUCache(max_cache=5)
228
 
 
229
 
        cache[1] = 10
230
 
        cache[2] = 20
231
 
        self.assertEqual(20, cache.get(2))
232
 
        self.assertIs(None, cache.get(3))
233
 
        obj = object()
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)])
238
 
 
239
 
    def test_keys(self):
240
 
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5)
241
 
 
242
 
        cache[1] = 2
243
 
        cache[2] = 3
244
 
        cache[3] = 4
245
 
        self.assertEqual([1, 2, 3], sorted(cache.keys()))
246
 
        cache[4] = 5
247
 
        cache[5] = 6
248
 
        cache[6] = 7
249
 
        self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
250
 
 
251
 
    def test_resize_smaller(self):
252
 
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
253
 
        cache[1] = 2
254
 
        cache[2] = 3
255
 
        cache[3] = 4
256
 
        cache[4] = 5
257
 
        cache[5] = 6
258
 
        self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
259
 
        cache[6] = 7
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
265
 
        cache[7] = 8
266
 
        self.assertEqual([5, 6, 7], sorted(cache.keys()))
267
 
        cache[8] = 9
268
 
        self.assertEqual([7, 8], sorted(cache.keys()))
269
 
 
270
 
    def test_resize_larger(self):
271
 
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
272
 
        cache[1] = 2
273
 
        cache[2] = 3
274
 
        cache[3] = 4
275
 
        cache[4] = 5
276
 
        cache[5] = 6
277
 
        self.assertEqual([1, 2, 3, 4, 5], sorted(cache.keys()))
278
 
        cache[6] = 7
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()))
282
 
        cache[7] = 8
283
 
        cache[8] = 9
284
 
        cache[9] = 10
285
 
        cache[10] = 11
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()))
289
 
 
290
 
 
291
 
class TestLRUSizeCache(tests.TestCase):
292
 
 
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)
298
 
 
299
 
    def test_add__null_key(self):
300
 
        cache = lru_cache.LRUSizeCache()
301
 
        self.assertRaises(ValueError,
302
 
            cache.__setitem__, lru_cache._null_key, 1)
303
 
 
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)
309
 
 
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)
318
 
 
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())
335
 
 
336
 
        cache['test4'] = 'bikey'
337
 
        self.assertEqual(3, cache._value_size)
338
 
        self.assertEqual({'test':'key'}, cache.as_dict())
339
 
 
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'},
352
 
                         cache.as_dict())
353
 
 
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())
365
 
 
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)
371
 
 
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())
381
 
 
382
 
    def test_cleanup(self):
383
 
        cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
384
 
 
385
 
        # Add these in order
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)
390
 
 
391
 
        cache.cleanup()
392
 
        # Only the most recent fits after cleaning up
393
 
        self.assertEqual(7, cache._value_size)
394
 
 
395
 
    def test_keys(self):
396
 
        cache = lru_cache.LRUSizeCache(max_size=10)
397
 
 
398
 
        cache[1] = 'a'
399
 
        cache[2] = 'b'
400
 
        cache[3] = 'cdef'
401
 
        self.assertEqual([1, 2, 3], sorted(cache.keys()))
402
 
 
403
 
    def test_resize_smaller(self):
404
 
        cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
405
 
        cache[1] = 'abc'
406
 
        cache[2] = 'def'
407
 
        cache[3] = 'ghi'
408
 
        cache[4] = 'jkl'
409
 
        # Triggers a cleanup
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
415
 
        cache[5] = 'mno'
416
 
        self.assertEqual([4, 5], sorted(cache.keys()))
417
 
        cache[6] = 'pqr'
418
 
        self.assertEqual([6], sorted(cache.keys()))
419
 
 
420
 
    def test_resize_larger(self):
421
 
        cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=9)
422
 
        cache[1] = 'abc'
423
 
        cache[2] = 'def'
424
 
        cache[3] = 'ghi'
425
 
        cache[4] = 'jkl'
426
 
        # Triggers a cleanup
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()))
430
 
        cache[5] = 'mno'
431
 
        cache[6] = 'pqr'
432
 
        self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
433
 
        cache[7] = 'stu'
434
 
        self.assertEqual([4, 5, 6, 7], sorted(cache.keys()))
435