/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_lru_cache.py

  • Committer: Jelmer Vernooij
  • Date: 2018-07-08 14:45:27 UTC
  • mto: This revision was merged to the branch mainline in revision 7036.
  • Revision ID: jelmer@jelmer.uk-20180708144527-codhlvdcdg9y0nji
Fix a bunch of merge tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
"""Tests for the lru_cache module."""
18
18
 
19
 
from bzrlib import (
 
19
from .. import (
20
20
    lru_cache,
21
21
    tests,
22
22
    )
23
23
 
24
24
 
 
25
def walk_lru(lru):
 
26
    """Test helper to walk the LRU list and assert its consistency"""
 
27
    node = lru._most_recently_used
 
28
    if node is not None:
 
29
        if node.prev is not None:
 
30
            raise AssertionError('the _most_recently_used entry is not'
 
31
                                 ' supposed to have a previous entry'
 
32
                                 ' %s' % (node,))
 
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,))
 
38
            node_next = None
 
39
        else:
 
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,))
 
44
        if node.prev is None:
 
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'
 
48
                                     % (node,))
 
49
        else:
 
50
            if node.prev.next_key != node.key:
 
51
                raise AssertionError('inconsistency found, node.prev.next'
 
52
                                     ' != node: %s' % (node,))
 
53
        yield node
 
54
        node = node_next
 
55
 
 
56
 
25
57
class TestLRUCache(tests.TestCase):
26
58
    """Test that LRU cache properly keeps track of entries."""
27
59
 
38
70
    def test_missing(self):
39
71
        cache = lru_cache.LRUCache(max_cache=10)
40
72
 
41
 
        self.failIf('foo' in cache)
 
73
        self.assertFalse('foo' in cache)
42
74
        self.assertRaises(KeyError, cache.__getitem__, 'foo')
43
75
 
44
76
        cache['foo'] = 'bar'
45
77
        self.assertEqual('bar', cache['foo'])
46
 
        self.failUnless('foo' in cache)
47
 
        self.failIf('bar' in cache)
 
78
        self.assertTrue('foo' in cache)
 
79
        self.assertFalse('bar' in cache)
48
80
 
49
81
    def test_map_None(self):
50
82
        # Make sure that we can properly map None as a key.
51
83
        cache = lru_cache.LRUCache(max_cache=10)
52
 
        self.failIf(None in cache)
 
84
        self.assertFalse(None in cache)
53
85
        cache[None] = 1
54
86
        self.assertEqual(1, cache[None])
55
87
        cache[None] = 2
61
93
        cache[None]
62
94
        cache[1]
63
95
        cache[None]
64
 
        self.assertEqual([None, 1], [n.key for n in cache._walk_lru()])
 
96
        self.assertEqual([None, 1], [n.key for n in walk_lru(cache)])
65
97
 
66
98
    def test_add__null_key(self):
67
99
        cache = lru_cache.LRUCache(max_cache=10)
68
 
        self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1)
 
100
        self.assertRaises(ValueError,
 
101
            cache.__setitem__, lru_cache._null_key, 1)
69
102
 
70
103
    def test_overflow(self):
71
104
        """Adding extra entries will pop out old ones."""
75
108
        # With a max cache of 1, adding 'baz' should pop out 'foo'
76
109
        cache['baz'] = 'biz'
77
110
 
78
 
        self.failIf('foo' in cache)
79
 
        self.failUnless('baz' in cache)
 
111
        self.assertFalse('foo' in cache)
 
112
        self.assertTrue('baz' in cache)
80
113
 
81
114
        self.assertEqual('biz', cache['baz'])
82
115
 
92
125
        # This must kick out 'foo' because it was the last accessed
93
126
        cache['nub'] = 'in'
94
127
 
95
 
        self.failIf('foo' in cache)
96
 
 
97
 
    def test_cleanup(self):
98
 
        """Test that we can use a cleanup function."""
99
 
        cleanup_called = []
100
 
        def cleanup_func(key, val):
101
 
            cleanup_called.append((key, val))
102
 
 
103
 
        cache = lru_cache.LRUCache(max_cache=2)
104
 
 
105
 
        cache.add('baz', '1', cleanup=cleanup_func)
106
 
        cache.add('foo', '2', cleanup=cleanup_func)
107
 
        cache.add('biz', '3', cleanup=cleanup_func)
108
 
 
109
 
        self.assertEqual([('baz', '1')], cleanup_called)
