~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_knit.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-06-28 07:08:27 UTC
  • mfrom: (2553.1.3 integration)
  • Revision ID: pqm@pqm.ubuntu.com-20070628070827-h5s313dg5tnag9vj
(robertc) Show the names of commit hooks during commit.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006 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
20
20
import difflib
21
21
import gzip
22
22
import sha
23
 
import sys
24
23
 
25
24
from bzrlib import (
26
25
    errors,
27
 
    generate_ids,
28
 
    knit,
29
26
    )
30
27
from bzrlib.errors import (
31
28
    RevisionAlreadyPresent,
33
30
    RevisionNotPresent,
34
31
    NoSuchFile,
35
32
    )
36
 
from bzrlib.index import *
37
33
from bzrlib.knit import (
38
34
    KnitContent,
39
 
    KnitGraphIndex,
40
35
    KnitVersionedFile,
41
36
    KnitPlainFactory,
42
37
    KnitAnnotateFactory,
43
38
    _KnitData,
44
39
    _KnitIndex,
45
40
    WeaveToKnit,
46
 
    KnitSequenceMatcher,
47
41
    )
48
42
from bzrlib.osutils import split_lines
49
 
from bzrlib.tests import TestCase, TestCaseWithTransport, Feature
 
43
from bzrlib.tests import TestCase, TestCaseWithTransport
50
44
from bzrlib.transport import TransportLogger, get_transport
51
45
from bzrlib.transport.memory import MemoryTransport
52
46
from bzrlib.weave import Weave
53
47
 
54
48
 
55
 
class _CompiledKnitFeature(Feature):
56
 
 
57
 
    def _probe(self):
58
 
        try:
59
 
            import bzrlib._knit_load_data_c
60
 
        except ImportError:
61
 
            return False
62
 
        return True
63
 
 
64
 
    def feature_name(self):
65
 
        return 'bzrlib._knit_load_data_c'
66
 
 
67
 
CompiledKnitFeature = _CompiledKnitFeature()
68
 
 
69
 
 
70
49
class KnitContentTests(TestCase):
71
50
 
72
51
    def test_constructor(self):
261
240
 
262
241
class LowLevelKnitIndexTests(TestCase):
263
242
 
264
 
    def get_knit_index(self, *args, **kwargs):
265
 
        orig = knit._load_data
266
 
        def reset():
267
 
            knit._load_data = orig
268
 
        self.addCleanup(reset)
269
 
        from bzrlib._knit_load_data_py import _load_data_py
270
 
        knit._load_data = _load_data_py
271
 
        return _KnitIndex(*args, **kwargs)
272
 
 
273
243
    def test_no_such_file(self):
274
244
        transport = MockTransport()
275
245
 
276
 
        self.assertRaises(NoSuchFile, self.get_knit_index,
277
 
                          transport, "filename", "r")
278
 
        self.assertRaises(NoSuchFile, self.get_knit_index,
279
 
                          transport, "filename", "w", create=False)
 
246
        self.assertRaises(NoSuchFile, _KnitIndex, transport, "filename", "r")
 
247
        self.assertRaises(NoSuchFile, _KnitIndex, transport,
 
248
            "filename", "w", create=False)
280
249
 
281
250
    def test_create_file(self):
282
251
        transport = MockTransport()
283
252
 
284
 
        index = self.get_knit_index(transport, "filename", "w",
 
253
        index = _KnitIndex(transport, "filename", "w",
285
254
            file_mode="wb", create=True)
286
255
        self.assertEqual(
287
256
                ("put_bytes_non_atomic",
291
260
    def test_delay_create_file(self):
292
261
        transport = MockTransport()
293
262
 
294
 
        index = self.get_knit_index(transport, "filename", "w",
 
263
        index = _KnitIndex(transport, "filename", "w",
295
264
            create=True, file_mode="wb", create_parent_dir=True,
296
265
            delay_create=True, dir_mode=0777)
297
266
        self.assertEqual([], transport.calls)
316
285
            _KnitIndex.HEADER,
317
286
            '%s option 0 1 :' % (utf8_revision_id,)
318
287
            ])
319
 
        index = self.get_knit_index(transport, "filename", "r")
 
288
        index = _KnitIndex(transport, "filename", "r")
320
289
        # _KnitIndex is a private class, and deals in utf8 revision_ids, not
321
290
        # Unicode revision_ids.
322
291
        self.assertTrue(index.has_version(utf8_revision_id))
329
298
            _KnitIndex.HEADER,
330
299
            "version option 0 1 .%s :" % (utf8_revision_id,)
331
300
            ])
332
 
        index = self.get_knit_index(transport, "filename", "r")
 
301
        index = _KnitIndex(transport, "filename", "r")
333
302
        self.assertEqual([utf8_revision_id],
334
303
            index.get_parents_with_ghosts("version"))
335
304
 
340
309
            "corrupted options 0 1 .b .c ",
341
310
            "version options 0 1 :"
342
311
            ])
343
 
        index = self.get_knit_index(transport, "filename", "r")
 
312
        index = _KnitIndex(transport, "filename", "r")
344
313
        self.assertEqual(1, index.num_versions())
345
314
        self.assertTrue(index.has_version("version"))
346
315
 
347
316
    def test_read_corrupted_header(self):
348
317
        transport = MockTransport(['not a bzr knit index header\n'])
349
318
        self.assertRaises(KnitHeaderError,
350
 
            self.get_knit_index, transport, "filename", "r")
 
319
            _KnitIndex, transport, "filename", "r")
351
320
 
352
321
    def test_read_duplicate_entries(self):
353
322
        transport = MockTransport([
357
326
            "version options2 1 2 .other :",
358
327
            "version options3 3 4 0 .other :"
359
328
            ])
360
 
        index = self.get_knit_index(transport, "filename", "r")
 
329
        index = _KnitIndex(transport, "filename", "r")
361
330
        self.assertEqual(2, index.num_versions())
362
 
        # check that the index used is the first one written. (Specific
363
 
        # to KnitIndex style indices.
364
 
        self.assertEqual("1", index._version_list_to_index(["version"]))
 
331
        self.assertEqual(1, index.lookup("version"))
365
332
        self.assertEqual((3, 4), index.get_position("version"))
366
333
        self.assertEqual(["options3"], index.get_options("version"))
367
334
        self.assertEqual(["parent", "other"],
374
341
            "b option 0 1 0 :",
375
342
            "c option 0 1 1 0 :",
376
343
            ])
377
 
        index = self.get_knit_index(transport, "filename", "r")
 
344
        index = _KnitIndex(transport, "filename", "r")
378
345
        self.assertEqual(["a"], index.get_parents("b"))
379
346
        self.assertEqual(["b", "a"], index.get_parents("c"))
380
347
 
384
351
        transport = MockTransport([
385
352
            _KnitIndex.HEADER
386
353
            ])
387
 
        index = self.get_knit_index(transport, "filename", "r")
 
354
        index = _KnitIndex(transport, "filename", "r")
388
355
        index.add_version(utf8_revision_id, ["option"], 0, 1, [])
