~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_btree_index.py

  • Committer: Martin Pool
  • Date: 2009-07-27 05:38:00 UTC
  • mto: This revision was merged to the branch mainline in revision 4587.
  • Revision ID: mbp@sourcefrog.net-20090727053800-bgnhmzzgo0u0314s
Remove tests for deleted LockableFiles methods

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2008, 2009, 2010 Canonical Ltd
 
1
# Copyright (C) 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
23
23
from bzrlib import (
24
24
    btree_index,
25
25
    errors,
26
 
    fifo_cache,
27
 
    lru_cache,
28
 
    osutils,
29
26
    tests,
30
 
    transport,
31
27
    )
32
28
from bzrlib.tests import (
33
29
    TestCaseWithTransport,
35
31
    multiply_tests,
36
32
    split_suite_by_condition,
37
33
    )
 
34
from bzrlib.transport import get_transport
38
35
 
39
36
 
40
37
def load_tests(standard_tests, module, loader):
43
40
        condition_isinstance(TestBTreeNodes))
44
41
    import bzrlib._btree_serializer_py as py_module
45
42
    scenarios = [('python', {'parse_btree': py_module})]
46
 
    if compiled_btreeparser_feature.available():
47
 
        scenarios.append(('C', {'parse_btree':
48
 
                                compiled_btreeparser_feature.module}))
 
43
    if CompiledBtreeParserFeature.available():
 
44
        # Is there a way to do this that gets missing feature failures rather
 
45
        # than no indication to the user?
 
46
        import bzrlib._btree_serializer_pyx as c_module
 
47
        scenarios.append(('C', {'parse_btree': c_module}))
49
48
    return multiply_tests(node_tests, scenarios, others)
50
49
 
51
50
 
52
 
compiled_btreeparser_feature = tests.ModuleAvailableFeature(
53
 
                                'bzrlib._btree_serializer_pyx')
 
51
class _CompiledBtreeParserFeature(tests.Feature):
 
52
    def _probe(self):
 
53
        try:
 
54
            import bzrlib._btree_serializer_pyx
 
55
        except ImportError:
 
56
            return False
 
57
        return True
 
58
 
 
59
    def feature_name(self):
 
60
        return 'bzrlib._btree_serializer_pyx'
 
61
 
 
62
CompiledBtreeParserFeature = _CompiledBtreeParserFeature()
54
63
 
55
64
 
56
65
class BTreeTestCase(TestCaseWithTransport):
59
68
 
60
69
    def setUp(self):
61
70
        TestCaseWithTransport.setUp(self)
62
 
        self.overrideAttr(btree_index, '_RESERVED_HEADER_BYTES', 100)
 
71
        self._original_header = btree_index._RESERVED_HEADER_BYTES
 
72
        def restore():
 
73
            btree_index._RESERVED_HEADER_BYTES = self._original_header
 
74
        self.addCleanup(restore)
 
75
        btree_index._RESERVED_HEADER_BYTES = 100
63
76
 
64
77
    def make_nodes(self, count, key_elements, reference_lists):
65
78
        """Generate count*key_elements sample nodes."""
99
112
 
100
113
    def shrink_page_size(self):
101
114
        """Shrink the default page size so that less fits in a page."""
102
 
        self.overrideAttr(btree_index, '_PAGE_SIZE')
 
115
        old_page_size = btree_index._PAGE_SIZE
 
116
        def cleanup():
 
117
            btree_index._PAGE_SIZE = old_page_size
 
118
        self.addCleanup(cleanup)
103
119
        btree_index._PAGE_SIZE = 2048
104
120
 
105
121
 
106
122
class TestBTreeBuilder(BTreeTestCase):
107
123
 
108
 
    def test_clear_cache(self):
109
 
        builder = btree_index.BTreeBuilder(reference_lists=0, key_elements=1)
110
 
        # This is a no-op, but we need the api to be consistent with other
111
 
        # BTreeGraphIndex apis.
112
 
        builder.clear_cache()
113
 
 
114
124
    def test_empty_1_0(self):
115
125
        builder = btree_index.BTreeBuilder(key_elements=1, reference_lists=0)
116
126
        # NamedTemporaryFile dies on builder.finish().read(). weird.
142
152
        temp_file = builder.finish()
143
153
        content = temp_file.read()
144
154
        del temp_file
145
 
        self.assertEqual(131, len(content))
 
155
        self.assertEqual(158, len(content))