110
 
 
111
 
        # 'foo' is now most recent, so final cleanup will call it last
112
 
        cache['foo']
113
 
        cache.clear()
114
 
        self.assertEqual([('baz', '1'), ('biz', '3'), ('foo', '2')],
115
 
                         cleanup_called)
116
 
 
117
 
    def test_cleanup_on_replace(self):
118
 
        """Replacing an object should cleanup the old value."""
119
 
        cleanup_called = []
120
 
        def cleanup_func(key, val):
121
 
            cleanup_called.append((key, val))
122
 
 
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)
127
 
 
128
 
        self.assertEqual([(2, 20)], cleanup_called)
129
 
        self.assertEqual(25, cache[2])
130
 
 
131
 
        # Even __setitem__ should make sure cleanup() is called
132
 
        cache[2] = 26
133
 
        self.assertEqual([(2, 20), (2, 25)], cleanup_called)
134
 
 
135
 
    def test_cleanup_error_maintains_linked_list(self):
136
 
        cleanup_called = []
137
 
        def cleanup_func(key, val):
138
 
            cleanup_called.append((key, val))
139
 
            raise ValueError('failure during cleanup')
140
 
 
141
 
        cache = lru_cache.LRUCache(max_cache=10)
142
 
        for i in xrange(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)
147
 
 
148
 
        self.assertEqual([(i, i) for i in xrange(10)], cleanup_called)
149
 
 
150
 
        self.assertEqual(range(19, 9, -1), [n.key for n in cache._walk_lru()])
151
 
 
152
 
    def test_cleanup_during_replace_still_replaces(self):
153
 
        cleanup_called = []
154
 
        def cleanup_func(key, val):
155
 
            cleanup_called.append((key, val))
156
 
            raise ValueError('failure during cleanup')
157
 
 
158
 
        cache = lru_cache.LRUCache(max_cache=10)
159
 
        for i in xrange(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])
167
 
 
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()])
 
128
        self.assertFalse('foo' in cache)
171
129
 
172
130
    def test_len(self):
173
131
        cache = lru_cache.LRUCache(max_cache=10, after_cleanup_count=10)
197
155
        # We hit the max
198
156
        self.assertEqual(10, len(cache))
199
157
        self.assertEqual([11, 10, 9, 1, 8, 7, 6, 5, 4, 3],
200
 
                         [n.key for n in cache._walk_lru()])
 
158
                         [n.key for n in walk_lru(cache)])
201
159
 
202
160
    def test_cleanup_shrinks_to_after_clean_count(self):
203
161
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=3)
204
162
 
205
 
        cache.add(1, 10)
206
 
        cache.add(2, 20)
207
 
        cache.add(3, 25)
208
 
        cache.add(4, 30)
209
 
        cache.add(5, 35)
 
163
        cache[1] = 10
 
164
        cache[2] = 20
 
165
        cache[3] = 25
 
166
        cache[4] = 30
 
167
        cache[5] = 35
210
168
 
211
169
        self.assertEqual(5, len(cache))
212
170
        # This will bump us over the max, which causes us to shrink down to
213
171
        # after_cleanup_cache size
214
 
        cache.add(6, 40)
 
172
        cache[6] = 40
215
173
        self.assertEqual(3, len(cache))
216
174
 
217
175
    def test_after_cleanup_larger_than_max(self):
227
185
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=2)
228
186
 
229
187
        # Add these in order
230
 
        cache.add(1, 10)
231
 
        cache.add(2, 20)
232
 
        cache.add(3, 25)
233
 
        cache.add(4, 30)
234
 
        cache.add(5, 35)
 
188
        cache[1] = 10
 
189
        cache[2] = 20
 
190
        cache[3] = 25
 
191
        cache[4] = 30
 
192
        cache[5] = 35
235
193
 
236
194
        self.assertEqual(5, len(cache))
237
195
        # Force a compaction
242
200
        cache = lru_cache.LRUCache(max_cache=5)
243
201
 
244
202
        # Add these in order
245
 
        cache.add(1, 10)
246
 
        cache.add(2, 20)
247
 
        cache.add(3, 25)
248
 
        cache.add(4, 30)
249
 
        cache.add(5, 35)
 
203
        cache[1] = 10
 
204
        cache[2] = 20
 
205
        cache[3] = 25
 
206
        cache[4] = 30
 
207
        cache[5] = 35
250
208
 
251
 
        self.assertEqual([5, 4, 3, 2, 1], [n.key for n in cache._walk_lru()])
 