389
356
        self.assertEqual(("append_bytes", ("filename",
390
357
            "\n%s option 0 1  :" % (utf8_revision_id,)),
397
364
        transport = MockTransport([
398
365
            _KnitIndex.HEADER
399
366
            ])
400
 
        index = self.get_knit_index(transport, "filename", "r")
 
367
        index = _KnitIndex(transport, "filename", "r")
401
368
        index.add_version("version", ["option"], 0, 1, [utf8_revision_id])
402
369
        self.assertEqual(("append_bytes", ("filename",
403
370
            "\nversion option 0 1 .%s :" % (utf8_revision_id,)),
406
373
 
407
374
    def test_get_graph(self):
408
375
        transport = MockTransport()
409
 
        index = self.get_knit_index(transport, "filename", "w", create=True)
 
376
        index = _KnitIndex(transport, "filename", "w", create=True)
410
377
        self.assertEqual([], index.get_graph())
411
378
 
412
379
        index.add_version("a", ["option"], 0, 1, ["b"])
424
391
            "c option 0 1 1 0 :",
425
392
            "d option 0 1 2 .f :"
426
393
            ])
427
 
        index = self.get_knit_index(transport, "filename", "r")
 
394
        index = _KnitIndex(transport, "filename", "r")
428
395
 
429
396
        self.assertEqual([], index.get_ancestry([]))
430
397
        self.assertEqual(["a"], index.get_ancestry(["a"]))
444
411
            "c option 0 1 0 .f .g :",
445
412
            "d option 0 1 2 .h .j .k :"
446
413
            ])
447
 
        index = self.get_knit_index(transport, "filename", "r")
 
414
        index = _KnitIndex(transport, "filename", "r")
448
415
 
449
416
        self.assertEqual([], index.get_ancestry_with_ghosts([]))
450
417
        self.assertEqual(["a"], index.get_ancestry_with_ghosts(["a"]))
465
432
        self.assertRaises(RevisionNotPresent,
466
433
            index.get_ancestry_with_ghosts, ["e"])
467
434
 
468
 
    def test_iter_parents(self):
469
 
        transport = MockTransport()
470
 
        index = self.get_knit_index(transport, "filename", "w", create=True)
471
 
        # no parents
472
 
        index.add_version('r0', ['option'], 0, 1, [])
473
 
        # 1 parent
474
 
        index.add_version('r1', ['option'], 0, 1, ['r0'])
475
 
        # 2 parents
476
 
        index.add_version('r2', ['option'], 0, 1, ['r1', 'r0'])
477
 
        # XXX TODO a ghost
478
 
        # cases: each sample data individually:
479
 
        self.assertEqual(set([('r0', ())]),
480
 
            set(index.iter_parents(['r0'])))
481
 
        self.assertEqual(set([('r1', ('r0', ))]),
482
 
            set(index.iter_parents(['r1'])))
483
 
        self.assertEqual(set([('r2', ('r1', 'r0'))]),
484
 
            set(index.iter_parents(['r2'])))
485
 
        # no nodes returned for a missing node
486
 
        self.assertEqual(set(),
487
 
            set(index.iter_parents(['missing'])))
488
 
        # 1 node returned with missing nodes skipped
489
 
        self.assertEqual(set([('r1', ('r0', ))]),
490
 
            set(index.iter_parents(['ghost1', 'r1', 'ghost'])))
491
 
        # 2 nodes returned
492
 
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
493
 
            set(index.iter_parents(['r0', 'r1'])))
494
 
        # 2 nodes returned, missing skipped
495
 
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
496
 
            set(index.iter_parents(['a', 'r0', 'b', 'r1', 'c'])))
497
 
 
498
435
    def test_num_versions(self):
499
436
        transport = MockTransport([
500
437
            _KnitIndex.HEADER
501
438
            ])
502
 
        index = self.get_knit_index(transport, "filename", "r")
 
439
        index = _KnitIndex(transport, "filename", "r")
503
440
 
504
441
        self.assertEqual(0, index.num_versions())
505
442
        self.assertEqual(0, len(index))
520
457
        transport = MockTransport([
521
458
            _KnitIndex.HEADER
522
459
            ])
523
 
        index = self.get_knit_index(transport, "filename", "r")
 
460
        index = _KnitIndex(transport, "filename", "r")
524
461
 
525
462
        self.assertEqual([], index.get_versions())
526
463
 
533
470
        index.add_version("b", ["option"], 0, 1, [])
534
471
        self.assertEqual(["a", "b"], index.get_versions())
535
472
 
 
473
    def test_idx_to_name(self):
 
474
        transport = MockTransport([
 
475
            _KnitIndex.HEADER,
 
476
            "a option 0 1 :",
 
477
            "b option 0 1 :"
 
478
            ])
 
479
        index = _KnitIndex(transport, "filename", "r")
 
480
 
 
481
        self.assertEqual("a", index.idx_to_name(0))
 
482
        self.assertEqual("b", index.idx_to_name(1))
 
483
        self.assertEqual("b", index.idx_to_name(-1))
 
484
        self.assertEqual("a", index.idx_to_name(-2))
 
485
 
 
486
    def test_lookup(self):
 
487
        transport = MockTransport([
 
488
            _KnitIndex.HEADER,
 
489
            "a option 0 1 :",
 
490
            "b option 0 1 :"
 
491
            ])
 
492
        index = _KnitIndex(transport, "filename", "r")
 
493
 
 
494
        self.assertEqual(0, index.lookup("a"))
 
495
        self.assertEqual(1, index.lookup("b"))
 
496
 
536
497
    def test_add_version(self):
537
498
        transport = MockTransport([
538
499
            _KnitIndex.HEADER
539
500
            ])
540
 
        index = self.get_knit_index(transport, "filename", "r")
 
501
        index = _KnitIndex(transport, "filename", "r")
541
502
 
542
503
        index.add_version("a", ["option"], 0, 1, ["b"])
543
504
        self.assertEqual(("append_bytes",
573
534
        transport = MockTransport([
574
535
            _KnitIndex.HEADER
575
536
            ])
576
 
        index = self.get_knit_index(transport, "filename", "r")
 
537
        index = _KnitIndex(transport, "filename", "r")
577
538
 
578
539
        index.add_versions([
579
540
            ("a", ["option"], 0, 1, ["b"]),
598
559
    def test_delay_create_and_add_versions(self):
599
560
        transport = MockTransport()
600
561
 
601
 
        index = self.get_knit_index(transport, "filename", "w",
 
562
        index = _KnitIndex(transport, "filename", "w",
602
563
            create=True, file_mode="wb", create_parent_dir=True,
603
564
            delay_create=True, dir_mode=0777)
604
565
        self.assertEqual([], transport.calls)
626
587
            _KnitIndex.HEADER,
627
588
            "a option 0 1 :"
628
589
            ])
629
 
        index = self.get_knit_index(transport, "filename", "r")
 
590
        index = _KnitIndex(transport, "filename", "r")
630
591
 
631
592
        self.assertTrue(index.has_version("a"))
632
593
        self.assertFalse(index.has_version("b"))
637
598
            "a option 0 1 :",
638
599
            "b option 1 2 :"
639
600
            ])
640
 
        index = self.get_knit_index(transport, "filename", "r")
 
601
        index = _KnitIndex(transport, "filename", "r")
641
602
 
642
603
        self.assertEqual((0, 1), index.get_position("a"))
643
604
        self.assertEqual((1, 2), index.get_position("b"))
649
610
            "b unknown,line-delta 1 2 :",
650
611
            "c bad 3 4 :"
651
612
            ])