146
156
        self.assertEqual(
147
157
            "B+Tree Graph Index 2\nnode_ref_lists=0\nkey_elements=1\nlen=5\n"
148
158
            "row_lengths=1\n",
166
176
        temp_file = builder.finish()
167
177
        content = temp_file.read()
168
178
        del temp_file
169
 
        self.assertEqual(238, len(content))
 
179
        self.assertEqual(264, len(content))
170
180
        self.assertEqual(
171
181
            "B+Tree Graph Index 2\nnode_ref_lists=2\nkey_elements=2\nlen=10\n"
172
182
            "row_lengths=1\n",
216
226
        leaf1_bytes = zlib.decompress(leaf1)
217
227
        sorted_node_keys = sorted(node[0] for node in nodes)
218
228
        node = btree_index._LeafNode(leaf1_bytes, 1, 0)
219
 
        self.assertEqual(231, len(node))
220
 
        self.assertEqual(sorted_node_keys[:231], node.all_keys())
 
229
        self.assertEqual(231, len(node.keys))
 
230
        self.assertEqual(sorted_node_keys[:231], sorted(node.keys))
221
231
        leaf2_bytes = zlib.decompress(leaf2)
222
232
        node = btree_index._LeafNode(leaf2_bytes, 1, 0)
223
 
        self.assertEqual(400 - 231, len(node))
224
 
        self.assertEqual(sorted_node_keys[231:], node.all_keys())
 
233
        self.assertEqual(400 - 231, len(node.keys))
 
234
        self.assertEqual(sorted_node_keys[231:], sorted(node.keys))
225
235
 
226
236
    def test_last_page_rounded_1_layer(self):
227
237
        builder = btree_index.BTreeBuilder(key_elements=1, reference_lists=0)
232
242
        temp_file = builder.finish()
233
243
        content = temp_file.read()
234
244
        del temp_file
235
 
        self.assertEqual(155, len(content))
 
245
        self.assertEqual(181, len(content))
236
246
        self.assertEqual(
237
247
            "B+Tree Graph Index 2\nnode_ref_lists=0\nkey_elements=1\nlen=10\n"
238
248
            "row_lengths=1\n",
241
251
        leaf2 = content[74:]
242
252
        leaf2_bytes = zlib.decompress(leaf2)
243
253
        node = btree_index._LeafNode(leaf2_bytes, 1, 0)
244
 
        self.assertEqual(10, len(node))
 
254
        self.assertEqual(10, len(node.keys))
245
255
        sorted_node_keys = sorted(node[0] for node in nodes)
246
 
        self.assertEqual(sorted_node_keys, node.all_keys())
 
256
        self.assertEqual(sorted_node_keys, sorted(node.keys))
247
257
 
248
258
    def test_last_page_not_rounded_2_layer(self):
249
259
        builder = btree_index.BTreeBuilder(key_elements=1, reference_lists=0)
263
273
        leaf2 = content[8192:]
264
274
        leaf2_bytes = zlib.decompress(leaf2)
265
275
        node = btree_index._LeafNode(leaf2_bytes, 1, 0)
266
 
        self.assertEqual(400 - 231, len(node))
 
276
        self.assertEqual(400 - 231, len(node.keys))
267
277
        sorted_node_keys = sorted(node[0] for node in nodes)
268
 
        self.assertEqual(sorted_node_keys[231:], node.all_keys())
 
278
        self.assertEqual(sorted_node_keys[231:], sorted(node.keys))
269
279
 
270
280
    def test_three_level_tree_details(self):
271
281
        # The left most pointer in the second internal node in a row should
280
290
 
281
291
        for node in nodes:
282
292
            builder.add_node(*node)
283
 
        t = transport.get_transport('trace+' + self.get_url(''))
284
 
        size = t.put_file('index', self.time(builder.finish))
 
293
        transport = get_transport('trace+' + self.get_url(''))
 
294
        size = transport.put_file('index', self.time(builder.finish))
285
295
        del builder
286
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
 
296
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
287
297
        # Seed the metadata, we're using internal calls now.
288
298
        index.key_count()
289
299
        self.assertEqual(3, len(index._row_lengths),
302
312
        # in the second node it points at
303
313
        pos = index._row_offsets[2] + internal_node2.offset + 1
304
314
        leaf = index._get_leaf_nodes([pos])[pos]
305
 
        self.assertTrue(internal_node2.keys[0] in leaf)
 
315
        self.assertTrue(internal_node2.keys[0] in leaf.keys)
306
316
 
307
317
    def test_2_leaves_2_2(self):
308
318
        builder = btree_index.BTreeBuilder(key_elements=2, reference_lists=2)
340
350
        # Test the parts of the index that take up memory are doing so
341
351
        # predictably.
342
352
        self.assertEqual(1, len(builder._nodes))
 
353
        self.assertEqual(1, len(builder._keys))
343
354
        self.assertIs(None, builder._nodes_by_key)
344
355
        builder.add_node(*nodes[1])
345
356
        self.assertEqual(0, len(builder._nodes))
 
357
        self.assertEqual(0, len(builder._keys))
346
358
        self.assertIs(None, builder._nodes_by_key)
347
359
        self.assertEqual(1, len(builder._backing_indices))
348
360
        self.assertEqual(2, builder._backing_indices[0].key_count())
349
361
        # now back to memory
350
362
        builder.add_node(*nodes[2])
351
363
        self.assertEqual(1, len(builder._nodes))
 
364
        self.assertEqual(1, len(builder._keys))
352
365
        self.assertIs(None, builder._nodes_by_key)
353
366
        # And spills to a second backing index combing all
354
367
        builder.add_node(*nodes[3])
355
368
        self.assertEqual(0, len(builder._nodes))
 
369
        self.assertEqual(0, len(builder._keys))
356
370
        self.assertIs(None, builder._nodes_by_key)
357
371
        self.assertEqual(2, len(builder._backing_indices))
358
372
        self.assertEqual(None, builder._backing_indices[0])
361
375
        builder.add_node(*nodes[4])
362
376
        builder.add_node(*nodes[5])
363
377
        self.assertEqual(0, len(builder._nodes))
 
378
        self.assertEqual(0, len(builder._keys))
364
379
        self.assertIs(None, builder._nodes_by_key)
365
380
        self.assertEqual(2, len(builder._backing_indices))
366
381
        self.assertEqual(2, builder._backing_indices[0].key_count())
409
424
        self.assertEqual(None, builder._backing_indices[2])
410
425
        self.assertEqual(16, builder._backing_indices[3].key_count())
411
426
        # Now finish, and check we got a correctly ordered tree
412
 
        t = self.get_transport('')
413
 
        size = t.put_file('index', builder.finish())
414
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
 
427
        transport = self.get_transport('')
 
428
        size = transport.put_file('index', builder.finish())
 
429
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
415
430
        nodes = list(index.iter_all_entries())
416
431
        self.assertEqual(sorted(nodes), nodes)
417
432
        self.assertEqual(16, len(nodes))
424
439
        # Test the parts of the index that take up memory are doing so
425
440
        # predictably.
426
441
        self.assertEqual(1, len(builder._nodes))
 
442
        self.assertEqual(1, len(builder._keys))
427
443
        self.assertIs(None, builder._nodes_by_key)
428
444
        builder.add_node(*nodes[1])
429
445
        self.assertEqual(0, len(builder._nodes))
 
446
        self.assertEqual(0, len(builder._keys))
430
447
        self.assertIs(None, builder._nodes_by_key)
431
448
        self.assertEqual(1, len(builder._backing_indices))
432
449
        self.assertEqual(2, builder._backing_indices[0].key_count())
433
450
        # now back to memory
434
451
        builder.add_node(*nodes[2])
435
452
        self.assertEqual(1, len(builder._nodes))
 
453
        self.assertEqual(1, len(builder._keys))
436
454
        self.assertIs(None, builder._nodes_by_key)
437
455
        # And spills to a second backing index but doesn't combine
438
456
        builder.add_node(*nodes[3])
439
457
        self.assertEqual(0, len(builder._nodes))
 
458
        self.assertEqual(0, len(builder._keys))
440
459
        self.assertIs(None, builder._nodes_by_key)
441
460
        self.assertEqual(2, len(builder._backing_indices))
442
461
        for backing_index in builder._backing_indices:
445
464
        builder.add_node(*nodes[4])
446
465
        builder.add_node(*nodes[5])
447
466
        self.assertEqual(0, len(builder._nodes))
 
467
        self.assertEqual(0, len(builder._keys))
448
468
        self.assertIs(None, builder._nodes_by_key)
449
469
        self.assertEqual(3, len(builder._backing_indices))
450
470
        for backing_index in builder._backing_indices:
509
529
        builder.add_node(*nodes[0])
510
530
        # Test the parts of the index that take up memory are doing so
511
531
        # predictably.
 
532
        self.assertEqual(1, len(builder._keys))
512
533
        self.assertEqual(1, len(builder._nodes))
513
534
        self.assertIs(None, builder._nodes_by_key)
514
535
        builder.add_node(*nodes[1])
 
536
        self.assertEqual(0, len(builder._keys))
515
537
        self.assertEqual(0, len(builder._nodes))
516
538
        self.assertIs(None, builder._nodes_by_key)
517
539
        self.assertEqual(1, len(builder._backing_indices))
520
542
        old = dict(builder._get_nodes_by_key()) #Build up the nodes by key dict
521
543
        builder.add_node(*nodes[2])
522
544
        self.assertEqual(1, len(builder._nodes))
 
545
        self.assertEqual(1, len(builder._keys))
523
546
        self.assertIsNot(None, builder._nodes_by_key)
524
547
        self.assertNotEqual({}, builder._nodes_by_key)
525
548
        # We should have a new entry
527
550
        # And spills to a second backing index combing all
528
551
        builder.add_node(*nodes[3])
529
552
        self.assertEqual(0, len(builder._nodes))
 
553
        self.assertEqual(0, len(builder._keys))
530
554
        self.assertIs(None, builder._nodes_by_key)
531
555
        self.assertEqual(2, len(builder._backing_indices))
532
556
        self.assertEqual(None, builder._backing_indices[0])
535
559
        builder.add_node(*nodes[4])
536
560
        builder.add_node(*nodes[5])
537
561
        self.assertEqual(0, len(builder._nodes))
 
562
        self.assertEqual(0, len(builder._keys))
538
563
        self.assertIs(None, builder._nodes_by_key)
539
564
        self.assertEqual(2, len(builder._backing_indices))
540
565
        self.assertEqual(2, builder._backing_indices[0].key_count())
607
632
        for key, value, references in nodes:
608
633
            builder.add_node(key, value, references)
609
634
        stream = builder.finish()
610
 
        trans = transport.get_transport('trace+' + self.get_url())
 
635
        trans = get_transport('trace+' + self.get_url())
611
636
        size = trans.put_file('index', stream)
612
637
        return btree_index.BTreeGraphIndex(trans, 'index', size)
613
638
 
614
 
    def make_index_with_offset(self, ref_lists=1, key_elements=1, nodes=[],
615
 
                               offset=0):
616
 
        builder = btree_index.BTreeBuilder(key_elements=key_elements,
617
 
                                           reference_lists=ref_lists)
618
 
        builder.add_nodes(nodes)
619
 
        transport = self.get_transport('')
620
 
        # NamedTemporaryFile dies on builder.finish().read(). weird.
621
 
        temp_file = builder.finish()
622
 
        content = temp_file.read()
623
 
        del temp_file
624
 
        size = len(content)
625
 
        transport.put_bytes('index', (' '*offset)+content)
626
 
        return btree_index.BTreeGraphIndex(transport, 'index', size=size,
627
 
                                           offset=offset)
628
 
 
629
 
    def test_clear_cache(self):
630
 
        nodes = self.make_nodes(160, 2, 2)
631
 
        index = self.make_index(ref_lists=2, key_elements=2, nodes=nodes)
632
 
        self.assertEqual(1, len(list(index.iter_entries([nodes[30][0]]))))
633
 
        self.assertEqual([1, 4], index._row_lengths)
634
 
        self.assertIsNot(None, index._root_node)
635
 
        internal_node_pre_clear = index._internal_node_cache.keys()
636
 
        self.assertTrue(len(index._leaf_node_cache) > 0)
637
 
        index.clear_cache()
638
 
        # We don't touch _root_node or _internal_node_cache, both should be
639
 
        # small, and can save a round trip or two
640
 
        self.assertIsNot(None, index._root_node)
641
 
        # NOTE: We don't want to affect the _internal_node_cache, as we expect
642
 
        #       it will be small, and if we ever do touch this index again, it
643
 
        #       will save round-trips.  This assertion isn't very strong,
644
 
        #       becuase without a 3-level index, we don't have any internal
645
 
        #       nodes cached.
646
 
        self.assertEqual(internal_node_pre_clear,
647
 
                         index._internal_node_cache.keys())
648
 
        self.assertEqual(0, len(index._leaf_node_cache))
649
 
 
650
639
    def test_trivial_constructor(self):
651
 
        t = transport.get_transport('trace+' + self.get_url(''))
652
 
        index = btree_index.BTreeGraphIndex(t, 'index', None)
 
640
        transport = get_transport('trace+' + self.get_url(''))
 
641
        index = btree_index.BTreeGraphIndex(transport, 'index', None)
653
642
        # Checks the page size at load, but that isn't logged yet.
654
 
        self.assertEqual([], t._activity)
 
643
        self.assertEqual([], transport._activity)
655
644
 
656
645
    def test_with_size_constructor(self):
657
 
        t = transport.get_transport('trace+' + self.get_url(''))
658
 
        index = btree_index.BTreeGraphIndex(t, 'index', 1)
 
646
        transport = get_transport('trace+' + self.get_url(''))
 
647
        index = btree_index.BTreeGraphIndex(transport, 'index', 1)
659
648
        # Checks the page size at load, but that isn't logged yet.
660
 
        self.assertEqual([], t._activity)
 
649
        self.assertEqual([], transport._activity)
661
650
 
662
651
    def test_empty_key_count_no_size(self):
663
652
        builder = btree_index.BTreeBuilder(key_elements=1, reference_lists=0)
664
 
        t = transport.get_transport('trace+' + self.get_url(''))
665
 
        t.put_file('index', builder.finish())
666
 
        index = btree_index.BTreeGraphIndex(t, 'index', None)
667
 
        del t._activity[:]
668
 
        self.assertEqual([], t._activity)
 
653
        transport = get_transport('trace+' + self.get_url(''))
 
654
        transport.put_file('index', builder.finish())
 
655
        index = btree_index.BTreeGraphIndex(transport, 'index', None)
 
656
        del transport._activity[:]
 
657
        self.assertEqual([], transport._activity)
669
658
        self.assertEqual(0, index.key_count())
670
659
        # The entire index should have been requested (as we generally have the
671
660
        # size available, and doing many small readvs is inappropriate).
672
661
        # We can't tell how much was actually read here, but - check the code.
673
 
        self.assertEqual([('get', 'index')], t._activity)
 
662
        self.assertEqual([('get', 'index')], transport._activity)
674
663
 
675
664
    def test_empty_key_count(self):
676
665
        builder = btree_index.BTreeBuilder(key_elements=1, reference_lists=0)
677
 
        t = transport.get_transport('trace+' + self.get_url(''))
678
 
        size = t.put_file('index', builder.finish())
 
666
        transport = get_transport('trace+' + self.get_url(''))
 
667
        size = transport.put_file('index', builder.finish())
679
668
        self.assertEqual(72, size)
680
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
681
 
        del t._activity[:]
682
 
        self.assertEqual([], t._activity)
 
669
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
 
670
        del transport._activity[:]
 
671
        self.assertEqual([], transport._activity)
683
672
        self.assertEqual(0, index.key_count())
684
673
        # The entire index should have been read, as 4K > size
685
674
        self.assertEqual([('readv', 'index', [(0, 72)], False, None)],
686
 
                         t._activity)
 
675
            transport._activity)
687
676
 
688
677
    def test_non_empty_key_count_2_2(self):
689
678
        builder = btree_index.BTreeBuilder(key_elements=2, reference_lists=2)
690
679
        nodes = self.make_nodes(35, 2, 2)
691
680
        for node in nodes:
692
681
            builder.add_node(*node)
693
 
        t = transport.get_transport('trace+' + self.get_url(''))
694
 
        size = t.put_file('index', builder.finish())
695
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
696
 
        del t._activity[:]
697
 
        self.assertEqual([], t._activity)
 
682
        transport = get_transport('trace+' + self.get_url(''))
 
683
        size = transport.put_file('index', builder.finish())
 
684
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
 
685
        del transport._activity[:]
 
686
        self.assertEqual([], transport._activity)
698
687
        self.assertEqual(70, index.key_count())
699
688
        # The entire index should have been read, as it is one page long.
700
689
        self.assertEqual([('readv', 'index', [(0, size)], False, None)],
701
 
            t._activity)
702
 
        self.assertEqual(1173, size)
703
 
 
704
 
    def test_with_offset_no_size(self):
705
 
        index = self.make_index_with_offset(key_elements=1, ref_lists=1,
706
 
                                            offset=1234,
707
 
                                            nodes=self.make_nodes(200, 1, 1))
708
 
        index._size = None # throw away the size info
709
 
        self.assertEqual(200, index.key_count())
710
 
 
711
 
    def test_with_small_offset(self):
712
 
        index = self.make_index_with_offset(key_elements=1, ref_lists=1,
713
 
                                            offset=1234,
714
 
                                            nodes=self.make_nodes(200, 1, 1))
715
 
        self.assertEqual(200, index.key_count())
716
 
 
717
 
    def test_with_large_offset(self):
718
 
        index = self.make_index_with_offset(key_elements=1, ref_lists=1,
719
 
                                            offset=123456,
720
 
                                            nodes=self.make_nodes(200, 1, 1))
721
 
        self.assertEqual(200, index.key_count())
 
690
            transport._activity)
 
691
        self.assertEqual(1199, size)
722
692
 
723
693
    def test__read_nodes_no_size_one_page_reads_once(self):
724
694
        self.make_index(nodes=[(('key',), 'value', ())])
725
 
        trans = transport.get_transport('trace+' + self.get_url())
 
695
        trans = get_transport('trace+' + self.get_url())
726
696
        index = btree_index.BTreeGraphIndex(trans, 'index', None)
727
697
        del trans._activity[:]
728
698
        nodes = dict(index._read_nodes([0]))
729
699
        self.assertEqual([0], nodes.keys())
730
700
        node = nodes[0]
731
 
        self.assertEqual([('key',)], node.all_keys())
 
701
        self.assertEqual([('key',)], node.keys.keys())
732
702
        self.assertEqual([('get', 'index')], trans._activity)
733
703
 
734
704
    def test__read_nodes_no_size_multiple_pages(self):
736
706
        index.key_count()
737
707
        num_pages = index._row_offsets[-1]
738
708
        # Reopen with a traced transport and no size
739
 
        trans = transport.get_transport('trace+' + self.get_url())
 
709
        trans = get_transport('trace+' + self.get_url())
740
710
        index = btree_index.BTreeGraphIndex(trans, 'index', None)
741
711
        del trans._activity[:]
742
712
        nodes = dict(index._read_nodes([0]))
747
717
        nodes = self.make_nodes(160, 2, 2)
748
718
        for node in nodes:
749
719
            builder.add_node(*node)
750
 
        t = transport.get_transport('trace+' + self.get_url(''))
751
 
        size = t.put_file('index', builder.finish())
 
720
        transport = get_transport('trace+' + self.get_url(''))
 
721
        size = transport.put_file('index', builder.finish())
752
722
        self.assertEqual(17692, size)
753
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
754
 
        del t._activity[:]
755
 
        self.assertEqual([], t._activity)
 
723
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
 
724
        del transport._activity[:]
 
725
        self.assertEqual([], transport._activity)
756
726
        self.assertEqual(320, index.key_count())
757
727
        # The entire index should not have been read.
758
728
        self.assertEqual([('readv', 'index', [(0, 4096)], False, None)],
759
 
                         t._activity)
 
729
            transport._activity)
760
730
 
761
731
    def test_validate_one_page(self):
762
732
        builder = btree_index.BTreeBuilder(key_elements=2, reference_lists=2)
763
733
        nodes = self.make_nodes(45, 2, 2)
764
734
        for node in nodes:
765
735
            builder.add_node(*node)
766
 
        t = transport.get_transport('trace+' + self.get_url(''))
767
 
        size = t.put_file('index', builder.finish())
768
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
769
 
        del t._activity[:]
770
 
        self.assertEqual([], t._activity)
 
736
        transport = get_transport('trace+' + self.get_url(''))
 
737
        size = transport.put_file('index', builder.finish())
 
738
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
 
739
        del transport._activity[:]
 
740
        self.assertEqual([], transport._activity)
771
741
        index.validate()
772
742
        # The entire index should have been read linearly.
773
743
        self.assertEqual([('readv', 'index', [(0, size)], False, None)],
774
 
                         t._activity)
775
 
        self.assertEqual(1488, size)
 
744
            transport._activity)
 
