~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_index.py

  • Committer: Danny van Heumen
  • Date: 2010-03-09 21:42:11 UTC
  • mto: (4634.139.5 2.0)
  • mto: This revision was merged to the branch mainline in revision 5160.
  • Revision ID: danny@dannyvanheumen.nl-20100309214211-iqh42x6qcikgd9p3
Reverted now-useless TODO list.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 Canonical Ltd
 
1
# Copyright (C) 2007, 2009 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""Tests for indices."""
18
18
 
350
350
        builder.add_node(('k', 'ey'), 'data', ([('reference', 'tokey')], ))
351
351
        builder.add_node(('reference', 'tokey'), 'data', ([],))
352
352
 
 
353
    def test_set_optimize(self):
 
354
        builder = GraphIndexBuilder(reference_lists=1, key_elements=2)
 
355
        builder.set_optimize(for_size=True)
 
356
        self.assertTrue(builder._optimize_for_size)
 
357
        builder.set_optimize(for_size=False)
 
358
        self.assertFalse(builder._optimize_for_size)
 
359
 
353
360
 
354
361
class TestGraphIndex(TestCaseWithMemoryTransport):
355
362
 
 
363
    def make_key(self, number):
 
364
        return (str(number) + 'X'*100,)
 
365
 
 
366
    def make_value(self, number):
 
367
            return str(number) + 'Y'*100
 
368
 
 
369
    def make_nodes(self, count=64):
 
370
        # generate a big enough index that we only read some of it on a typical
 
371
        # bisection lookup.
 
372
        nodes = []
 
373
        for counter in range(count):
 
374
            nodes.append((self.make_key(counter), self.make_value(counter), ()))
 
375
        return nodes
 
376
 
356
377
    def make_index(self, ref_lists=0, key_elements=1, nodes=[]):
357
378
        builder = GraphIndexBuilder(ref_lists, key_elements=key_elements)
358
379
        for key, value, references in nodes:
372
393
        self.assertEqual([], index._parsed_byte_map)
373
394
        self.assertEqual([], index._parsed_key_map)
374
395
 
 
396
    def test_key_count_buffers(self):
 
397
        index = self.make_index(nodes=self.make_nodes(2))
 
398
        # reset the transport log
 
399
        del index._transport._activity[:]
 
400
        self.assertEqual(2, index.key_count())
 
401
        # We should have requested reading the header bytes
 
402
        self.assertEqual([
 
403
            ('readv', 'index', [(0, 200)], True, index._size),
 
404
            ],
 
405
            index._transport._activity)
 
406
        # And that should have been enough to trigger reading the whole index
 
407
        # with buffering
 
408
        self.assertIsNot(None, index._nodes)
 
409
 
 
410
    def test_lookup_key_via_location_buffers(self):
 
411
        index = self.make_index()
 
412
        # reset the transport log
 
413
        del index._transport._activity[:]
 
414
        # do a _lookup_keys_via_location call for the middle of the file, which
 
415
        # is what bisection uses.
 