652
 
        index = self.get_knit_index(transport, "filename", "r")
 
613
        index = _KnitIndex(transport, "filename", "r")
653
614
 
654
615
        self.assertEqual("fulltext", index.get_method("a"))
655
616
        self.assertEqual("line-delta", index.get_method("b"))
661
622
            "a opt1 0 1 :",
662
623
            "b opt2,opt3 1 2 :"
663
624
            ])
664
 
        index = self.get_knit_index(transport, "filename", "r")
 
625
        index = _KnitIndex(transport, "filename", "r")
665
626
 
666
627
        self.assertEqual(["opt1"], index.get_options("a"))
667
628
        self.assertEqual(["opt2", "opt3"], index.get_options("b"))
673
634
            "b option 1 2 0 .c :",
674
635
            "c option 1 2 1 0 .e :"
675
636
            ])
676
 
        index = self.get_knit_index(transport, "filename", "r")
 
637
        index = _KnitIndex(transport, "filename", "r")
677
638
 
678
639
        self.assertEqual([], index.get_parents("a"))
679
640
        self.assertEqual(["a", "c"], index.get_parents("b"))
686
647
            "b option 1 2 0 .c :",
687
648
            "c option 1 2 1 0 .e :"
688
649
            ])
689
 
        index = self.get_knit_index(transport, "filename", "r")
 
650
        index = _KnitIndex(transport, "filename", "r")
690
651
 
691
652
        self.assertEqual([], index.get_parents_with_ghosts("a"))
692
653
        self.assertEqual(["a", "c"], index.get_parents_with_ghosts("b"))
699
660
            "a option 0 1 :",
700
661
            "b option 0 1 :"
701
662
            ])
702
 
        index = self.get_knit_index(transport, "filename", "r")
 
663
        index = _KnitIndex(transport, "filename", "r")
703
664
 
704
665
        check = index.check_versions_present
705
666
 
710
671
        self.assertRaises(RevisionNotPresent, check, ["c"])
711
672
        self.assertRaises(RevisionNotPresent, check, ["a", "b", "c"])
712
673
 
713
 
    def test_impossible_parent(self):
714
 
        """Test we get KnitCorrupt if the parent couldn't possibly exist."""
715
 
        transport = MockTransport([
716
 
            _KnitIndex.HEADER,
717
 
            "a option 0 1 :",
718
 
            "b option 0 1 4 :"  # We don't have a 4th record
719
 
            ])
720
 
        try:
721
 
            self.assertRaises(errors.KnitCorrupt,
722
 
                              self.get_knit_index, transport, 'filename', 'r')
723
 
        except TypeError, e:
724
 
            if (str(e) == ('exceptions must be strings, classes, or instances,'
725
 
                           ' not exceptions.IndexError')
726
 
                and sys.version_info[0:2] >= (2,5)):
727
 
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
728
 
                                  ' raising new style exceptions with python'
729
 
                                  ' >=2.5')
730
 
            else:
731
 
                raise
732
 
 
733
 
    def test_corrupted_parent(self):
734
 
        transport = MockTransport([
735
 
            _KnitIndex.HEADER,
736
 
            "a option 0 1 :",
737
 
            "b option 0 1 :",
738
 
            "c option 0 1 1v :", # Can't have a parent of '1v'
739
 
            ])
740
 
        try:
741
 
            self.assertRaises(errors.KnitCorrupt,
742
 
                              self.get_knit_index, transport, 'filename', 'r')
743
 
        except TypeError, e:
744
 
            if (str(e) == ('exceptions must be strings, classes, or instances,'
745
 
                           ' not exceptions.ValueError')
746
 
                and sys.version_info[0:2] >= (2,5)):
747
 
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
748
 
                                  ' raising new style exceptions with python'
749
 
                                  ' >=2.5')
750
 
            else:
751
 
                raise
752
 
 
753
 
    def test_corrupted_parent_in_list(self):
754
 
        transport = MockTransport([
755
 
            _KnitIndex.HEADER,
756
 
            "a option 0 1 :",
757
 
            "b option 0 1 :",
758
 
            "c option 0 1 1 v :", # Can't have a parent of 'v'
759
 
            ])
760
 
        try:
761
 
            self.assertRaises(errors.KnitCorrupt,
762
 
                              self.get_knit_index, transport, 'filename', 'r')
763
 
        except TypeError, e:
764
 
            if (str(e) == ('exceptions must be strings, classes, or instances,'
765
 
                           ' not exceptions.ValueError')
766
 
                and sys.version_info[0:2] >= (2,5)):
767
 
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
768
 
                                  ' raising new style exceptions with python'
769
 
                                  ' >=2.5')
770
 
            else:
771
 
                raise
772
 
 
773
 
    def test_invalid_position(self):
774
 
        transport = MockTransport([
775
 
            _KnitIndex.HEADER,
776
 
            "a option 1v 1 :",
777
 
            ])
778
 
        try:
779
 
            self.assertRaises(errors.KnitCorrupt,
780
 
                              self.get_knit_index, transport, 'filename', 'r')
781
 
        except TypeError, e:
782
 
            if (str(e) == ('exceptions must be strings, classes, or instances,'
783
 
                           ' not exceptions.ValueError')
784
 
                and sys.version_info[0:2] >= (2,5)):
785
 
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
786
 
                                  ' raising new style exceptions with python'
787
 
                                  ' >=2.5')
788
 
            else:
789
 
                raise
790
 
 
791
 
    def test_invalid_size(self):
792
 
        transport = MockTransport([
793
 
            _KnitIndex.HEADER,
794
 
            "a option 1 1v :",
795
 
            ])
796
 
        try:
797
 
            self.assertRaises(errors.KnitCorrupt,
798
 
                              self.get_knit_index, transport, 'filename', 'r')
799
 
        except TypeError, e:
800
 
            if (str(e) == ('exceptions must be strings, classes, or instances,'
801
 
                           ' not exceptions.ValueError')
802
 
                and sys.version_info[0:2] >= (2,5)):
803
 
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
804
 
                                  ' raising new style exceptions with python'
805
 
                                  ' >=2.5')
806
 
            else:
807
 
                raise
808
 
 
809
 
    def test_short_line(self):
810
 
        transport = MockTransport([
811
 
            _KnitIndex.HEADER,
812
 
            "a option 0 10  :",
813
 
            "b option 10 10 0", # This line isn't terminated, ignored
814
 
            ])
815
 
        index = self.get_knit_index(transport, "filename", "r")
816
 
        self.assertEqual(['a'], index.get_versions())
817
 
 
818
 
    def test_skip_incomplete_record(self):
819
 
        # A line with bogus data should just be skipped
820
 
        transport = MockTransport([
821
 
            _KnitIndex.HEADER,
822
 
            "a option 0 10  :",
823
 
            "b option 10 10 0", # This line isn't terminated, ignored
824
 
            "c option 20 10 0 :", # Properly terminated, and starts with '\n'
825
 
            ])
826
 
        index = self.get_knit_index(transport, "filename", "r")
827
 
        self.assertEqual(['a', 'c'], index.get_versions())
828
 
 
829
 
    def test_trailing_characters(self):
830
 
        # A line with bogus data should just be skipped
