454
473
# Change 2 bytes in the middle to \xff
455
474
gz_txt = gz_txt[:10] + '\xff\xff' + gz_txt[12:]
456
475
transport = MockTransport([gz_txt])
457
access = _KnitAccess(transport, 'filename', None, None, False, False)
458
data = _KnitData(access=access)
459
records = [('rev-id-1', (None, 0, len(gz_txt)))]
461
self.assertRaises(errors.KnitCorrupt, data.read_records, records)
463
# read_records_iter_raw will notice if we request the wrong version.
464
self.assertRaises(errors.KnitCorrupt, list,
465
data.read_records_iter_raw(records))
476
access = _KnitKeyAccess(transport, ConstantMapper('filename'))
477
knit = KnitVersionedFiles(None, access)
478
records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
479
self.assertRaises(errors.KnitCorrupt, list,
480
knit._read_records_iter(records))
481
# read_records_iter_raw will barf on bad gz data
482
self.assertRaises(errors.KnitCorrupt, list,
483
knit._read_records_iter_raw(records))
468
486
class LowLevelKnitIndexTests(TestCase):
470
def get_knit_index(self, *args, **kwargs):
488
def get_knit_index(self, transport, name, mode):
489
mapper = ConstantMapper(name)
471
490
orig = knit._load_data
473
492
knit._load_data = orig
474
493
self.addCleanup(reset)
475
494
from bzrlib._knit_load_data_py import _load_data_py
476
495
knit._load_data = _load_data_py
477
return _KnitIndex(get_scope=lambda:None, *args, **kwargs)
479
def test_no_such_file(self):
480
transport = MockTransport()
482
self.assertRaises(NoSuchFile, self.get_knit_index,
483
transport, "filename", "r")
484
self.assertRaises(NoSuchFile, self.get_knit_index,
485
transport, "filename", "w", create=False)
496
allow_writes = lambda: 'w' in mode
497
return _KndxIndex(transport, mapper, lambda:None, allow_writes, lambda:True)
487
499
def test_create_file(self):
488
500
transport = MockTransport()
490
index = self.get_knit_index(transport, "filename", "w",
491
file_mode="wb", create=True)
493
("put_bytes_non_atomic",
494
("filename", index.HEADER), {"mode": "wb"}),
495
transport.calls.pop(0))
497
def test_delay_create_file(self):
498
transport = MockTransport()
500
index = self.get_knit_index(transport, "filename", "w",
501
create=True, file_mode="wb", create_parent_dir=True,
502
delay_create=True, dir_mode=0777)
503
self.assertEqual([], transport.calls)
505
index.add_versions([])
506
name, (filename, f), kwargs = transport.calls.pop(0)
507
self.assertEqual("put_file_non_atomic", name)
509
{"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
511
self.assertEqual("filename", filename)
512
self.assertEqual(index.HEADER, f.read())
514
index.add_versions([])
515
self.assertEqual(("append_bytes", ("filename", ""), {}),
516
transport.calls.pop(0))
501
index = self.get_knit_index(transport, "filename", "w")
503
call = transport.calls.pop(0)
504
# call[1][1] is a StringIO - we can't test it by simple equality.
505
self.assertEqual('put_file_non_atomic', call[0])
506
self.assertEqual('filename.kndx', call[1][0])
507
# With no history, _KndxIndex writes a new index:
508
self.assertEqual(_KndxIndex.HEADER,
509
call[1][1].getvalue())
510
self.assertEqual({'create_parent_dir': True}, call[2])
518
512
def test_read_utf8_version_id(self):
519
513
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
520
514
utf8_revision_id = unicode_revision_id.encode('utf-8')
521
515
transport = MockTransport([
523
517
'%s option 0 1 :' % (utf8_revision_id,)
525
519
index = self.get_knit_index(transport, "filename", "r")
526
# _KnitIndex is a private class, and deals in utf8 revision_ids, not
520
# _KndxIndex is a private class, and deals in utf8 revision_ids, not
527
521
# Unicode revision_ids.
528
self.assertTrue(index.has_version(utf8_revision_id))
529
self.assertFalse(index.has_version(unicode_revision_id))
522
self.assertEqual({(utf8_revision_id,):()},
523
index.get_parent_map(index.keys()))
524
self.assertFalse((unicode_revision_id,) in index.keys())
531
526
def test_read_utf8_parents(self):
532
527
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
533
528
utf8_revision_id = unicode_revision_id.encode('utf-8')
534
529
transport = MockTransport([
536
531
"version option 0 1 .%s :" % (utf8_revision_id,)
538
533
index = self.get_knit_index(transport, "filename", "r")
539
self.assertEqual((utf8_revision_id,),
540
index.get_parents_with_ghosts("version"))
534
self.assertEqual({("version",):((utf8_revision_id,),)},
535
index.get_parent_map(index.keys()))
542
537
def test_read_ignore_corrupted_lines(self):
543
538
transport = MockTransport([
546
541
"corrupted options 0 1 .b .c ",
547
542
"version options 0 1 :"
549
544
index = self.get_knit_index(transport, "filename", "r")
550
self.assertEqual(1, index.num_versions())
551
self.assertTrue(index.has_version("version"))
545
self.assertEqual(1, len(index.keys()))
546
self.assertEqual(set([("version",)]), index.keys())
553
548
def test_read_corrupted_header(self):
554
549
transport = MockTransport(['not a bzr knit index header\n'])
555
self.assertRaises(KnitHeaderError,
556
self.get_knit_index, transport, "filename", "r")
550
index = self.get_knit_index(transport, "filename", "r")
551
self.assertRaises(KnitHeaderError, index.keys)
558
553
def test_read_duplicate_entries(self):
559
554
transport = MockTransport([
561
556
"parent options 0 1 :",
562
557
"version options1 0 1 0 :",
563
558
"version options2 1 2 .other :",
564
559
"version options3 3 4 0 .other :"
566
561
index = self.get_knit_index(transport, "filename", "r")
567
self.assertEqual(2, index.num_versions())
562
self.assertEqual(2, len(index.keys()))
568
563
# check that the index used is the first one written. (Specific
569
564
# to KnitIndex style indices.
570
self.assertEqual("1", index._version_list_to_index(["version"]))
571
self.assertEqual((None, 3, 4), index.get_position("version"))
572
self.assertEqual(["options3"], index.get_options("version"))
573
self.assertEqual(("parent", "other"),
574
index.get_parents_with_ghosts("version"))
565
self.assertEqual("1", index._dictionary_compress([("version",)]))
566
self.assertEqual((("version",), 3, 4), index.get_position(("version",)))
567
self.assertEqual(["options3"], index.get_options(("version",)))
568
self.assertEqual({("version",):(("parent",), ("other",))},
569
index.get_parent_map([("version",)]))
576
571
def test_read_compressed_parents(self):
577
572
transport = MockTransport([
579
574
"a option 0 1 :",
580
575
"b option 0 1 0 :",
581
576
"c option 0 1 1 0 :",
583
578
index = self.get_knit_index(transport, "filename", "r")
584
self.assertEqual({"b":("a",), "c":("b", "a")},
585
index.get_parent_map(["b", "c"]))
579
self.assertEqual({("b",):(("a",),), ("c",):(("b",), ("a",))},
580
index.get_parent_map([("b",), ("c",)]))
587
582
def test_write_utf8_version_id(self):
588
583
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
589
584
utf8_revision_id = unicode_revision_id.encode('utf-8')
590
585
transport = MockTransport([
593
588
index = self.get_knit_index(transport, "filename", "r")
594
index.add_version(utf8_revision_id, ["option"], (None, 0, 1), [])
595
self.assertEqual(("append_bytes", ("filename",
596
"\n%s option 0 1 :" % (utf8_revision_id,)),
598
transport.calls.pop(0))
590
((utf8_revision_id,), ["option"], ((utf8_revision_id,), 0, 1), [])])
591
call = transport.calls.pop(0)
592
# call[1][1] is a StringIO - we can't test it by simple equality.
593
self.assertEqual('put_file_non_atomic', call[0])
594
self.assertEqual('filename.kndx', call[1][0])
595
# With no history, _KndxIndex writes a new index:
596
self.assertEqual(_KndxIndex.HEADER +
597
"\n%s option 0 1 :" % (utf8_revision_id,),
598
call[1][1].getvalue())
599
self.assertEqual({'create_parent_dir': True}, call[2])
600
601
def test_write_utf8_parents(self):
601
602
unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
602
603
utf8_revision_id = unicode_revision_id.encode('utf-8')
603
604
transport = MockTransport([
606
index = self.get_knit_index(transport, "filename", "r")
607
index.add_version("version", ["option"], (None, 0, 1), [utf8_revision_id])
608
self.assertEqual(("append_bytes", ("filename",
609
"\nversion option 0 1 .%s :" % (utf8_revision_id,)),
611
transport.calls.pop(0))
613
def test_get_ancestry(self):
614
transport = MockTransport([
617
"b option 0 1 0 .e :",
618
"c option 0 1 1 0 :",
619
"d option 0 1 2 .f :"
621
index = self.get_knit_index(transport, "filename", "r")
623
self.assertEqual([], index.get_ancestry([]))
624
self.assertEqual(["a"], index.get_ancestry(["a"]))
625
self.assertEqual(["a", "b"], index.get_ancestry(["b"]))
626
self.assertEqual(["a", "b", "c"], index.get_ancestry(["c"]))
627
self.assertEqual(["a", "b", "c", "d"], index.get_ancestry(["d"]))
628
self.assertEqual(["a", "b"], index.get_ancestry(["a", "b"]))
629
self.assertEqual(["a", "b", "c"], index.get_ancestry(["a", "c"]))
631
self.assertRaises(RevisionNotPresent, index.get_ancestry, ["e"])
633
def test_get_ancestry_with_ghosts(self):
634
transport = MockTransport([
637
"b option 0 1 0 .e :",
638
"c option 0 1 0 .f .g :",
639
"d option 0 1 2 .h .j .k :"
641
index = self.get_knit_index(transport, "filename", "r")
643
self.assertEqual([], index.get_ancestry_with_ghosts([]))
644
self.assertEqual(["a"], index.get_ancestry_with_ghosts(["a"]))
645
self.assertEqual(["a", "e", "b"],
646
index.get_ancestry_with_ghosts(["b"]))
647
self.assertEqual(["a", "g", "f", "c"],
648
index.get_ancestry_with_ghosts(["c"]))
649
self.assertEqual(["a", "g", "f", "c", "k", "j", "h", "d"],
650
index.get_ancestry_with_ghosts(["d"]))
651
self.assertEqual(["a", "e", "b"],
652
index.get_ancestry_with_ghosts(["a", "b"]))
653
self.assertEqual(["a", "g", "f", "c"],
654
index.get_ancestry_with_ghosts(["a", "c"]))
607
index = self.get_knit_index(transport, "filename", "r")
609
(("version",), ["option"], (("version",), 0, 1), [(utf8_revision_id,)])])
610
call = transport.calls.pop(0)
611
# call[1][1] is a StringIO - we can't test it by simple equality.
612
self.assertEqual('put_file_non_atomic', call[0])
613
self.assertEqual('filename.kndx', call[1][0])
614
# With no history, _KndxIndex writes a new index:
615
self.assertEqual(_KndxIndex.HEADER +
616
"\nversion option 0 1 .%s :" % (utf8_revision_id,),
617
call[1][1].getvalue())
618
self.assertEqual({'create_parent_dir': True}, call[2])
621
transport = MockTransport([
624
index = self.get_knit_index(transport, "filename", "r")
626
self.assertEqual(set(), index.keys())
628
index.add_records([(("a",), ["option"], (("a",), 0, 1), [])])
629
self.assertEqual(set([("a",)]), index.keys())
631
index.add_records([(("a",), ["option"], (("a",), 0, 1), [])])
632
self.assertEqual(set([("a",)]), index.keys())
634
index.add_records([(("b",), ["option"], (("b",), 0, 1), [])])
635
self.assertEqual(set([("a",), ("b",)]), index.keys())
637
def add_a_b(self, index, random_id=None):
639
if random_id is not None:
640
kwargs["random_id"] = random_id
642
(("a",), ["option"], (("a",), 0, 1), [("b",)]),
643
(("a",), ["opt"], (("a",), 1, 2), [("c",)]),
644
(("b",), ["option"], (("b",), 2, 3), [("a",)])
647
def assertIndexIsAB(self, index):
652
index.get_parent_map(index.keys()))
653
self.assertEqual((("a",), 1, 2), index.get_position(("a",)))
654
self.assertEqual((("b",), 2, 3), index.get_position(("b",)))
655
self.assertEqual(["opt"], index.get_options(("a",)))
657
def test_add_versions(self):
658
transport = MockTransport([
661
index = self.get_knit_index(transport, "filename", "r")
664
call = transport.calls.pop(0)
665
# call[1][1] is a StringIO - we can't test it by simple equality.
666
self.assertEqual('put_file_non_atomic', call[0])
667
self.assertEqual('filename.kndx', call[1][0])
668
# With no history, _KndxIndex writes a new index:
655
669
self.assertEqual(
656
["a", "g", "f", "c", "e", "b", "k", "j", "h", "d"],
657
index.get_ancestry_with_ghosts(["b", "d"]))
659
self.assertRaises(RevisionNotPresent,
660
index.get_ancestry_with_ghosts, ["e"])
662
def test_num_versions(self):
663
transport = MockTransport([
666
index = self.get_knit_index(transport, "filename", "r")
668
self.assertEqual(0, index.num_versions())
669
self.assertEqual(0, len(index))
671
index.add_version("a", ["option"], (None, 0, 1), [])
672
self.assertEqual(1, index.num_versions())
673
self.assertEqual(1, len(index))
675
index.add_version("a", ["option2"], (None, 1, 2), [])
676
self.assertEqual(1, index.num_versions())
677
self.assertEqual(1, len(index))
679
index.add_version("b", ["option"], (None, 0, 1), [])
680
self.assertEqual(2, index.num_versions())
681
self.assertEqual(2, len(index))
683
def test_get_versions(self):
684
transport = MockTransport([
687
index = self.get_knit_index(transport, "filename", "r")
689
self.assertEqual([], index.get_versions())
691
index.add_version("a", ["option"], (None, 0, 1), [])
692
self.assertEqual(["a"], index.get_versions())
694
index.add_version("a", ["option"], (None, 0, 1), [])
695
self.assertEqual(["a"], index.get_versions())
697
index.add_version("b", ["option"], (None, 0, 1), [])
698
self.assertEqual(["a", "b"], index.get_versions())
700
def test_add_version(self):
701
transport = MockTransport([
704
index = self.get_knit_index(transport, "filename", "r")
706
index.add_version("a", ["option"], (None, 0, 1), ["b"])
707
self.assertEqual(("append_bytes",
708
("filename", "\na option 0 1 .b :"),
709
{}), transport.calls.pop(0))
710
self.assertTrue(index.has_version("a"))
711
self.assertEqual(1, index.num_versions())
712
self.assertEqual((None, 0, 1), index.get_position("a"))
713
self.assertEqual(["option"], index.get_options("a"))
714
self.assertEqual(("b",), index.get_parents_with_ghosts("a"))
716
index.add_version("a", ["opt"], (None, 1, 2), ["c"])
717
self.assertEqual(("append_bytes",
718
("filename", "\na opt 1 2 .c :"),
719
{}), transport.calls.pop(0))
720
self.assertTrue(index.has_version("a"))
721
self.assertEqual(1, index.num_versions())
722
self.assertEqual((None, 1, 2), index.get_position("a"))
723
self.assertEqual(["opt"], index.get_options("a"))
724
self.assertEqual(("c",), index.get_parents_with_ghosts("a"))
726
index.add_version("b", ["option"], (None, 2, 3), ["a"])
727
self.assertEqual(("append_bytes",
728
("filename", "\nb option 2 3 0 :"),
729
{}), transport.calls.pop(0))
730
self.assertTrue(index.has_version("b"))
731
self.assertEqual(2, index.num_versions())
732
self.assertEqual((None, 2, 3), index.get_position("b"))
733
self.assertEqual(["option"], index.get_options("b"))
734
self.assertEqual(("a",), index.get_parents_with_ghosts("b"))
736
def test_add_versions(self):
737
transport = MockTransport([
740
index = self.get_knit_index(transport, "filename", "r")
743
("a", ["option"], (None, 0, 1), ["b"]),
744
("a", ["opt"], (None, 1, 2), ["c"]),
745
("b", ["option"], (None, 2, 3), ["a"])
747
self.assertEqual(("append_bytes", ("filename",
748
671
"\na option 0 1 .b :"
749
672
"\na opt 1 2 .c :"
751
), {}), transport.calls.pop(0))
752
self.assertTrue(index.has_version("a"))
753
self.assertTrue(index.has_version("b"))
754
self.assertEqual(2, index.num_versions())
755
self.assertEqual((None, 1, 2), index.get_position("a"))
756
self.assertEqual((None, 2, 3), index.get_position("b"))
757
self.assertEqual(["opt"], index.get_options("a"))
758
self.assertEqual(["option"], index.get_options("b"))
759
self.assertEqual(("c",), index.get_parents_with_ghosts("a"))
760
self.assertEqual(("a",), index.get_parents_with_ghosts("b"))
673
"\nb option 2 3 0 :",
674
call[1][1].getvalue())
675
self.assertEqual({'create_parent_dir': True}, call[2])
676
self.assertIndexIsAB(index)
762
678
def test_add_versions_random_id_is_accepted(self):
763
679
transport = MockTransport([
766
682
index = self.get_knit_index(transport, "filename", "r")
769
("a", ["option"], (None, 0, 1), ["b"]),
770
("a", ["opt"], (None, 1, 2), ["c"]),
771
("b", ["option"], (None, 2, 3), ["a"])
683
self.add_a_b(index, random_id=True)
774
685
def test_delay_create_and_add_versions(self):
775
686
transport = MockTransport()
777
index = self.get_knit_index(transport, "filename", "w",
778
create=True, file_mode="wb", create_parent_dir=True,
779
delay_create=True, dir_mode=0777)
688
index = self.get_knit_index(transport, "filename", "w")
780
690
self.assertEqual([], transport.calls)
783
("a", ["option"], (None, 0, 1), ["b"]),
784
("a", ["opt"], (None, 1, 2), ["c"]),
785
("b", ["option"], (None, 2, 3), ["a"])
787
name, (filename, f), kwargs = transport.calls.pop(0)
788
self.assertEqual("put_file_non_atomic", name)
790
{"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
792
self.assertEqual("filename", filename)
693
#[ {"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
695
# Two calls: one during which we load the existing index (and when its
696
# missing create it), then a second where we write the contents out.
697
self.assertEqual(2, len(transport.calls))
698
call = transport.calls.pop(0)
699
self.assertEqual('put_file_non_atomic', call[0])
700
self.assertEqual('filename.kndx', call[1][0])
701
# With no history, _KndxIndex writes a new index:
702
self.assertEqual(_KndxIndex.HEADER, call[1][1].getvalue())
703
self.assertEqual({'create_parent_dir': True}, call[2])
704
call = transport.calls.pop(0)
705
# call[1][1] is a StringIO - we can't test it by simple equality.
706
self.assertEqual('put_file_non_atomic', call[0])
707
self.assertEqual('filename.kndx', call[1][0])
708
# With no history, _KndxIndex writes a new index:
795
711
"\na option 0 1 .b :"
796
712
"\na opt 1 2 .c :"
797
713
"\nb option 2 3 0 :",
800
def test_has_version(self):
801
transport = MockTransport([
805
index = self.get_knit_index(transport, "filename", "r")
807
self.assertTrue(index.has_version("a"))
808
self.assertFalse(index.has_version("b"))
714
call[1][1].getvalue())
715
self.assertEqual({'create_parent_dir': True}, call[2])
810
717
def test_get_position(self):
811
718
transport = MockTransport([
813
720
"a option 0 1 :",
816
723
index = self.get_knit_index(transport, "filename", "r")
818
self.assertEqual((None, 0, 1), index.get_position("a"))
819
self.assertEqual((None, 1, 2), index.get_position("b"))
725
self.assertEqual((("a",), 0, 1), index.get_position(("a",)))
726
self.assertEqual((("b",), 1, 2), index.get_position(("b",)))
821
728
def test_get_method(self):
822
729
transport = MockTransport([
824
731
"a fulltext,unknown 0 1 :",
825
732
"b unknown,line-delta 1 2 :",
987
863
def test_short_line(self):
988
864
transport = MockTransport([
990
866
"a option 0 10 :",
991
867
"b option 10 10 0", # This line isn't terminated, ignored
993
869
index = self.get_knit_index(transport, "filename", "r")
994
self.assertEqual(['a'], index.get_versions())
870
self.assertEqual(set([('a',)]), index.keys())
996
872
def test_skip_incomplete_record(self):
997
873
# A line with bogus data should just be skipped
998
874
transport = MockTransport([
1000
876
"a option 0 10 :",
1001
877
"b option 10 10 0", # This line isn't terminated, ignored
1002
878
"c option 20 10 0 :", # Properly terminated, and starts with '\n'
1004
880
index = self.get_knit_index(transport, "filename", "r")
1005
self.assertEqual(['a', 'c'], index.get_versions())
881
self.assertEqual(set([('a',), ('c',)]), index.keys())
1007
883
def test_trailing_characters(self):
1008
884
# A line with bogus data should just be skipped
1009
885
transport = MockTransport([
1011
887
"a option 0 10 :",
1012
888
"b option 10 10 0 :a", # This line has extra trailing characters
1013
889
"c option 20 10 0 :", # Properly terminated, and starts with '\n'
1015
891
index = self.get_knit_index(transport, "filename", "r")
1016
self.assertEqual(['a', 'c'], index.get_versions())
892
self.assertEqual(set([('a',), ('c',)]), index.keys())
1019
895
class LowLevelKnitIndexTests_c(LowLevelKnitIndexTests):
1021
897
_test_needs_features = [CompiledKnitFeature]
1023
def get_knit_index(self, *args, **kwargs):
899
def get_knit_index(self, transport, name, mode):
900
mapper = ConstantMapper(name)
1024
901
orig = knit._load_data
1026
903
knit._load_data = orig
1027
904
self.addCleanup(reset)
1028
905
from bzrlib._knit_load_data_c import _load_data_c
1029
906
knit._load_data = _load_data_c
1030
return _KnitIndex(get_scope=lambda:None, *args, **kwargs)
907
allow_writes = lambda: mode == 'w'
908
return _KndxIndex(transport, mapper, lambda:None, allow_writes, lambda:True)
1033
911
class KnitTests(TestCaseWithTransport):
1034
912
"""Class containing knit test helper routines."""
1036
def make_test_knit(self, annotate=False, delay_create=False, index=None,
1037
name='test', delta=True, access_mode='w'):
1039
factory = KnitPlainFactory()
1043
index = _KnitIndex(get_transport('.'), name + INDEX_SUFFIX,
1044
access_mode, create=True, file_mode=None,
1045
create_parent_dir=False, delay_create=delay_create,
1046
dir_mode=None, get_scope=lambda:None)
1047
access = _KnitAccess(get_transport('.'), name + DATA_SUFFIX, None,
1048
None, delay_create, False)
1049
return KnitVersionedFile(name, get_transport('.'), factory=factory,
1050
create=True, delay_create=delay_create, index=index,
1051
access_method=access, delta=delta)
1053
def assertRecordContentEqual(self, knit, version_id, candidate_content):
1054
"""Assert that some raw record content matches the raw record content
1055
for a particular version_id in the given knit.
1057
index_memo = knit._index.get_position(version_id)
1058
record = (version_id, index_memo)
1059
[(_, expected_content, _)] = list(knit._data.read_records_iter_raw([record]))
1060
self.assertEqual(expected_content, candidate_content)
1063
class BasicKnitTests(KnitTests):
1065
def add_stock_one_and_one_a(self, k):
1066
k.add_lines('text-1', [], split_lines(TEXT_1))
1067
k.add_lines('text-1a', ['text-1'], split_lines(TEXT_1A))
1069
def test_knit_constructor(self):
1070
"""Construct empty k"""
1071
self.make_test_knit()
1073
def test_make_explicit_index(self):
1074
"""We can supply an index to use."""
1075
knit = KnitVersionedFile('test', get_transport('.'),
1076
index='strangelove', access_method="a")
1077
self.assertEqual(knit._index, 'strangelove')
1079
def test_knit_add(self):
1080
"""Store one text in knit and retrieve"""
1081
k = self.make_test_knit()
1082
k.add_lines('text-1', [], split_lines(TEXT_1))
1083
self.assertTrue(k.has_version('text-1'))
1084
self.assertEqualDiff(''.join(k.get_lines('text-1')), TEXT_1)
1086
def test_newline_empty_lines(self):
1087
# ensure that ["\n"] round trips ok.
1088
knit = self.make_test_knit()
1089
knit.add_lines('a', [], ["\n"])
1090
knit.add_lines_with_ghosts('b', [], ["\n"])
1091
self.assertEqual(["\n"], knit.get_lines('a'))
1092
self.assertEqual(["\n"], knit.get_lines('b'))
1093
self.assertEqual(['fulltext'], knit._index.get_options('a'))
1094
self.assertEqual(['fulltext'], knit._index.get_options('b'))
1095
knit.add_lines('c', ['a'], ["\n"])
1096
knit.add_lines_with_ghosts('d', ['b'], ["\n"])
1097
self.assertEqual(["\n"], knit.get_lines('c'))
1098
self.assertEqual(["\n"], knit.get_lines('d'))
1099
self.assertEqual(['line-delta'], knit._index.get_options('c'))
1100
self.assertEqual(['line-delta'], knit._index.get_options('d'))
1102
def test_empty_lines(self):
1103
# bizarrely, [] is not listed as having no-eol.
1104
knit = self.make_test_knit()
1105
knit.add_lines('a', [], [])
1106
knit.add_lines_with_ghosts('b', [], [])
1107
self.assertEqual([], knit.get_lines('a'))
1108
self.assertEqual([], knit.get_lines('b'))
1109
self.assertEqual(['fulltext'], knit._index.get_options('a'))
1110
self.assertEqual(['fulltext'], knit._index.get_options('b'))
1111
knit.add_lines('c', ['a'], [])
1112
knit.add_lines_with_ghosts('d', ['b'], [])
1113
self.assertEqual([], knit.get_lines('c'))
1114
self.assertEqual([], knit.get_lines('d'))
1115
self.assertEqual(['line-delta'], knit._index.get_options('c'))
1116
self.assertEqual(['line-delta'], knit._index.get_options('d'))
1118
def test_knit_reload(self):
1119
# test that the content in a reloaded knit is correct
1120
k = self.make_test_knit()
1121
k.add_lines('text-1', [], split_lines(TEXT_1))
1123
k2 = make_file_knit('test', get_transport('.'), access_mode='r',
1124
factory=KnitPlainFactory(), create=True)
1125
self.assertTrue(k2.has_version('text-1'))
1126
self.assertEqualDiff(''.join(k2.get_lines('text-1')), TEXT_1)
1128
def test_knit_several(self):
1129
"""Store several texts in a knit"""
1130
k = self.make_test_knit()
1131
k.add_lines('text-1', [], split_lines(TEXT_1))
1132
k.add_lines('text-2', [], split_lines(TEXT_2))
1133
self.assertEqualDiff(''.join(k.get_lines('text-1')), TEXT_1)
1134
self.assertEqualDiff(''.join(k.get_lines('text-2')), TEXT_2)
1136
def test_repeated_add(self):
1137
"""Knit traps attempt to replace existing version"""
1138
k = self.make_test_knit()
1139
k.add_lines('text-1', [], split_lines(TEXT_1))
1140
self.assertRaises(RevisionAlreadyPresent,
1142
'text-1', [], split_lines(TEXT_1))
1144
def test_empty(self):
1145
k = self.make_test_knit(True)
1146
k.add_lines('text-1', [], [])
1147
self.assertEquals(k.get_lines('text-1'), [])
1149
def test_incomplete(self):
1150
"""Test if texts without a ending line-end can be inserted and
1152
k = make_file_knit('test', get_transport('.'), delta=False, create=True)
1153
k.add_lines('text-1', [], ['a\n', 'b' ])
1154
k.add_lines('text-2', ['text-1'], ['a\rb\n', 'b\n'])
1155
# reopening ensures maximum room for confusion
1156
k = make_file_knit('test', get_transport('.'), delta=False, create=True)
1157
self.assertEquals(k.get_lines('text-1'), ['a\n', 'b' ])
1158
self.assertEquals(k.get_lines('text-2'), ['a\rb\n', 'b\n'])
1160
def test_delta(self):
1161
"""Expression of knit delta as lines"""
1162
k = self.make_test_knit()
1163
td = list(line_delta(TEXT_1.splitlines(True),
1164
TEXT_1A.splitlines(True)))
1165
self.assertEqualDiff(''.join(td), delta_1_1a)
1166
out = apply_line_delta(TEXT_1.splitlines(True), td)
1167
self.assertEqualDiff(''.join(out), TEXT_1A)
1169
def test_add_with_parents(self):
1170
"""Store in knit with parents"""
1171
k = self.make_test_knit()
1172
self.add_stock_one_and_one_a(k)
1173
self.assertEqual({'text-1':(), 'text-1a':('text-1',)},
1174
k.get_parent_map(['text-1', 'text-1a']))
1176
def test_ancestry(self):
1177
"""Store in knit with parents"""
1178
k = self.make_test_knit()
1179
self.add_stock_one_and_one_a(k)
1180
self.assertEquals(set(k.get_ancestry(['text-1a'])), set(['text-1a', 'text-1']))
1182
def test_add_delta(self):
1183
"""Store in knit with parents"""
1184
k = self.make_test_knit(annotate=False)
1185
self.add_stock_one_and_one_a(k)
1186
self.assertEqualDiff(''.join(k.get_lines('text-1a')), TEXT_1A)
1188
def test_add_delta_knit_graph_index(self):
1189
"""Does adding work with a KnitGraphIndex."""
1190
index = InMemoryGraphIndex(2)
1191
knit_index = KnitGraphIndex(index, add_callback=index.add_nodes,
1193
k = self.make_test_knit(annotate=True, index=knit_index)
1194
self.add_stock_one_and_one_a(k)
1195
self.assertEqualDiff(''.join(k.get_lines('text-1a')), TEXT_1A)
1196
# check the index had the right data added.
1197
self.assertEqual(set([
1198
(index, ('text-1', ), ' 0 127', ((), ())),
1199
(index, ('text-1a', ), ' 127 140', ((('text-1', ),), (('text-1', ),))),
1200
]), set(index.iter_all_entries()))
1201
# we should not have a .kndx file
1202
self.assertFalse(get_transport('.').has('test.kndx'))
1204
def test_annotate(self):
1206
k = self.make_test_knit(annotate=True, name='knit')
1207
self.insert_and_test_small_annotate(k)
1209
def insert_and_test_small_annotate(self, k):
1210
"""test annotation with k works correctly."""
1211
k.add_lines('text-1', [], ['a\n', 'b\n'])
1212
k.add_lines('text-2', ['text-1'], ['a\n', 'c\n'])
1214
origins = k.annotate('text-2')
1215
self.assertEquals(origins[0], ('text-1', 'a\n'))
1216
self.assertEquals(origins[1], ('text-2', 'c\n'))
1218
def test_annotate_fulltext(self):
1220
k = self.make_test_knit(annotate=True, name='knit', delta=False)
1221
self.insert_and_test_small_annotate(k)
1223
def test_annotate_merge_1(self):
1224
k = self.make_test_knit(True)
1225
k.add_lines('text-a1', [], ['a\n', 'b\n'])
1226
k.add_lines('text-a2', [], ['d\n', 'c\n'])
1227
k.add_lines('text-am', ['text-a1', 'text-a2'], ['d\n', 'b\n'])
1228
origins = k.annotate('text-am')
1229
self.assertEquals(origins[0], ('text-a2', 'd\n'))
1230
self.assertEquals(origins[1], ('text-a1', 'b\n'))
1232
def test_annotate_merge_2(self):
1233
k = self.make_test_knit(True)
1234
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1235
k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
1236
k.add_lines('text-am', ['text-a1', 'text-a2'], ['a\n', 'y\n', 'c\n'])
1237
origins = k.annotate('text-am')
1238
self.assertEquals(origins[0], ('text-a1', 'a\n'))
1239
self.assertEquals(origins[1], ('text-a2', 'y\n'))
1240
self.assertEquals(origins[2], ('text-a1', 'c\n'))
1242
def test_annotate_merge_9(self):
1243
k = self.make_test_knit(True)
1244
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1245
k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
1246
k.add_lines('text-am', ['text-a1', 'text-a2'], ['k\n', 'y\n', 'c\n'])
1247
origins = k.annotate('text-am')
1248
self.assertEquals(origins[0], ('text-am', 'k\n'))
1249
self.assertEquals(origins[1], ('text-a2', 'y\n'))
1250
self.assertEquals(origins[2], ('text-a1', 'c\n'))
1252
def test_annotate_merge_3(self):
1253
k = self.make_test_knit(True)
1254
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1255
k.add_lines('text-a2', [] ,['x\n', 'y\n', 'z\n'])
1256
k.add_lines('text-am', ['text-a1', 'text-a2'], ['k\n', 'y\n', 'z\n'])
1257
origins = k.annotate('text-am')
1258
self.assertEquals(origins[0], ('text-am', 'k\n'))
1259
self.assertEquals(origins[1], ('text-a2', 'y\n'))
1260
self.assertEquals(origins[2], ('text-a2', 'z\n'))
1262
def test_annotate_merge_4(self):
1263
k = self.make_test_knit(True)
1264
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1265
k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
1266
k.add_lines('text-a3', ['text-a1'], ['a\n', 'b\n', 'p\n'])
1267
k.add_lines('text-am', ['text-a2', 'text-a3'], ['a\n', 'b\n', 'z\n'])
1268
origins = k.annotate('text-am')
1269
self.assertEquals(origins[0], ('text-a1', 'a\n'))
1270
self.assertEquals(origins[1], ('text-a1', 'b\n'))
1271
self.assertEquals(origins[2], ('text-a2', 'z\n'))
1273
def test_annotate_merge_5(self):
1274
k = self.make_test_knit(True)
1275
k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1276
k.add_lines('text-a2', [], ['d\n', 'e\n', 'f\n'])
1277
k.add_lines('text-a3', [], ['x\n', 'y\n', 'z\n'])
1278
k.add_lines('text-am',
1279
['text-a1', 'text-a2', 'text-a3'],
1280
['a\n', 'e\n', 'z\n'])
1281
origins = k.annotate('text-am')
1282
self.assertEquals(origins[0], ('text-a1', 'a\n'))
1283
self.assertEquals(origins[1], ('text-a2', 'e\n'))
1284
self.assertEquals(origins[2], ('text-a3', 'z\n'))
1286
def test_annotate_file_cherry_pick(self):
1287
k = self.make_test_knit(True)
1288
k.add_lines('text-1', [], ['a\n', 'b\n', 'c\n'])
1289
k.add_lines('text-2', ['text-1'], ['d\n', 'e\n', 'f\n'])
1290
k.add_lines('text-3', ['text-2', 'text-1'], ['a\n', 'b\n', 'c\n'])
1291
origins = k.annotate('text-3')
1292
self.assertEquals(origins[0], ('text-1', 'a\n'))
1293
self.assertEquals(origins[1], ('text-1', 'b\n'))
1294
self.assertEquals(origins[2], ('text-1', 'c\n'))
1296
def test_reannotate(self):
1297
k1 = make_file_knit('knit1', get_transport('.'),
1298
factory=KnitAnnotateFactory(), create=True)
1300
k1.add_lines('text-a', [], ['a\n', 'b\n'])
1302
k1.add_lines('text-b', ['text-a'], ['a\n', 'c\n'])
1304
k2 = make_file_knit('test2', get_transport('.'),
1305
factory=KnitAnnotateFactory(), create=True)
1306
k2.insert_record_stream(k1.get_record_stream(k1.versions(),
1307
'unordered', False))
1310
k1.add_lines('text-X', ['text-b'], ['a\n', 'b\n'])
1312
k2.add_lines('text-c', ['text-b'], ['z\n', 'c\n'])
1314
k2.add_lines('text-Y', ['text-b'], ['b\n', 'c\n'])
1316
# test-c will have index 3
1317
k1.insert_record_stream(k2.get_record_stream(['text-c'],
1318
'unordered', False))
1320
lines = k1.get_lines('text-c')
1321
self.assertEquals(lines, ['z\n', 'c\n'])
1323
origins = k1.annotate('text-c')
1324
self.assertEquals(origins[0], ('text-c', 'z\n'))
1325
self.assertEquals(origins[1], ('text-b', 'c\n'))
1327
def test_get_line_delta_texts(self):
1328
"""Make sure we can call get_texts on text with reused line deltas"""
1329
k1 = make_file_knit('test1', get_transport('.'),
1330
factory=KnitPlainFactory(), create=True)
1335
parents = ['%d' % (t-1)]
1336
k1.add_lines('%d' % t, parents, ['hello\n'] * t)
1337
k1.get_texts(('%d' % t) for t in range(3))
1339
def test_iter_lines_reads_in_order(self):
1340
instrumented_t = get_transport('trace+memory:///')
1341
k1 = make_file_knit('id', instrumented_t, create=True, delta=True)
1342
self.assertEqual([('get', 'id.kndx',)], instrumented_t._activity)
1343
# add texts with no required ordering
1344
k1.add_lines('base', [], ['text\n'])
1345
k1.add_lines('base2', [], ['text2\n'])
1346
# clear the logged activity, but preserve the list instance in case of
1347
# clones pointing at it.
1348
del instrumented_t._activity[:]
1349
# request a last-first iteration
1350
results = list(k1.iter_lines_added_or_present_in_versions(
1353
[('readv', 'id.knit', [(0, 87), (87, 89)], False, None)],
1354
instrumented_t._activity)
1355
self.assertEqual([('text\n', 'base'), ('text2\n', 'base2')], results)
1357
def test_knit_format(self):
1358
# this tests that a new knit index file has the expected content
1359
# and that is writes the data we expect as records are added.
1360
knit = self.make_test_knit(True)
1361
# Now knit files are not created until we first add data to them
1362
self.assertFileEqual("# bzr knit index 8\n", 'test.kndx')
1363
knit.add_lines_with_ghosts('revid', ['a_ghost'], ['a\n'])
1364
self.assertFileEqual(
1365
"# bzr knit index 8\n"
1367
"revid fulltext 0 84 .a_ghost :",
1369
knit.add_lines_with_ghosts('revid2', ['revid'], ['a\n'])
1370
self.assertFileEqual(
1371
"# bzr knit index 8\n"
1372
"\nrevid fulltext 0 84 .a_ghost :"
1373
"\nrevid2 line-delta 84 82 0 :",
1375
# we should be able to load this file again
1376
knit = make_file_knit('test', get_transport('.'), access_mode='r')
1377
self.assertEqual(['revid', 'revid2'], knit.versions())
1378
# write a short write to the file and ensure that its ignored
1379
indexfile = file('test.kndx', 'ab')
1380
indexfile.write('\nrevid3 line-delta 166 82 1 2 3 4 5 .phwoar:demo ')
1382
# we should be able to load this file again
1383
knit = make_file_knit('test', get_transport('.'), access_mode='w')
1384
self.assertEqual(['revid', 'revid2'], knit.versions())
1385
# and add a revision with the same id the failed write had
1386
knit.add_lines('revid3', ['revid2'], ['a\n'])
1387
# and when reading it revid3 should now appear.
1388
knit = make_file_knit('test', get_transport('.'), access_mode='r')
1389
self.assertEqual(['revid', 'revid2', 'revid3'], knit.versions())
1390
self.assertEqual({'revid3':('revid2',)}, knit.get_parent_map(['revid3']))
1392
def test_delay_create(self):
1393
"""Test that passing delay_create=True creates files late"""
1394
knit = self.make_test_knit(annotate=True, delay_create=True)
1395
self.failIfExists('test.knit')
1396
self.failIfExists('test.kndx')
1397
knit.add_lines_with_ghosts('revid', ['a_ghost'], ['a\n'])
1398
self.failUnlessExists('test.knit')
1399
self.assertFileEqual(
1400
"# bzr knit index 8\n"
1402
"revid fulltext 0 84 .a_ghost :",
1405
def test_create_parent_dir(self):
1406
"""create_parent_dir can create knits in nonexistant dirs"""
1407
# Has no effect if we don't set 'delay_create'
1408
trans = get_transport('.')
1409
self.assertRaises(NoSuchFile, make_file_knit, 'dir/test',
1410
trans, access_mode='w', factory=None,
1411
create=True, create_parent_dir=True)
1412
# Nothing should have changed yet
1413
knit = make_file_knit('dir/test', trans, access_mode='w',
1414
factory=None, create=True,
1415
create_parent_dir=True,
1417
self.failIfExists('dir/test.knit')
1418
self.failIfExists('dir/test.kndx')
1419
self.failIfExists('dir')
1420
knit.add_lines('revid', [], ['a\n'])
1421
self.failUnlessExists('dir')
1422
self.failUnlessExists('dir/test.knit')
1423
self.assertFileEqual(
1424
"# bzr knit index 8\n"
1426
"revid fulltext 0 84 :",
1429
def test_create_mode_700(self):
1430
trans = get_transport('.')
1431
if not trans._can_roundtrip_unix_modebits():
1432
# Can't roundtrip, so no need to run this test
1434
knit = make_file_knit('dir/test', trans, access_mode='w', factory=None,
1435
create=True, create_parent_dir=True, delay_create=True,
1436
file_mode=0600, dir_mode=0700)
1437
knit.add_lines('revid', [], ['a\n'])
1438
self.assertTransportMode(trans, 'dir', 0700)
1439
self.assertTransportMode(trans, 'dir/test.knit', 0600)
1440
self.assertTransportMode(trans, 'dir/test.kndx', 0600)
1442
def test_create_mode_770(self):
1443
trans = get_transport('.')
1444
if not trans._can_roundtrip_unix_modebits():
1445
# Can't roundtrip, so no need to run this test
1447
knit = make_file_knit('dir/test', trans, access_mode='w', factory=None,
1448
create=True, create_parent_dir=True, delay_create=True,
1449
file_mode=0660, dir_mode=0770)
1450
knit.add_lines('revid', [], ['a\n'])
1451
self.assertTransportMode(trans, 'dir', 0770)
1452
self.assertTransportMode(trans, 'dir/test.knit', 0660)
1453
self.assertTransportMode(trans, 'dir/test.kndx', 0660)
1455
def test_create_mode_777(self):
1456
trans = get_transport('.')
1457
if not trans._can_roundtrip_unix_modebits():
1458
# Can't roundtrip, so no need to run this test
1460
knit = make_file_knit('dir/test', trans, access_mode='w', factory=None,
1461
create=True, create_parent_dir=True, delay_create=True,
1462
file_mode=0666, dir_mode=0777)
1463
knit.add_lines('revid', [], ['a\n'])
1464
self.assertTransportMode(trans, 'dir', 0777)
1465
self.assertTransportMode(trans, 'dir/test.knit', 0666)
1466
self.assertTransportMode(trans, 'dir/test.kndx', 0666)
1468
def test_plan_merge(self):
1469
my_knit = self.make_test_knit(annotate=True)
1470
my_knit.add_lines('text1', [], split_lines(TEXT_1))
1471
my_knit.add_lines('text1a', ['text1'], split_lines(TEXT_1A))
1472
my_knit.add_lines('text1b', ['text1'], split_lines(TEXT_1B))
1473
plan = list(my_knit.plan_merge('text1a', 'text1b'))
1474
for plan_line, expected_line in zip(plan, AB_MERGE):
1475
self.assertEqual(plan_line, expected_line)
1478
class GetDataStreamTests(KnitTests):
1479
"""Tests for get_data_stream."""
1481
def test_get_stream_empty(self):
1482
"""Get a data stream for an empty knit file."""
1483
k1 = self.make_test_knit()
1484
format, data_list, reader_callable = k1.get_data_stream([])
1485
self.assertEqual('knit-plain', format)
1486
self.assertEqual([], data_list)
1487
content = reader_callable(None)
1488
self.assertEqual('', content)
1489
self.assertIsInstance(content, str)
1491
def test_get_stream_one_version(self):
1492
"""Get a data stream for a single record out of a knit containing just
1495
k1 = self.make_test_knit()
1497
('text-a', [], TEXT_1),
1499
expected_data_list = [
1500
# version, options, length, parents
1501
('text-a', ['fulltext'], 122, ()),
1503
for version_id, parents, lines in test_data:
1504
k1.add_lines(version_id, parents, split_lines(lines))
1506
format, data_list, reader_callable = k1.get_data_stream(['text-a'])
1507
self.assertEqual('knit-plain', format)
1508
self.assertEqual(expected_data_list, data_list)
1509
# There's only one record in the knit, so the content should be the
1510
# entire knit data file's contents.
1511
self.assertEqual(k1.transport.get_bytes(k1._data._access._filename),
1512
reader_callable(None))
1514
def test_get_stream_get_one_version_of_many(self):
1515
"""Get a data stream for just one version out of a knit containing many
1518
k1 = self.make_test_knit()
1519
# Insert the same data as test_knit_join, as they seem to cover a range
1520
# of cases (no parents, one parent, multiple parents).
1522
('text-a', [], TEXT_1),
1523
('text-b', ['text-a'], TEXT_1),
1524
('text-c', [], TEXT_1),
1525
('text-d', ['text-c'], TEXT_1),
1526
('text-m', ['text-b', 'text-d'], TEXT_1),
1528
expected_data_list = [
1529
# version, options, length, parents
1530
('text-m', ['line-delta'], 84, ('text-b', 'text-d')),
1532
for version_id, parents, lines in test_data:
1533
k1.add_lines(version_id, parents, split_lines(lines))
1535
format, data_list, reader_callable = k1.get_data_stream(['text-m'])
1536
self.assertEqual('knit-plain', format)
1537
self.assertEqual(expected_data_list, data_list)
1538
self.assertRecordContentEqual(k1, 'text-m', reader_callable(None))
1540
def test_get_data_stream_unordered_index(self):
1541
"""Get a data stream when the knit index reports versions out of order.
1543
https://bugs.launchpad.net/bzr/+bug/164637
1545
k1 = self.make_test_knit()
1547
('text-a', [], TEXT_1),
1548
('text-b', ['text-a'], TEXT_1),
1549
('text-c', [], TEXT_1),
1550
('text-d', ['text-c'], TEXT_1),
1551
('text-m', ['text-b', 'text-d'], TEXT_1),
1553
for version_id, parents, lines in test_data:
1554
k1.add_lines(version_id, parents, split_lines(lines))
1555
# monkey-patch versions method to return out of order, as if coming
1556
# from multiple independently indexed packs
1557
original_versions = k1.versions
1558
k1.versions = lambda: reversed(original_versions())
1559
expected_data_list = [
1560
('text-a', ['fulltext'], 122, ()),
1561
('text-b', ['line-delta'], 84, ('text-a',))]
1562
# now check the fulltext is first and the delta second
1563
format, data_list, _ = k1.get_data_stream(['text-a', 'text-b'])
1564
self.assertEqual('knit-plain', format)
1565
self.assertEqual(expected_data_list, data_list)
1566
# and that's true if we ask for them in the opposite order too
1567
format, data_list, _ = k1.get_data_stream(['text-b', 'text-a'])
1568
self.assertEqual(expected_data_list, data_list)
1569
# also try requesting more versions
1570
format, data_list, _ = k1.get_data_stream([
1571
'text-m', 'text-b', 'text-a'])
1573
('text-a', ['fulltext'], 122, ()),
1574
('text-b', ['line-delta'], 84, ('text-a',)),
1575
('text-m', ['line-delta'], 84, ('text-b', 'text-d')),
1578
def test_get_stream_ghost_parent(self):
1579
"""Get a data stream for a version with a ghost parent."""
1580
k1 = self.make_test_knit()
1582
k1.add_lines('text-a', [], split_lines(TEXT_1))
1583
k1.add_lines_with_ghosts('text-b', ['text-a', 'text-ghost'],
1584
split_lines(TEXT_1))
1586
expected_data_list = [
1587
# version, options, length, parents
1588
('text-b', ['line-delta'], 84, ('text-a', 'text-ghost')),
1591
format, data_list, reader_callable = k1.get_data_stream(['text-b'])
1592
self.assertEqual('knit-plain', format)
1593
self.assertEqual(expected_data_list, data_list)
1594
self.assertRecordContentEqual(k1, 'text-b', reader_callable(None))
1596
def test_get_stream_get_multiple_records(self):
1597
"""Get a stream for multiple records of a knit."""
1598
k1 = self.make_test_knit()
1599
# Insert the same data as test_knit_join, as they seem to cover a range
1600
# of cases (no parents, one parent, multiple parents).
1602
('text-a', [], TEXT_1),
1603
('text-b', ['text-a'], TEXT_1),
1604
('text-c', [], TEXT_1),
1605
('text-d', ['text-c'], TEXT_1),
1606
('text-m', ['text-b', 'text-d'], TEXT_1),
1608
for version_id, parents, lines in test_data:
1609
k1.add_lines(version_id, parents, split_lines(lines))
1611
# This test is actually a bit strict as the order in which they're
1612
# returned is not defined. This matches the current (deterministic)
1614
expected_data_list = [
1615
# version, options, length, parents
1616
('text-d', ['line-delta'], 84, ('text-c',)),
1617
('text-b', ['line-delta'], 84, ('text-a',)),
1619
# Note that even though we request the revision IDs in a particular
1620
# order, the data stream may return them in any order it likes. In this
1621
# case, they'll be in the order they were inserted into the knit.
1622
format, data_list, reader_callable = k1.get_data_stream(
1623
['text-d', 'text-b'])
1624
self.assertEqual('knit-plain', format)
1625
self.assertEqual(expected_data_list, data_list)
1626
# must match order they're returned
1627
self.assertRecordContentEqual(k1, 'text-d', reader_callable(84))
1628
self.assertRecordContentEqual(k1, 'text-b', reader_callable(84))
1629
self.assertEqual('', reader_callable(None),
1630
"There should be no more bytes left to read.")
1632
def test_get_stream_all(self):
1633
"""Get a data stream for all the records in a knit.
1635
This exercises fulltext records, line-delta records, records with
1636
various numbers of parents, and reading multiple records out of the
1637
callable. These cases ought to all be exercised individually by the
1638
other test_get_stream_* tests; this test is basically just paranoia.
1640
k1 = self.make_test_knit()
1641
# Insert the same data as test_knit_join, as they seem to cover a range
1642
# of cases (no parents, one parent, multiple parents).
1644
('text-a', [], TEXT_1),
1645
('text-b', ['text-a'], TEXT_1),
1646
('text-c', [], TEXT_1),
1647
('text-d', ['text-c'], TEXT_1),
1648
('text-m', ['text-b', 'text-d'], TEXT_1),
1650
for version_id, parents, lines in test_data:
1651
k1.add_lines(version_id, parents, split_lines(lines))
1653
# This test is actually a bit strict as the order in which they're
1654
# returned is not defined. This matches the current (deterministic)
1656
expected_data_list = [
1657
# version, options, length, parents
1658
('text-a', ['fulltext'], 122, ()),
1659
('text-b', ['line-delta'], 84, ('text-a',)),
1660
('text-m', ['line-delta'], 84, ('text-b', 'text-d')),
1661
('text-c', ['fulltext'], 121, ()),
1662
('text-d', ['line-delta'], 84, ('text-c',)),
1664
format, data_list, reader_callable = k1.get_data_stream(
1665
['text-a', 'text-b', 'text-c', 'text-d', 'text-m'])
1666
self.assertEqual('knit-plain', format)
1667
self.assertEqual(expected_data_list, data_list)
1668
for version_id, options, length, parents in expected_data_list:
1669
bytes = reader_callable(length)
1670
self.assertRecordContentEqual(k1, version_id, bytes)
1673
class InsertDataStreamTests(KnitTests):
1674
"""Tests for insert_data_stream."""
1676
def assertKnitFilesEqual(self, knit1, knit2):
1677
"""Assert that the contents of the index and data files of two knits are
1681
knit1.transport.get_bytes(knit1._data._access._filename),
1682
knit2.transport.get_bytes(knit2._data._access._filename))
1684
knit1.transport.get_bytes(knit1._index._filename),
1685
knit2.transport.get_bytes(knit2._index._filename))
1687
def assertKnitValuesEqual(self, left, right):
1688
"""Assert that the texts, annotations and graph of left and right are
1691
self.assertEqual(set(left.versions()), set(right.versions()))
1692
for version in left.versions():
1693
self.assertEqual(left.get_parents_with_ghosts(version),
1694
right.get_parents_with_ghosts(version))
1695
self.assertEqual(left.get_lines(version),
1696
right.get_lines(version))
1697
self.assertEqual(left.annotate(version),
1698
right.annotate(version))
1700
def test_empty_stream(self):
1701
"""Inserting a data stream with no records should not put any data into
1704
k1 = self.make_test_knit()
1705
k1.insert_data_stream(
1706
(k1.get_format_signature(), [], lambda ignored: ''))
1707
self.assertEqual('', k1.transport.get_bytes(k1._data._access._filename),
1708
"The .knit should be completely empty.")
1709
self.assertEqual(k1._index.HEADER,
1710
k1.transport.get_bytes(k1._index._filename),
1711
"The .kndx should have nothing apart from the header.")
1713
def test_one_record(self):
1714
"""Inserting a data stream with one record from a knit with one record
1715
results in byte-identical files.
1717
source = self.make_test_knit(name='source')
1718
source.add_lines('text-a', [], split_lines(TEXT_1))
1719
data_stream = source.get_data_stream(['text-a'])
1720
target = self.make_test_knit(name='target')
1721
target.insert_data_stream(data_stream)
1722
self.assertKnitFilesEqual(source, target)
1724
def test_annotated_stream_into_unannotated_knit(self):
1725
"""Inserting an annotated datastream to an unannotated knit works."""
1726
# case one - full texts.
1727
source = self.make_test_knit(name='source', annotate=True)
1728
target = self.make_test_knit(name='target', annotate=False)
1729
source.add_lines('text-a', [], split_lines(TEXT_1))
1730
target.insert_data_stream(source.get_data_stream(['text-a']))
1731
self.assertKnitValuesEqual(source, target)
1732
# case two - deltas.
1733
source.add_lines('text-b', ['text-a'], split_lines(TEXT_2))
1734
target.insert_data_stream(source.get_data_stream(['text-b']))
1735
self.assertKnitValuesEqual(source, target)
1737
def test_unannotated_stream_into_annotated_knit(self):
1738
"""Inserting an unannotated datastream to an annotated knit works."""
1739
# case one - full texts.
1740
source = self.make_test_knit(name='source', annotate=False)
1741
target = self.make_test_knit(name='target', annotate=True)
1742
source.add_lines('text-a', [], split_lines(TEXT_1))
1743
target.insert_data_stream(source.get_data_stream(['text-a']))
1744
self.assertKnitValuesEqual(source, target)
1745
# case two - deltas.
1746
source.add_lines('text-b', ['text-a'], split_lines(TEXT_2))
1747
target.insert_data_stream(source.get_data_stream(['text-b']))
1748
self.assertKnitValuesEqual(source, target)
1750
def test_records_already_present(self):
1751
"""Insert a data stream where some records are alreday present in the
1752
target, and some not. Only the new records are inserted.
1754
source = self.make_test_knit(name='source')
1755
target = self.make_test_knit(name='target')
1756
# Insert 'text-a' into both source and target
1757
source.add_lines('text-a', [], split_lines(TEXT_1))
1758
target.insert_data_stream(source.get_data_stream(['text-a']))
1759
# Insert 'text-b' into just the source.
1760
source.add_lines('text-b', ['text-a'], split_lines(TEXT_1))
1761
# Get a data stream of both text-a and text-b, and insert it.
1762
data_stream = source.get_data_stream(['text-a', 'text-b'])
1763
target.insert_data_stream(data_stream)
1764
# The source and target will now be identical. This means the text-a
1765
# record was not added a second time.
1766
self.assertKnitFilesEqual(source, target)
1768
def test_multiple_records(self):
1769
"""Inserting a data stream of all records from a knit with multiple
1770
records results in byte-identical files.
1772
source = self.make_test_knit(name='source')
1773
source.add_lines('text-a', [], split_lines(TEXT_1))
1774
source.add_lines('text-b', ['text-a'], split_lines(TEXT_1))
1775
source.add_lines('text-c', [], split_lines(TEXT_1))
1776
data_stream = source.get_data_stream(['text-a', 'text-b', 'text-c'])
1778
target = self.make_test_knit(name='target')
1779
target.insert_data_stream(data_stream)
1781
self.assertKnitFilesEqual(source, target)
1783
def test_ghost_parent(self):
1784
"""Insert a data stream with a record that has a ghost parent."""
1785
# Make a knit with a record, text-a, that has a ghost parent.
1786
source = self.make_test_knit(name='source')
1787
source.add_lines_with_ghosts('text-a', ['text-ghost'],
1788
split_lines(TEXT_1))
1789
data_stream = source.get_data_stream(['text-a'])
1791
target = self.make_test_knit(name='target')
1792
target.insert_data_stream(data_stream)
1794
self.assertKnitFilesEqual(source, target)
1796
# The target knit object is in a consistent state, i.e. the record we
1797
# just added is immediately visible.
1798
self.assertTrue(target.has_version('text-a'))
1799
self.assertFalse(target.has_version('text-ghost'))
1800
self.assertEqual({'text-a':('text-ghost',)},
1801
target.get_parent_map(['text-a', 'text-ghost']))
1802
self.assertEqual(split_lines(TEXT_1), target.get_lines('text-a'))
1804
def test_inconsistent_version_lines(self):
1805
"""Inserting a data stream which has different content for a version_id
1806
than already exists in the knit will raise KnitCorrupt.
1808
source = self.make_test_knit(name='source')
1809
target = self.make_test_knit(name='target')
1810
# Insert a different 'text-a' into both source and target
1811
source.add_lines('text-a', [], split_lines(TEXT_1))
1812
target.add_lines('text-a', [], split_lines(TEXT_2))
1813
# Insert a data stream with conflicting content into the target
1814
data_stream = source.get_data_stream(['text-a'])
1816
errors.KnitCorrupt, target.insert_data_stream, data_stream)
1818
def test_inconsistent_version_parents(self):
1819
"""Inserting a data stream which has different parents for a version_id
1820
than already exists in the knit will raise KnitCorrupt.
1822
source = self.make_test_knit(name='source')
1823
target = self.make_test_knit(name='target')
1824
# Insert a different 'text-a' into both source and target. They differ
1825
# only by the parents list, the content is the same.
1826
source.add_lines_with_ghosts('text-a', [], split_lines(TEXT_1))
1827
target.add_lines_with_ghosts('text-a', ['a-ghost'], split_lines(TEXT_1))
1828
# Insert a data stream with conflicting content into the target
1829
data_stream = source.get_data_stream(['text-a'])
1831
errors.KnitCorrupt, target.insert_data_stream, data_stream)
1833
def test_unknown_stream_format(self):
1834
"""A data stream in a different format to the target knit cannot be
1837
It will raise KnitDataStreamUnknown because the fallback code will fail
1838
to make a knit. In future we may need KnitDataStreamIncompatible again,
1839
for more exotic cases.
1841
data_stream = ('fake-format-signature', [], lambda _: '')
1842
target = self.make_test_knit(name='target')
1844
errors.KnitDataStreamUnknown,
1845
target.insert_data_stream, data_stream)
1847
def test_bug_208418(self):
1848
"""You can insert a stream with an incompatible format, even when:
1849
* the stream has a line-delta record,
1850
* whose parent is in the target, also stored as a line-delta
1852
See <https://launchpad.net/bugs/208418>.
1854
base_lines = split_lines(TEXT_1)
1856
target = self.make_test_knit(name='target', annotate=True)
1857
target.add_lines('version-1', [], base_lines)
1858
target.add_lines('version-2', ['version-1'], base_lines + ['a\n'])
1859
# The second record should be a delta.
1860
self.assertEqual('line-delta', target._index.get_method('version-2'))
1862
# Make a source, with a different format, but the same data
1863
source = self.make_test_knit(name='source', annotate=False)
1864
source.add_lines('version-1', [], base_lines)
1865
source.add_lines('version-2', ['version-1'], base_lines + ['a\n'])
1866
# Now add another record, which should be stored as a delta against
1868
source.add_lines('version-3', ['version-2'], base_lines + ['b\n'])
1869
self.assertEqual('line-delta', source._index.get_method('version-3'))
1871
# Make a stream of the new version
1872
data_stream = source.get_data_stream(['version-3'])
1873
# And insert into the target
1874
target.insert_data_stream(data_stream)
1875
# No errors should have been raised.
1877
def test_line_delta_record_into_non_delta_knit(self):
1878
# Make a data stream with a line-delta record
1879
source = self.make_test_knit(name='source', delta=True)
1880
base_lines = split_lines(TEXT_1)
1881
source.add_lines('version-1', [], base_lines)
1882
source.add_lines('version-2', ['version-1'], base_lines + ['a\n'])
1883
# The second record should be a delta.
1884
self.assertEqual('line-delta', source._index.get_method('version-2'))
1885
data_stream = source.get_data_stream(['version-1', 'version-2'])
1887
# Insert the stream into a non-delta knit.
1888
target = self.make_test_knit(name='target', delta=False)
1889
target.insert_data_stream(data_stream)
1891
# Both versions are fulltexts in the target
1892
self.assertEqual('fulltext', target._index.get_method('version-1'))
1893
self.assertEqual('fulltext', target._index.get_method('version-2'))
1896
class DataStreamTests(KnitTests):
1898
def assertMadeStreamKnit(self, source_knit, versions, target_knit):
1899
"""Assert that a knit made from a stream is as expected."""
1900
a_stream = source_knit.get_data_stream(versions)
1901
expected_data = a_stream[2](None)
1902
a_stream = source_knit.get_data_stream(versions)
1903
a_knit = target_knit._knit_from_datastream(a_stream)
1904
self.assertEqual(source_knit.factory.__class__,
1905
a_knit.factory.__class__)
1906
self.assertIsInstance(a_knit._data._access, _StreamAccess)
1907
self.assertIsInstance(a_knit._index, _StreamIndex)
1908
self.assertEqual(a_knit._index.data_list, a_stream[1])
1909
self.assertEqual(a_knit._data._access.data, expected_data)
1910
self.assertEqual(a_knit.filename, target_knit.filename)
1911
self.assertEqual(a_knit.transport, target_knit.transport)
1912
self.assertEqual(a_knit._index, a_knit._data._access.stream_index)
1913
self.assertEqual(target_knit, a_knit._data._access.backing_knit)
1914
self.assertIsInstance(a_knit._data._access.orig_factory,
1915
source_knit.factory.__class__)
1917
def test__knit_from_data_stream_empty(self):
1918
"""Create a knit object from a datastream."""
1919
annotated = self.make_test_knit(name='source', annotate=True)
1920
plain = self.make_test_knit(name='target', annotate=False)
1921
# case 1: annotated source
1922
self.assertMadeStreamKnit(annotated, [], annotated)
1923
self.assertMadeStreamKnit(annotated, [], plain)
1924
# case 2: plain source
1925
self.assertMadeStreamKnit(plain, [], annotated)
1926
self.assertMadeStreamKnit(plain, [], plain)
1928
def test__knit_from_data_stream_unknown_format(self):
1929
annotated = self.make_test_knit(name='source', annotate=True)
1930
self.assertRaises(errors.KnitDataStreamUnknown,
1931
annotated._knit_from_datastream, ("unknown", None, None))
1943
Banana cup cake recipe
1949
- self-raising flour
1953
Banana cup cake recipe
1955
- bananas (do not use plantains!!!)
1962
Banana cup cake recipe
1965
- self-raising flour
1978
AB_MERGE_TEXT="""unchanged|Banana cup cake recipe
1983
new-b|- bananas (do not use plantains!!!)
1984
unchanged|- broken tea cups
1985
new-a|- self-raising flour
1988
AB_MERGE=[tuple(l.split('|')) for l in AB_MERGE_TEXT.splitlines(True)]
1991
def line_delta(from_lines, to_lines):
1992
"""Generate line-based delta from one text to another"""
1993
s = difflib.SequenceMatcher(None, from_lines, to_lines)
1994
for op in s.get_opcodes():
1995
if op[0] == 'equal':
1997
yield '%d,%d,%d\n' % (op[1], op[2], op[4]-op[3])
1998
for i in range(op[3], op[4]):
2002
def apply_line_delta(basis_lines, delta_lines):
2003
"""Apply a line-based perfect diff
2005
basis_lines -- text to apply the patch to
2006
delta_lines -- diff instructions and content
2008
out = basis_lines[:]
2011
while i < len(delta_lines):
2013
a, b, c = map(long, l.split(','))
2015
out[offset+a:offset+b] = delta_lines[i:i+c]
2017
offset = offset + (b - a) + c
2021
class TestWeaveToKnit(KnitTests):
2023
def test_weave_to_knit_matches(self):
2024
# check that the WeaveToKnit is_compatible function
2025
# registers True for a Weave to a Knit.
2026
w = Weave(get_scope=lambda:None)
2027
k = self.make_test_knit()
2028
self.failUnless(WeaveToKnit.is_compatible(w, k))
2029
self.failIf(WeaveToKnit.is_compatible(k, w))
2030
self.failIf(WeaveToKnit.is_compatible(w, w))
2031
self.failIf(WeaveToKnit.is_compatible(k, k))
914
def make_test_knit(self, annotate=False, name='test'):
915
mapper = ConstantMapper(name)
916
return make_file_factory(annotate, mapper)(self.get_transport())
2034
919
class TestKnitIndex(KnitTests):
2153
1047
add_callback = self.catch_add
2155
1049
add_callback = None
2156
return KnitGraphIndex(combined_index, deltas=deltas,
1050
return _KnitGraphIndex(combined_index, lambda:True, deltas=deltas,
2157
1051
add_callback=add_callback)
2159
def test_get_ancestry(self):
2160
# get_ancestry is defined as eliding ghosts, not erroring.
2161
index = self.two_graph_index()
2162
self.assertEqual([], index.get_ancestry([]))
2163
self.assertEqual(['separate'], index.get_ancestry(['separate']))
2164
self.assertEqual(['tail'], index.get_ancestry(['tail']))
2165
self.assertEqual(['tail', 'parent'], index.get_ancestry(['parent']))
2166
self.assertEqual(['tail', 'parent', 'tip'], index.get_ancestry(['tip']))
2167
self.assertTrue(index.get_ancestry(['tip', 'separate']) in
2168
(['tail', 'parent', 'tip', 'separate'],
2169
['separate', 'tail', 'parent', 'tip'],
2171
# and without topo_sort
2172
self.assertEqual(set(['separate']),
2173
set(index.get_ancestry(['separate'], topo_sorted=False)))
2174
self.assertEqual(set(['tail']),
2175
set(index.get_ancestry(['tail'], topo_sorted=False)))
2176
self.assertEqual(set(['tail', 'parent']),
2177
set(index.get_ancestry(['parent'], topo_sorted=False)))
2178
self.assertEqual(set(['tail', 'parent', 'tip']),
2179
set(index.get_ancestry(['tip'], topo_sorted=False)))
2180
self.assertEqual(set(['separate', 'tail', 'parent', 'tip']),
2181
set(index.get_ancestry(['tip', 'separate'])))
2182
# asking for a ghost makes it go boom.
2183
self.assertRaises(errors.RevisionNotPresent, index.get_ancestry, ['ghost'])
2185
def test_get_ancestry_with_ghosts(self):
2186
index = self.two_graph_index()
2187
self.assertEqual([], index.get_ancestry_with_ghosts([]))
2188
self.assertEqual(['separate'], index.get_ancestry_with_ghosts(['separate']))
2189
self.assertEqual(['tail'], index.get_ancestry_with_ghosts(['tail']))
2190
self.assertTrue(index.get_ancestry_with_ghosts(['parent']) in
2191
(['tail', 'ghost', 'parent'],
2192
['ghost', 'tail', 'parent'],
2194
self.assertTrue(index.get_ancestry_with_ghosts(['tip']) in
2195
(['tail', 'ghost', 'parent', 'tip'],
2196
['ghost', 'tail', 'parent', 'tip'],
2198
self.assertTrue(index.get_ancestry_with_ghosts(['tip', 'separate']) in
2199
(['tail', 'ghost', 'parent', 'tip', 'separate'],
2200
['ghost', 'tail', 'parent', 'tip', 'separate'],
2201
['separate', 'tail', 'ghost', 'parent', 'tip'],
2202
['separate', 'ghost', 'tail', 'parent', 'tip'],
2204
# asking for a ghost makes it go boom.
2205
self.assertRaises(errors.RevisionNotPresent, index.get_ancestry_with_ghosts, ['ghost'])
2207
def test_num_versions(self):
2208
index = self.two_graph_index()
2209
self.assertEqual(4, index.num_versions())
2211
def test_get_versions(self):
2212
index = self.two_graph_index()
2213
self.assertEqual(set(['tail', 'tip', 'parent', 'separate']),
2214
set(index.get_versions()))
2216
def test_has_version(self):
2217
index = self.two_graph_index()
2218
self.assertTrue(index.has_version('tail'))
2219
self.assertFalse(index.has_version('ghost'))
1053
def test_keys(self):
1054
index = self.two_graph_index()
1055
self.assertEqual(set([('tail',), ('tip',), ('parent',), ('separate',)]),
2221
1058
def test_get_position(self):
2222
1059
index = self.two_graph_index()
2223
self.assertEqual((index._graph_index._indices[0], 0, 100), index.get_position('tip'))
2224
self.assertEqual((index._graph_index._indices[1], 100, 78), index.get_position('parent'))
1060
self.assertEqual((index._graph_index._indices[0], 0, 100), index.get_position(('tip',)))
1061
self.assertEqual((index._graph_index._indices[1], 100, 78), index.get_position(('parent',)))
2226
1063
def test_get_method_deltas(self):
2227
1064
index = self.two_graph_index(deltas=True)
2228
self.assertEqual('fulltext', index.get_method('tip'))
2229
self.assertEqual('line-delta', index.get_method('parent'))
1065
self.assertEqual('fulltext', index.get_method(('tip',)))
1066
self.assertEqual('line-delta', index.get_method(('parent',)))
2231
1068
def test_get_method_no_deltas(self):
2232
1069
# check that the parent-history lookup is ignored with deltas=False.
2233
1070
index = self.two_graph_index(deltas=False)
2234
self.assertEqual('fulltext', index.get_method('tip'))
2235
self.assertEqual('fulltext', index.get_method('parent'))
1071
self.assertEqual('fulltext', index.get_method(('tip',)))
1072
self.assertEqual('fulltext', index.get_method(('parent',)))
2237
1074
def test_get_options_deltas(self):
2238
1075
index = self.two_graph_index(deltas=True)
2239
self.assertEqual(['fulltext', 'no-eol'], index.get_options('tip'))
2240
self.assertEqual(['line-delta'], index.get_options('parent'))
1076
self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1077
self.assertEqual(['line-delta'], index.get_options(('parent',)))
2242
1079
def test_get_options_no_deltas(self):
2243
1080
# check that the parent-history lookup is ignored with deltas=False.
2244
1081
index = self.two_graph_index(deltas=False)
2245
self.assertEqual(['fulltext', 'no-eol'], index.get_options('tip'))
2246
self.assertEqual(['fulltext'], index.get_options('parent'))
2248
def test_get_parents_with_ghosts(self):
2249
index = self.two_graph_index()
2250
self.assertEqual(('tail', 'ghost'), index.get_parents_with_ghosts('parent'))
2251
# and errors on ghosts.
2252
self.assertRaises(errors.RevisionNotPresent,
2253
index.get_parents_with_ghosts, 'ghost')
2255
def test_check_versions_present(self):
2256
# ghosts should not be considered present
2257
index = self.two_graph_index()
2258
self.assertRaises(RevisionNotPresent, index.check_versions_present,
2260
self.assertRaises(RevisionNotPresent, index.check_versions_present,
2262
index.check_versions_present(['tail', 'separate'])
1082
self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1083
self.assertEqual(['fulltext'], index.get_options(('parent',)))
1085
def test_get_parent_map(self):
1086
index = self.two_graph_index()
1087
self.assertEqual({('parent',):(('tail',), ('ghost',))},
1088
index.get_parent_map([('parent',), ('ghost',)]))
2264
1090
def catch_add(self, entries):
2265
1091
self.caught_entries.append(entries)
2267
1093
def test_add_no_callback_errors(self):
2268
1094
index = self.two_graph_index()
2269
self.assertRaises(errors.ReadOnlyError, index.add_version,
2270
'new', 'fulltext,no-eol', (None, 50, 60), ['separate'])
1095
self.assertRaises(errors.ReadOnlyError, index.add_records,
1096
[(('new',), 'fulltext,no-eol', (None, 50, 60), ['separate'])])
2272
1098
def test_add_version_smoke(self):
2273
1099
index = self.two_graph_index(catch_adds=True)
2274
index.add_version('new', 'fulltext,no-eol', (None, 50, 60), ['separate'])
1100
index.add_records([(('new',), 'fulltext,no-eol', (None, 50, 60),
2275
1102
self.assertEqual([[(('new', ), 'N50 60', ((('separate',),),))]],
2276
1103
self.caught_entries)
2278
1105
def test_add_version_delta_not_delta_index(self):
2279
1106
index = self.two_graph_index(catch_adds=True)
2280
self.assertRaises(errors.KnitCorrupt, index.add_version,
2281
'new', 'no-eol,line-delta', (None, 0, 100), ['parent'])
1107
self.assertRaises(errors.KnitCorrupt, index.add_records,
1108
[(('new',), 'no-eol,line-delta', (None, 0, 100), [('parent',)])])
2282
1109
self.assertEqual([], self.caught_entries)
2284
1111
def test_add_version_same_dup(self):
2285
1112
index = self.two_graph_index(catch_adds=True)
2286
1113
# options can be spelt two different ways
2287
index.add_version('tip', 'fulltext,no-eol', (None, 0, 100), ['parent'])
2288
index.add_version('tip', 'no-eol,fulltext', (None, 0, 100), ['parent'])
2289
# but neither should have added data.
2290
self.assertEqual([[], []], self.caught_entries)
1114
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
1115
index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [('parent',)])])
1116
# position/length are ignored (because each pack could have fulltext or
1117
# delta, and be at a different position.
1118
index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100),
1120
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000),
1122
# but neither should have added data:
1123
self.assertEqual([[], [], [], []], self.caught_entries)
2292
1125
def test_add_version_different_dup(self):
2293
1126
index = self.two_graph_index(deltas=True, catch_adds=True)
2294
1127
# change options
2295
self.assertRaises(errors.KnitCorrupt, index.add_version,
2296
'tip', 'no-eol,line-delta', (None, 0, 100), ['parent'])
2297
self.assertRaises(errors.KnitCorrupt, index.add_version,
2298
'tip', 'line-delta,no-eol', (None, 0, 100), ['parent'])
2299
self.assertRaises(errors.KnitCorrupt, index.add_version,
2300
'tip', 'fulltext', (None, 0, 100), ['parent'])
2302
self.assertRaises(errors.KnitCorrupt, index.add_version,
2303
'tip', 'fulltext,no-eol', (None, 50, 100), ['parent'])
2304
self.assertRaises(errors.KnitCorrupt, index.add_version,
2305
'tip', 'fulltext,no-eol', (None, 0, 1000), ['parent'])
1128
self.assertRaises(errors.KnitCorrupt, index.add_records,
1129
[(('tip',), 'no-eol,line-delta', (None, 0, 100), [('parent',)])])
1130
self.assertRaises(errors.KnitCorrupt, index.add_records,
1131
[(('tip',), 'line-delta,no-eol', (None, 0, 100), [('parent',)])])
1132
self.assertRaises(errors.KnitCorrupt, index.add_records,
1133
[(('tip',), 'fulltext', (None, 0, 100), [('parent',)])])
2307
self.assertRaises(errors.KnitCorrupt, index.add_version,
2308
'tip', 'fulltext,no-eol', (None, 0, 100), [])
1135
self.assertRaises(errors.KnitCorrupt, index.add_records,
1136
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
2309
1137
self.assertEqual([], self.caught_entries)
2311
1139
def test_add_versions_nodeltas(self):
2312
1140
index = self.two_graph_index(catch_adds=True)
2313
index.add_versions([
2314
('new', 'fulltext,no-eol', (None, 50, 60), ['separate']),
2315
('new2', 'fulltext', (None, 0, 6), ['new']),
1142
(('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)]),
1143
(('new2',), 'fulltext', (None, 0, 6), [('new',)]),
2317
1145
self.assertEqual([(('new', ), 'N50 60', ((('separate',),),)),
2318
1146
(('new2', ), ' 0 6', ((('new',),),))],
2408
1240
add_callback = self.catch_add
2410
1242
add_callback = None
2411
return KnitGraphIndex(combined_index, parents=False,
1243
return _KnitGraphIndex(combined_index, lambda:True, parents=False,
2412
1244
add_callback=add_callback)
2414
def test_get_ancestry(self):
2415
# with no parents, ancestry is always just the key.
2416
index = self.two_graph_index()
2417
self.assertEqual([], index.get_ancestry([]))
2418
self.assertEqual(['separate'], index.get_ancestry(['separate']))
2419
self.assertEqual(['tail'], index.get_ancestry(['tail']))
2420
self.assertEqual(['parent'], index.get_ancestry(['parent']))
2421
self.assertEqual(['tip'], index.get_ancestry(['tip']))
2422
self.assertTrue(index.get_ancestry(['tip', 'separate']) in
2423
(['tip', 'separate'],
2424
['separate', 'tip'],
2426
# asking for a ghost makes it go boom.
2427
self.assertRaises(errors.RevisionNotPresent, index.get_ancestry, ['ghost'])
2429
def test_get_ancestry_with_ghosts(self):
2430
index = self.two_graph_index()
2431
self.assertEqual([], index.get_ancestry_with_ghosts([]))
2432
self.assertEqual(['separate'], index.get_ancestry_with_ghosts(['separate']))
2433
self.assertEqual(['tail'], index.get_ancestry_with_ghosts(['tail']))
2434
self.assertEqual(['parent'], index.get_ancestry_with_ghosts(['parent']))
2435
self.assertEqual(['tip'], index.get_ancestry_with_ghosts(['tip']))
2436
self.assertTrue(index.get_ancestry_with_ghosts(['tip', 'separate']) in
2437
(['tip', 'separate'],
2438
['separate', 'tip'],
2440
# asking for a ghost makes it go boom.
2441
self.assertRaises(errors.RevisionNotPresent, index.get_ancestry_with_ghosts, ['ghost'])
2443
def test_num_versions(self):
2444
index = self.two_graph_index()
2445
self.assertEqual(4, index.num_versions())
2447
def test_get_versions(self):
2448
index = self.two_graph_index()
2449
self.assertEqual(set(['tail', 'tip', 'parent', 'separate']),
2450
set(index.get_versions()))
2452
def test_has_version(self):
2453
index = self.two_graph_index()
2454
self.assertTrue(index.has_version('tail'))
2455
self.assertFalse(index.has_version('ghost'))
1246
def test_keys(self):
1247
index = self.two_graph_index()
1248
self.assertEqual(set([('tail',), ('tip',), ('parent',), ('separate',)]),
2457
1251
def test_get_position(self):
2458
1252
index = self.two_graph_index()
2459
self.assertEqual((index._graph_index._indices[0], 0, 100), index.get_position('tip'))
2460
self.assertEqual((index._graph_index._indices[1], 100, 78), index.get_position('parent'))
1253
self.assertEqual((index._graph_index._indices[0], 0, 100),
1254
index.get_position(('tip',)))
1255
self.assertEqual((index._graph_index._indices[1], 100, 78),
1256
index.get_position(('parent',)))
2462
1258
def test_get_method(self):
2463
1259
index = self.two_graph_index()
2464
self.assertEqual('fulltext', index.get_method('tip'))
2465
self.assertEqual(['fulltext'], index.get_options('parent'))
1260
self.assertEqual('fulltext', index.get_method(('tip',)))
1261
self.assertEqual(['fulltext'], index.get_options(('parent',)))
2467
1263
def test_get_options(self):
2468
1264
index = self.two_graph_index()
2469
self.assertEqual(['fulltext', 'no-eol'], index.get_options('tip'))
2470
self.assertEqual(['fulltext'], index.get_options('parent'))
2472
def test_get_parents_with_ghosts(self):
2473
index = self.two_graph_index()
2474
self.assertEqual((), index.get_parents_with_ghosts('parent'))
2475
# and errors on ghosts.
2476
self.assertRaises(errors.RevisionNotPresent,
2477
index.get_parents_with_ghosts, 'ghost')
2479
def test_check_versions_present(self):
2480
index = self.two_graph_index()
2481
self.assertRaises(RevisionNotPresent, index.check_versions_present,
2483
self.assertRaises(RevisionNotPresent, index.check_versions_present,
2484
['tail', 'missing'])
2485
index.check_versions_present(['tail', 'separate'])
1265
self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1266
self.assertEqual(['fulltext'], index.get_options(('parent',)))
1268
def test_get_parent_map(self):
1269
index = self.two_graph_index()
1270
self.assertEqual({('parent',):None},
1271
index.get_parent_map([('parent',), ('ghost',)]))
2487
1273
def catch_add(self, entries):
2488
1274
self.caught_entries.append(entries)
2490
1276
def test_add_no_callback_errors(self):
2491
1277
index = self.two_graph_index()
2492
self.assertRaises(errors.ReadOnlyError, index.add_version,
2493
'new', 'fulltext,no-eol', (None, 50, 60), ['separate'])
1278
self.assertRaises(errors.ReadOnlyError, index.add_records,
1279
[(('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)])])
2495
1281
def test_add_version_smoke(self):
2496
1282
index = self.two_graph_index(catch_adds=True)
2497
index.add_version('new', 'fulltext,no-eol', (None, 50, 60), [])
1283
index.add_records([(('new',), 'fulltext,no-eol', (None, 50, 60), [])])
2498
1284
self.assertEqual([[(('new', ), 'N50 60')]],
2499
1285
self.caught_entries)
2501
1287
def test_add_version_delta_not_delta_index(self):
2502
1288
index = self.two_graph_index(catch_adds=True)
2503
self.assertRaises(errors.KnitCorrupt, index.add_version,
2504
'new', 'no-eol,line-delta', (None, 0, 100), [])
1289
self.assertRaises(errors.KnitCorrupt, index.add_records,
1290
[(('new',), 'no-eol,line-delta', (None, 0, 100), [])])
2505
1291
self.assertEqual([], self.caught_entries)
2507
1293
def test_add_version_same_dup(self):
2508
1294
index = self.two_graph_index(catch_adds=True)
2509
1295
# options can be spelt two different ways
2510
index.add_version('tip', 'fulltext,no-eol', (None, 0, 100), [])
2511
index.add_version('tip', 'no-eol,fulltext', (None, 0, 100), [])
1296
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
1297
index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [])])
1298
# position/length are ignored (because each pack could have fulltext or
1299
# delta, and be at a different position.
1300
index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100), [])])
1301
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000), [])])
2512
1302
# but neither should have added data.
2513
self.assertEqual([[], []], self.caught_entries)
1303
self.assertEqual([[], [], [], []], self.caught_entries)
2515
1305
def test_add_version_different_dup(self):
2516
1306
index = self.two_graph_index(catch_adds=True)
2517
1307
# change options
2518
self.assertRaises(errors.KnitCorrupt, index.add_version,
2519
'tip', 'no-eol,line-delta', (None, 0, 100), [])
2520
self.assertRaises(errors.KnitCorrupt, index.add_version,
2521
'tip', 'line-delta,no-eol', (None, 0, 100), [])
2522
self.assertRaises(errors.KnitCorrupt, index.add_version,
2523
'tip', 'fulltext', (None, 0, 100), [])
2525
self.assertRaises(errors.KnitCorrupt, index.add_version,
2526
'tip', 'fulltext,no-eol', (None, 50, 100), [])
2527
self.assertRaises(errors.KnitCorrupt, index.add_version,
2528
'tip', 'fulltext,no-eol', (None, 0, 1000), [])
1308
self.assertRaises(errors.KnitCorrupt, index.add_records,
1309
[(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
1310
self.assertRaises(errors.KnitCorrupt, index.add_records,
1311
[(('tip',), 'line-delta,no-eol', (None, 0, 100), [])])
1312
self.assertRaises(errors.KnitCorrupt, index.add_records,
1313
[(('tip',), 'fulltext', (None, 0, 100), [])])
2530
self.assertRaises(errors.KnitCorrupt, index.add_version,
2531
'tip', 'fulltext,no-eol', (None, 0, 100), ['parent'])
1315
self.assertRaises(errors.KnitCorrupt, index.add_records,
1316
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
2532
1317
self.assertEqual([], self.caught_entries)
2534
1319
def test_add_versions(self):
2535
1320
index = self.two_graph_index(catch_adds=True)
2536
index.add_versions([
2537
('new', 'fulltext,no-eol', (None, 50, 60), []),
2538
('new2', 'fulltext', (None, 0, 6), []),
1322
(('new',), 'fulltext,no-eol', (None, 50, 60), []),
1323
(('new2',), 'fulltext', (None, 0, 6), []),
2540
1325
self.assertEqual([(('new', ), 'N50 60'), (('new2', ), ' 0 6')],
2541
1326
sorted(self.caught_entries[0]))
2544
1329
def test_add_versions_delta_not_delta_index(self):
2545
1330
index = self.two_graph_index(catch_adds=True)
2546
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2547
[('new', 'no-eol,line-delta', (None, 0, 100), ['parent'])])
1331
self.assertRaises(errors.KnitCorrupt, index.add_records,
1332
[(('new',), 'no-eol,line-delta', (None, 0, 100), [('parent',)])])
2548
1333
self.assertEqual([], self.caught_entries)
2550
1335
def test_add_versions_parents_not_parents_index(self):
2551
1336
index = self.two_graph_index(catch_adds=True)
2552
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2553
[('new', 'no-eol,fulltext', (None, 0, 100), ['parent'])])
1337
self.assertRaises(errors.KnitCorrupt, index.add_records,
1338
[(('new',), 'no-eol,fulltext', (None, 0, 100), [('parent',)])])
2554
1339
self.assertEqual([], self.caught_entries)
2556
1341
def test_add_versions_random_id_accepted(self):
2557
1342
index = self.two_graph_index(catch_adds=True)
2558
index.add_versions([], random_id=True)
1343
index.add_records([], random_id=True)
2560
1345
def test_add_versions_same_dup(self):
2561
1346
index = self.two_graph_index(catch_adds=True)
2562
1347
# options can be spelt two different ways
2563
index.add_versions([('tip', 'fulltext,no-eol', (None, 0, 100), [])])
2564
index.add_versions([('tip', 'no-eol,fulltext', (None, 0, 100), [])])
1348
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
1349
index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [])])
1350
# position/length are ignored (because each pack could have fulltext or
1351
# delta, and be at a different position.
1352
index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100), [])])
1353
index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000), [])])
2565
1354
# but neither should have added data.
2566
self.assertEqual([[], []], self.caught_entries)
1355
self.assertEqual([[], [], [], []], self.caught_entries)
2568
1357
def test_add_versions_different_dup(self):
2569
1358
index = self.two_graph_index(catch_adds=True)
2570
1359
# change options
2571
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2572
[('tip', 'no-eol,line-delta', (None, 0, 100), [])])
2573
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2574
[('tip', 'line-delta,no-eol', (None, 0, 100), [])])
2575
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2576
[('tip', 'fulltext', (None, 0, 100), [])])
2578
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2579
[('tip', 'fulltext,no-eol', (None, 50, 100), [])])
2580
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2581
[('tip', 'fulltext,no-eol', (None, 0, 1000), [])])
1360
self.assertRaises(errors.KnitCorrupt, index.add_records,
1361
[(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
1362
self.assertRaises(errors.KnitCorrupt, index.add_records,
1363
[(('tip',), 'line-delta,no-eol', (None, 0, 100), [])])
1364
self.assertRaises(errors.KnitCorrupt, index.add_records,
1365
[(('tip',), 'fulltext', (None, 0, 100), [])])
2583
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2584
[('tip', 'fulltext,no-eol', (None, 0, 100), ['parent'])])
1367
self.assertRaises(errors.KnitCorrupt, index.add_records,
1368
[(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
2585
1369
# change options in the second record
2586
self.assertRaises(errors.KnitCorrupt, index.add_versions,
2587
[('tip', 'fulltext,no-eol', (None, 0, 100), []),
2588
('tip', 'no-eol,line-delta', (None, 0, 100), [])])
1370
self.assertRaises(errors.KnitCorrupt, index.add_records,
1371
[(('tip',), 'fulltext,no-eol', (None, 0, 100), []),
1372
(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
2589
1373
self.assertEqual([], self.caught_entries)
2591
class TestPackKnits(KnitTests):
2592
"""Tests that use a _PackAccess and KnitGraphIndex."""
2594
def test_get_data_stream_packs_ignores_pack_overhead(self):
2595
# Packs have an encoding overhead that should not be included in the
2596
# 'size' field of a data stream, because it is not returned by the
2597
# raw_reading functions - it is why index_memo's are opaque, and
2598
# get_data_stream was abusing this.
2599
packname = 'test.pack'
2600
transport = self.get_transport()
2601
def write_data(bytes):
2602
transport.append_bytes(packname, bytes)
2603
writer = pack.ContainerWriter(write_data)
2605
index = InMemoryGraphIndex(2)
2606
knit_index = KnitGraphIndex(index, add_callback=index.add_nodes,
2608
indices = {index:(transport, packname)}
2609
access = _PackAccess(indices, writer=(writer, index))
2610
k = KnitVersionedFile('test', get_transport('.'),
2611
delta=True, create=True, index=knit_index, access_method=access)
2612
# insert something into the knit
2613
k.add_lines('text-1', [], ["foo\n"])
2614
# get a data stream for it
2615
stream = k.get_data_stream(['text-1'])
2616
# if the stream has been incorrectly assembled, we will get a short read
2617
# reading from the stream (as streams have no trailer)
2618
expected_length = stream[1][0][2]
2619
# we use -1 to do the read, so that if a trailer is added this test
2620
# will fail and we'll adjust it to handle that case correctly, rather
2621
# than allowing an over-read that is bogus.
2622
self.assertEqual(expected_length, len(stream[2](-1)))
2625
class Test_StreamIndex(KnitTests):
2627
def get_index(self, knit, stream):
2628
"""Get a _StreamIndex from knit and stream."""
2629
return knit._knit_from_datastream(stream)._index
2631
def assertIndexVersions(self, knit, versions):
2632
"""Check that the _StreamIndex versions are those of the stream."""
2633
index = self.get_index(knit, knit.get_data_stream(versions))
2634
self.assertEqual(set(index.get_versions()), set(versions))
2635
# check we didn't get duplicates
2636
self.assertEqual(len(index.get_versions()), len(versions))
2638
def assertIndexAncestry(self, knit, ancestry_versions, versions, result):
2639
"""Check the result of a get_ancestry call on knit."""
2640
index = self.get_index(knit, knit.get_data_stream(versions))
2643
set(index.get_ancestry(ancestry_versions, False)))
2645
def assertGetMethod(self, knit, versions, version, result):
2646
index = self.get_index(knit, knit.get_data_stream(versions))
2647
self.assertEqual(result, index.get_method(version))
2649
def assertGetOptions(self, knit, version, options):
2650
index = self.get_index(knit, knit.get_data_stream(version))
2651
self.assertEqual(options, index.get_options(version))
2653
def assertGetPosition(self, knit, versions, version, result):
2654
index = self.get_index(knit, knit.get_data_stream(versions))
2655
if result[1] is None:
2656
result = (result[0], index, result[2], result[3])
2657
self.assertEqual(result, index.get_position(version))
2659
def assertGetParentsWithGhosts(self, knit, versions, version, parents):
2660
index = self.get_index(knit, knit.get_data_stream(versions))
2661
self.assertEqual(parents, index.get_parents_with_ghosts(version))
2663
def make_knit_with_4_versions_2_dags(self):
2664
knit = self.make_test_knit()
2665
knit.add_lines('a', [], ["foo"])
2666
knit.add_lines('b', [], [])
2667
knit.add_lines('c', ['b', 'a'], [])
2668
knit.add_lines_with_ghosts('d', ['e', 'f'], [])
2671
def test_versions(self):
2672
"""The versions of a StreamIndex are those of the datastream."""
2673
knit = self.make_knit_with_4_versions_2_dags()
2674
# ask for most permutations, which catches bugs like falling back to the
2675
# target knit, or showing ghosts, etc.
2676
self.assertIndexVersions(knit, [])
2677
self.assertIndexVersions(knit, ['a'])
2678
self.assertIndexVersions(knit, ['b'])
2679
self.assertIndexVersions(knit, ['c'])
2680
self.assertIndexVersions(knit, ['d'])
2681
self.assertIndexVersions(knit, ['a', 'b'])
2682
self.assertIndexVersions(knit, ['b', 'c'])
2683
self.assertIndexVersions(knit, ['a', 'c'])
2684
self.assertIndexVersions(knit, ['a', 'b', 'c'])
2685
self.assertIndexVersions(knit, ['a', 'b', 'c', 'd'])
2687
def test_construct(self):
2688
"""Constructing a StreamIndex generates index data."""
2689
data_list = [('text-a', ['fulltext'], 127, []),
2690
('text-b', ['option'], 128, ['text-c'])]
2691
index = _StreamIndex(data_list, None)
2692
self.assertEqual({'text-a':(['fulltext'], (0, 127), []),
2693
'text-b':(['option'], (127, 127 + 128), ['text-c'])},
2696
def test_get_ancestry(self):
2697
knit = self.make_knit_with_4_versions_2_dags()
2698
self.assertIndexAncestry(knit, ['a'], ['a'], ['a'])
2699
self.assertIndexAncestry(knit, ['b'], ['b'], ['b'])
2700
self.assertIndexAncestry(knit, ['c'], ['c'], ['c'])
2701
self.assertIndexAncestry(knit, ['c'], ['a', 'b', 'c'],
2702
set(['a', 'b', 'c']))
2703
self.assertIndexAncestry(knit, ['c', 'd'], ['a', 'b', 'c', 'd'],
2704
set(['a', 'b', 'c', 'd']))
2706
def test_get_method(self):
2707
knit = self.make_knit_with_4_versions_2_dags()
2708
self.assertGetMethod(knit, ['a'], 'a', 'fulltext')
2709
self.assertGetMethod(knit, ['c'], 'c', 'line-delta')
2710
# get_method on a basis that is not in the datastream (but in the
2711
# backing knit) returns 'fulltext', because thats what we'll create as
2713
self.assertGetMethod(knit, ['c'], 'b', 'fulltext')
2715
def test_get_options(self):
2716
knit = self.make_knit_with_4_versions_2_dags()
2717
self.assertGetOptions(knit, 'a', ['no-eol', 'fulltext'])
2718
self.assertGetOptions(knit, 'c', ['line-delta'])
2720
def test_get_parents_with_ghosts(self):
2721
knit = self.make_knit_with_4_versions_2_dags()
2722
self.assertGetParentsWithGhosts(knit, ['a'], 'a', ())
2723
self.assertGetParentsWithGhosts(knit, ['c'], 'c', ('b', 'a'))
2724
self.assertGetParentsWithGhosts(knit, ['d'], 'd', ('e', 'f'))
2726
def test_get_position(self):
2727
knit = self.make_knit_with_4_versions_2_dags()
2728
# get_position returns (thunk_flag, index(can be None), start, end) for
2729
# _StreamAccess to use.
2730
self.assertGetPosition(knit, ['a'], 'a', (False, None, 0, 78))
2731
self.assertGetPosition(knit, ['a', 'c'], 'c', (False, None, 78, 156))
2732
# get_position on a text that is not in the datastream (but in the
2733
# backing knit) returns (True, 'versionid', None, None) - and then the
2734
# access object can construct the relevant data as needed.
2735
self.assertGetPosition(knit, ['a', 'c'], 'b', (True, 'b', None, None))
2738
class Test_StreamAccess(KnitTests):
2740
def get_index_access(self, knit, stream):
2741
"""Get a _StreamAccess from knit and stream."""
2742
knit = knit._knit_from_datastream(stream)
2743
return knit._index, knit._data._access
2745
def assertGetRawRecords(self, knit, versions):
2746
index, access = self.get_index_access(knit,
2747
knit.get_data_stream(versions))
2748
# check that every version asked for can be obtained from the resulting
2752
for version in versions:
2753
memos.append(knit._index.get_position(version))
2755
for version, data in zip(
2756
versions, knit._data._access.get_raw_records(memos)):
2757
original[version] = data
2759
for version in versions:
2760
memos.append(index.get_position(version))
2762
for version, data in zip(versions, access.get_raw_records(memos)):
2763
streamed[version] = data
2764
self.assertEqual(original, streamed)
2766
for version in versions:
2767
data = list(access.get_raw_records(
2768
[index.get_position(version)]))[0]
2769
self.assertEqual(original[version], data)
2771
def make_knit_with_two_versions(self):
2772
knit = self.make_test_knit()
2773
knit.add_lines('a', [], ["foo"])
2774
knit.add_lines('b', [], ["bar"])
2777
def test_get_raw_records(self):
2778
knit = self.make_knit_with_two_versions()
2779
self.assertGetRawRecords(knit, ['a', 'b'])
2780
self.assertGetRawRecords(knit, ['a'])
2781
self.assertGetRawRecords(knit, ['b'])
2783
def test_get_raw_record_from_backing_knit(self):
2784
# the thunk layer should create an artificial A on-demand when needed.
2785
source_knit = self.make_test_knit(name='plain', annotate=False)
2786
target_knit = self.make_test_knit(name='annotated', annotate=True)
2787
source_knit.add_lines("A", [], ["Foo\n"])
2788
# Give the target A, so we can try to thunk across to it.
2789
target_knit.insert_record_stream(source_knit.get_record_stream(['A'],
2790
'unordered', False))
2791
index, access = self.get_index_access(target_knit,
2792
source_knit.get_data_stream([]))
2793
raw_data = list(access.get_raw_records([(True, "A", None, None)]))[0]
2794
df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
2796
'version A 1 5d36b88bb697a2d778f024048bafabd443d74503\n'
2800
def test_asking_for_thunk_stream_is_not_plain_errors(self):
2801
knit = self.make_test_knit(name='annotated', annotate=True)
2802
knit.add_lines("A", [], ["Foo\n"])
2803
index, access = self.get_index_access(knit,
2804
knit.get_data_stream([]))
2805
self.assertRaises(errors.KnitCorrupt,
2806
list, access.get_raw_records([(True, "A", None, None)]))
2809
class TestFormatSignatures(KnitTests):
2811
def test_knit_format_signatures(self):
2812
"""Different formats of knit have different signature strings."""
2813
knit = self.make_test_knit(name='a', annotate=True)
2814
self.assertEqual('knit-annotated', knit.get_format_signature())
2815
knit = self.make_test_knit(name='p', annotate=False)
2816
self.assertEqual('knit-plain', knit.get_format_signature())