745
        self.assertEqual(1514, size)
776
746
 
777
747
    def test_validate_two_pages(self):
778
748
        builder = btree_index.BTreeBuilder(key_elements=2, reference_lists=2)
779
749
        nodes = self.make_nodes(80, 2, 2)
780
750
        for node in nodes:
781
751
            builder.add_node(*node)
782
 
        t = transport.get_transport('trace+' + self.get_url(''))
783
 
        size = t.put_file('index', builder.finish())
 
752
        transport = get_transport('trace+' + self.get_url(''))
 
753
        size = transport.put_file('index', builder.finish())
784
754
        # Root page, 2 leaf pages
785
755
        self.assertEqual(9339, size)
786
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
787
 
        del t._activity[:]
788
 
        self.assertEqual([], t._activity)
 
756
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
 
757
        del transport._activity[:]
 
758
        self.assertEqual([], transport._activity)
789
759
        index.validate()
790
760
        # The entire index should have been read linearly.
791
 
        self.assertEqual(
792
 
            [('readv', 'index', [(0, 4096)], False, None),
793
 
             ('readv', 'index', [(4096, 4096), (8192, 1147)], False, None)],
794
 
            t._activity)
 
761
        self.assertEqual([('readv', 'index', [(0, 4096)], False, None),
 
762
            ('readv', 'index', [(4096, 4096), (8192, 1147)], False, None)],
 
763
            transport._activity)