416
        result = index._lookup_keys_via_location(
 
417
            [(index._size // 2, ('missing', ))])
 
418
        # this should have asked for a readv request, with adjust_for_latency,
 
419
        # and two regions: the header, and half-way into the file.
 
420
        self.assertEqual([
 
421
            ('readv', 'index', [(30, 30), (0, 200)], True, 60),
 
422
            ],
 
423
            index._transport._activity)
 
424
        # and the result should be that the key cannot be present, because this
 
425
        # is a trivial index.
 
426
        self.assertEqual([((index._size // 2, ('missing', )), False)],
 
427
            result)
 
428
        # And this should have caused the file to be fully buffered
 
429
        self.assertIsNot(None, index._nodes)
 
430
        self.assertEqual([], index._parsed_byte_map)
 
431
 
375
432
    def test_first_lookup_key_via_location(self):
376
 
        index = self.make_index()
 
433
        # We need enough data so that the _HEADER_READV doesn't consume the
 
434
        # whole file. We always read 800 bytes for every key, and the local
 
435
        # transport natural expansion is 4096 bytes. So we have to have >8192
 
436
        # bytes or we will trigger "buffer_all".
 
437
        # We also want the 'missing' key to fall within the range that *did*
 
438
        # read
 
439
        nodes = []
 
440
        index = self.make_index(nodes=self.make_nodes(64))
377
441
        # reset the transport log
378
442
        del index._transport._activity[:]
379
443
        # do a _lookup_keys_via_location call for the middle of the file, which
380
444
        # is what bisection uses.
 
445
        start_lookup = index._size // 2
381
446
        result = index._lookup_keys_via_location(
382
 
            [(index._size // 2, ('missing', ))])
 
447
            [(start_lookup, ('40missing', ))])
383
448
        # this should have asked for a readv request, with adjust_for_latency,
384
449
        # and two regions: the header, and half-way into the file.
385
450
        self.assertEqual([
386
 
            ('readv', 'index', [(30, 30), (0, 200)], True, 60),
 
451
            ('readv', 'index',
 
452
             [(start_lookup, 800), (0, 200)], True, index._size),
387
453
            ],
388
454
            index._transport._activity)
389
455
        # and the result should be that the key cannot be present, because this
390
456
        # is a trivial index.
391
 
        self.assertEqual([((index._size // 2, ('missing', )), False)],
392
 
            result)
393
 
        # And the regions of the file that have been parsed - in this case the
394
 
        # entire file - should be in the parsed region map.
395
 
        self.assertEqual([(0, 60)], index._parsed_byte_map)
396
 
        self.assertEqual([(None, None)], index._parsed_key_map)
397
 
 
398
 
    def test_parsing_parses_data_adjacent_to_parsed_regions(self):
399
 
        # we trim data we recieve to remove the first and trailing
400
 
        # partial lines, except when they start at the end/finish at the start
401
 
        # of a region we've alread parsed/ the end of the file. The trivial
402
 
        # test for this is an index with 1 key.
403
 
        index = self.make_index(nodes=[(('name', ), 'data', ())])
404
 
        # reset the transport log
405
 
        del index._transport._activity[:]
406
 
        result = index._lookup_keys_via_location(
407
 
            [(index._size // 2, ('missing', ))])
408
 
        # this should have asked for a readv request, with adjust_for_latency,
409
 
        # and two regions: the header, and half-way into the file.
410
 
        self.assertEqual([
411
 
            ('readv', 'index', [(36, 36), (0, 200)], True, 72),
412
 
            ],
413
 
            index._transport._activity)
414
 
        # and the result should be that the key cannot be present, because this
415
 
        # is a trivial index and we should not have to do more round trips.
416
 
        self.assertEqual([((index._size // 2, ('missing', )), False)],
417
 
            result)
418
 
        # The whole file should be parsed at this point.
419
 
        self.assertEqual([(0, 72)], index._parsed_byte_map)
420
 
        self.assertEqual([(None, ('name',))], index._parsed_key_map)
 
457
        self.assertEqual([((start_lookup, ('40missing', )), False)],
 
458
            result)
 
459
        # And this should not have caused the file to be fully buffered
 
460
        self.assertIs(None, index._nodes)
 
461
        # And the regions of the file that have been parsed should be in the
 
462
        # parsed_byte_map and the parsed_key_map
 
463
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
464
        self.assertEqual([(None, self.make_key(26)),
 
465
                          (self.make_key(31), self.make_key(48))],
 
466
                         index._parsed_key_map)
421
467
 
422
468
    def test_parsing_non_adjacent_data_trims(self):
423
 
        # generate a big enough index that we only read some of it on a typical
424
 
        # bisection lookup.
425
 
        nodes = []
426
 
        def make_key(number):
427
 
            return (str(number) + 'X'*100,)
428
 
        for counter in range(64):
429
 
            nodes.append((make_key(counter), 'Y'*100, ()))
430
 
        index = self.make_index(nodes=nodes)
 
469
        index = self.make_index(nodes=self.make_nodes(64))
431
470
        result = index._lookup_keys_via_location(
432
471
            [(index._size // 2, ('40', ))])
433
472
        # and the result should be that the key cannot be present, because key is
437
476
            result)
438
477
        # and we should have a parse map that includes the header and the
439
478
        # region that was parsed after trimming.
440
 
        self.assertEqual([(0, 3972), (5001, 8914)], index._parsed_byte_map)
441
 
        self.assertEqual([(None, make_key(26)), (make_key(31), make_key(48))],
 
479
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
480
        self.assertEqual([(None, self.make_key(26)),
 
481
                          (self.make_key(31), self.make_key(48))],
442
482
            index._parsed_key_map)
443
483
 
444
484
    def test_parsing_data_handles_parsed_contained_regions(self):
448
488
        # which then trims the start and end so the parsed size is < readv
449
489
        # miniumum.
450
490
        # then a dual lookup (or a reference lookup for that matter) which
451
 
        # abuts or overlaps the parsed region on both sides will need to 
 
491
        # abuts or overlaps the parsed region on both sides will need to
452
492
        # discard the data in the middle, but parse the end as well.
453
493
        #
454
 
        # we test this by doing a single lookup to seed the data, then 
455
 
        # a lookup for two keys that are present, and adjacent - 
 
494
        # we test this by doing a single lookup to seed the data, then
 
495
        # a lookup for two keys that are present, and adjacent -
456
496
        # we except both to be found, and the parsed byte map to include the
457
497
        # locations of both keys.
458
 
        nodes = []
459
 
        def make_key(number):
460
 
            return (str(number) + 'X'*100,)
461
 
        def make_value(number):
462
 
            return 'Y'*100
463
 
        for counter in range(128):
464
 
            nodes.append((make_key(counter), make_value(counter), ()))
465
 
        index = self.make_index(nodes=nodes)
 
498
        index = self.make_index(nodes=self.make_nodes(128))
466
499
        result = index._lookup_keys_via_location(
467
500
            [(index._size // 2, ('40', ))])
468
501
        # and we should have a parse map that includes the header and the
469
502
        # region that was parsed after trimming.
470
 
        self.assertEqual([(0, 3991), (11622, 15534)], index._parsed_byte_map)
471
 
        self.assertEqual([(None, make_key(116)), (make_key(35), make_key(51))],
 
503
        self.assertEqual([(0, 4045), (11759, 15707)], index._parsed_byte_map)
 
504
        self.assertEqual([(None, self.make_key(116)),
 
505
                          (self.make_key(35), self.make_key(51))],
472
506
            index._parsed_key_map)
473
507
        # now ask for two keys, right before and after the parsed region
474
508
        result = index._lookup_keys_via_location(
475
 
            [(11450, make_key(34)), (15534, make_key(52))])
 
509
            [(11450, self.make_key(34)), (15707, self.make_key(52))])
476
510
        self.assertEqual([
477
 
            ((11450, make_key(34)), (index, make_key(34), make_value(34))),
478
 
            ((15534, make_key(52)), (index, make_key(52), make_value(52))),
 
511
            ((11450, self.make_key(34)),
 
512
             (index, self.make_key(34), self.make_value(34))),
 
513
            ((15707, self.make_key(52)),
 
514
             (index, self.make_key(52), self.make_value(52))),
479
515
            ],
480
516
            result)
481
 
        self.assertEqual([(0, 3991), (9975, 17799)], index._parsed_byte_map)
 
517
        self.assertEqual([(0, 4045), (9889, 17993)], index._parsed_byte_map)
482
518
 
483
519
    def test_lookup_missing_key_answers_without_io_when_map_permits(self):
484
520
        # generate a big enough index that we only read some of it on a typical
485
521
        # bisection lookup.
486
 
        nodes = []
487
 
        def make_key(number):
488
 
            return (str(number) + 'X'*100,)
489
 
        for counter in range(64):
490
 
            nodes.append((make_key(counter), 'Y'*100, ()))
491
 
        index = self.make_index(nodes=nodes)
 
522
        index = self.make_index(nodes=self.make_nodes(64))
492
523
        # lookup the keys in the middle of the file
493
524
        result =index._lookup_keys_via_location(
494
525
            [(index._size // 2, ('40', ))])
495
526
        # check the parse map, this determines the test validity
496
 
        self.assertEqual([(0, 3972), (5001, 8914)], index._parsed_byte_map)
497
 
        self.assertEqual([(None, make_key(26)), (make_key(31), make_key(48))],
 
527
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
528
        self.assertEqual([(None, self.make_key(26)),
 
529
                          (self.make_key(31), self.make_key(48))],
498
530
            index._parsed_key_map)
499
531
        # reset the transport log
500
532
        del index._transport._activity[:]
502
534
        # not create a new transport request, and should return False (cannot
503
535
        # be in the index) - even when the byte location we ask for is outside
504
536
        # the parsed region
505
 
        # 
506
537
        result = index._lookup_keys_via_location(
507
538
            [(4000, ('40', ))])
508
539
        self.assertEqual([((4000, ('40', )), False)],
512
543
    def test_lookup_present_key_answers_without_io_when_map_permits(self):
513
544
        # generate a big enough index that we only read some of it on a typical
514
545
        # bisection lookup.
515
 
        nodes = []
516
 
        def make_key(number):
517
 
            return (str(number) + 'X'*100,)
518
 
        def make_value(number):
519
 
            return str(number) + 'Y'*100
520
 
        for counter in range(64):
521
 
            nodes.append((make_key(counter), make_value(counter), ()))
522
 
        index = self.make_index(nodes=nodes)
 
546
        index = self.make_index(nodes=self.make_nodes(64))
523
547
        # lookup the keys in the middle of the file
524
548
        result =index._lookup_keys_via_location(
525
549
            [(index._size // 2, ('40', ))])
526
550
        # check the parse map, this determines the test validity
527
551
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
528
 
        self.assertEqual([(None, make_key(26)), (make_key(31), make_key(48))],
 
552
        self.assertEqual([(None, self.make_key(26)),
 
553
                          (self.make_key(31), self.make_key(48))],
529
554
            index._parsed_key_map)
530
555
        # reset the transport log
531
556
        del index._transport._activity[:]
533
558
        # not create a new transport request, and should return False (cannot
534
559
        # be in the index) - even when the byte location we ask for is outside
535
560
        # the parsed region
536
 
        # 
537
 
        result = index._lookup_keys_via_location([(4000, make_key(40))])
 
561
        #
 
562
        result = index._lookup_keys_via_location([(4000, self.make_key(40))])
538
563
        self.assertEqual(
539
 
            [((4000, make_key(40)), (index, make_key(40), make_value(40)))],
 
564
            [((4000, self.make_key(40)),
 
565
              (index, self.make_key(40), self.make_value(40)))],
540
566
            result)
541
567
        self.assertEqual([], index._transport._activity)
542
568
 
543
569
    def test_lookup_key_below_probed_area(self):
544
570
        # generate a big enough index that we only read some of it on a typical
545
571
        # bisection lookup.
546
 
        nodes = []
547
 
        def make_key(number):
548
 
            return (str(number) + 'X'*100,)
549
 
        for counter in range(64):
550
 
            nodes.append((make_key(counter), 'Y'*100, ()))
551
 
        index = self.make_index(nodes=nodes)
 
572
        index = self.make_index(nodes=self.make_nodes(64))
552
573
        # ask for the key in the middle, but a key that is located in the
553
574
        # unparsed region before the middle.
554
575
        result =index._lookup_keys_via_location(
555
576
            [(index._size // 2, ('30', ))])
556
577
        # check the parse map, this determines the test validity
557
 
        self.assertEqual([(0, 3972), (5001, 8914)], index._parsed_byte_map)
558
 
        self.assertEqual([(None, make_key(26)), (make_key(31), make_key(48))],
 
578
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
579
        self.assertEqual([(None, self.make_key(26)),
 
580
                          (self.make_key(31), self.make_key(48))],
559
581
            index._parsed_key_map)
560
582
        self.assertEqual([((index._size // 2, ('30', )), -1)],
561
583
            result)
563
585
    def test_lookup_key_above_probed_area(self):
564
586
        # generate a big enough index that we only read some of it on a typical
565
587
        # bisection lookup.
566
 
        nodes = []
567
 
        def make_key(number):
568
 
            return (str(number) + 'X'*100,)
569
 
        for counter in range(64):
570
 
            nodes.append((make_key(counter), 'Y'*100, ()))
571
 
        index = self.make_index(nodes=nodes)
 
588
        index = self.make_index(nodes=self.make_nodes(64))
572
589
        # ask for the key in the middle, but a key that is located in the
573
590
        # unparsed region after the middle.
574
591
        result =index._lookup_keys_via_location(
575
592
            [(index._size // 2, ('50', ))])
576
593
        # check the parse map, this determines the test validity
577
 
        self.assertEqual([(0, 3972), (5001, 8914)], index._parsed_byte_map)
578
 
        self.assertEqual([(None, make_key(26)), (make_key(31), make_key(48))],
 
594
        self.assertEqual([(0, 4008), (5046, 8996)], index._parsed_byte_map)
 
595
        self.assertEqual([(None, self.make_key(26)),
 
596
                          (self.make_key(31), self.make_key(48))],
579
597
            index._parsed_key_map)
580
598
        self.assertEqual([((index._size // 2, ('50', )), +1)],
581
599
            result)
584
602
        # generate a big enough index that we only read some of it on a typical
585
603
        # bisection lookup.
586
604
        nodes = []
587
 
        def make_key(number):
588
 
            return (str(number) + 'X'*100,)
589
 
        def make_value(number):
590
 
            return str(number) + 'Y'*100
 
605
        for counter in range(99):
 
606
            nodes.append((self.make_key(counter), self.make_value(counter),
 
607
                ((self.make_key(counter + 20),),)  ))
 
608
        index = self.make_index(ref_lists=1, nodes=nodes)
 
609
        # lookup a key in the middle that does not exist, so that when we can
 
610
        # check that the referred-to-keys are not accessed automatically.
 
611
        index_size = index._size
 
612
        index_center = index_size // 2
 
613
        result = index._lookup_keys_via_location(
 
614
            [(index_center, ('40', ))])
 
615
        # check the parse map - only the start and middle should have been
 
616
        # parsed.
 
617
        self.assertEqual([(0, 4027), (10198, 14028)], index._parsed_byte_map)
 
618
        self.assertEqual([(None, self.make_key(17)),
 
619
                          (self.make_key(44), self.make_key(5))],
 
620
            index._parsed_key_map)
 
621
        # and check the transport activity likewise.
 
622
        self.assertEqual(
 
623
            [('readv', 'index', [(index_center, 800), (0, 200)], True,
 
624
                                  index_size)],
 
625
            index._transport._activity)
 
626
        # reset the transport log for testing the reference lookup
 
627
        del index._transport._activity[:]
 
628
        # now looking up a key in the portion of the file already parsed should
 
629
        # only perform IO to resolve its key references.
 
630
        result = index._lookup_keys_via_location([(11000, self.make_key(45))])
 
631
        self.assertEqual(
 
632
            [((11000, self.make_key(45)),
 
633
              (index, self.make_key(45), self.make_value(45),
 
634
               ((self.make_key(65),),)))],
 
635
            result)
 
636
        self.assertEqual([('readv', 'index', [(15093, 800)], True, index_size)],
 
637
            index._transport._activity)
 
638
 
 
639
    def test_lookup_key_can_buffer_all(self):
 
640
        nodes = []
591
641
        for counter in range(64):
592
 
            nodes.append((make_key(counter), make_value(counter),
593
 
                ((make_key(counter + 20),),)  ))
 
642
            nodes.append((self.make_key(counter), self.make_value(counter),
 
643
                ((self.make_key(counter + 20),),)  ))
594
644
        index = self.make_index(ref_lists=1, nodes=nodes)
595
645
        # lookup a key in the middle that does not exist, so that when we can
596
646
        # check that the referred-to-keys are not accessed automatically.
597
 
        result =index._lookup_keys_via_location(
598
 
            [(index._size // 2, ('40', ))])
 
647
        index_size = index._size
 
648
        index_center = index_size // 2
 
649
        result = index._lookup_keys_via_location([(index_center, ('40', ))])
599
650
        # check the parse map - only the start and middle should have been
600
651
        # parsed.
601
652
        self.assertEqual([(0, 3890), (6444, 10274)], index._parsed_byte_map)
602
 
        self.assertEqual([(None, make_key(25)), (make_key(37), make_key(52))],
 
653
        self.assertEqual([(None, self.make_key(25)),
 
654
                          (self.make_key(37), self.make_key(52))],
603
655
            index._parsed_key_map)
604
656
        # and check the transport activity likewise.
605
657
        self.assertEqual(
606
 
            [('readv', 'index', [(7906, 800), (0, 200)], True, 15813)],
 
658
            [('readv', 'index', [(index_center, 800), (0, 200)], True,
 
659
                                  index_size)],
607
660
            index._transport._activity)
608
661
        # reset the transport log for testing the reference lookup
609
662
        del index._transport._activity[:]
610
663
        # now looking up a key in the portion of the file already parsed should
611
664
        # only perform IO to resolve its key references.
612
 
        result = index._lookup_keys_via_location([(4000, make_key(40))])
 
665
        result = index._lookup_keys_via_location([(7000, self.make_key(40))])
613
666
        self.assertEqual(
614
 
            [((4000, make_key(40)),
615
 
              (index, make_key(40), make_value(40), ((make_key(60),),)))],
 
667
            [((7000, self.make_key(40)),
 
668
              (index, self.make_key(40), self.make_value(40),
 
669
               ((self.make_key(60),),)))],
616
670
            result)
617
 
        self.assertEqual([('readv', 'index', [(11976, 800)], True, 15813)],
618
 
            index._transport._activity)
 
671
        # Resolving the references would have required more data read, and we
 
672
        # are already above the 50% threshold, so it triggered a _buffer_all
 
673
        self.assertEqual([('get', 'index')], index._transport._activity)
619
674
 
620
675
    def test_iter_all_entries_empty(self):
621
676
        index = self.make_index()
640
695
            (index, ('ref', ), 'refdata', ((), ))]),
641
696
            set(index.iter_all_entries()))
642
697
 
 
698
    def test_iter_entries_buffers_once(self):
 
699
        index = self.make_index(nodes=self.make_nodes(2))
 
700
        # reset the transport log
 
701
        del index._transport._activity[:]
 
702
        self.assertEqual(set([(index, self.make_key(1), self.make_value(1))]),
 
703
                         set(index.iter_entries([self.make_key(1)])))
 
704
        # We should have requested reading the header bytes
 
705
        # But not needed any more than that because it would have triggered a
 
706
        # buffer all
 
707
        self.assertEqual([
 
708
            ('readv', 'index', [(0, 200)], True, index._size),
 
709
            ],
 
710
            index._transport._activity)
 
711
        # And that should have been enough to trigger reading the whole index
 
712
        # with buffering
 
713
        self.assertIsNot(None, index._nodes)
 
714
 
 
715
    def test_iter_entries_buffers_by_bytes_read(self):
 
716
        index = self.make_index(nodes=self.make_nodes(64))
 
717
        list(index.iter_entries([self.make_key(10)]))
 
718
        # The first time through isn't enough to trigger a buffer all
 
719
        self.assertIs(None, index._nodes)
 
720
        self.assertEqual(4096, index._bytes_read)
 
721
        # Grabbing a key in that same page won't trigger a buffer all, as we
 
722
        # still haven't read 50% of the file
 
723
        list(index.iter_entries([self.make_key(11)]))
 
724
        self.assertIs(None, index._nodes)
 
725
        self.assertEqual(4096, index._bytes_read)
 
726
        # We haven't read more data, so reading outside the range won't trigger
 
727
        # a buffer all right away
 
728
        list(index.iter_entries([self.make_key(40)]))
 
729
        self.assertIs(None, index._nodes)
 
730
        self.assertEqual(8192, index._bytes_read)
 
731
        # On the next pass, we will not trigger buffer all if the key is
 
732
        # available without reading more
 
733
        list(index.iter_entries([self.make_key(32)]))
 
734
        self.assertIs(None, index._nodes)
 
735
        # But if we *would* need to read more to resolve it, then we will
 
736
        # buffer all.
 
737
        list(index.iter_entries([self.make_key(60)]))
 
738
        self.assertIsNot(None, index._nodes)
 
739
 
643
740
    def test_iter_entries_references_resolved(self):
644
741
        index = self.make_index(1, nodes=[
645
742
            (('name', ), 'data', ([('ref', ), ('ref', )], )),
763
860
            (('name', ), '', ()), (('foo', ), '', ())])
764
861
        self.assertEqual(2, index.key_count())
765
862
 
 
863
    def test_read_and_parse_tracks_real_read_value(self):
 
864
        index = self.make_index(nodes=self.make_nodes(10))
 
865
        del index._transport._activity[:]
 
866
        index._read_and_parse([(0, 200)])
 
867
        self.assertEqual([
 
868
            ('readv', 'index', [(0, 200)], True, index._size),
 
869
            ],
 
870
            index._transport._activity)
 
871
        # The readv expansion code will expand the initial request to 4096
 
872
        # bytes, which is more than enough to read the entire index, and we
 
873
        # will track the fact that we read that many bytes.
 
874
        self.assertEqual(index._size, index._bytes_read)
 
875
 
 
876
    def test_read_and_parse_triggers_buffer_all(self):
 
877
        index = self.make_index(key_elements=2, nodes=[
 
878
            (('name', 'fin1'), 'data', ()),
 
879
            (('name', 'fin2'), 'beta', ()),
 
880
            (('ref', 'erence'), 'refdata', ())])
 
881
        self.assertTrue(index._size > 0)
 
882
        self.assertIs(None, index._nodes)
 
883
        index._read_and_parse([(0, index._size)])
 
884
        self.assertIsNot(None, index._nodes)
 
885
 
766
886
    def test_validate_bad_index_errors(self):
767
887
        trans = self.get_transport()
768
888
        trans.put_bytes('name', "not an index\n")
802
922
        index = self.make_index(nodes=[(('key', ), 'value', ())])
803
923
        index.validate()
804
924
 
 
925
    # XXX: external_references tests are duplicated in test_btree_index.  We
 
926
    # probably should have per_graph_index tests...
 
927
    def test_external_references_no_refs(self):
 
928
        index = self.make_index(ref_lists=0, nodes=[])
 
929
        self.assertRaises(ValueError, index.external_references, 0)
 
930
 
 
931
    def test_external_references_no_results(self):
 
932
        index = self.make_index(ref_lists=1, nodes=[
 
933
            (('key',), 'value', ([],))])
 
934
        self.assertEqual(set(), index.external_references(0))
 
935
 
 
936
    def test_external_references_missing_ref(self):
 
937
        missing_key = ('missing',)
 
938
        index = self.make_index(ref_lists=1, nodes=[
 
939
            (('key',), 'value', ([missing_key],))])
 
940
        self.assertEqual(set([missing_key]), index.external_references(0))
 
941
 
 
942
    def test_external_references_multiple_ref_lists(self):
 
943
        missing_key = ('missing',)
 
944
        index = self.make_index(ref_lists=2, nodes=[
 
945
            (('key',), 'value', ([], [missing_key]))])
 
946
        self.assertEqual(set([]), index.external_references(0))
 
947
        self.assertEqual(set([missing_key]), index.external_references(1))
 
948
 
 
949
    def test_external_references_two_records(self):
 
950
        index = self.make_index(ref_lists=1, nodes=[
 
951
            (('key-1',), 'value', ([('key-2',)],)),
 
952
            (('key-2',), 'value', ([],)),
 
953
            ])
 
954
        self.assertEqual(set([]), index.external_references(0))
 
955
 
 
956
    def test__find_ancestors(self):
 
957
        key1 = ('key-1',)
 
958
        key2 = ('key-2',)
 
959
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[
 
960
            (key1, 'value', ([key2],)),
 
961
            (key2, 'value', ([],)),
 
962
            ])
 
963
        parent_map = {}
 
964
        missing_keys = set()
 
965
        search_keys = index._find_ancestors([key1], 0, parent_map, missing_keys)
 
966
        self.assertEqual({key1: (key2,)}, parent_map)
 
967
        self.assertEqual(set(), missing_keys)
 
968
        self.assertEqual(set([key2]), search_keys)
 
969
        search_keys = index._find_ancestors(search_keys, 0, parent_map,
 
970
                                            missing_keys)
 
971
        self.assertEqual({key1: (key2,), key2: ()}, parent_map)
 
972
        self.assertEqual(set(), missing_keys)
 
973
        self.assertEqual(set(), search_keys)
 
974
 
 
975
    def test__find_ancestors_w_missing(self):
 
976
        key1 = ('key-1',)
 
977
        key2 = ('key-2',)
 
978
        key3 = ('key-3',)
 
979
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[
 
980
            (key1, 'value', ([key2],)),
 
981
            (key2, 'value', ([],)),
 
982
            ])
 
983
        parent_map = {}
 
984
        missing_keys = set()
 
985
        search_keys = index._find_ancestors([key2, key3], 0, parent_map,
 
986
                                            missing_keys)
 
987
        self.assertEqual({key2: ()}, parent_map)
 
988
        self.assertEqual(set([key3]), missing_keys)
 
989
        self.assertEqual(set(), search_keys)
 
990
 
 
991
    def test__find_ancestors_dont_search_known(self):
 
992
        key1 = ('key-1',)
 
993
        key2 = ('key-2',)
 
994
        key3 = ('key-3',)
 
995
        index = self.make_index(ref_lists=1, key_elements=1, nodes=[
 
996
            (key1, 'value', ([key2],)),
 
997
            (key2, 'value', ([key3],)),
 
998
            (key3, 'value', ([],)),
 
999
            ])
 
1000
        # We already know about key2, so we won't try to search for key3
 
1001
        parent_map = {key2: (key3,)}
 
1002
        missing_keys = set()
 
1003
        search_keys = index._find_ancestors([key1], 0, parent_map,
 
1004
                                            missing_keys)
 
1005
        self.assertEqual({key1: (key2,), key2: (key3,)}, parent_map)
 
1006
        self.assertEqual(set(), missing_keys)
 
1007
        self.assertEqual(set(), search_keys)
 
1008
 
 
1009
    def test_supports_unlimited_cache(self):
 
1010
        builder = GraphIndexBuilder(0, key_elements=1)
 
1011
        stream = builder.finish()
 
1012
        trans = get_transport(self.get_url())
 
1013
        size = trans.put_file('index', stream)
 
1014
        # It doesn't matter what unlimited_cache does here, just that it can be
 
1015
        # passed
 
1016
        index = GraphIndex(trans, 'index', size, unlimited_cache=True)
 
1017
 
805
1018
 
806
1019
class TestCombinedGraphIndex(TestCaseWithMemoryTransport):
807
1020
 
814
1027
        size = trans.put_file(name, stream)
815
1028
        return GraphIndex(trans, name, size)
816
1029
 
 
1030
    def make_combined_index_with_missing(self, missing=['1', '2']):
 
1031
        """Create a CombinedGraphIndex which will have missing indexes.
 
1032
 
 
1033
        This creates a CGI which thinks it has 2 indexes, however they have
 
1034
        been deleted. If CGI._reload_func() is called, then it will repopulate
 
1035
        with a new index.
 
1036
 
 
1037
        :param missing: The underlying indexes to delete
 
1038
        :return: (CombinedGraphIndex, reload_counter)
 
1039
        """
 
1040
        index1 = self.make_index('1', nodes=[(('1',), '', ())])
 
1041
        index2 = self.make_index('2', nodes=[(('2',), '', ())])
 
1042
        index3 = self.make_index('3', nodes=[
 
1043
            (('1',), '', ()),
 
1044
            (('2',), '', ())])
 
1045
 
 
1046
        # total_reloads, num_changed, num_unchanged
 
1047
        reload_counter = [0, 0, 0]
 
1048
        def reload():
 
1049
            reload_counter[0] += 1
 
1050
            new_indices = [index3]
 
1051
            if index._indices == new_indices:
 
1052
                reload_counter[2] += 1
 
1053
                return False
 
1054
            reload_counter[1] += 1
 
1055
            index._indices[:] = new_indices
 
1056
            return True
 
1057
        index = CombinedGraphIndex([index1, index2], reload_func=reload)
 
1058
        trans = self.get_transport()
 
1059
        for fname in missing:
 
1060
            trans.delete(fname)
 
1061
        return index, reload_counter
 
1062
 
817
1063
    def test_open_missing_index_no_error(self):
818
1064
        trans = self.get_transport()
819
1065
        index1 = GraphIndex(trans, 'missing', 100)
894
1140
        self.assertEqual(set([(index1, ('name', ), 'data', ((('ref', ), ), )),
895
1141
            (index2, ('ref', ), 'refdata', ((), ))]),
896
1142
            set(index.iter_entries([('name', ), ('ref', )])))
897
 
 
 
1143
 
898
1144
    def test_iter_all_keys_dup_entry(self):
899
1145
        index1 = self.make_index('1', 1, nodes=[
900
1146
            (('name', ), 'data', ([('ref', )], )),
905
1151
        self.assertEqual(set([(index1, ('name', ), 'data', ((('ref',),),)),
906
1152
            (index1, ('ref', ), 'refdata', ((), ))]),
907
1153
            set(index.iter_entries([('name', ), ('ref', )])))
908
 
 
 
1154
 
909
1155
    def test_iter_missing_entry_empty(self):
910
1156
        index = CombinedGraphIndex([])
911
1157
        self.assertEqual([], list(index.iter_entries([('a', )])))
920
1166
        index2 = self.make_index('2')
921
1167
        index = CombinedGraphIndex([index1, index2])
922
1168
        self.assertEqual([], list(index.iter_entries([('a', )])))
923
 
 
 
1169
 
924
1170
    def test_iter_entry_present_one_index_only(self):
925
1171
        index1 = self.make_index('1', nodes=[(('key', ), '', ())])
926
1172
        index2 = self.make_index('2', nodes=[])
957
1203
        index = CombinedGraphIndex([])
958
1204
        index.validate()
959
1205
 
 
1206
    def test_key_count_reloads(self):
 
1207
        index, reload_counter = self.make_combined_index_with_missing()
 
1208
        self.assertEqual(2, index.key_count())
 
1209
        self.assertEqual([1, 1, 0], reload_counter)
 
1210
 
 
1211
    def test_key_count_no_reload(self):
 
1212
        index, reload_counter = self.make_combined_index_with_missing()
 
1213
        index._reload_func = None
 
1214
        # Without a _reload_func we just raise the exception
 
1215
        self.assertRaises(errors.NoSuchFile, index.key_count)
 
1216
 
 
1217
    def test_key_count_reloads_and_fails(self):
 
1218
        # We have deleted all underlying indexes, so we will try to reload, but
 
1219
        # still fail. This is mostly to test we don't get stuck in an infinite
 
1220
        # loop trying to reload
 
1221
        index, reload_counter = self.make_combined_index_with_missing(
 
1222
                                    ['1', '2', '3'])
 
1223
        self.assertRaises(errors.NoSuchFile, index.key_count)
 
1224
        self.assertEqual([2, 1, 1], reload_counter)
 
1225
 
 
1226
    def test_iter_entries_reloads(self):
 
1227
        index, reload_counter = self.make_combined_index_with_missing()
 
1228
        result = list(index.iter_entries([('1',), ('2',), ('3',)]))
 
1229
        index3 = index._indices[0]
 
1230
        self.assertEqual([(index3, ('1',), ''), (index3, ('2',), '')],
 
1231
                         result)
 
1232
        self.assertEqual([1, 1, 0], reload_counter)
 
1233
 
 
1234
    def test_iter_entries_reloads_midway(self):
 
1235
        # The first index still looks present, so we get interrupted mid-way
 
1236
        # through
 
1237
        index, reload_counter = self.make_combined_index_with_missing(['2'])
 
1238
        index1, index2 = index._indices
 
1239
        result = list(index.iter_entries([('1',), ('2',), ('3',)]))
 
1240
        index3 = index._indices[0]
 
1241
        # We had already yielded '1', so we just go on to the next, we should
 
1242
        # not yield '1' twice.
 
1243
        self.assertEqual([(index1, ('1',), ''), (index3, ('2',), '')],
 
1244
                         result)
 
1245
        self.assertEqual([1, 1, 0], reload_counter)
 
1246
 
 
1247
    def test_iter_entries_no_reload(self):
 
1248
        index, reload_counter = self.make_combined_index_with_missing()
 
1249
        index._reload_func = None
 
1250
        # Without a _reload_func we just raise the exception
 
1251
        self.assertListRaises(errors.NoSuchFile, index.iter_entries, [('3',)])
 
1252
 
 
1253
    def test_iter_entries_reloads_and_fails(self):
 
1254
        index, reload_counter = self.make_combined_index_with_missing(
 
1255
                                    ['1', '2', '3'])
 
1256
        self.assertListRaises(errors.NoSuchFile, index.iter_entries, [('3',)])
 
1257
        self.assertEqual([2, 1, 1], reload_counter)
 
1258
 
 
1259
    def test_iter_all_entries_reloads(self):
 
1260
        index, reload_counter = self.make_combined_index_with_missing()
 
1261
        result = list(index.iter_all_entries())
 
1262
        index3 = index._indices[0]
 
1263
        self.assertEqual([(index3, ('1',), ''), (index3, ('2',), '')],
 
1264
                         result)
 
1265
        self.assertEqual([1, 1, 0], reload_counter)
 
1266
 
 
1267
    def test_iter_all_entries_reloads_midway(self):
 
1268
        index, reload_counter = self.make_combined_index_with_missing(['2'])
 
1269
        index1, index2 = index._indices
 
1270
        result = list(index.iter_all_entries())
 
1271
        index3 = index._indices[0]
 
1272
        # We had already yielded '1', so we just go on to the next, we should
 
1273
        # not yield '1' twice.
 
1274
        self.assertEqual([(index1, ('1',), ''), (index3, ('2',), '')],
 
1275
                         result)
 
1276
        self.assertEqual([1, 1, 0], reload_counter)
 
1277
 
 
1278
    def test_iter_all_entries_no_reload(self):
 
1279
        index, reload_counter = self.make_combined_index_with_missing()
 
1280
        index._reload_func = None
 
1281
        self.assertListRaises(errors.NoSuchFile, index.iter_all_entries)
 
1282
 
 
1283
    def test_iter_all_entries_reloads_and_fails(self):
 
1284
        index, reload_counter = self.make_combined_index_with_missing(
 
1285
                                    ['1', '2', '3'])
 
1286
        self.assertListRaises(errors.NoSuchFile, index.iter_all_entries)
 
1287
 
 
1288
    def test_iter_entries_prefix_reloads(self):
 
1289
        index, reload_counter = self.make_combined_index_with_missing()
 
1290
        result = list(index.iter_entries_prefix([('1',)]))
 
1291
        index3 = index._indices[0]
 
1292
        self.assertEqual([(index3, ('1',), '')], result)
 
1293
        self.assertEqual([1, 1, 0], reload_counter)
 
1294
 
 
1295
    def test_iter_entries_prefix_reloads_midway(self):
 
1296
        index, reload_counter = self.make_combined_index_with_missing(['2'])
 
1297
        index1, index2 = index._indices
 
1298
        result = list(index.iter_entries_prefix([('1',)]))
 
1299
        index3 = index._indices[0]
 
1300
        # We had already yielded '1', so we just go on to the next, we should
 
1301
        # not yield '1' twice.
 
1302
        self.assertEqual([(index1, ('1',), '')], result)
 
1303
        self.assertEqual([1, 1, 0], reload_counter)
 
1304
 
 
1305
    def test_iter_entries_prefix_no_reload(self):
 
1306
        index, reload_counter = self.make_combined_index_with_missing()
 
1307
        index._reload_func = None
 
1308
        self.assertListRaises(errors.NoSuchFile, index.iter_entries_prefix,
 
1309
                                                 [('1',)])
 
1310
 
 
1311
    def test_iter_entries_prefix_reloads_and_fails(self):
 
1312
        index, reload_counter = self.make_combined_index_with_missing(
 
1313
                                    ['1', '2', '3'])
 
1314
        self.assertListRaises(errors.NoSuchFile, index.iter_entries_prefix,
 
1315
                                                 [('1',)])
 
1316
 
 
1317
    def test_validate_reloads(self):
 
1318
        index, reload_counter = self.make_combined_index_with_missing()
 
1319
        index.validate()
 
1320
        self.assertEqual([1, 1, 0], reload_counter)
 
1321
 
 
1322
    def test_validate_reloads_midway(self):
 
1323
        index, reload_counter = self.make_combined_index_with_missing(['2'])
 
1324
        index.validate()
 
1325
 
 
1326
    def test_validate_no_reload(self):
 
1327
        index, reload_counter = self.make_combined_index_with_missing()
 
1328
        index._reload_func = None
 
1329
        self.assertRaises(errors.NoSuchFile, index.validate)
 
1330
 
 
1331
    def test_validate_reloads_and_fails(self):
 
1332
        index, reload_counter = self.make_combined_index_with_missing(
 
1333
                                    ['1', '2', '3'])
 
1334
        self.assertRaises(errors.NoSuchFile, index.validate)
 
1335
 
 
1336
    def test_find_ancestors_across_indexes(self):
 
1337
        key1 = ('key-1',)
 
1338
        key2 = ('key-2',)
 
1339
        key3 = ('key-3',)
 
1340
        key4 = ('key-4',)
 
1341
        index1 = self.make_index('12', ref_lists=1, nodes=[
 
1342
            (key1, 'value', ([],)),
 
1343
            (key2, 'value', ([key1],)),
 
1344
            ])
 
1345
        index2 = self.make_index('34', ref_lists=1, nodes=[
 
1346
            (key3, 'value', ([key2],)),
 
1347
            (key4, 'value', ([key3],)),
 
1348
            ])
 
1349
        c_index = CombinedGraphIndex([index1, index2])
 
1350
        parent_map, missing_keys = c_index.find_ancestry([key1], 0)
 
1351
        self.assertEqual({key1: ()}, parent_map)
 
1352
        self.assertEqual(set(), missing_keys)
 
1353
        # Now look for a key from index2 which requires us to find the key in
 
1354
        # the second index, and then continue searching for parents in the
 
1355
        # first index
 
1356
        parent_map, missing_keys = c_index.find_ancestry([key3], 0)
 
1357
        self.assertEqual({key1: (), key2: (key1,), key3: (key2,)}, parent_map)
 
1358
        self.assertEqual(set(), missing_keys)
 
1359
 
 
1360
    def test_find_ancestors_missing_keys(self):
 
1361
        key1 = ('key-1',)
 
1362
        key2 = ('key-2',)
 
1363
        key3 = ('key-3',)
 
1364
        key4 = ('key-4',)
 
1365
        index1 = self.make_index('12', ref_lists=1, nodes=[
 
1366
            (key1, 'value', ([],)),
 
1367
            (key2, 'value', ([key1],)),
 
1368
            ])
 
1369
        index2 = self.make_index('34', ref_lists=1, nodes=[
 
1370
            (key3, 'value', ([key2],)),
 
1371
            ])
 
1372
        c_index = CombinedGraphIndex([index1, index2])
 
1373
        # Searching for a key which is actually not present at all should
 
1374
        # eventually converge
 
1375
        parent_map, missing_keys = c_index.find_ancestry([key4], 0)
 
1376
        self.assertEqual({}, parent_map)
 
1377
        self.assertEqual(set([key4]), missing_keys)
 
1378
 
 
1379
    def test_find_ancestors_no_indexes(self):
 
1380
        c_index = CombinedGraphIndex([])
 
1381
        key1 = ('key-1',)
 
1382
        parent_map, missing_keys = c_index.find_ancestry([key1], 0)
 
1383
        self.assertEqual({}, parent_map)
 
1384
        self.assertEqual(set([key1]), missing_keys)
 
1385
 
 
1386
    def test_find_ancestors_ghost_parent(self):
 
1387
        key1 = ('key-1',)
 
1388
        key2 = ('key-2',)
 
1389
        key3 = ('key-3',)
 
1390
        key4 = ('key-4',)
 
1391
        index1 = self.make_index('12', ref_lists=1, nodes=[
 
1392
            (key1, 'value', ([],)),
 
1393
            (key2, 'value', ([key1],)),
 
1394
            ])
 
1395
        index2 = self.make_index('34', ref_lists=1, nodes=[
 
1396
            (key4, 'value', ([key2, key3],)),
 
1397
            ])
 
1398
        c_index = CombinedGraphIndex([index1, index2])
 
1399
        # Searching for a key which is actually not present at all should
 
1400
        # eventually converge
 
1401
        parent_map, missing_keys = c_index.find_ancestry([key4], 0)
 
1402
        self.assertEqual({key4: (key2, key3), key2: (key1,), key1: ()},
 
1403
                         parent_map)
 
1404
        self.assertEqual(set([key3]), missing_keys)
 
1405
 
 
1406
    def test__find_ancestors_empty_index(self):
 
1407
        index = self.make_index('test', ref_lists=1, key_elements=1, nodes=[])
 
1408
        parent_map = {}
 
1409
        missing_keys = set()
 
1410
        search_keys = index._find_ancestors([('one',), ('two',)], 0, parent_map,
 
1411
                                            missing_keys)
 
1412
        self.assertEqual(set(), search_keys)
 
1413
        self.assertEqual({}, parent_map)
 
1414
        self.assertEqual(set([('one',), ('two',)]), missing_keys)
 
1415
 
960
1416
 
961
1417
class TestInMemoryGraphIndex(TestCaseWithMemoryTransport):
962
1418