831
 
        transport = MockTransport([
832
 
            _KnitIndex.HEADER,
833
 
            "a option 0 10  :",
834
 
            "b option 10 10 0 :a", # This line has extra trailing characters
835
 
            "c option 20 10 0 :", # Properly terminated, and starts with '\n'
836
 
            ])
837
 
        index = self.get_knit_index(transport, "filename", "r")
838
 
        self.assertEqual(['a', 'c'], index.get_versions())
839
 
 
840
 
 
841
 
class LowLevelKnitIndexTests_c(LowLevelKnitIndexTests):
842
 
 
843
 
    _test_needs_features = [CompiledKnitFeature]
844
 
 
845
 
    def get_knit_index(self, *args, **kwargs):
846
 
        orig = knit._load_data
847
 
        def reset():
848
 
            knit._load_data = orig
849
 
        self.addCleanup(reset)
850
 
        from bzrlib._knit_load_data_c import _load_data_c
851
 
        knit._load_data = _load_data_c
852
 
        return _KnitIndex(*args, **kwargs)
853
 
 
854
 
 
855
674
 
856
675
class KnitTests(TestCaseWithTransport):
857
676
    """Class containing knit test helper routines."""
858
677
 
859
 
    def make_test_knit(self, annotate=False, delay_create=False, index=None):
 
678
    def make_test_knit(self, annotate=False, delay_create=False):
860
679
        if not annotate:
861
680
            factory = KnitPlainFactory()
862
681
        else:
863
682
            factory = None
864
683
        return KnitVersionedFile('test', get_transport('.'), access_mode='w',
865
684
                                 factory=factory, create=True,
866
 
                                 delay_create=delay_create, index=index)
 
685
                                 delay_create=delay_create)
867
686
 
868
687
 
869
688
class BasicKnitTests(KnitTests):
876
695
        """Construct empty k"""
877
696
        self.make_test_knit()
878
697
 
879
 
    def test_make_explicit_index(self):
880
 
        """We can supply an index to use."""
881
 
        knit = KnitVersionedFile('test', get_transport('.'),
882
 
            index='strangelove')
883
 
        self.assertEqual(knit._index, 'strangelove')
884
 
 
885
698
    def test_knit_add(self):
886
699
        """Store one text in knit and retrieve"""
887
700
        k = self.make_test_knit()
933
746
    def test_delta(self):
934
747
        """Expression of knit delta as lines"""
935
748
        k = self.make_test_knit()
936
 
        KnitContent
937
749
        td = list(line_delta(TEXT_1.splitlines(True),
938
750
                             TEXT_1A.splitlines(True)))
939
751
        self.assertEqualDiff(''.join(td), delta_1_1a)
940
752
        out = apply_line_delta(TEXT_1.splitlines(True), td)
941
753
        self.assertEqualDiff(''.join(out), TEXT_1A)
942
754
 
943
 
    def assertDerivedBlocksEqual(self, source, target, noeol=False):
944
 
        """Assert that the derived matching blocks match real output"""
945
 
        source_lines = source.splitlines(True)
946
 
        target_lines = target.splitlines(True)
947
 
        def nl(line):
948
 
            if noeol and not line.endswith('\n'):
949
 
                return line + '\n'
950
 
            else:
951
 
                return line
952
 
        source_content = KnitContent([(None, nl(l)) for l in source_lines])
953
 
        target_content = KnitContent([(None, nl(l)) for l in target_lines])
954
 
        line_delta = source_content.line_delta(target_content)
955
 
        delta_blocks = list(KnitContent.get_line_delta_blocks(line_delta,
956
 
            source_lines, target_lines))
957
 
        matcher = KnitSequenceMatcher(None, source_lines, target_lines)
958
 
        matcher_blocks = list(list(matcher.get_matching_blocks()))
959
 
        self.assertEqual(matcher_blocks, delta_blocks)
960
 
 
961
 
    def test_get_line_delta_blocks(self):
962
 
        self.assertDerivedBlocksEqual('a\nb\nc\n', 'q\nc\n')
963
 
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1)
964
 
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1A)
965
 
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1B)
966
 
        self.assertDerivedBlocksEqual(TEXT_1B, TEXT_1A)
967
 
        self.assertDerivedBlocksEqual(TEXT_1A, TEXT_1B)
968
 
        self.assertDerivedBlocksEqual(TEXT_1A, '')
969
 
        self.assertDerivedBlocksEqual('', TEXT_1A)
970
 
        self.assertDerivedBlocksEqual('', '')
971
 
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\nd')
972
 
 
973
 
    def test_get_line_delta_blocks_noeol(self):
974
 
        """Handle historical knit deltas safely
975
 
 
976
 
        Some existing knit deltas don't consider the last line to differ
977
 
        when the only difference whether it has a final newline.
978
 
 
979
 
        New knit deltas appear to always consider the last line to differ
980
 
        in this case.
981
 
        """
982
 
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\nd\n', noeol=True)
983
 
        self.assertDerivedBlocksEqual('a\nb\nc\nd\n', 'a\nb\nc', noeol=True)
984
 
        self.assertDerivedBlocksEqual('a\nb\nc\n', 'a\nb\nc', noeol=True)
985
 
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\n', noeol=True)
986
 
 
987
755
    def test_add_with_parents(self):
988
756
        """Store in knit with parents"""
989
757
        k = self.make_test_knit()
1005
773
        k.clear_cache()
1006
774
        self.assertEqualDiff(''.join(k.get_lines('text-1a')), TEXT_1A)
1007
775
 
1008
 
    def test_add_delta_knit_graph_index(self):
1009
 
        """Does adding work with a KnitGraphIndex."""
1010
 
        index = InMemoryGraphIndex(2)
1011
 
        knit_index = KnitGraphIndex(index, add_callback=index.add_nodes,
1012
 
            deltas=True)
1013
 
        k = KnitVersionedFile('test', get_transport('.'),
1014
 
            delta=True, create=True, index=knit_index)
1015
 
        self.add_stock_one_and_one_a(k)
1016
 
        k.clear_cache()
1017
 
        self.assertEqualDiff(''.join(k.get_lines('text-1a')), TEXT_1A)
1018
 
        # check the index had the right data added.
1019
 
        self.assertEqual(set([
1020
 
            (index, ('text-1', ), ' 0 127', ((), ())),
1021
 
            (index, ('text-1a', ), ' 127 140', ((('text-1', ),), (('text-1', ),))),
1022
 
            ]), set(index.iter_all_entries()))
1023
 
        # we should not have a .kndx file
1024
 
        self.assertFalse(get_transport('.').has('test.kndx'))
1025
 
 
1026
776
    def test_annotate(self):
1027
777
        """Annotations"""
