~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to tools/testweave.py

  • Committer: Robert Collins
  • Date: 2005-09-29 02:55:34 UTC
  • mfrom: (1185.1.47)
  • mto: This revision was merged to the branch mainline in revision 1397.
  • Revision ID: robertc@robertcollins.net-20050929025534-1782933743abbfd5
update with integration

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 Canonical Ltd
2
 
#
 
1
#! /usr/bin/python2.4
 
2
 
 
3
# Copyright (C) 2005 by Canonical Ltd
 
4
 
3
5
# This program is free software; you can redistribute it and/or modify
4
6
# it under the terms of the GNU General Public License as published by
5
7
# the Free Software Foundation; either version 2 of the License, or
6
8
# (at your option) any later version.
7
 
#
 
9
 
8
10
# This program is distributed in the hope that it will be useful,
9
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
13
# GNU General Public License for more details.
12
 
#
 
14
 
13
15
# You should have received a copy of the GNU General Public License
14
16
# along with this program; if not, write to the Free Software
15
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
18
 
17
19
 
18
20
# TODO: tests regarding version names
19
 
# TODO: rbc 20050108 test that join does not leave an inconsistent weave 
20
 
#       if it fails.
 
21
 
 
22
 
21
23
 
22
24
"""test suite for weave algorithm"""
23
25
 
 
26
 
 
27
import testsweet
 
28
from bzrlib.weave import Weave, WeaveFormatError
 
29
from bzrlib.weavefile import write_weave, read_weave
24
30
from pprint import pformat
25
31
 
26
 
from bzrlib import (
27
 
    errors,
28
 
    )
29
 
from bzrlib.osutils import sha_string
30
 
from bzrlib.tests import TestCase, TestCaseInTempDir
31
 
from bzrlib.weave import Weave, WeaveFormatError, WeaveError
32
 
from bzrlib.weavefile import write_weave, read_weave
 
32
 
 
33
try:
 
34
    set
 
35
    frozenset
 
36
except NameError:
 
37
    from sets import Set, ImmutableSet
 
38
    set = Set
 
39
    frozenset = ImmutableSet
 
40
    del Set, ImmutableSet
 
41
 
33
42
 
34
43
 
35
44
# texts for use in testing
38
47
          "A second line"]
39
48
 
40
49
 
41
 
class TestBase(TestCase):
42
50
 
 
51
class TestBase(testsweet.TestBase):
43
52
    def check_read_write(self, k):
44
53
        """Check the weave k can be written & re-read."""
45
54
        from tempfile import TemporaryFile
59
68
            self.log('         %r' % k._parents)
60
69
            self.log('         %r' % k2._parents)
61
70
            self.log('')
 
71
 
 
72
            
62
73
            self.fail('read/write check failed')
63
 
 
64
 
 
65
 
class WeaveContains(TestBase):
66
 
    """Weave __contains__ operator"""
67
 
    def runTest(self):
68
 
        k = Weave()
69
 
        self.assertFalse('foo' in k)
70
 
        k.add_lines('foo', [], TEXT_1)
71
 
        self.assertTrue('foo' in k)
 
74
        
 
75
        
72
76
 
73
77
 
74
78
class Easy(TestBase):
76
80
        k = Weave()
77
81
 
78
82
 
 
83
class StoreText(TestBase):
 
84
    """Store and retrieve a simple text."""
 
85
    def runTest(self):
 
86
        k = Weave()
 
87
        idx = k.add('text0', [], TEXT_0)
 
88
        self.assertEqual(k.get(idx), TEXT_0)
 
89
        self.assertEqual(idx, 0)
 
90
 
 
91
 
 
92
 
79
93
class AnnotateOne(TestBase):
80
94
    def runTest(self):
81
95
        k = Weave()
82
 
        k.add_lines('text0', [], TEXT_0)
83
 
        self.assertEqual(k.annotate('text0'),
84
 
                         [('text0', TEXT_0[0])])
85
 
 
86
 
 
87
 
class GetSha1(TestBase):
88
 
    def test_get_sha1(self):
 
96
        k.add('text0', [], TEXT_0)
 
97
        self.assertEqual(k.annotate(0),
 
98
                         [(0, TEXT_0[0])])
 
99
 
 
100
 
 
101
class StoreTwo(TestBase):
 
102
    def runTest(self):
89
103
        k = Weave()
90
 
        k.add_lines('text0', [], 'text0')
91
 
        self.assertEqual('34dc0e430c642a26c3dd1c2beb7a8b4f4445eb79',
92
 
                         k.get_sha1('text0'))
93
 
        self.assertRaises(errors.RevisionNotPresent,
94
 
                          k.get_sha1, 0)
95
 
        self.assertRaises(errors.RevisionNotPresent,
96
 
                          k.get_sha1, 'text1')
97
 
                        
 
104
 
 
105
        idx = k.add('text0', [], TEXT_0)
 
106
        self.assertEqual(idx, 0)
 