795
764
        # XXX: TODO: write some badly-ordered nodes, and some pointers-to-wrong
796
765
        # node and make validate find them.
797
766
 
798
767
    def test_eq_ne(self):
799
768
        # two indices are equal when constructed with the same parameters:
800
 
        t1 = transport.get_transport('trace+' + self.get_url(''))
801
 
        t2 = transport.get_transport(self.get_url(''))
802
 
        self.assertTrue(
803
 
            btree_index.BTreeGraphIndex(t1, 'index', None) ==
804
 
            btree_index.BTreeGraphIndex(t1, 'index', None))
805
 
        self.assertTrue(
806
 
            btree_index.BTreeGraphIndex(t1, 'index', 20) ==
807
 
            btree_index.BTreeGraphIndex(t1, 'index', 20))
808
 
        self.assertFalse(
809
 
            btree_index.BTreeGraphIndex(t1, 'index', 20) ==
810
 
            btree_index.BTreeGraphIndex(t2, 'index', 20))
811
 
        self.assertFalse(
812
 
            btree_index.BTreeGraphIndex(t1, 'inde1', 20) ==
813
 
            btree_index.BTreeGraphIndex(t1, 'inde2', 20))
814
 
        self.assertFalse(
815
 
            btree_index.BTreeGraphIndex(t1, 'index', 10) ==
816
 
            btree_index.BTreeGraphIndex(t1, 'index', 20))