1028
778
        k = KnitVersionedFile('knit', get_transport('.'), factory=KnitAnnotateFactory(),
1221
971
        knit = KnitVersionedFile('test', get_transport('.'), access_mode='r')
1222
972
        self.assertEqual(['revid', 'revid2'], knit.versions())
1223
973
        # write a short write to the file and ensure that its ignored
1224
 
        indexfile = file('test.kndx', 'ab')
 
974
        indexfile = file('test.kndx', 'at')
1225
975
        indexfile.write('\nrevid3 line-delta 166 82 1 2 3 4 5 .phwoar:demo ')
1226
976
        indexfile.close()
1227
977
        # we should be able to load this file again
1599
1349
        t.put_bytes('test.kndx', '# not really a knit header\n\n')
1600
1350
 
1601
1351
        self.assertRaises(KnitHeaderError, self.make_test_knit)
1602
 
 
1603
 
 
1604
 
class TestGraphIndexKnit(KnitTests):
1605
 
    """Tests for knits using a GraphIndex rather than a KnitIndex."""
1606
 
 
1607
 
    def make_g_index(self, name, ref_lists=0, nodes=[]):
1608
 
        builder = GraphIndexBuilder(ref_lists)
1609
 
        for node, references, value in nodes:
1610
 
            builder.add_node(node, references, value)
1611
 
        stream = builder.finish()
1612
 
        trans = self.get_transport()
1613
 
        trans.put_file(name, stream)
1614
 
        return GraphIndex(trans, name)
1615
 
 
1616
 
    def two_graph_index(self, deltas=False, catch_adds=False):
1617
 
        """Build a two-graph index.
1618
 
 
1619
 
        :param deltas: If true, use underlying indices with two node-ref
1620
 
            lists and 'parent' set to a delta-compressed against tail.
1621
 
        """
1622
 
        # build a complex graph across several indices.
1623
 
        if deltas:
1624
 
            # delta compression inn the index
1625
 
            index1 = self.make_g_index('1', 2, [
1626
 
                (('tip', ), 'N0 100', ([('parent', )], [], )),
1627
 
                (('tail', ), '', ([], []))])
1628
 
            index2 = self.make_g_index('2', 2, [
1629
 
                (('parent', ), ' 100 78', ([('tail', ), ('ghost', )], [('tail', )])),
1630
 
                (('separate', ), '', ([], []))])
1631
 
        else:
1632
 
            # just blob location and graph in the index.
1633
 
            index1 = self.make_g_index('1', 1, [
1634
 
                (('tip', ), 'N0 100', ([('parent', )], )),
1635
 
                (('tail', ), '', ([], ))])
1636
 
            index2 = self.make_g_index('2', 1, [
1637
 
                (('parent', ), ' 100 78', ([('tail', ), ('ghost', )], )),
1638
 
                (('separate', ), '', ([], ))])
1639
 
        combined_index = CombinedGraphIndex([index1, index2])
1640
 
        if catch_adds:
1641
 
            self.combined_index = combined_index
1642
 
            self.caught_entries = []
1643
 
            add_callback = self.catch_add
1644
 
        else:
1645
 
            add_callback = None
1646
 
        return KnitGraphIndex(combined_index, deltas=deltas,
1647
 
            add_callback=add_callback)
1648
 
 
1649
 
    def test_get_graph(self):
1650
 
        index = self.two_graph_index()
1651
 
        self.assertEqual(set([
1652
 
            ('tip', ('parent', )),
1653
 
            ('tail', ()),
1654
 
            ('parent', ('tail', 'ghost')),
1655
 
            ('separate', ()),
1656
 
            ]), set(index.get_graph()))
1657
 
 
1658
 
    def test_get_ancestry(self):
1659
 
        # get_ancestry is defined as eliding ghosts, not erroring.
1660
 
        index = self.two_graph_index()
1661
 
        self.assertEqual([], index.get_ancestry([]))
1662
 
        self.assertEqual(['separate'], index.get_ancestry(['separate']))
1663
 
        self.assertEqual(['tail'], index.get_ancestry(['tail']))
1664
 
        self.assertEqual(['tail', 'parent'], index.get_ancestry(['parent']))
1665
 
        self.assertEqual(['tail', 'parent', 'tip'], index.get_ancestry(['tip']))
1666
 
        self.assertTrue(index.get_ancestry(['tip', 'separate']) in
1667
 
            (['tail', 'parent', 'tip', 'separate'],
1668
 
             ['separate', 'tail', 'parent', 'tip'],
1669
 
            ))
1670
 
        # and without topo_sort
1671
 
        self.assertEqual(set(['separate']),
1672
 
            set(index.get_ancestry(['separate'], topo_sorted=False)))
1673
 
        self.assertEqual(set(['tail']),
1674
 
            set(index.get_ancestry(['tail'], topo_sorted=False)))
1675
 
        self.assertEqual(set(['tail', 'parent']),
1676
 
            set(index.get_ancestry(['parent'], topo_sorted=False)))
1677
 
        self.assertEqual(set(['tail', 'parent', 'tip']),
1678
 
            set(index.get_ancestry(['tip'], topo_sorted=False)))
1679
 
        self.assertEqual(set(['separate', 'tail', 'parent', 'tip']),
1680
 
            set(index.get_ancestry(['tip', 'separate'])))
1681
 
        # asking for a ghost makes it go boom.
1682
 
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry, ['ghost'])
1683
 
 
1684
 
    def test_get_ancestry_with_ghosts(self):
1685
 
        index = self.two_graph_index()
1686
 
        self.assertEqual([], index.get_ancestry_with_ghosts([]))
1687
 
        self.assertEqual(['separate'], index.get_ancestry_with_ghosts(['separate']))
1688
 
        self.assertEqual(['tail'], index.get_ancestry_with_ghosts(['tail']))
1689
 
        self.assertTrue(index.get_ancestry_with_ghosts(['parent']) in
1690
 
            (['tail', 'ghost', 'parent'],
1691
 
             ['ghost', 'tail', 'parent'],
1692
 
            ))
1693
 
        self.assertTrue(index.get_ancestry_with_ghosts(['tip']) in
1694
 
            (['tail', 'ghost', 'parent', 'tip'],
1695
 
             ['ghost', 'tail', 'parent', 'tip'],
1696
 
            ))
1697
 
        self.assertTrue(index.get_ancestry_with_ghosts(['tip', 'separate']) in
1698
 
            (['tail', 'ghost', 'parent', 'tip', 'separate'],
1699
 
             ['ghost', 'tail', 'parent', 'tip', 'separate'],
1700
 
             ['separate', 'tail', 'ghost', 'parent', 'tip'],
1701
 
             ['separate', 'ghost', 'tail', 'parent', 'tip'],
1702
 
            ))
1703
 
        # asking for a ghost makes it go boom.
1704
 
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry_with_ghosts, ['ghost'])
1705
 
 
1706
 
    def test_num_versions(self):
1707
 
        index = self.two_graph_index()
1708
 
        self.assertEqual(4, index.num_versions())
1709
 
 
1710
 
    def test_get_versions(self):
1711
 
        index = self.two_graph_index()
1712
 
        self.assertEqual(set(['tail', 'tip', 'parent', 'separate']),
1713
 
            set(index.get_versions()))
1714
 
 
1715
 
    def test_has_version(self):
1716
 
        index = self.two_graph_index()
1717
 
        self.assertTrue(index.has_version('tail'))
1718
 
        self.assertFalse(index.has_version('ghost'))
1719
 
 
1720
 
    def test_get_position(self):
1721
 
        index = self.two_graph_index()
1722
 
        self.assertEqual((0, 100), index.get_position('tip'))
1723
 
        self.assertEqual((100, 78), index.get_position('parent'))
1724
 
 
1725
 
    def test_get_method_deltas(self):
1726
 
        index = self.two_graph_index(deltas=True)