107
 
 
108
        idx = k.add('text1', [], TEXT_1)
 
109
        self.assertEqual(idx, 1)
 
110
 
 
111
        self.assertEqual(k.get(0), TEXT_0)
 
112
        self.assertEqual(k.get(1), TEXT_1)
 
113
 
 
114
        k.dump(self.TEST_LOG)
 
115
 
 
116
 
98
117
 
99
118
class InvalidAdd(TestBase):
100
119
    """Try to use invalid version number during add."""
101
120
    def runTest(self):
102
121
        k = Weave()
103
122
 
104
 
        self.assertRaises(errors.RevisionNotPresent,
105
 
                          k.add_lines,
 
123
        self.assertRaises(IndexError,
 
124
                          k.add,
106
125
                          'text0',
107
 
                          ['69'],
 
126
                          [69],
108
127
                          ['new text!'])
109
128
 
110
129
 
111
 
class RepeatedAdd(TestBase):
112
 
    """Add the same version twice; harmless."""
113
 
 
114
 
    def test_duplicate_add(self):
115
 
        k = Weave()
116
 
        idx = k.add_lines('text0', [], TEXT_0)
117
 
        idx2 = k.add_lines('text0', [], TEXT_0)
118
 
        self.assertEqual(idx, idx2)
119
 
 
120
 
 
121
 
class InvalidRepeatedAdd(TestBase):
122
 
    def runTest(self):
123
 
        k = Weave()
124
 
        k.add_lines('basis', [], TEXT_0)
125
 
        idx = k.add_lines('text0', [], TEXT_0)
126
 
        self.assertRaises(errors.RevisionAlreadyPresent,
127
 
                          k.add_lines,
128
 
                          'text0',
129
 
                          [],
130
 
                          ['not the same text'])
131
 
        self.assertRaises(errors.RevisionAlreadyPresent,
132
 
                          k.add_lines,
133
 
                          'text0',
134
 
                          ['basis'],         # not the right parents
135
 
                          TEXT_0)
136
 
        
137
 
 
138
130
class InsertLines(TestBase):
139
131
    """Store a revision that adds one line to the original.
140
132
 
143
135
    def runTest(self):
144
136
        k = Weave()
145
137
 
146
 
        k.add_lines('text0', [], ['line 1'])
147
 
        k.add_lines('text1', ['text0'], ['line 1', 'line 2'])
148
 
 
149
 
        self.assertEqual(k.annotate('text0'),
150
 
                         [('text0', 'line 1')])
151
 
 
152
 
        self.assertEqual(k.get_lines(1),
 
138
        k.add('text0', [], ['line 1'])
 
139
        k.add('text1', [0], ['line 1', 'line 2'])
 
140
 
 
141
        self.assertEqual(k.annotate(0),
 
142
                         [(0, 'line 1')])
 
143
 
 
144
        self.assertEqual(k.get(1),
153
145
                         ['line 1',
154
146
                          'line 2'])
155
147
 
156
 
        self.assertEqual(k.annotate('text1'),
157
 
                         [('text0', 'line 1'),
158
 
                          ('text1', 'line 2')])
159
 
 
160
 
        k.add_lines('text2', ['text0'], ['line 1', 'diverged line'])
161
 
 
162
 
        self.assertEqual(k.annotate('text2'),
163
 
                         [('text0', 'line 1'),
164
 
                          ('text2', 'diverged line')])
 
148
        self.assertEqual(k.annotate(1),
 
149
                         [(0, 'line 1'),
 
150
                          (1, 'line 2')])
 
151
 
 
152
        k.add('text2', [0], ['line 1', 'diverged line'])
 
153
 
 
154
        self.assertEqual(k.annotate(2),
 
155
                         [(0, 'line 1'),
 
156
                          (2, 'diverged line')])
165
157
 
166
158
        text3 = ['line 1', 'middle line', 'line 2']
167
 
        k.add_lines('text3',
168
 
              ['text0', 'text1'],
 
159
        k.add('text3',
 
160
              [0, 1],
169
161
              text3)
170
162
 
171
163
        # self.log("changes to text3: " + pformat(list(k._delta(set([0, 1]), text3))))
172
164
 
173
165
        self.log("k._weave=" + pformat(k._weave))
174
166
 
175
 
        self.assertEqual(k.annotate('text3'),
176
 
                         [('text0', 'line 1'),
177
 
                          ('text3', 'middle line'),
178
 
                          ('text1', 'line 2')])
 
167
        self.assertEqual(k.annotate(3),
 
168
                         [(0, 'line 1'),
 
169
                          (3, 'middle line'),
 
170
                          (1, 'line 2')])
179
171
 
180
172
        # now multiple insertions at different places
181
 
        k.add_lines('text4',
182
 
              ['text0', 'text1', 'text3'],
 
173
        k.add('text4',
 
174
              [0, 1, 3],
183
175
              ['line 1', 'aaa', 'middle line', 'bbb', 'line 2', 'ccc'])
184
176
 
185
 
        self.assertEqual(k.annotate('text4'), 
186
 
                         [('text0', 'line 1'),
187
 
                          ('text4', 'aaa'),
188
 
                          ('text3', 'middle line'),
189
 
                          ('text4', 'bbb'),
190
 
                          ('text1', 'line 2'),
191
 
                          ('text4', 'ccc')])
 
177
        self.assertEqual(k.annotate(4), 
 
178
                         [(0, 'line 1'),
 
179
                          (4, 'aaa'),
 
180
                          (3, 'middle line'),
 
181
                          (4, 'bbb'),
 
182
                          (1, 'line 2'),
 
183
                          (4, 'ccc')])
 
184
 
192
185
 
193
186
 
194
187
class DeleteLines(TestBase):
200
193
 
201
194
        base_text = ['one', 'two', 'three', 'four']
202
195
 
203
 
        k.add_lines('text0', [], base_text)
 
196
        k.add('text0', [], base_text)
204
197
        
205
198
        texts = [['one', 'two', 'three'],
206
199
                 ['two', 'three', 'four'],
210
203
 
211
204
        i = 1
212
205
        for t in texts:
213
 
            ver = k.add_lines('text%d' % i,
214
 
                        ['text0'], t)
 
206
            ver = k.add('text%d' % i,
 
207
                        [0], t)
215
208
            i += 1
216
209
 
217
210
        self.log('final weave:')
218
211
        self.log('k._weave=' + pformat(k._weave))
219
212
 
220
213
        for i in range(len(texts)):
221
 
            self.assertEqual(k.get_lines(i+1),
 
214
            self.assertEqual(k.get(i+1),
222
215
                             texts[i])
 
216
            
 
217
 
223
218
 
224
219
 
225
220
class SuicideDelete(TestBase):
241
236
        return 
242
237
 
243
238
        self.assertRaises(WeaveFormatError,
244
 
                          k.get_lines,
 
239
                          k.get,
245
240
                          0)        
246
241
 
247
242
 
 
243
 
248
244
class CannedDelete(TestBase):
249
245
    """Unpack canned weave with deleted lines."""
250
246
    def runTest(self):
261
257
                'last line',
262
258
                ('}', 0),
263
259
                ]
264
 
        k._sha1s = [sha_string('first lineline to be deletedlast line')
265
 
                  , sha_string('first linelast line')]
266
260
 
267
 
        self.assertEqual(k.get_lines(0),
 
261
        self.assertEqual(k.get(0),
268
262
                         ['first line',
269
263
                          'line to be deleted',
270
264
                          'last line',
271
265
                          ])
272
266
 
273
 
        self.assertEqual(k.get_lines(1),
 
267
        self.assertEqual(k.get(1),
274
268
                         ['first line',
275
269
                          'last line',
276
270
                          ])
277
271
 
278
272
 
 
273
 
279
274
class CannedReplacement(TestBase):
280
275
    """Unpack canned weave with deleted lines."""
281
276
    def runTest(self):
295
290
                'last line',
296
291
                ('}', 0),
297
292
                ]
298
 
        k._sha1s = [sha_string('first lineline to be deletedlast line')
299
 
                  , sha_string('first linereplacement linelast line')]
300
293
 
301
 
        self.assertEqual(k.get_lines(0),
 
294
        self.assertEqual(k.get(0),
302
295
                         ['first line',
303
296
                          'line to be deleted',
304
297
                          'last line',
305
298
                          ])
306
299
 
307
 
        self.assertEqual(k.get_lines(1),
 
300
        self.assertEqual(k.get(1),
308
301
                         ['first line',
309
302
                          'replacement line',
310
303
                          'last line',
311
304
                          ])
312
305
 
313
306
 
 
307
 
314
308
class BadWeave(TestBase):
315
309
    """Test that we trap an insert which should not occur."""
316
310
    def runTest(self):
396
390
                '}',
397
391
                ('}', 0)]
398
392
 
399
 
        k._sha1s = [sha_string('foo {}')
400
 
                  , sha_string('foo {  added in version 1  also from v1}')
401
 
                  , sha_string('foo {  added in v2}')
402
 
                  , sha_string('foo {  added in version 1  added in v2  also from v1}')
403
 
                  ]
404
 
 
405
 
        self.assertEqual(k.get_lines(0),
 
393
        self.assertEqual(k.get(0),
406
394
                         ['foo {',
407
395
                          '}'])
408
396
 
409
 
        self.assertEqual(k.get_lines(1),
 
397
        self.assertEqual(k.get(1),
410
398
                         ['foo {',
411
399
                          '  added in version 1',
412
400
                          '  also from v1',
413
401
                          '}'])
414
402
                       
415
 
        self.assertEqual(k.get_lines(2),
 
403
        self.assertEqual(k.get(2),
416
404
                         ['foo {',
417
405
                          '  added in v2',
418
406
                          '}'])
419
407
 
420
 
        self.assertEqual(k.get_lines(3),
 
408
        self.assertEqual(k.get(3),
421
409
                         ['foo {',
422
410
                          '  added in version 1',
423
411
                          '  added in v2',
425
413
                          '}'])
426
414
                         
427
415
 
 
416
 
428
417
class DeleteLines2(TestBase):
429
418
    """Test recording revisions that delete lines.
430
419
 
433
422
    def runTest(self):
434
423
        k = Weave()
435
424
 
436
 
        k.add_lines('text0', [], ["line the first",
 
425
        k.add('text0', [], ["line the first",
437
426
                   "line 2",
438
427
                   "line 3",
439
428
                   "fine"])
440
429
 
441
 
        self.assertEqual(len(k.get_lines(0)), 4)
 
430
        self.assertEqual(len(k.get(0)), 4)
442
431
 
443
 
        k.add_lines('text1', ['text0'], ["line the first",
 
432
        k.add('text1', [0], ["line the first",
444
433
                   "fine"])
445
434
 
446
 
        self.assertEqual(k.get_lines(1),
 
435
        self.assertEqual(k.get(1),
447
436
                         ["line the first",
448
437
                          "fine"])
449
438
 
450
 
        self.assertEqual(k.annotate('text1'),
451
 
                         [('text0', "line the first"),
452
 
                          ('text0', "fine")])
 
439
        self.assertEqual(k.annotate(1),
 
440
                         [(0, "line the first"),
 
441
                          (0, "fine")])
 
442
 
453
443
 
454
444
 
455
445
class IncludeVersions(TestBase):
473
463
                "second line",
474
464
                ('}', 1)]
475
465
 
476
 
        k._sha1s = [sha_string('first line')
477
 
                  , sha_string('first linesecond line')]
478
 
 
479
 
        self.assertEqual(k.get_lines(1),
 
466
        self.assertEqual(k.get(1),
480
467
                         ["first line",
481
468
                          "second line"])
482
469
 
483
 
        self.assertEqual(k.get_lines(0),
 
470
        self.assertEqual(k.get(0),
484
471
                         ["first line"])
485
472
 
 
473
        k.dump(self.TEST_LOG)
 
474
 
486
475
 
487
476
class DivergedIncludes(TestBase):
488
477
    """Weave with two diverged texts based on version 0.
489
478
    """
490
479
    def runTest(self):
491
 
        # FIXME make the weave, dont poke at it.
492
480
        k = Weave()
493
481
 
494
 
        k._names = ['0', '1', '2']
495
 
        k._name_map = {'0':0, '1':1, '2':2}
496
482
        k._parents = [frozenset(),
497
483
                frozenset([0]),
498
484
                frozenset([0]),
508
494
                ('}', 2),                
509
495
                ]
510
496
 
511
 
        k._sha1s = [sha_string('first line')
512
 
                  , sha_string('first linesecond line')
513
 
                  , sha_string('first linealternative second line')]
514
 
 
515
 
        self.assertEqual(k.get_lines(0),
 
497
        self.assertEqual(k.get(0),
516
498
                         ["first line"])
517
499
 
518
 
        self.assertEqual(k.get_lines(1),
 
500
        self.assertEqual(k.get(1),
519
501
                         ["first line",
520
502
                          "second line"])
521
503
 
522
 
        self.assertEqual(k.get_lines('2'),
 
504
        self.assertEqual(k.get(2),
523
505
                         ["first line",
524
506
                          "alternative second line"])
525
507
 
526
 
        self.assertEqual(list(k.get_ancestry(['2'])),
527
 
                         ['0', '2'])
 
508
        self.assertEqual(list(k.inclusions([2])),
 
509
                         [0, 2])
 
510
 
528
511
 
529
512
 
530
513
class ReplaceLine(TestBase):
534
517
        text0 = ['cheddar', 'stilton', 'gruyere']
535
518
        text1 = ['cheddar', 'blue vein', 'neufchatel', 'chevre']
536
519
        
537
 
        k.add_lines('text0', [], text0)
538
 
        k.add_lines('text1', ['text0'], text1)
 
520
        k.add('text0', [], text0)
 
521
        k.add('text1', [0], text1)
539
522
 
540
523
        self.log('k._weave=' + pformat(k._weave))
541
524
 
542
 
        self.assertEqual(k.get_lines(0), text0)
543
 
        self.assertEqual(k.get_lines(1), text1)
 
525
        self.assertEqual(k.get(0), text0)
 
526
        self.assertEqual(k.get(1), text1)
 
527
 
544
528
 
545
529
 
546
530
class Merge(TestBase):
554
538
                 ['header', '', 'line from 1', 'fixup line', 'line from 2'],
555
539
                 ]
556
540
 
557
 
        k.add_lines('text0', [], texts[0])
558
 
        k.add_lines('text1', ['text0'], texts[1])
559
 
        k.add_lines('text2', ['text0'], texts[2])
560
 
        k.add_lines('merge', ['text0', 'text1', 'text2'], texts[3])
 
541
        k.add('text0', [], texts[0])
 
542
        k.add('text1', [0], texts[1])
 
543
        k.add('text2', [0], texts[2])
 
544
        k.add('merge', [0, 1, 2], texts[3])
561
545
 
562
546
        for i, t in enumerate(texts):
563
 
            self.assertEqual(k.get_lines(i), t)
 
547
            self.assertEqual(k.get(i), t)
564
548
 
565
 
        self.assertEqual(k.annotate('merge'),
566
 
                         [('text0', 'header'),
567
 
                          ('text1', ''),
568
 
                          ('text1', 'line from 1'),
569
 
                          ('merge', 'fixup line'),
570
 
                          ('text2', 'line from 2'),
 
549
        self.assertEqual(k.annotate(3),
 
550
                         [(0, 'header'),
 
551
                          (1, ''),
 
552
                          (1, 'line from 1'),
 
553
                          (3, 'fixup line'),
 
554
                          (2, 'line from 2'),
571
555
                          ])
572
556
 
573
 
        self.assertEqual(list(k.get_ancestry(['merge'])),
574
 
                         ['text0', 'text1', 'text2', 'merge'])
 
557
        self.assertEqual(list(k.inclusions([3])),
 
558
                         [0, 1, 2, 3])
575
559
 
576
560
        self.log('k._weave=' + pformat(k._weave))
577
561
 
588
572
        return  # NOT RUN
589
573
        k = Weave()
590
574
 
591
 
        k.add_lines([], ['aaa', 'bbb'])
592
 
        k.add_lines([0], ['aaa', '111', 'bbb'])
593
 
        k.add_lines([1], ['aaa', '222', 'bbb'])
 
575
        k.add([], ['aaa', 'bbb'])
 
576
        k.add([0], ['aaa', '111', 'bbb'])
 
577
        k.add([1], ['aaa', '222', 'bbb'])
594
578
 
595
579
        merged = k.merge([1, 2])
596
580
 
599
583
                           [['bbb']]])
600
584
 
601
585
 
 
586
 
602
587
class NonConflict(TestBase):
603
588
    """Two descendants insert compatible changes.
604
589
 
607
592
        return  # NOT RUN
608
593
        k = Weave()
609
594
 
610
 
        k.add_lines([], ['aaa', 'bbb'])
611
 
        k.add_lines([0], ['111', 'aaa', 'ccc', 'bbb'])
612
 
        k.add_lines([1], ['aaa', 'ccc', 'bbb', '222'])
 
595
        k.add([], ['aaa', 'bbb'])
 
596
        k.add([0], ['111', 'aaa', 'ccc', 'bbb'])
 
597
        k.add([1], ['aaa', 'ccc', 'bbb', '222'])
 
598
 
 
599
    
 
600
    
 
601
 
 
602
 
 
603
class AutoMerge(TestBase):
 
604
    def runTest(self):
 
605
        k = Weave()
 
606
 
 
607
        texts = [['header', 'aaa', 'bbb'],
 
608
                 ['header', 'aaa', 'line from 1', 'bbb'],
 
609
                 ['header', 'aaa', 'bbb', 'line from 2', 'more from 2'],
 
610
                 ]
 
611
 
 
612
        k.add('text0', [], texts[0])
 
613
        k.add('text1', [0], texts[1])
 
614
        k.add('text2', [0], texts[2])
 
615
 
 
616
        self.log('k._weave=' + pformat(k._weave))
 
617
 
 
618
        m = list(k.mash_iter([0, 1, 2]))
 
619
 
 
620
        self.assertEqual(m,
 
621
                         ['header', 'aaa',
 
622
                          'line from 1',
 
623
                          'bbb',
 
624
                          'line from 2', 'more from 2'])
 
625
        
613
626
 
614
627
 
615
628
class Khayyam(TestBase):
616
629
    """Test changes to multi-line texts, and read/write"""
617
 
 
618
 
    def test_multi_line_merge(self):
 
630
    def runTest(self):
619
631
        rawtexts = [
620
632
            """A Book of Verses underneath the Bough,
621
633
            A Jug of Wine, a Loaf of Bread, -- and Thou
647
659
        parents = set()
648
660
        i = 0
649
661
        for t in texts:
650
 
            ver = k.add_lines('text%d' % i,
 
662
            ver = k.add('text%d' % i,
651
663
                        list(parents), t)
652
 
            parents.add('text%d' % i)
 
664
            parents.add(ver)
653
665
            i += 1
654
666
 
655
667
        self.log("k._weave=" + pformat(k._weave))
656
668
 
657
669
        for i, t in enumerate(texts):
658
 
            self.assertEqual(k.get_lines(i), t)
 
670
            self.assertEqual(k.get(i), t)
659
671
 
660
672
        self.check_read_write(k)
661
673
 
662
674
 
663
 
class JoinWeavesTests(TestBase):
664
 
    def setUp(self):
665
 
        super(JoinWeavesTests, self).setUp()
666
 
        self.weave1 = Weave()
667
 
        self.lines1 = ['hello\n']
668
 
        self.lines3 = ['hello\n', 'cruel\n', 'world\n']
669
 
        self.weave1.add_lines('v1', [], self.lines1)
670
 
        self.weave1.add_lines('v2', ['v1'], ['hello\n', 'world\n'])
671
 
        self.weave1.add_lines('v3', ['v2'], self.lines3)
672
 
        
673
 
    def test_join_empty(self):
674
 
        """Join two empty weaves."""
675
 
        eq = self.assertEqual
676
 
        w1 = Weave()
677
 
        w2 = Weave()
678
 
        w1.join(w2)
679
 
        eq(len(w1), 0)
680
 
        
681
 
    def test_join_empty_to_nonempty(self):
682
 
        """Join empty weave onto nonempty."""
683
 
        self.weave1.join(Weave())
684
 
        self.assertEqual(len(self.weave1), 3)
685
 
 
686
 
    def test_join_unrelated(self):
687
 
        """Join two weaves with no history in common."""
688
 
        wb = Weave()
689
 
        wb.add_lines('b1', [], ['line from b\n'])
690
 
        w1 = self.weave1
691
 
        w1.join(wb)
692
 
        eq = self.assertEqual
693
 
        eq(len(w1), 4)
694
 
        eq(sorted(w1.versions()),
695
 
           ['b1', 'v1', 'v2', 'v3'])
696
 
 
697
 
    def test_join_related(self):
698
 
        wa = self.weave1.copy()
699
 
        wb = self.weave1.copy()
700
 
        wa.add_lines('a1', ['v3'], ['hello\n', 'sweet\n', 'world\n'])
701
 
        wb.add_lines('b1', ['v3'], ['hello\n', 'pale blue\n', 'world\n'])
702
 
        eq = self.assertEquals
703
 
        eq(len(wa), 4)
704
 
        eq(len(wb), 4)
705
 
        wa.join(wb)
706
 
        eq(len(wa), 5)
707
 
        eq(wa.get_lines('b1'),
708
 
           ['hello\n', 'pale blue\n', 'world\n'])
709
 
 
710
 
    def test_join_text_disagreement(self):
711
 
        """Cannot join weaves with different texts for a version."""
712
 
        wa = Weave()
713
 
        wb = Weave()
714
 
        wa.add_lines('v1', [], ['hello\n'])
715
 
        wb.add_lines('v1', [], ['not\n', 'hello\n'])
716
 
        self.assertRaises(WeaveError,
717
 
                          wa.join, wb)
718
 
 
719
 
    def test_join_unordered(self):
720
 
        """Join weaves where indexes differ.
721
 
        
722
 
        The source weave contains a different version at index 0."""
723
 
        wa = self.weave1.copy()
724
 
        wb = Weave()
725
 
        wb.add_lines('x1', [], ['line from x1\n'])
726
 
        wb.add_lines('v1', [], ['hello\n'])
727
 
        wb.add_lines('v2', ['v1'], ['hello\n', 'world\n'])
728
 
        wa.join(wb)
729
 
        eq = self.assertEquals
730
 
        eq(sorted(wa.versions()), ['v1', 'v2', 'v3', 'x1',])
731
 
        eq(wa.get_text('x1'), 'line from x1\n')
732
 
 
733
 
    def test_written_detection(self):
734
 
        # Test detection of weave file corruption.
735
 
        #
736
 
        # Make sure that we can detect if a weave file has
737
 
        # been corrupted. This doesn't test all forms of corruption,
738
 
        # but it at least helps verify the data you get, is what you want.
 
675
 
 
676
class MergeCases(TestBase):
 
677
    def doMerge(self, base, a, b, mp):
739
678
        from cStringIO import StringIO
 
679
        from textwrap import dedent
740
680
 
 
681
        def addcrlf(x):
 
682
            return x + '\n'
 
683
        
741
684
        w = Weave()
742
 
        w.add_lines('v1', [], ['hello\n'])
743
 
        w.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
 
685
        w.add('text0', [], map(addcrlf, base))
 
686
        w.add('text1', [0], map(addcrlf, a))
 
687
        w.add('text2', [0], map(addcrlf, b))
744
688
 
 
689
        self.log('weave is:')
745
690
        tmpf = StringIO()
746
691
        write_weave(w, tmpf)
747
 
 
748
 
        # Because we are corrupting, we need to make sure we have the exact text
749
 
        self.assertEquals('# bzr weave file v5\n'
750
 
                          'i\n1 f572d396fae9206628714fb2ce00f72e94f2258f\nn v1\n\n'
751
 
                          'i 0\n1 90f265c6e75f1c8f9ab76dcf85528352c5f215ef\nn v2\n\n'
752
 
                          'w\n{ 0\n. hello\n}\n{ 1\n. there\n}\nW\n',
753
 
                          tmpf.getvalue())
754
 
 
755
 
        # Change a single letter
756
 
        tmpf = StringIO('# bzr weave file v5\n'
757
 
                        'i\n1 f572d396fae9206628714fb2ce00f72e94f2258f\nn v1\n\n'
758
 
                        'i 0\n1 90f265c6e75f1c8f9ab76dcf85528352c5f215ef\nn v2\n\n'
759
 
                        'w\n{ 0\n. hello\n}\n{ 1\n. There\n}\nW\n')
760
 
 
761
 
        w = read_weave(tmpf)
762
 
 
763
 
        self.assertEqual('hello\n', w.get_text('v1'))
764
 
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_text, 'v2')
765
 
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_lines, 'v2')
766
 
        self.assertRaises(errors.WeaveInvalidChecksum, w.check)
767
 
 
768
 
        # Change the sha checksum
769
 
        tmpf = StringIO('# bzr weave file v5\n'
770
 
                        'i\n1 f572d396fae9206628714fb2ce00f72e94f2258f\nn v1\n\n'
771
 
                        'i 0\n1 f0f265c6e75f1c8f9ab76dcf85528352c5f215ef\nn v2\n\n'
772
 
                        'w\n{ 0\n. hello\n}\n{ 1\n. there\n}\nW\n')
773
 
 
774
 
        w = read_weave(tmpf)
775
 
 
776
 
        self.assertEqual('hello\n', w.get_text('v1'))
777
 
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_text, 'v2')
778
 
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_lines, 'v2')
779
 
        self.assertRaises(errors.WeaveInvalidChecksum, w.check)
780
 
 
781
 
 
782
 
class InstrumentedWeave(Weave):
783
 
    """Keep track of how many times functions are called."""
784
 
    
785
 
    def __init__(self, weave_name=None):
786
 
        self._extract_count = 0
787
 
        Weave.__init__(self, weave_name=weave_name)
788
 
 
789
 
    def _extract(self, versions):
790
 
        self._extract_count += 1
791
 
        return Weave._extract(self, versions)
792
 
 
793
 
 
794
 
class JoinOptimization(TestCase):
795
 
    """Test that Weave.join() doesn't extract all texts, only what must be done."""
796
 
 
797
 
    def test_join(self):
798
 
        w1 = InstrumentedWeave()
799
 
        w2 = InstrumentedWeave()
800
 
 
801
 
        txt0 = ['a\n']
802
 
        txt1 = ['a\n', 'b\n']
803
 
        txt2 = ['a\n', 'c\n']
804
 
        txt3 = ['a\n', 'b\n', 'c\n']
805
 
 
806
 
        w1.add_lines('txt0', [], txt0) # extract 1a
807
 
        w2.add_lines('txt0', [], txt0) # extract 1b
808
 
        w1.add_lines('txt1', ['txt0'], txt1)# extract 2a
809
 
        w2.add_lines('txt2', ['txt0'], txt2)# extract 2b
810
 
        w1.join(w2) # extract 3a to add txt2 
811
 
        w2.join(w1) # extract 3b to add txt1 
812
 
 
813
 
        w1.add_lines('txt3', ['txt1', 'txt2'], txt3) # extract 4a 
814
 
        w2.add_lines('txt3', ['txt2', 'txt1'], txt3) # extract 4b
815
 
        # These secretly have inverted parents
816
 
 
817
 
        # This should not have to do any extractions
818
 
        w1.join(w2) # NO extract, texts already present with same parents
819
 
        w2.join(w1) # NO extract, texts already present with same parents
820
 
 
821
 
        self.assertEqual(4, w1._extract_count)
822
 
        self.assertEqual(4, w2._extract_count)
823
 
 
824
 
    def test_double_parent(self):
825
 
        # It should not be considered illegal to add
826
 
        # a revision with the same parent twice
827
 
        w1 = InstrumentedWeave()
828
 
        w2 = InstrumentedWeave()
829
 
 
830
 
        txt0 = ['a\n']
831
 
        txt1 = ['a\n', 'b\n']
832
 
        txt2 = ['a\n', 'c\n']
833
 
        txt3 = ['a\n', 'b\n', 'c\n']
834
 
 
835
 
        w1.add_lines('txt0', [], txt0)
836
 
        w2.add_lines('txt0', [], txt0)
837
 
        w1.add_lines('txt1', ['txt0'], txt1)
838
 
        w2.add_lines('txt1', ['txt0', 'txt0'], txt1)
839
 
        # Same text, effectively the same, because the
840
 
        # parent is only repeated
841
 
        w1.join(w2) # extract 3a to add txt2 
842
 
        w2.join(w1) # extract 3b to add txt1 
843
 
 
844
 
 
845
 
class TestNeedsReweave(TestCase):
846
 
    """Internal corner cases for when reweave is needed."""
847
 
 
848
 
    def test_compatible_parents(self):
849
 
        w1 = Weave('a')
850
 
        my_parents = set([1, 2, 3])
851
 
        # subsets are ok
852
 
        self.assertTrue(w1._compatible_parents(my_parents, set([3])))
853
 
        # same sets
854
 
        self.assertTrue(w1._compatible_parents(my_parents, set(my_parents)))
855
 
        # same empty corner case
856
 
        self.assertTrue(w1._compatible_parents(set(), set()))
857
 
        # other cannot contain stuff my_parents does not
858
 
        self.assertFalse(w1._compatible_parents(set(), set([1])))
859
 
        self.assertFalse(w1._compatible_parents(my_parents, set([1, 2, 3, 4])))
860
 
        self.assertFalse(w1._compatible_parents(my_parents, set([4])))
861
 
 
862
 
 
863
 
class TestWeaveFile(TestCaseInTempDir):
864
 
    
865
 
    def test_empty_file(self):
866
 
        f = open('empty.weave', 'wb+')
867
 
        try:
868
 
            self.assertRaises(errors.WeaveFormatError,
869
 
                              read_weave, f)
870
 
        finally:
871
 
            f.close()
 
692
        self.log(tmpf.getvalue())
 
693
 
 
694
        self.log('merge plan:')
 
695
        p = list(w.plan_merge(1, 2))
 
696
        for state, line in p:
 
697
            if line:
 
698
                self.log('%12s | %s' % (state, line[:-1]))
 
699
 
 
700
        self.log('merge:')
 
701
        mt = StringIO()
 
702
        mt.writelines(w.weave_merge(p))
 
703
        mt.seek(0)
 
704
        self.log(mt.getvalue())
 
705
 
 
706
        mp = map(addcrlf, mp)
 
707
        self.assertEqual(mt.readlines(), mp)
 
708
        
 
709
        
 
710
    def testOneInsert(self):
 
711
        self.doMerge([],
 
712
                     ['aa'],
 
713
                     [],
 
714
                     ['aa'])
 
715
 
 
716
    def testSeparateInserts(self):
 
717
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
718
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
719
                     ['aaa', 'bbb', 'yyy', 'ccc'],
 
720
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
721
 
 
722
    def testSameInsert(self):
 
723
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
724
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
725
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'],
 
726
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
727
 
 
728
    def testOverlappedInsert(self):
 
729
        self.doMerge(['aaa', 'bbb'],
 
730
                     ['aaa', 'xxx', 'yyy', 'bbb'],
 
731
                     ['aaa', 'xxx', 'bbb'],
 
732
                     ['aaa', '<<<<', 'xxx', 'yyy', '====', 'xxx', '>>>>', 'bbb'])
 
733
 
 
734
        # really it ought to reduce this to 
 
735
        # ['aaa', 'xxx', 'yyy', 'bbb']
 
736
 
 
737
 
 
738
    def testClashReplace(self):
 
739
        self.doMerge(['aaa'],
 
740
                     ['xxx'],
 
741
                     ['yyy', 'zzz'],
 
742
                     ['<<<<', 'xxx', '====', 'yyy', 'zzz', '>>>>'])
 
743
 
 
744
    def testNonClashInsert(self):
 
745
        self.doMerge(['aaa'],
 
746
                     ['xxx', 'aaa'],
 
747
                     ['yyy', 'zzz'],
 
748
                     ['<<<<', 'xxx', 'aaa', '====', 'yyy', 'zzz', '>>>>'])
 
749
 
 
750
        self.doMerge(['aaa'],
 
751
                     ['aaa'],
 
752
                     ['yyy', 'zzz'],
 
753
                     ['yyy', 'zzz'])
 
754
 
 
755
 
 
756
    def testDeleteAndModify(self):
 
757
        """Clashing delete and modification.
 
758
 
 
759
        If one side modifies a region and the other deletes it then
 
760
        there should be a conflict with one side blank.
 
761
        """
 
762
 
 
763
        #######################################
 
764
        # skippd, not working yet
 
765
        return
 
766
        
 
767
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
768
                     ['aaa', 'ddd', 'ccc'],
 
769
                     ['aaa', 'ccc'],
 
770
                     ['<<<<', 'aaa', '====', '>>>>', 'ccc'])
 
771
    
 
772
 
 
773
 
 
774
def testweave():
 
775
    import testsweet
 
776
    from unittest import TestSuite, TestLoader
 
777
    import testweave
 
778
 
 
779
    tl = TestLoader()
 
780
    suite = TestSuite()
 
781
    suite.addTest(tl.loadTestsFromModule(testweave))
 
782
    
 
783
    return int(not testsweet.run_suite(suite)) # for shell 0=true
 
784
 
 
785
 
 
786
if __name__ == '__main__':
 
787
    import sys
 
788
    sys.exit(testweave())
 
789