817
 
        self.assertFalse(
818
 
            btree_index.BTreeGraphIndex(t1, 'index', None) !=
819
 
            btree_index.BTreeGraphIndex(t1, 'index', None))
820
 
        self.assertFalse(
821
 
            btree_index.BTreeGraphIndex(t1, 'index', 20) !=
822
 
            btree_index.BTreeGraphIndex(t1, 'index', 20))
823
 
        self.assertTrue(
824
 
            btree_index.BTreeGraphIndex(t1, 'index', 20) !=
825
 
            btree_index.BTreeGraphIndex(t2, 'index', 20))
826
 
        self.assertTrue(
827
 
            btree_index.BTreeGraphIndex(t1, 'inde1', 20) !=
828
 
            btree_index.BTreeGraphIndex(t1, 'inde2', 20))
829
 
        self.assertTrue(
830
 
            btree_index.BTreeGraphIndex(t1, 'index', 10) !=
831
 
            btree_index.BTreeGraphIndex(t1, 'index', 20))
 
769
        transport1 = get_transport('trace+' + self.get_url(''))
 
770
        transport2 = get_transport(self.get_url(''))
 
771
        self.assertTrue(
 
772
            btree_index.BTreeGraphIndex(transport1, 'index', None) ==
 
773
            btree_index.BTreeGraphIndex(transport1, 'index', None))
 
774
        self.assertTrue(
 
775
            btree_index.BTreeGraphIndex(transport1, 'index', 20) ==
 
776
            btree_index.BTreeGraphIndex(transport1, 'index', 20))
 