1727
 
        self.assertEqual('fulltext', index.get_method('tip'))
1728
 
        self.assertEqual('line-delta', index.get_method('parent'))
1729
 
 
1730
 
    def test_get_method_no_deltas(self):
1731
 
        # check that the parent-history lookup is ignored with deltas=False.
1732
 
        index = self.two_graph_index(deltas=False)
1733
 
        self.assertEqual('fulltext', index.get_method('tip'))
1734
 
        self.assertEqual('fulltext', index.get_method('parent'))
1735
 
 
1736
 
    def test_get_options_deltas(self):
1737
 
        index = self.two_graph_index(deltas=True)
1738
 
        self.assertEqual('fulltext,no-eol', index.get_options('tip'))
1739
 
        self.assertEqual('line-delta', index.get_options('parent'))
1740
 
 
1741
 
    def test_get_options_no_deltas(self):
1742
 
        # check that the parent-history lookup is ignored with deltas=False.
1743
 
        index = self.two_graph_index(deltas=False)
1744
 
        self.assertEqual('fulltext,no-eol', index.get_options('tip'))
1745
 
        self.assertEqual('fulltext', index.get_options('parent'))
1746
 
 
1747
 
    def test_get_parents(self):
1748
 
        # get_parents ignores ghosts
1749
 
        index = self.two_graph_index()
1750
 
        self.assertEqual(('tail', ), index.get_parents('parent'))
1751
 
        # and errors on ghosts.
1752
 
        self.assertRaises(errors.RevisionNotPresent,
1753
 
            index.get_parents, 'ghost')
1754
 
 
1755
 
    def test_get_parents_with_ghosts(self):
1756
 
        index = self.two_graph_index()
1757
 
        self.assertEqual(('tail', 'ghost'), index.get_parents_with_ghosts('parent'))
1758
 
        # and errors on ghosts.
1759
 
        self.assertRaises(errors.RevisionNotPresent,
1760
 
            index.get_parents_with_ghosts, 'ghost')
1761
 
 
1762
 
    def test_check_versions_present(self):
1763
 
        # ghosts should not be considered present
1764
 
        index = self.two_graph_index()
1765
 
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
1766
 
            ['ghost'])
1767
 
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
1768
 
            ['tail', 'ghost'])
1769
 
        index.check_versions_present(['tail', 'separate'])
1770
 
 
1771
 
    def catch_add(self, entries):
1772
 
        self.caught_entries.append(entries)
1773
 
 
1774
 
    def test_add_no_callback_errors(self):
1775
 
        index = self.two_graph_index()
1776
 
        self.assertRaises(errors.ReadOnlyError, index.add_version,
1777
 
            'new', 'fulltext,no-eol', 50, 60, ['separate'])
1778
 
 
1779
 
    def test_add_version_smoke(self):
1780
 
        index = self.two_graph_index(catch_adds=True)
1781
 
        index.add_version('new', 'fulltext,no-eol', 50, 60, ['separate'])
1782
 
        self.assertEqual([[(('new', ), 'N50 60', ((('separate',),),))]],
1783
 
            self.caught_entries)
1784
 
 
1785
 
    def test_add_version_delta_not_delta_index(self):
1786
 
        index = self.two_graph_index(catch_adds=True)
1787
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
1788
 
            'new', 'no-eol,line-delta', 0, 100, ['parent'])
1789
 
        self.assertEqual([], self.caught_entries)
1790
 
 
1791
 
    def test_add_version_same_dup(self):
1792
 
        index = self.two_graph_index(catch_adds=True)
1793
 
        # options can be spelt two different ways
1794
 
        index.add_version('tip', 'fulltext,no-eol', 0, 100, ['parent'])
1795
 
        index.add_version('tip', 'no-eol,fulltext', 0, 100, ['parent'])
1796
 
        # but neither should have added data.
1797
 
        self.assertEqual([[], []], self.caught_entries)
1798
 
        
1799
 
    def test_add_version_different_dup(self):
1800
 
        index = self.two_graph_index(deltas=True, catch_adds=True)
1801
 
        # change options
1802
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
1803
 
            'tip', 'no-eol,line-delta', 0, 100, ['parent'])
1804
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
1805
 
            'tip', 'line-delta,no-eol', 0, 100, ['parent'])
1806
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
1807
 
            'tip', 'fulltext', 0, 100, ['parent'])
1808
 
        # position/length
1809
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
1810
 
            'tip', 'fulltext,no-eol', 50, 100, ['parent'])
1811
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
1812
 
            'tip', 'fulltext,no-eol', 0, 1000, ['parent'])
1813
 
        # parents
1814
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
1815
 
            'tip', 'fulltext,no-eol', 0, 100, [])
1816
 
        self.assertEqual([], self.caught_entries)
1817
 
        
1818
 
    def test_add_versions_nodeltas(self):
1819
 
        index = self.two_graph_index(catch_adds=True)
1820
 
        index.add_versions([
1821
 
                ('new', 'fulltext,no-eol', 50, 60, ['separate']),
1822
 
                ('new2', 'fulltext', 0, 6, ['new']),
1823
 
                ])
1824
 
        self.assertEqual([(('new', ), 'N50 60', ((('separate',),),)),
1825
 
            (('new2', ), ' 0 6', ((('new',),),))],
1826
 
            sorted(self.caught_entries[0]))
1827
 
        self.assertEqual(1, len(self.caught_entries))
1828
 
 
1829
 
    def test_add_versions_deltas(self):
1830
 
        index = self.two_graph_index(deltas=True, catch_adds=True)
1831
 
        index.add_versions([
1832
 
                ('new', 'fulltext,no-eol', 50, 60, ['separate']),
1833
 
                ('new2', 'line-delta', 0, 6, ['new']),
1834
 
                ])
1835
 
        self.assertEqual([(('new', ), 'N50 60', ((('separate',),), ())),
1836
 
            (('new2', ), ' 0 6', ((('new',),), (('new',),), ))],
1837
 
            sorted(self.caught_entries[0]))
1838
 
        self.assertEqual(1, len(self.caught_entries))
1839
 
 
1840
 
    def test_add_versions_delta_not_delta_index(self):
1841
 
        index = self.two_graph_index(catch_adds=True)
1842
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1843
 
            [('new', 'no-eol,line-delta', 0, 100, ['parent'])])
1844
 
        self.assertEqual([], self.caught_entries)
1845
 
 
1846
 
    def test_add_versions_same_dup(self):
1847
 
        index = self.two_graph_index(catch_adds=True)
1848
 
        # options can be spelt two different ways
1849
 
        index.add_versions([('tip', 'fulltext,no-eol', 0, 100, ['parent'])])
1850
 
        index.add_versions([('tip', 'no-eol,fulltext', 0, 100, ['parent'])])
1851
 
        # but neither should have added data.
1852
 
        self.assertEqual([[], []], self.caught_entries)
1853
 
        
1854
 
    def test_add_versions_different_dup(self):
1855
 
        index = self.two_graph_index(deltas=True, catch_adds=True)
1856
 
        # change options
1857
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1858
 
            [('tip', 'no-eol,line-delta', 0, 100, ['parent'])])
1859
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1860
 
            [('tip', 'line-delta,no-eol', 0, 100, ['parent'])])
1861
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1862
 
            [('tip', 'fulltext', 0, 100, ['parent'])])