209
        self.assertEqual([5, 4, 3, 2, 1], [n.key for n in walk_lru(cache)])
252
210
 
253
211
        # Now access some randomly
254
212
        cache[2]
255
213
        cache[5]
256
214
        cache[3]
257
215
        cache[2]
258
 
        self.assertEqual([2, 3, 5, 4, 1], [n.key for n in cache._walk_lru()])
 
216
        self.assertEqual([2, 3, 5, 4, 1], [n.key for n in walk_lru(cache)])
259
217
 
260
218
    def test_get(self):
261
219
        cache = lru_cache.LRUCache(max_cache=5)
262
220
 
263
 
        cache.add(1, 10)
264
 
        cache.add(2, 20)
 
221
        cache[1] = 10
 
222
        cache[2] = 20
265
223
        self.assertEqual(20, cache.get(2))
266
224
        self.assertIs(None, cache.get(3))
267
225
        obj = object()
268
226
        self.assertIs(obj, cache.get(3, obj))
269
 
        self.assertEqual([2, 1], [n.key for n in cache._walk_lru()])
 
227
        self.assertEqual([2, 1], [n.key for n in walk_lru(cache)])
270
228
        self.assertEqual(10, cache.get(1))
271
 
        self.assertEqual([1, 2], [n.key for n in cache._walk_lru()])
 
229
        self.assertEqual([1, 2], [n.key for n in walk_lru(cache)])
272
230
 
273
231
    def test_keys(self):
274
232
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=5)
282
240
        cache[6] = 7
283
241
        self.assertEqual([2, 3, 4, 5, 6], sorted(cache.keys()))
284
242
 
285
 
    def test_after_cleanup_size_deprecated(self):
286
 
        obj = self.callDeprecated([
287
 
            'LRUCache.__init__(after_cleanup_size) was deprecated in 1.11.'
288
 
            ' Use after_cleanup_count instead.'],
289
 
            lru_cache.LRUCache, 50, after_cleanup_size=25)
290
 
        self.assertEqual(obj._after_cleanup_count, 25)
291
 
 
292
243
    def test_resize_smaller(self):
293
244
        cache = lru_cache.LRUCache(max_cache=5, after_cleanup_count=4)
294
245
        cache[1] = 2
339
290
 
340
291
    def test_add__null_key(self):
341
292
        cache = lru_cache.LRUSizeCache()
342
 
        self.assertRaises(ValueError, cache.add, lru_cache._null_key, 1)
 
293
        self.assertRaises(ValueError,
 
294
            cache.__setitem__, lru_cache._null_key, 1)
343
295
 
344
296
    def test_add_tracks_size(self):
345
297
        cache = lru_cache.LRUSizeCache()
346
298
        self.assertEqual(0, cache._value_size)
347
 
        cache.add('my key', 'my value text')
 
299
        cache['my key'] = 'my value text'
348
300
        self.assertEqual(13, cache._value_size)
349
301
 
350
302
    def test_remove_tracks_size(self):
351
303
        cache = lru_cache.LRUSizeCache()
352
304
        self.assertEqual(0, cache._value_size)
353
 
        cache.add('my key', 'my value text')
 
305
        cache['my key'] = 'my value text'
354
306
        self.assertEqual(13, cache._value_size)
355
307
        node = cache._cache['my key']
356
308
        cache._remove_node(node)
360
312
        """Adding a large value may not be cached at all."""
361
313
        cache = lru_cache.LRUSizeCache(max_size=10, after_cleanup_size=5)
362
314
        self.assertEqual(0, cache._value_size)
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())
 
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())
370
322
        # If we would add a key, only to cleanup and remove all cached entries,
371
323
        # then obviously that value should not be stored
372
 
        cache.add('test3', 'bigkey')
373
 
        self.assertEqual(3, cache._value_size)
374
 
        self.assertEqual({'test':'key'}, cache.items())
375
 
 
376
 
        cache.add('test4', 'bikey')
377
 
        self.assertEqual(3, cache._value_size)
378
 
        self.assertEqual({'test':'key'}, cache.items())
379
 
 
380
 
    def test_no_add_over_size_cleanup(self):
381
 
        """If a large value is not cached, we will call cleanup right away."""
382
 
        cleanup_calls = []
383
 
        def cleanup(key, value):
384
 
            cleanup_calls.append((key, value))
385
 
 
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)
390
 
        # key was not added
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)
 
324
        cache['test3'] = 'bigkey'
 
