1
# Copyright (C) 2005-2009, 2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
# TODO: tests regarding version names
19
# TODO: rbc 20050108 test that join does not leave an inconsistent weave
22
"""test suite for weave algorithm"""
24
from pprint import pformat
29
from bzrlib.osutils import sha_string
30
from bzrlib.tests import TestCase, TestCaseInTempDir
31
from bzrlib.weave import Weave, WeaveFormatError
32
from bzrlib.weavefile import write_weave, read_weave
35
# texts for use in testing
36
TEXT_0 = ["Hello world"]
37
TEXT_1 = ["Hello world",
41
class TestBase(TestCase):
43
def check_read_write(self, k):
44
"""Check the weave k can be written & re-read."""
45
from tempfile import TemporaryFile
54
self.log('serialized weave:')
58
self.log('parents: %s' % (k._parents == k2._parents))
59
self.log(' %r' % k._parents)
60
self.log(' %r' % k2._parents)
62
self.fail('read/write check failed')
65
class WeaveContains(TestBase):
66
"""Weave __contains__ operator"""
69
k = Weave(get_scope=lambda:None)
70
self.assertFalse('foo' in k)
71
k.add_lines('foo', [], TEXT_1)
72
self.assertTrue('foo' in k)
81
class AnnotateOne(TestBase):
85
k.add_lines('text0', [], TEXT_0)
86
self.assertEqual(k.annotate('text0'),
87
[('text0', TEXT_0[0])])
90
class InvalidAdd(TestBase):
91
"""Try to use invalid version number during add."""
96
self.assertRaises(errors.RevisionNotPresent,
103
class RepeatedAdd(TestBase):
104
"""Add the same version twice; harmless."""
106
def test_duplicate_add(self):
108
idx = k.add_lines('text0', [], TEXT_0)
109
idx2 = k.add_lines('text0', [], TEXT_0)
110
self.assertEqual(idx, idx2)
113
class InvalidRepeatedAdd(TestBase):
117
k.add_lines('basis', [], TEXT_0)
118
idx = k.add_lines('text0', [], TEXT_0)
119
self.assertRaises(errors.RevisionAlreadyPresent,
123
['not the same text'])
124
self.assertRaises(errors.RevisionAlreadyPresent,
127
['basis'], # not the right parents
131
class InsertLines(TestBase):
132
"""Store a revision that adds one line to the original.
134
Look at the annotations to make sure that the first line is matched
135
and not stored repeatedly."""
139
k.add_lines('text0', [], ['line 1'])
140
k.add_lines('text1', ['text0'], ['line 1', 'line 2'])
142
self.assertEqual(k.annotate('text0'),
143
[('text0', 'line 1')])
145
self.assertEqual(k.get_lines(1),
149
self.assertEqual(k.annotate('text1'),
150
[('text0', 'line 1'),
151
('text1', 'line 2')])
153
k.add_lines('text2', ['text0'], ['line 1', 'diverged line'])
155
self.assertEqual(k.annotate('text2'),
156
[('text0', 'line 1'),
157
('text2', 'diverged line')])
159
text3 = ['line 1', 'middle line', 'line 2']
164
# self.log("changes to text3: " + pformat(list(k._delta(set([0, 1]), text3))))
166
self.log("k._weave=" + pformat(k._weave))
168
self.assertEqual(k.annotate('text3'),
169
[('text0', 'line 1'),
170
('text3', 'middle line'),
171
('text1', 'line 2')])
173
# now multiple insertions at different places
175
['text0', 'text1', 'text3'],
176
['line 1', 'aaa', 'middle line', 'bbb', 'line 2', 'ccc'])
178
self.assertEqual(k.annotate('text4'),
179
[('text0', 'line 1'),
181
('text3', 'middle line'),
187
class DeleteLines(TestBase):
188
"""Deletion of lines from existing text.
190
Try various texts all based on a common ancestor."""
194
base_text = ['one', 'two', 'three', 'four']
196
k.add_lines('text0', [], base_text)
198
texts = [['one', 'two', 'three'],
199
['two', 'three', 'four'],
201
['one', 'two', 'three', 'four'],
206
ver = k.add_lines('text%d' % i,
210
self.log('final weave:')
211
self.log('k._weave=' + pformat(k._weave))
213
for i in range(len(texts)):
214
self.assertEqual(k.get_lines(i+1),
218
class SuicideDelete(TestBase):
219
"""Invalid weave which tries to add and delete simultaneously."""
225
k._weave = [('{', 0),
232
################################### SKIPPED
233
# Weave.get doesn't trap this anymore
236
self.assertRaises(WeaveFormatError,
241
class CannedDelete(TestBase):
242
"""Unpack canned weave with deleted lines."""
249
k._weave = [('{', 0),
252
'line to be deleted',
257
k._sha1s = [sha_string('first lineline to be deletedlast line')
258
, sha_string('first linelast line')]
260
self.assertEqual(k.get_lines(0),
262
'line to be deleted',
266
self.assertEqual(k.get_lines(1),
272
class CannedReplacement(TestBase):
273
"""Unpack canned weave with deleted lines."""
277
k._parents = [frozenset(),
280
k._weave = [('{', 0),
283
'line to be deleted',
291
k._sha1s = [sha_string('first lineline to be deletedlast line')
292
, sha_string('first linereplacement linelast line')]
294
self.assertEqual(k.get_lines(0),
296
'line to be deleted',
300
self.assertEqual(k.get_lines(1),
307
class BadWeave(TestBase):
308
"""Test that we trap an insert which should not occur."""
312
k._parents = [frozenset(),
314
k._weave = ['bad line',
318
' added in version 1',
327
################################### SKIPPED
328
# Weave.get doesn't trap this anymore
332
self.assertRaises(WeaveFormatError,
337
class BadInsert(TestBase):
338
"""Test that we trap an insert which should not occur."""
342
k._parents = [frozenset(),
347
k._weave = [('{', 0),
350
' added in version 1',
358
# this is not currently enforced by get
359
return ##########################################
361
self.assertRaises(WeaveFormatError,
365
self.assertRaises(WeaveFormatError,
370
class InsertNested(TestBase):
371
"""Insertion with nested instructions."""
375
k._parents = [frozenset(),
380
k._weave = [('{', 0),
383
' added in version 1',
392
k._sha1s = [sha_string('foo {}')
393
, sha_string('foo { added in version 1 also from v1}')
394
, sha_string('foo { added in v2}')
395
, sha_string('foo { added in version 1 added in v2 also from v1}')
398
self.assertEqual(k.get_lines(0),
402
self.assertEqual(k.get_lines(1),
404
' added in version 1',
408
self.assertEqual(k.get_lines(2),
413
self.assertEqual(k.get_lines(3),
415
' added in version 1',
421
class DeleteLines2(TestBase):
422
"""Test recording revisions that delete lines.
424
This relies on the weave having a way to represent lines knocked
425
out by a later revision."""
429
k.add_lines('text0', [], ["line the first",
434
self.assertEqual(len(k.get_lines(0)), 4)
436
k.add_lines('text1', ['text0'], ["line the first",
439
self.assertEqual(k.get_lines(1),
443
self.assertEqual(k.annotate('text1'),
444
[('text0', "line the first"),
448
class IncludeVersions(TestBase):
449
"""Check texts that are stored across multiple revisions.
451
Here we manually create a weave with particular encoding and make
452
sure it unpacks properly.
454
Text 0 includes nothing; text 1 includes text 0 and adds some
461
k._parents = [frozenset(), frozenset([0])]
462
k._weave = [('{', 0),
469
k._sha1s = [sha_string('first line')
470
, sha_string('first linesecond line')]
472
self.assertEqual(k.get_lines(1),
476
self.assertEqual(k.get_lines(0),
480
class DivergedIncludes(TestBase):
481
"""Weave with two diverged texts based on version 0.
484
# FIXME make the weave, dont poke at it.
487
k._names = ['0', '1', '2']
488
k._name_map = {'0':0, '1':1, '2':2}
489
k._parents = [frozenset(),
493
k._weave = [('{', 0),
500
"alternative second line",
504
k._sha1s = [sha_string('first line')
505
, sha_string('first linesecond line')
506
, sha_string('first linealternative second line')]
508
self.assertEqual(k.get_lines(0),
511
self.assertEqual(k.get_lines(1),
515
self.assertEqual(k.get_lines('2'),
517
"alternative second line"])
519
self.assertEqual(list(k.get_ancestry(['2'])),
523
class ReplaceLine(TestBase):
527
text0 = ['cheddar', 'stilton', 'gruyere']
528
text1 = ['cheddar', 'blue vein', 'neufchatel', 'chevre']
530
k.add_lines('text0', [], text0)
531
k.add_lines('text1', ['text0'], text1)
533
self.log('k._weave=' + pformat(k._weave))
535
self.assertEqual(k.get_lines(0), text0)
536
self.assertEqual(k.get_lines(1), text1)
539
class Merge(TestBase):
540
"""Storage of versions that merge diverged parents"""
546
['header', '', 'line from 1'],
547
['header', '', 'line from 2', 'more from 2'],
548
['header', '', 'line from 1', 'fixup line', 'line from 2'],
551
k.add_lines('text0', [], texts[0])
552
k.add_lines('text1', ['text0'], texts[1])
553
k.add_lines('text2', ['text0'], texts[2])
554
k.add_lines('merge', ['text0', 'text1', 'text2'], texts[3])
556
for i, t in enumerate(texts):
557
self.assertEqual(k.get_lines(i), t)
559
self.assertEqual(k.annotate('merge'),
560
[('text0', 'header'),
562
('text1', 'line from 1'),
563
('merge', 'fixup line'),
564
('text2', 'line from 2'),
567
self.assertEqual(list(k.get_ancestry(['merge'])),
568
['text0', 'text1', 'text2', 'merge'])
570
self.log('k._weave=' + pformat(k._weave))
572
self.check_read_write(k)
575
class Conflicts(TestBase):
576
"""Test detection of conflicting regions during a merge.
578
A base version is inserted, then two descendents try to
579
insert different lines in the same place. These should be
580
reported as a possible conflict and forwarded to the user."""
585
k.add_lines([], ['aaa', 'bbb'])
586
k.add_lines([0], ['aaa', '111', 'bbb'])
587
k.add_lines([1], ['aaa', '222', 'bbb'])
589
merged = k.merge([1, 2])
591
self.assertEquals([[['aaa']],
596
class NonConflict(TestBase):
597
"""Two descendants insert compatible changes.
599
No conflict should be reported."""
604
k.add_lines([], ['aaa', 'bbb'])
605
k.add_lines([0], ['111', 'aaa', 'ccc', 'bbb'])
606
k.add_lines([1], ['aaa', 'ccc', 'bbb', '222'])
609
class Khayyam(TestBase):
610
"""Test changes to multi-line texts, and read/write"""
612
def test_multi_line_merge(self):
614
"""A Book of Verses underneath the Bough,
615
A Jug of Wine, a Loaf of Bread, -- and Thou
616
Beside me singing in the Wilderness --
617
Oh, Wilderness were Paradise enow!""",
619
"""A Book of Verses underneath the Bough,
620
A Jug of Wine, a Loaf of Bread, -- and Thou
621
Beside me singing in the Wilderness --
622
Oh, Wilderness were Paradise now!""",
624
"""A Book of poems underneath the tree,
625
A Jug of Wine, a Loaf of Bread,
627
Beside me singing in the Wilderness --
628
Oh, Wilderness were Paradise now!
632
"""A Book of Verses underneath the Bough,
633
A Jug of Wine, a Loaf of Bread,
635
Beside me singing in the Wilderness --
636
Oh, Wilderness were Paradise now!""",
638
texts = [[l.strip() for l in t.split('\n')] for t in rawtexts]
644
ver = k.add_lines('text%d' % i,
646
parents.add('text%d' % i)
649
self.log("k._weave=" + pformat(k._weave))
651
for i, t in enumerate(texts):
652
self.assertEqual(k.get_lines(i), t)
654
self.check_read_write(k)
657
class JoinWeavesTests(TestBase):
660
super(JoinWeavesTests, self).setUp()
661
self.weave1 = Weave()
662
self.lines1 = ['hello\n']
663
self.lines3 = ['hello\n', 'cruel\n', 'world\n']
664
self.weave1.add_lines('v1', [], self.lines1)
665
self.weave1.add_lines('v2', ['v1'], ['hello\n', 'world\n'])
666
self.weave1.add_lines('v3', ['v2'], self.lines3)
668
def test_written_detection(self):
669
# Test detection of weave file corruption.
671
# Make sure that we can detect if a weave file has
672
# been corrupted. This doesn't test all forms of corruption,
673
# but it at least helps verify the data you get, is what you want.
674
from cStringIO import StringIO
677
w.add_lines('v1', [], ['hello\n'])
678
w.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
683
# Because we are corrupting, we need to make sure we have the exact text
684
self.assertEquals('# bzr weave file v5\n'
685
'i\n1 f572d396fae9206628714fb2ce00f72e94f2258f\nn v1\n\n'
686
'i 0\n1 90f265c6e75f1c8f9ab76dcf85528352c5f215ef\nn v2\n\n'
687
'w\n{ 0\n. hello\n}\n{ 1\n. there\n}\nW\n',
690
# Change a single letter
691
tmpf = StringIO('# bzr weave file v5\n'
692
'i\n1 f572d396fae9206628714fb2ce00f72e94f2258f\nn v1\n\n'
693
'i 0\n1 90f265c6e75f1c8f9ab76dcf85528352c5f215ef\nn v2\n\n'
694
'w\n{ 0\n. hello\n}\n{ 1\n. There\n}\nW\n')
698
self.assertEqual('hello\n', w.get_text('v1'))
699
self.assertRaises(errors.WeaveInvalidChecksum, w.get_text, 'v2')
700
self.assertRaises(errors.WeaveInvalidChecksum, w.get_lines, 'v2')
701
self.assertRaises(errors.WeaveInvalidChecksum, w.check)
703
# Change the sha checksum
704
tmpf = StringIO('# bzr weave file v5\n'
705
'i\n1 f572d396fae9206628714fb2ce00f72e94f2258f\nn v1\n\n'
706
'i 0\n1 f0f265c6e75f1c8f9ab76dcf85528352c5f215ef\nn v2\n\n'
707
'w\n{ 0\n. hello\n}\n{ 1\n. there\n}\nW\n')
711
self.assertEqual('hello\n', w.get_text('v1'))
712
self.assertRaises(errors.WeaveInvalidChecksum, w.get_text, 'v2')
713
self.assertRaises(errors.WeaveInvalidChecksum, w.get_lines, 'v2')
714
self.assertRaises(errors.WeaveInvalidChecksum, w.check)
717
class TestWeave(TestCase):
719
def test_allow_reserved_false(self):
720
w = Weave('name', allow_reserved=False)
721
# Add lines is checked at the WeaveFile level, not at the Weave level
722
w.add_lines('name:', [], TEXT_1)
723
# But get_lines is checked at this level
724
self.assertRaises(errors.ReservedId, w.get_lines, 'name:')
726
def test_allow_reserved_true(self):
727
w = Weave('name', allow_reserved=True)
728
w.add_lines('name:', [], TEXT_1)
729
self.assertEqual(TEXT_1, w.get_lines('name:'))
732
class InstrumentedWeave(Weave):
733
"""Keep track of how many times functions are called."""
735
def __init__(self, weave_name=None):
736
self._extract_count = 0
737
Weave.__init__(self, weave_name=weave_name)
739
def _extract(self, versions):
740
self._extract_count += 1
741
return Weave._extract(self, versions)
744
class TestNeedsReweave(TestCase):
745
"""Internal corner cases for when reweave is needed."""
747
def test_compatible_parents(self):
749
my_parents = set([1, 2, 3])
751
self.assertTrue(w1._compatible_parents(my_parents, set([3])))
753
self.assertTrue(w1._compatible_parents(my_parents, set(my_parents)))
754
# same empty corner case
755
self.assertTrue(w1._compatible_parents(set(), set()))
756
# other cannot contain stuff my_parents does not
757
self.assertFalse(w1._compatible_parents(set(), set([1])))
758
self.assertFalse(w1._compatible_parents(my_parents, set([1, 2, 3, 4])))
759
self.assertFalse(w1._compatible_parents(my_parents, set([4])))
762
class TestWeaveFile(TestCaseInTempDir):
764
def test_empty_file(self):
765
f = open('empty.weave', 'wb+')
767
self.assertRaises(errors.WeaveFormatError,