1863
 
        # position/length
1864
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1865
 
            [('tip', 'fulltext,no-eol', 50, 100, ['parent'])])
1866
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1867
 
            [('tip', 'fulltext,no-eol', 0, 1000, ['parent'])])
1868
 
        # parents
1869
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1870
 
            [('tip', 'fulltext,no-eol', 0, 100, [])])
1871
 
        # change options in the second record
1872
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
1873
 
            [('tip', 'fulltext,no-eol', 0, 100, ['parent']),
1874
 
             ('tip', 'no-eol,line-delta', 0, 100, ['parent'])])
1875
 
        self.assertEqual([], self.caught_entries)
1876
 
 
1877
 
    def test_iter_parents(self):
1878
 
        index1 = self.make_g_index('1', 1, [
1879
 
        # no parents
1880
 
            (('r0', ), 'N0 100', ([], )),
1881
 
        # 1 parent
1882
 
            (('r1', ), '', ([('r0', )], ))])
1883
 
        index2 = self.make_g_index('2', 1, [
1884
 
        # 2 parents
1885
 
            (('r2', ), 'N0 100', ([('r1', ), ('r0', )], )),
1886
 
            ])
1887
 
        combined_index = CombinedGraphIndex([index1, index2])
1888
 
        index = KnitGraphIndex(combined_index)
1889
 
        # XXX TODO a ghost
1890
 
        # cases: each sample data individually:
1891
 
        self.assertEqual(set([('r0', ())]),
1892
 
            set(index.iter_parents(['r0'])))
1893
 
        self.assertEqual(set([('r1', ('r0', ))]),
1894
 
            set(index.iter_parents(['r1'])))
1895
 
        self.assertEqual(set([('r2', ('r1', 'r0'))]),
1896
 
            set(index.iter_parents(['r2'])))
1897
 
        # no nodes returned for a missing node
1898
 
        self.assertEqual(set(),
1899
 
            set(index.iter_parents(['missing'])))
1900
 
        # 1 node returned with missing nodes skipped
1901
 
        self.assertEqual(set([('r1', ('r0', ))]),
1902
 
            set(index.iter_parents(['ghost1', 'r1', 'ghost'])))
1903
 
        # 2 nodes returned
1904
 
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
1905
 
            set(index.iter_parents(['r0', 'r1'])))
1906
 
        # 2 nodes returned, missing skipped
1907
 
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
1908
 
            set(index.iter_parents(['a', 'r0', 'b', 'r1', 'c'])))
1909
 
 
1910
 
 
1911
 
class TestNoParentsGraphIndexKnit(KnitTests):
1912
 
    """Tests for knits using KnitGraphIndex with no parents."""
1913
 
 
1914
 
    def make_g_index(self, name, ref_lists=0, nodes=[]):
1915
 
        builder = GraphIndexBuilder(ref_lists)
1916
 
        for node, references in nodes:
1917
 
            builder.add_node(node, references)
1918
 
        stream = builder.finish()
1919
 
        trans = self.get_transport()
1920
 
        trans.put_file(name, stream)
1921
 
        return GraphIndex(trans, name)
1922
 
 
1923
 
    def test_parents_deltas_incompatible(self):
1924
 
        index = CombinedGraphIndex([])
1925
 
        self.assertRaises(errors.KnitError, KnitGraphIndex, index,
1926
 
            deltas=True, parents=False)
1927
 
 
1928
 
    def two_graph_index(self, catch_adds=False):
1929
 
        """Build a two-graph index.
1930
 
 
1931
 
        :param deltas: If true, use underlying indices with two node-ref
1932
 
            lists and 'parent' set to a delta-compressed against tail.
1933
 
        """
1934
 
        # put several versions in the index.
1935
 
        index1 = self.make_g_index('1', 0, [
1936
 
            (('tip', ), 'N0 100'),
1937
 
            (('tail', ), '')])
1938
 
        index2 = self.make_g_index('2', 0, [
1939
 
            (('parent', ), ' 100 78'),
1940
 
            (('separate', ), '')])
1941
 
        combined_index = CombinedGraphIndex([index1, index2])
1942
 
        if catch_adds:
1943
 
            self.combined_index = combined_index
1944
 
            self.caught_entries = []
1945
 
            add_callback = self.catch_add
1946
 
        else:
1947
 
            add_callback = None
1948
 
        return KnitGraphIndex(combined_index, parents=False,
1949
 
            add_callback=add_callback)
1950
 
 
1951
 
    def test_get_graph(self):
1952
 
        index = self.two_graph_index()
1953
 
        self.assertEqual(set([
1954
 
            ('tip', ()),
1955
 
            ('tail', ()),
1956
 
            ('parent', ()),
1957
 
            ('separate', ()),
1958
 
            ]), set(index.get_graph()))
1959
 
 
1960
 
    def test_get_ancestry(self):
1961
 
        # with no parents, ancestry is always just the key.
1962
 
        index = self.two_graph_index()
1963
 
        self.assertEqual([], index.get_ancestry([]))
1964
 
        self.assertEqual(['separate'], index.get_ancestry(['separate']))
1965
 
        self.assertEqual(['tail'], index.get_ancestry(['tail']))
1966
 
        self.assertEqual(['parent'], index.get_ancestry(['parent']))
1967
 
        self.assertEqual(['tip'], index.get_ancestry(['tip']))
1968
 
        self.assertTrue(index.get_ancestry(['tip', 'separate']) in
1969
 
            (['tip', 'separate'],
1970
 
             ['separate', 'tip'],
1971
 
            ))
1972
 
        # asking for a ghost makes it go boom.
1973
 
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry, ['ghost'])
1974
 
 
1975
 
    def test_get_ancestry_with_ghosts(self):
1976
 
        index = self.two_graph_index()
1977
 
        self.assertEqual([], index.get_ancestry_with_ghosts([]))
1978
 
        self.assertEqual(['separate'], index.get_ancestry_with_ghosts(['separate']))
1979
 
        self.assertEqual(['tail'], index.get_ancestry_with_ghosts(['tail']))
1980
 
        self.assertEqual(['parent'], index.get_ancestry_with_ghosts(['parent']))
1981
 
        self.assertEqual(['tip'], index.get_ancestry_with_ghosts(['tip']))
1982
 
        self.assertTrue(index.get_ancestry_with_ghosts(['tip', 'separate']) in
1983
 
            (['tip', 'separate'],
1984
 
             ['separate', 'tip'],
1985
 
            ))
1986
 
        # asking for a ghost makes it go boom.
1987
 
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry_with_ghosts, ['ghost'])
1988
 
 
1989
 
    def test_num_versions(self):
1990
 
        index = self.two_graph_index()
1991
 
        self.assertEqual(4, index.num_versions())
1992
 
 
1993
 
    def test_get_versions(self):
1994
 
        index = self.two_graph_index()
1995
 
        self.assertEqual(set(['tail', 'tip', 'parent', 'separate']),
1996
 
            set(index.get_versions()))
1997
 
 
1998
 
    def test_has_version(self):
1999
 
        index = self.two_graph_index()
2000
 
        self.assertTrue(index.has_version('tail'))
2001
 
        self.assertFalse(index.has_version('ghost'))
2002
 
 
2003
 
    def test_get_position(self):