777
        self.assertFalse(
 
778
            btree_index.BTreeGraphIndex(transport1, 'index', 20) ==
 
779
            btree_index.BTreeGraphIndex(transport2, 'index', 20))
 
780
        self.assertFalse(
 
781
            btree_index.BTreeGraphIndex(transport1, 'inde1', 20) ==
 
782
            btree_index.BTreeGraphIndex(transport1, 'inde2', 20))
 
783
        self.assertFalse(
 
784
            btree_index.BTreeGraphIndex(transport1, 'index', 10) ==
 
785
            btree_index.BTreeGraphIndex(transport1, 'index', 20))
 
786
        self.assertFalse(
 
787
            btree_index.BTreeGraphIndex(transport1, 'index', None) !=
 
788
            btree_index.BTreeGraphIndex(transport1, 'index', None))
 
789
        self.assertFalse(
 
790
            btree_index.BTreeGraphIndex(transport1, 'index', 20) !=
 
791
            btree_index.BTreeGraphIndex(transport1, 'index', 20))
 
792
        self.assertTrue(
 
793
            btree_index.BTreeGraphIndex(transport1, 'index', 20) !=
 
794
            btree_index.BTreeGraphIndex(transport2, 'index', 20))
 
795
        self.assertTrue(
 
796
            btree_index.BTreeGraphIndex(transport1, 'inde1', 20) !=
 
797
            btree_index.BTreeGraphIndex(transport1, 'inde2', 20))
 
798
        self.assertTrue(
 
799
            btree_index.BTreeGraphIndex(transport1, 'index', 10) !=
 
800
            btree_index.BTreeGraphIndex(transport1, 'index', 20))
832
801
 
833
802
    def test_iter_all_only_root_no_size(self):
834
803
        self.make_index(nodes=[(('key',), 'value', ())])
835
 
        t = transport.get_transport('trace+' + self.get_url(''))
836
 
        index = btree_index.BTreeGraphIndex(t, 'index', None)
837
 
        del t._activity[:]
 
804
        trans = get_transport('trace+' + self.get_url(''))
 
805
        index = btree_index.BTreeGraphIndex(trans, 'index', None)
 
806
        del trans._activity[:]
838
807
        self.assertEqual([(('key',), 'value')],
839
808
                         [x[1:] for x in index.iter_all_entries()])
840
 
        self.assertEqual([('get', 'index')], t._activity)
 
809
        self.assertEqual([('get', 'index')], trans._activity)
841
810
 
842
811
    def test_iter_all_entries_reads(self):
843
812
        # iterating all entries reads the header, then does a linear
849
818
        nodes = self.make_nodes(10000, 2, 2)
850
819
        for node in nodes:
851
820
            builder.add_node(*node)
852
 
        t = transport.get_transport('trace+' + self.get_url(''))
853
 
        size = t.put_file('index', builder.finish())
 
821
        transport = get_transport('trace+' + self.get_url(''))
 
822
        size = transport.put_file('index', builder.finish())
854
823
        self.assertEqual(1303220, size, 'number of expected bytes in the'
855
824
                                        ' output changed')
856
825
        page_size = btree_index._PAGE_SIZE
857
826
        del builder
858
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
859
 
        del t._activity[:]
860
 
        self.assertEqual([], t._activity)
 
827
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
 
828
        del transport._activity[:]
 
829
        self.assertEqual([], transport._activity)
861
830
        found_nodes = self.time(list, index.iter_all_entries())
862
831
        bare_nodes = []
863
832
        for node in found_nodes:
884
853
        readv_request[-1] = (readv_request[-1][0], 1303220 % page_size)
885
854
        expected = [('readv', 'index', [(0, page_size)], False, None),
886
855
             ('readv',  'index', readv_request, False, None)]
887
 
        if expected != t._activity:
 
856
        if expected != transport._activity:
888
857
            self.assertEqualDiff(pprint.pformat(expected),
889
858
                                 pprint.pformat(transport._activity))
890
859
 
904
873
        nodes = self.make_nodes(160, 2, 2)
905
874
        for node in nodes:
906
875
            builder.add_node(*node)
907
 
        t = transport.get_transport('trace+' + self.get_url(''))
908
 
        size = t.put_file('index', builder.finish())
 
876
        transport = get_transport('trace+' + self.get_url(''))
 
877
        size = transport.put_file('index', builder.finish())
909
878
        del builder
910
 
        index = btree_index.BTreeGraphIndex(t, 'index', size)
911
 
        del t._activity[:]
912
 
        self.assertEqual([], t._activity)
 
879
        index = btree_index.BTreeGraphIndex(transport, 'index', size)
 
880
        del transport._activity[:]
 
881
        self.assertEqual([], transport._activity)
913
882
        # search for one key
914
883
        found_nodes = list(index.iter_entries([nodes[30][0]]))
915
884
        bare_nodes = []
923
892
        # Should have read the root node, then one leaf page:
924
893
        self.assertEqual([('readv', 'index', [(0, 4096)], False, None),
925
894
             ('readv',  'index', [(8192, 4096), ], False, None)],
926
 
            t._activity)
 
895
            transport._activity)
927
896
 
928
897
    def test_iter_key_prefix_1_element_key_None(self):
929
898
        index = self.make_index()
1011
980
            ])
1012
981
        self.assertEqual(set([]), index.external_references(0))
1013
982
 
1014
 
    def test__find_ancestors_one_page(self):
1015
 
        key1 = ('key-1',)
1016
 
        key2 = ('key-2',)
1017
 
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[
1018
 
            (key1, 'value', ([key2],)),
1019
 
            (key2, 'value', ([],)),
1020
 
            ])
1021
 
        parent_map = {}
1022
 
        missing_keys = set()
1023
 
        search_keys = index._find_ancestors([key1], 0, parent_map, missing_keys)
1024
 
        self.assertEqual({key1: (key2,), key2: ()}, parent_map)
1025
 
        self.assertEqual(set(), missing_keys)
1026
 
        self.assertEqual(set(), search_keys)