325
        self.assertEqual(3, cache._value_size)
 
326
        self.assertEqual({'test':'key'}, cache.as_dict())
 
327
 
 
328
        cache['test4'] = 'bikey'
 
329
        self.assertEqual(3, cache._value_size)
 
330
        self.assertEqual({'test':'key'}, cache.as_dict())
395
331
 
396
332
    def test_adding_clears_cache_based_on_size(self):
397
333
        """The cache is cleared in LRU order until small enough"""
398
334
        cache = lru_cache.LRUSizeCache(max_size=20)
399
 
        cache.add('key1', 'value') # 5 chars
400
 
        cache.add('key2', 'value2') # 6 chars
401
 
        cache.add('key3', 'value23') # 7 chars
 
335
        cache['key1'] = 'value' # 5 chars
 
336
        cache['key2'] = 'value2' # 6 chars
 
337
        cache['key3'] = 'value23' # 7 chars
402
338
        self.assertEqual(5+6+7, cache._value_size)
403
339
        cache['key2'] # reference key2 so it gets a newer reference time
404
 
        cache.add('key4', 'value234') # 8 chars, over limit
 
340
        cache['key4'] = 'value234' # 8 chars, over limit
405
341
        # We have to remove 2 keys to get back under limit
406
342
        self.assertEqual(6+8, cache._value_size)
407
343
        self.assertEqual({'key2':'value2', 'key4':'value234'},
408
 
                         cache.items())
 
344
                         cache.as_dict())
409
345
 
410
346
    def test_adding_clears_to_after_cleanup_size(self):
411
347
        cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
412
 
        cache.add('key1', 'value') # 5 chars
413
 
        cache.add('key2', 'value2') # 6 chars
414
 
        cache.add('key3', 'value23') # 7 chars
 
348
        cache['key1'] = 'value' # 5 chars
 
349
        cache['key2'] = 'value2' # 6 chars
 
350
        cache['key3'] = 'value23' # 7 chars
415
351
        self.assertEqual(5+6+7, cache._value_size)
416
352
        cache['key2'] # reference key2 so it gets a newer reference time
417
 
        cache.add('key4', 'value234') # 8 chars, over limit
 
353
        cache['key4'] = 'value234' # 8 chars, over limit
418
354
        # We have to remove 3 keys to get back under limit
419
355
        self.assertEqual(8, cache._value_size)
420
 
        self.assertEqual({'key4':'value234'}, cache.items())
 
356
        self.assertEqual({'key4':'value234'}, cache.as_dict())
421
357
 
422
358
    def test_custom_sizes(self):
423
359
        def size_of_list(lst):
425
361
        cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10,
426
362
                                       compute_size=size_of_list)
427
363
 
428
 
        cache.add('key1', ['val', 'ue']) # 5 chars
429
 
        cache.add('key2', ['val', 'ue2']) # 6 chars
430
 
        cache.add('key3', ['val', 'ue23']) # 7 chars
 
364
        cache['key1'] = ['val', 'ue'] # 5 chars
 
365
        cache['key2'] = ['val', 'ue2'] # 6 chars
 
366
        cache['key3'] = ['val', 'ue23'] # 7 chars
431
367
        self.assertEqual(5+6+7, cache._value_size)
432
368
        cache['key2'] # reference key2 so it gets a newer reference time
433
 
        cache.add('key4', ['value', '234']) # 8 chars, over limit
 
369
        cache['key4'] = ['value', '234'] # 8 chars, over limit
434
370
        # We have to remove 3 keys to get back under limit
435
371
        self.assertEqual(8, cache._value_size)
436
 
        self.assertEqual({'key4':['value', '234']}, cache.items())
 
372
        self.assertEqual({'key4':['value', '234']}, cache.as_dict())
437
373
 
438
374
    def test_cleanup(self):
439
375
        cache = lru_cache.LRUSizeCache(max_size=20, after_cleanup_size=10)
440
376
 
441
377
        # Add these in order
442
 
        cache.add('key1', 'value') # 5 chars
443
 
        cache.add('key2', 'value2') # 6 chars
444
 
        cache.add('key3', 'value23') # 7 chars
 
378
        cache['key1'] = 'value' # 5 chars
 
379
        cache['key2'] = 'value2' # 6 chars
 
380
        cache['key3'] = 'value23' # 7 chars
445
381
        self.assertEqual(5+6+7, cache._value_size)
446
382
 
447
383
        cache.cleanup()