2004
 
        index = self.two_graph_index()
2005
 
        self.assertEqual((0, 100), index.get_position('tip'))
2006
 
        self.assertEqual((100, 78), index.get_position('parent'))
2007
 
 
2008
 
    def test_get_method(self):
2009
 
        index = self.two_graph_index()
2010
 
        self.assertEqual('fulltext', index.get_method('tip'))
2011
 
        self.assertEqual('fulltext', index.get_options('parent'))
2012
 
 
2013
 
    def test_get_options(self):
2014
 
        index = self.two_graph_index()
2015
 
        self.assertEqual('fulltext,no-eol', index.get_options('tip'))
2016
 
        self.assertEqual('fulltext', index.get_options('parent'))
2017
 
 
2018
 
    def test_get_parents(self):
2019
 
        index = self.two_graph_index()
2020
 
        self.assertEqual((), index.get_parents('parent'))
2021
 
        # and errors on ghosts.
2022
 
        self.assertRaises(errors.RevisionNotPresent,
2023
 
            index.get_parents, 'ghost')
2024
 
 
2025
 
    def test_get_parents_with_ghosts(self):
2026
 
        index = self.two_graph_index()
2027
 
        self.assertEqual((), index.get_parents_with_ghosts('parent'))
2028
 
        # and errors on ghosts.
2029
 
        self.assertRaises(errors.RevisionNotPresent,
2030
 
            index.get_parents_with_ghosts, 'ghost')
2031
 
 
2032
 
    def test_check_versions_present(self):
2033
 
        index = self.two_graph_index()
2034
 
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
2035
 
            ['missing'])
2036
 
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
2037
 
            ['tail', 'missing'])
2038
 
        index.check_versions_present(['tail', 'separate'])
2039
 
 
2040
 
    def catch_add(self, entries):
2041
 
        self.caught_entries.append(entries)
2042
 
 
2043
 
    def test_add_no_callback_errors(self):
2044
 
        index = self.two_graph_index()
2045
 
        self.assertRaises(errors.ReadOnlyError, index.add_version,
2046
 
            'new', 'fulltext,no-eol', 50, 60, ['separate'])
2047
 
 
2048
 
    def test_add_version_smoke(self):
2049
 
        index = self.two_graph_index(catch_adds=True)
2050
 
        index.add_version('new', 'fulltext,no-eol', 50, 60, [])
2051
 
        self.assertEqual([[(('new', ), 'N50 60')]],
2052
 
            self.caught_entries)
2053
 
 
2054
 
    def test_add_version_delta_not_delta_index(self):
2055
 
        index = self.two_graph_index(catch_adds=True)
2056
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2057
 
            'new', 'no-eol,line-delta', 0, 100, [])
2058
 
        self.assertEqual([], self.caught_entries)
2059
 
 
2060
 
    def test_add_version_same_dup(self):
2061
 
        index = self.two_graph_index(catch_adds=True)
2062
 
        # options can be spelt two different ways
2063
 
        index.add_version('tip', 'fulltext,no-eol', 0, 100, [])
2064
 
        index.add_version('tip', 'no-eol,fulltext', 0, 100, [])
2065
 
        # but neither should have added data.
2066
 
        self.assertEqual([[], []], self.caught_entries)
2067
 
        
2068
 
    def test_add_version_different_dup(self):
2069
 
        index = self.two_graph_index(catch_adds=True)
2070
 
        # change options
2071
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2072
 
            'tip', 'no-eol,line-delta', 0, 100, [])
2073
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2074
 
            'tip', 'line-delta,no-eol', 0, 100, [])
2075
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2076
 
            'tip', 'fulltext', 0, 100, [])
2077
 
        # position/length
2078
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2079
 
            'tip', 'fulltext,no-eol', 50, 100, [])
2080
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2081
 
            'tip', 'fulltext,no-eol', 0, 1000, [])
2082
 
        # parents
2083
 
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2084
 
            'tip', 'fulltext,no-eol', 0, 100, ['parent'])
2085
 
        self.assertEqual([], self.caught_entries)
2086
 
        
2087
 
    def test_add_versions(self):
2088
 
        index = self.two_graph_index(catch_adds=True)
2089
 
        index.add_versions([
2090
 
                ('new', 'fulltext,no-eol', 50, 60, []),
2091
 
                ('new2', 'fulltext', 0, 6, []),
2092
 
                ])
2093
 
        self.assertEqual([(('new', ), 'N50 60'), (('new2', ), ' 0 6')],
2094
 
            sorted(self.caught_entries[0]))
2095
 
        self.assertEqual(1, len(self.caught_entries))
2096
 
 
2097
 
    def test_add_versions_delta_not_delta_index(self):
2098
 
        index = self.two_graph_index(catch_adds=True)
2099
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2100
 
            [('new', 'no-eol,line-delta', 0, 100, ['parent'])])
2101
 
        self.assertEqual([], self.caught_entries)
2102
 
 
2103
 
    def test_add_versions_parents_not_parents_index(self):
2104
 
        index = self.two_graph_index(catch_adds=True)
2105
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2106
 
            [('new', 'no-eol,fulltext', 0, 100, ['parent'])])
2107
 
        self.assertEqual([], self.caught_entries)
2108
 
 
2109
 
    def test_add_versions_same_dup(self):
2110
 
        index = self.two_graph_index(catch_adds=True)
2111
 
        # options can be spelt two different ways
2112
 
        index.add_versions([('tip', 'fulltext,no-eol', 0, 100, [])])
2113
 
        index.add_versions([('tip', 'no-eol,fulltext', 0, 100, [])])
2114
 
        # but neither should have added data.
2115
 
        self.assertEqual([[], []], self.caught_entries)
2116
 
        
2117
 
    def test_add_versions_different_dup(self):
2118
 
        index = self.two_graph_index(catch_adds=True)
2119
 
        # change options
2120
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2121
 
            [('tip', 'no-eol,line-delta', 0, 100, [])])
2122
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2123
 
            [('tip', 'line-delta,no-eol', 0, 100, [])])
2124
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2125
 
            [('tip', 'fulltext', 0, 100, [])])
2126
 
        # position/length
2127
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2128
 
            [('tip', 'fulltext,no-eol', 50, 100, [])])
2129
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2130
 
            [('tip', 'fulltext,no-eol', 0, 1000, [])])
2131
 
        # parents
2132
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2133
 
            [('tip', 'fulltext,no-eol', 0, 100, ['parent'])])
2134
 
        # change options in the second record
2135
 
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2136
 
            [('tip', 'fulltext,no-eol', 0, 100, []),
2137
 
             ('tip', 'no-eol,line-delta', 0, 100, [])])
2138
 
        self.assertEqual([], self.caught_entries)
2139
 
 
2140
 
    def test_iter_parents(self):
2141
 
        index = self.two_graph_index()
2142
 
        self.assertEqual(set([
2143
 
            ('tip', ()), ('tail', ()), ('parent', ()), ('separate', ())
2144
 
            ]),
2145
 
            set(index.iter_parents(['tip', 'tail', 'ghost', 'parent', 'separate'])))
2146
 
        self.assertEqual(set([('tip', ())]),
2147
 
            set(index.iter_parents(['tip'])))
2148
 
        self.assertEqual(set(),
2149
 
            set(index.iter_parents([])))