1027
 
 
1028
 
    def test__find_ancestors_one_page_w_missing(self):
1029
 
        key1 = ('key-1',)
1030
 
        key2 = ('key-2',)
1031
 
        key3 = ('key-3',)
1032
 
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[
1033
 
            (key1, 'value', ([key2],)),
1034
 
            (key2, 'value', ([],)),
1035
 
            ])
1036
 
        parent_map = {}
1037
 
        missing_keys = set()
1038
 
        search_keys = index._find_ancestors([key2, key3], 0, parent_map,
1039
 
                                            missing_keys)
1040
 
        self.assertEqual({key2: ()}, parent_map)
1041
 
        # we know that key3 is missing because we read the page that it would
1042
 
        # otherwise be on
1043
 
        self.assertEqual(set([key3]), missing_keys)
1044
 
        self.assertEqual(set(), search_keys)
1045
 
 
1046
 
    def test__find_ancestors_one_parent_missing(self):
1047
 
        key1 = ('key-1',)
1048
 
        key2 = ('key-2',)
1049
 
        key3 = ('key-3',)
1050
 
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[
1051
 
            (key1, 'value', ([key2],)),
1052
 
            (key2, 'value', ([key3],)),
1053
 
            ])
1054
 
        parent_map = {}
1055
 
        missing_keys = set()
1056
 
        search_keys = index._find_ancestors([key1], 0, parent_map,
1057
 
                                            missing_keys)
1058
 
        self.assertEqual({key1: (key2,), key2: (key3,)}, parent_map)
1059
 
        self.assertEqual(set(), missing_keys)
1060
 
        # all we know is that key3 wasn't present on the page we were reading
1061
 
        # but if you look, the last key is key2 which comes before key3, so we
1062
 
        # don't know whether key3 would land on this page or not.
1063
 
        self.assertEqual(set([key3]), search_keys)
1064
 
        search_keys = index._find_ancestors(search_keys, 0, parent_map,
1065
 
                                            missing_keys)
1066
 
        # passing it back in, we are sure it is 'missing'
1067
 
        self.assertEqual({key1: (key2,), key2: (key3,)}, parent_map)
1068
 
        self.assertEqual(set([key3]), missing_keys)
1069
 
        self.assertEqual(set([]), search_keys)
1070
 
 
1071
 
    def test__find_ancestors_dont_search_known(self):
1072
 
        key1 = ('key-1',)
1073
 
        key2 = ('key-2',)
1074
 
        key3 = ('key-3',)
1075
 
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[
1076
 
            (key1, 'value', ([key2],)),
1077
 
            (key2, 'value', ([key3],)),
1078
 
            (key3, 'value', ([],)),
1079
 
            ])
1080
 
        # We already know about key2, so we won't try to search for key3
1081
 
        parent_map = {key2: (key3,)}
1082
 
        missing_keys = set()
1083
 
        search_keys = index._find_ancestors([key1], 0, parent_map,
1084
 
                                            missing_keys)
1085
 
        self.assertEqual({key1: (key2,), key2: (key3,)}, parent_map)
1086
 
        self.assertEqual(set(), missing_keys)
1087
 
        self.assertEqual(set(), search_keys)
1088
 
 
1089
 
    def test__find_ancestors_multiple_pages(self):
1090
 
        # We need to use enough keys that we actually cause a split
1091
 
        start_time = 1249671539
1092
 
        email = "joebob@example.com"
1093
 
        nodes = []
1094
 
        ref_lists = ((),)
1095
 
        rev_keys = []
1096
 
        for i in xrange(400):
1097
 
            rev_id = '%s-%s-%s' % (email,
1098
 
                                   osutils.compact_date(start_time + i),
1099
 
                                   osutils.rand_chars(16))
1100
 
            rev_key = (rev_id,)
1101
 
            nodes.append((rev_key, 'value', ref_lists))
1102
 
            # We have a ref 'list' of length 1, with a list of parents, with 1
1103
 
            # parent which is a key
1104
 
            ref_lists = ((rev_key,),)
1105
 
            rev_keys.append(rev_key)
1106
 
        index = self.make_index(ref_lists=1, key_elements=1, nodes=nodes)
1107
 
        self.assertEqual(400, index.key_count())
1108
 
        self.assertEqual(3, len(index._row_offsets))
1109
 
        nodes = dict(index._read_nodes([1, 2]))
1110
 
        l1 = nodes[1]
1111
 
        l2 = nodes[2]
1112
 
        min_l2_key = l2.min_key
1113
 
        max_l1_key = l1.max_key
1114
 
        self.assertTrue(max_l1_key < min_l2_key)
1115
 
        parents_min_l2_key = l2[min_l2_key][1][0]
1116
 
        self.assertEqual((l1.max_key,), parents_min_l2_key)
1117
 
        # Now, whatever key we select that would fall on the second page,
1118
 
        # should give us all the parents until the page break
1119
 
        key_idx = rev_keys.index(min_l2_key)
1120
 
        next_key = rev_keys[key_idx+1]
1121
 
        # So now when we get the parent map, we should get the key we are
1122
 
        # looking for, min_l2_key, and then a reference to go look for the
1123
 
        # parent of that key
1124
 
        parent_map = {}
1125
 
        missing_keys = set()
1126
 
        search_keys = index._find_ancestors([next_key], 0, parent_map,
1127
 
                                            missing_keys)
1128
 
        self.assertEqual([min_l2_key, next_key], sorted(parent_map))
1129
 
        self.assertEqual(set(), missing_keys)
1130
 
        self.assertEqual(set([max_l1_key]), search_keys)
1131
 
        parent_map = {}
1132
 
        search_keys = index._find_ancestors([max_l1_key], 0, parent_map,
1133
 
                                            missing_keys)
1134
 
        self.assertEqual(l1.all_keys(), sorted(parent_map))
1135
 
        self.assertEqual(set(), missing_keys)
1136
 
        self.assertEqual(set(), search_keys)
1137
 
 
1138
 
    def test__find_ancestors_empty_index(self):
1139
 
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[])
1140
 
        parent_map = {}
1141
 
        missing_keys = set()
1142
 
        search_keys = index._find_ancestors([('one',), ('two',)], 0, parent_map,
1143
 
                                            missing_keys)
1144
 
        self.assertEqual(set(), search_keys)
1145
 
        self.assertEqual({}, parent_map)
1146
 
        self.assertEqual(set([('one',), ('two',)]), missing_keys)
1147
 
 
1148
 
    def test_supports_unlimited_cache(self):
1149
 
        builder = btree_index.BTreeBuilder(reference_lists=0, key_elements=1)
1150
 
        # We need enough nodes to cause a page split (so we have both an
1151
 
        # internal node and a couple leaf nodes. 500 seems to be enough.)
1152
 
        nodes = self.make_nodes(500, 1, 0)
1153
 
        for node in nodes:
1154
 
            builder.add_node(*node)
1155
 
        stream = builder.finish()
1156
 
        trans = transport.get_transport(self.get_url())
1157
 
        size = trans.put_file('index', stream)
1158
 
        index = btree_index.BTreeGraphIndex(trans, 'index', size)
1159
 
        self.assertEqual(500, index.key_count())
1160
 
        # We have an internal node
1161
 
        self.assertEqual(2, len(index._row_lengths))
1162
 
        # We have at least 2 leaf nodes
1163
 
        self.assertTrue(index._row_lengths[-1] >= 2)
1164
 
        self.assertIsInstance(index._leaf_node_cache, lru_cache.LRUCache)
1165
 
        self.assertEqual(btree_index._NODE_CACHE_SIZE,
1166
 
                         index._leaf_node_cache._max_cache)
1167
 
        self.assertIsInstance(index._internal_node_cache, fifo_cache.FIFOCache)
1168
 
        self.assertEqual(100, index._internal_node_cache._max_cache)
1169
 
        # No change if unlimited_cache=False is passed
1170
 
        index = btree_index.BTreeGraphIndex(trans, 'index', size,
1171
 
                                            unlimited_cache=False)
1172
 
        self.assertIsInstance(index._leaf_node_cache, lru_cache.LRUCache)
1173
 
        self.assertEqual(btree_index._NODE_CACHE_SIZE,
1174
 
                         index._leaf_node_cache._max_cache)
1175
 
        self.assertIsInstance(index._internal_node_cache, fifo_cache.FIFOCache)
1176
 
        self.assertEqual(100, index._internal_node_cache._max_cache)
1177
 
        index = btree_index.BTreeGraphIndex(trans, 'index', size,
1178
 
                                            unlimited_cache=True)
1179
 
        self.assertIsInstance(index._leaf_node_cache, dict)
1180
 
        self.assertIs(type(index._internal_node_cache), dict)
1181
 
        # Exercise the lookup code
1182
 
        entries = set(index.iter_entries([n[0] for n in nodes]))
1183
 
        self.assertEqual(500, len(entries))
1184
 
 
1185
983
 
1186
984
class TestBTreeNodes(BTreeTestCase):
1187
985
 
 
986
    def restore_parser(self):
 
987
        btree_index._btree_serializer = self.saved_parser
 
988
 
1188
989
    def setUp(self):
1189
990
        BTreeTestCase.setUp(self)
1190
 
        self.overrideAttr(btree_index, '_btree_serializer', self.parse_btree)
 
991
        self.saved_parser = btree_index._btree_serializer
 
992
        self.addCleanup(self.restore_parser)
 
993
        btree_index._btree_serializer = self.parse_btree
1191
994
 
1192
995
    def test_LeafNode_1_0(self):
1193
996
        node_bytes = ("type=leaf\n"
1205
1008
            ("2222222222222222222222222222222222222222",): ("value:2", ()),
1206
1009
            ("3333333333333333333333333333333333333333",): ("value:3", ()),
1207
1010
            ("4444444444444444444444444444444444444444",): ("value:4", ()),
1208
 
            }, dict(node.all_items()))
 
1011
            }, node.keys)
1209
1012
 
1210
1013
    def test_LeafNode_2_2(self):
1211
1014
        node_bytes = ("type=leaf\n"
1225
1028
            ('11', '33'): ('value:3',
1226
1029
                ((('11', 'ref22'),), (('11', 'ref22'), ('11', 'ref22')))),
1227
1030
            ('11', '44'): ('value:4', ((), (('11', 'ref00'),)))
1228
 
            }, dict(node.all_items()))
 
1031
            }, node.keys)
1229
1032
 
1230
1033
    def test_InternalNode_1(self):
1231
1034
        node_bytes = ("type=internal\n"
1266
1069
            ('11', '33'): ('value:3',
1267
1070
                ((('11', 'ref22'),), (('11', 'ref22'), ('11', 'ref22')))),
1268
1071
            ('11', '44'): ('value:4', ((), (('11', 'ref00'),)))
1269
 
            }, dict(node.all_items()))
 
1072
            }, node.keys)
1270
1073
 
1271
1074
    def assertFlattened(self, expected, key, value, refs):
1272
1075
        flat_key, flat_line = self.parse_btree._flatten_node(
1304
1107
    def test_exists(self):
1305
1108
        # This is just to let the user know if they don't have the feature
1306
1109
        # available
1307
 
        self.requireFeature(compiled_btreeparser_feature)
 
1110
        self.requireFeature(CompiledBtreeParserFeature)
1308
1111
 
1309
1112
 
1310
1113
class TestMultiBisectRight(tests.TestCase):
1350
1153
        This doesn't actually create anything on disk, it just primes a
1351
1154
        BTreeGraphIndex with the recommended information.
1352
1155
        """
1353
 
        index = btree_index.BTreeGraphIndex(
1354
 
            transport.get_transport('memory:///'), 'test-index', size=size)
 
1156
        index = btree_index.BTreeGraphIndex(get_transport('memory:///'),
 
1157
                                            'test-index', size=size)
1355
1158
        if recommended_pages is not None:
1356
1159
            index._recommended_pages = recommended_pages
1357
1160
        return index