/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to tools/testweave.py

  • Committer: Martin Pool
  • Date: 2005-08-04 22:04:40 UTC
  • Revision ID: mbp@sourcefrog.net-20050804220440-99562df8151d1ac5
- add pending merge from aaron

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
 
# TODO: tests regarding version names
19
 
# TODO: rbc 20050108 test that join does not leave an inconsistent weave 
20
 
#       if it fails.
 
20
 
21
21
 
22
22
"""test suite for weave algorithm"""
23
23
 
 
24
 
 
25
import testsweet
 
26
from bzrlib.weave import Weave, WeaveFormatError
 
27
from bzrlib.weavefile import write_weave, read_weave
24
28
from pprint import pformat
25
29
 
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
 
30
 
 
31
try:
 
32
    set
 
33
    frozenset
 
34
except NameError:
 
35
    from sets import Set, ImmutableSet
 
36
    set = Set
 
37
    frozenset = ImmutableSet
 
38
    del Set, ImmutableSet
 
39
 
33
40
 
34
41
 
35
42
# texts for use in testing
38
45
          "A second line"]
39
46
 
40
47
 
41
 
class TestBase(TestCase):
42
48
 
 
49
class TestBase(testsweet.TestBase):
43
50
    def check_read_write(self, k):
44
51
        """Check the weave k can be written & re-read."""
45
52
        from tempfile import TemporaryFile
53
60
            tf.seek(0)
54
61
            self.log('serialized weave:')
55
62
            self.log(tf.read())
56
 
 
57
 
            self.log('')
58
 
            self.log('parents: %s' % (k._parents == k2._parents))
59
 
            self.log('         %r' % k._parents)
60
 
            self.log('         %r' % k2._parents)
61
 
            self.log('')
62
63
            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)
 
64
        
 
65
        
72
66
 
73
67
 
74
68
class Easy(TestBase):
76
70
        k = Weave()
77
71
 
78
72
 
 
73
class StoreText(TestBase):
 
74
    """Store and retrieve a simple text."""
 
75
    def runTest(self):
 
76
        k = Weave()
 
77
        idx = k.add([], TEXT_0)
 
78
        self.assertEqual(k.get(idx), TEXT_0)
 
79
        self.assertEqual(idx, 0)
 
80
 
 
81
 
 
82
 
79
83
class AnnotateOne(TestBase):
80
84
    def runTest(self):
81
85
        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):
 
86
        k.add([], TEXT_0)
 
87
        self.assertEqual(k.annotate(0),
 
88
                         [(0, TEXT_0[0])])
 
89
 
 
90
 
 
91
class StoreTwo(TestBase):
 
92
    def runTest(self):
89
93
        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
 
                        
 
94
 
 
95
        idx = k.add([], TEXT_0)
 
96
        self.assertEqual(idx, 0)
 
97
 
 
98
        idx = k.add([], TEXT_1)
 
99
        self.assertEqual(idx, 1)
 
100
 
 
101
        self.assertEqual(k.get(0), TEXT_0)
 
102
        self.assertEqual(k.get(1), TEXT_1)
 
103
 
 
104
        k.dump(self.TEST_LOG)
 
105
 
 
106
 
98
107
 
99
108
class InvalidAdd(TestBase):
100
109
    """Try to use invalid version number during add."""
101
110
    def runTest(self):
102
111
        k = Weave()
103
112
 
104
 
        self.assertRaises(errors.RevisionNotPresent,
105
 
                          k.add_lines,
106
 
                          'text0',
107
 
                          ['69'],
 
113
        self.assertRaises(IndexError,
 
114
                          k.add,
 
115
                          [69],
108
116
                          ['new text!'])
109
117
 
110
118
 
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
119
class InsertLines(TestBase):
139
120
    """Store a revision that adds one line to the original.
140
121
 
143
124
    def runTest(self):
144
125
        k = Weave()
145
126
 
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),
 
127
        k.add([], ['line 1'])
 
128
        k.add([0], ['line 1', 'line 2'])
 
129
 
 
130
        self.assertEqual(k.annotate(0),
 
131
                         [(0, 'line 1')])
 
132
 
 
133
        self.assertEqual(k.get(1),
153
134
                         ['line 1',
154
135
                          'line 2'])
155
136
 
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')])
 
137
        self.assertEqual(k.annotate(1),
 
138
                         [(0, 'line 1'),
 
139
                          (1, 'line 2')])
 
140
 
 
141
        k.add([0], ['line 1', 'diverged line'])
 
142
 
 
143
        self.assertEqual(k.annotate(2),
 
144
                         [(0, 'line 1'),
 
145
                          (2, 'diverged line')])
165
146
 
166
147
        text3 = ['line 1', 'middle line', 'line 2']
167
 
        k.add_lines('text3',
168
 
              ['text0', 'text1'],
 
148
        k.add([0, 1],
169
149
              text3)
170
150
 
171
151
        # self.log("changes to text3: " + pformat(list(k._delta(set([0, 1]), text3))))
172
152
 
173
153
        self.log("k._weave=" + pformat(k._weave))
174
154
 
175
 
        self.assertEqual(k.annotate('text3'),
176
 
                         [('text0', 'line 1'),
177
 
                          ('text3', 'middle line'),
178
 
                          ('text1', 'line 2')])
 
155
        self.assertEqual(k.annotate(3),
 
156
                         [(0, 'line 1'),
 
157
                          (3, 'middle line'),
 
158
                          (1, 'line 2')])
179
159
 
180
160
        # now multiple insertions at different places
181
 
        k.add_lines('text4',
182
 
              ['text0', 'text1', 'text3'],
 
161
        k.add([0, 1, 3],
183
162
              ['line 1', 'aaa', 'middle line', 'bbb', 'line 2', 'ccc'])
184
163
 
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')])
 
164
        self.assertEqual(k.annotate(4), 
 
165
                         [(0, 'line 1'),
 
166
                          (4, 'aaa'),
 
167
                          (3, 'middle line'),
 
168
                          (4, 'bbb'),
 
169
                          (1, 'line 2'),
 
170
                          (4, 'ccc')])
 
171
 
192
172
 
193
173
 
194
174
class DeleteLines(TestBase):
200
180
 
201
181
        base_text = ['one', 'two', 'three', 'four']
202
182
 
203
 
        k.add_lines('text0', [], base_text)
 
183
        k.add([], base_text)
204
184
        
205
185
        texts = [['one', 'two', 'three'],
206
186
                 ['two', 'three', 'four'],
208
188
                 ['one', 'two', 'three', 'four'],
209
189
                 ]
210
190
 
211
 
        i = 1
212
191
        for t in texts:
213
 
            ver = k.add_lines('text%d' % i,
214
 
                        ['text0'], t)
215
 
            i += 1
 
192
            ver = k.add([0], t)
216
193
 
217
194
        self.log('final weave:')
218
195
        self.log('k._weave=' + pformat(k._weave))
219
196
 
220
197
        for i in range(len(texts)):
221
 
            self.assertEqual(k.get_lines(i+1),
 
198
            self.assertEqual(k.get(i+1),
222
199
                             texts[i])
 
200
            
 
201
 
223
202
 
224
203
 
225
204
class SuicideDelete(TestBase):
241
220
        return 
242
221
 
243
222
        self.assertRaises(WeaveFormatError,
244
 
                          k.get_lines,
 
223
                          k.get,
245
224
                          0)        
246
225
 
247
226
 
 
227
 
248
228
class CannedDelete(TestBase):
249
229
    """Unpack canned weave with deleted lines."""
250
230
    def runTest(self):
261
241
                'last line',
262
242
                ('}', 0),
263
243
                ]
264
 
        k._sha1s = [sha_string('first lineline to be deletedlast line')
265
 
                  , sha_string('first linelast line')]
266
244
 
267
 
        self.assertEqual(k.get_lines(0),
 
245
        self.assertEqual(k.get(0),
268
246
                         ['first line',
269
247
                          'line to be deleted',
270
248
                          'last line',
271
249
                          ])
272
250
 
273
 
        self.assertEqual(k.get_lines(1),
 
251
        self.assertEqual(k.get(1),
274
252
                         ['first line',
275
253
                          'last line',
276
254
                          ])
277
255
 
278
256
 
 
257
 
279
258
class CannedReplacement(TestBase):
280
259
    """Unpack canned weave with deleted lines."""
281
260
    def runTest(self):
295
274
                'last line',
296
275
                ('}', 0),
297
276
                ]
298
 
        k._sha1s = [sha_string('first lineline to be deletedlast line')
299
 
                  , sha_string('first linereplacement linelast line')]
300
277
 
301
 
        self.assertEqual(k.get_lines(0),
 
278
        self.assertEqual(k.get(0),
302
279
                         ['first line',
303
280
                          'line to be deleted',
304
281
                          'last line',
305
282
                          ])
306
283
 
307
 
        self.assertEqual(k.get_lines(1),
 
284
        self.assertEqual(k.get(1),
308
285
                         ['first line',
309
286
                          'replacement line',
310
287
                          'last line',
311
288
                          ])
312
289
 
313
290
 
 
291
 
314
292
class BadWeave(TestBase):
315
293
    """Test that we trap an insert which should not occur."""
316
294
    def runTest(self):
396
374
                '}',
397
375
                ('}', 0)]
398
376
 
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),
 
377
        self.assertEqual(k.get(0),
406
378
                         ['foo {',
407
379
                          '}'])
408
380
 
409
 
        self.assertEqual(k.get_lines(1),
 
381
        self.assertEqual(k.get(1),
410
382
                         ['foo {',
411
383
                          '  added in version 1',
412
384
                          '  also from v1',
413
385
                          '}'])
414
386
                       
415
 
        self.assertEqual(k.get_lines(2),
 
387
        self.assertEqual(k.get(2),
416
388
                         ['foo {',
417
389
                          '  added in v2',
418
390
                          '}'])
419
391
 
420
 
        self.assertEqual(k.get_lines(3),
 
392
        self.assertEqual(k.get(3),
421
393
                         ['foo {',
422
394
                          '  added in version 1',
423
395
                          '  added in v2',
425
397
                          '}'])
426
398
                         
427
399
 
 
400
 
428
401
class DeleteLines2(TestBase):
429
402
    """Test recording revisions that delete lines.
430
403
 
433
406
    def runTest(self):
434
407
        k = Weave()
435
408
 
436
 
        k.add_lines('text0', [], ["line the first",
 
409
        k.add([], ["line the first",
437
410
                   "line 2",
438
411
                   "line 3",
439
412
                   "fine"])
440
413
 
441
 
        self.assertEqual(len(k.get_lines(0)), 4)
 
414
        self.assertEqual(len(k.get(0)), 4)
442
415
 
443
 
        k.add_lines('text1', ['text0'], ["line the first",
 
416
        k.add([0], ["line the first",
444
417
                   "fine"])
445
418
 
446
 
        self.assertEqual(k.get_lines(1),
 
419
        self.assertEqual(k.get(1),
447
420
                         ["line the first",
448
421
                          "fine"])
449
422
 
450
 
        self.assertEqual(k.annotate('text1'),
451
 
                         [('text0', "line the first"),
452
 
                          ('text0', "fine")])
 
423
        self.assertEqual(k.annotate(1),
 
424
                         [(0, "line the first"),
 
425
                          (0, "fine")])
 
426
 
453
427
 
454
428
 
455
429
class IncludeVersions(TestBase):
473
447
                "second line",
474
448
                ('}', 1)]
475
449
 
476
 
        k._sha1s = [sha_string('first line')
477
 
                  , sha_string('first linesecond line')]
478
 
 
479
 
        self.assertEqual(k.get_lines(1),
 
450
        self.assertEqual(k.get(1),
480
451
                         ["first line",
481
452
                          "second line"])
482
453
 
483
 
        self.assertEqual(k.get_lines(0),
 
454
        self.assertEqual(k.get(0),
484
455
                         ["first line"])
485
456
 
 
457
        k.dump(self.TEST_LOG)
 
458
 
486
459
 
487
460
class DivergedIncludes(TestBase):
488
461
    """Weave with two diverged texts based on version 0.
489
462
    """
490
463
    def runTest(self):
491
 
        # FIXME make the weave, dont poke at it.
492
464
        k = Weave()
493
465
 
494
 
        k._names = ['0', '1', '2']
495
 
        k._name_map = {'0':0, '1':1, '2':2}
496
466
        k._parents = [frozenset(),
497
467
                frozenset([0]),
498
468
                frozenset([0]),
508
478
                ('}', 2),                
509
479
                ]
510
480
 
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),
 
481
        self.assertEqual(k.get(0),
516
482
                         ["first line"])
517
483
 
518
 
        self.assertEqual(k.get_lines(1),
 
484
        self.assertEqual(k.get(1),
519
485
                         ["first line",
520
486
                          "second line"])
521
487
 
522
 
        self.assertEqual(k.get_lines('2'),
 
488
        self.assertEqual(k.get(2),
523
489
                         ["first line",
524
490
                          "alternative second line"])
525
491
 
526
 
        self.assertEqual(list(k.get_ancestry(['2'])),
527
 
                         ['0', '2'])
 
492
        self.assertEqual(list(k.inclusions([2])),
 
493
                         [0, 2])
 
494
 
528
495
 
529
496
 
530
497
class ReplaceLine(TestBase):
534
501
        text0 = ['cheddar', 'stilton', 'gruyere']
535
502
        text1 = ['cheddar', 'blue vein', 'neufchatel', 'chevre']
536
503
        
537
 
        k.add_lines('text0', [], text0)
538
 
        k.add_lines('text1', ['text0'], text1)
 
504
        k.add([], text0)
 
505
        k.add([0], text1)
539
506
 
540
507
        self.log('k._weave=' + pformat(k._weave))
541
508
 
542
 
        self.assertEqual(k.get_lines(0), text0)
543
 
        self.assertEqual(k.get_lines(1), text1)
 
509
        self.assertEqual(k.get(0), text0)
 
510
        self.assertEqual(k.get(1), text1)
 
511
 
544
512
 
545
513
 
546
514
class Merge(TestBase):
554
522
                 ['header', '', 'line from 1', 'fixup line', 'line from 2'],
555
523
                 ]
556
524
 
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])
 
525
        k.add([], texts[0])
 
526
        k.add([0], texts[1])
 
527
        k.add([0], texts[2])
 
528
        k.add([0, 1, 2], texts[3])
561
529
 
562
530
        for i, t in enumerate(texts):
563
 
            self.assertEqual(k.get_lines(i), t)
 
531
            self.assertEqual(k.get(i), t)
564
532
 
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'),
 
533
        self.assertEqual(k.annotate(3),
 
534
                         [(0, 'header'),
 
535
                          (1, ''),
 
536
                          (1, 'line from 1'),
 
537
                          (3, 'fixup line'),
 
538
                          (2, 'line from 2'),
571
539
                          ])
572
540
 
573
 
        self.assertEqual(list(k.get_ancestry(['merge'])),
574
 
                         ['text0', 'text1', 'text2', 'merge'])
 
541
        self.assertEqual(list(k.inclusions([3])),
 
542
                         [0, 1, 2, 3])
575
543
 
576
544
        self.log('k._weave=' + pformat(k._weave))
577
545
 
588
556
        return  # NOT RUN
589
557
        k = Weave()
590
558
 
591
 
        k.add_lines([], ['aaa', 'bbb'])
592
 
        k.add_lines([0], ['aaa', '111', 'bbb'])
593
 
        k.add_lines([1], ['aaa', '222', 'bbb'])
 
559
        k.add([], ['aaa', 'bbb'])
 
560
        k.add([0], ['aaa', '111', 'bbb'])
 
561
        k.add([1], ['aaa', '222', 'bbb'])
594
562
 
595
563
        merged = k.merge([1, 2])
596
564
 
599
567
                           [['bbb']]])
600
568
 
601
569
 
 
570
 
602
571
class NonConflict(TestBase):
603
572
    """Two descendants insert compatible changes.
604
573
 
607
576
        return  # NOT RUN
608
577
        k = Weave()
609
578
 
610
 
        k.add_lines([], ['aaa', 'bbb'])
611
 
        k.add_lines([0], ['111', 'aaa', 'ccc', 'bbb'])
612
 
        k.add_lines([1], ['aaa', 'ccc', 'bbb', '222'])
 
579
        k.add([], ['aaa', 'bbb'])
 
580
        k.add([0], ['111', 'aaa', 'ccc', 'bbb'])
 
581
        k.add([1], ['aaa', 'ccc', 'bbb', '222'])
 
582
 
 
583
    
 
584
    
 
585
 
 
586
 
 
587
class AutoMerge(TestBase):
 
588
    def runTest(self):
 
589
        k = Weave()
 
590
 
 
591
        texts = [['header', 'aaa', 'bbb'],
 
592
                 ['header', 'aaa', 'line from 1', 'bbb'],
 
593
                 ['header', 'aaa', 'bbb', 'line from 2', 'more from 2'],
 
594
                 ]
 
595
 
 
596
        k.add([], texts[0])
 
597
        k.add([0], texts[1])
 
598
        k.add([0], texts[2])
 
599
 
 
600
        self.log('k._weave=' + pformat(k._weave))
 
601
 
 
602
        m = list(k.mash_iter([0, 1, 2]))
 
603
 
 
604
        self.assertEqual(m,
 
605
                         ['header', 'aaa',
 
606
                          'line from 1',
 
607
                          'bbb',
 
608
                          'line from 2', 'more from 2'])
 
609
        
613
610
 
614
611
 
615
612
class Khayyam(TestBase):
616
613
    """Test changes to multi-line texts, and read/write"""
617
 
 
618
 
    def test_multi_line_merge(self):
 
614
    def runTest(self):
619
615
        rawtexts = [
620
616
            """A Book of Verses underneath the Bough,
621
617
            A Jug of Wine, a Loaf of Bread, -- and Thou
645
641
 
646
642
        k = Weave()
647
643
        parents = set()
648
 
        i = 0
649
644
        for t in texts:
650
 
            ver = k.add_lines('text%d' % i,
651
 
                        list(parents), t)
652
 
            parents.add('text%d' % i)
653
 
            i += 1
 
645
            ver = k.add(list(parents), t)
 
646
            parents.add(ver)
654
647
 
655
648
        self.log("k._weave=" + pformat(k._weave))
656
649
 
657
650
        for i, t in enumerate(texts):
658
 
            self.assertEqual(k.get_lines(i), t)
 
651
            self.assertEqual(k.get(i), t)
659
652
 
660
653
        self.check_read_write(k)
661
654
 
662
655
 
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.
 
656
 
 
657
class MergeCases(TestBase):
 
658
    def doMerge(self, base, a, b, mp):
739
659
        from cStringIO import StringIO
 
660
        from textwrap import dedent
740
661
 
 
662
        def addcrlf(x):
 
663
            return x + '\n'
 
664
        
741
665
        w = Weave()
742
 
        w.add_lines('v1', [], ['hello\n'])
743
 
        w.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
 
666
        w.add([], map(addcrlf, base))
 
667
        w.add([0], map(addcrlf, a))
 
668
        w.add([0], map(addcrlf, b))
744
669
 
 
670
        self.log('weave is:')
745
671
        tmpf = StringIO()
746
672
        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()
 
673
        self.log(tmpf.getvalue())
 
674
 
 
675
        self.log('merge plan:')
 
676
        p = list(w.plan_merge(1, 2))
 
677
        for state, line in p:
 
678
            if line:
 
679
                self.log('%12s | %s' % (state, line[:-1]))
 
680
 
 
681
        self.log('merge:')
 
682
        mt = StringIO()
 
683
        mt.writelines(w.weave_merge(p))
 
684
        mt.seek(0)
 
685
        self.log(mt.getvalue())
 
686
 
 
687
        mp = map(addcrlf, mp)
 
688
        self.assertEqual(mt.readlines(), mp)
 
689
        
 
690
        
 
691
    def testOneInsert(self):
 
692
        self.doMerge([],
 
693
                     ['aa'],
 
694
                     [],
 
695
                     ['aa'])
 
696
 
 
697
    def testSeparateInserts(self):
 
698
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
699
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
700
                     ['aaa', 'bbb', 'yyy', 'ccc'],
 
701
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
702
 
 
703
    def testSameInsert(self):
 
704
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
705
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
706
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'],
 
707
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
708
 
 
709
    def testOverlappedInsert(self):
 
710
        self.doMerge(['aaa', 'bbb'],
 
711
                     ['aaa', 'xxx', 'yyy', 'bbb'],
 
712
                     ['aaa', 'xxx', 'bbb'],
 
713
                     ['aaa', '<<<<', 'xxx', 'yyy', '====', 'xxx', '>>>>', 'bbb'])
 
714
 
 
715
        # really it ought to reduce this to 
 
716
        # ['aaa', 'xxx', 'yyy', 'bbb']
 
717
 
 
718
 
 
719
    def testClashReplace(self):
 
720
        self.doMerge(['aaa'],
 
721
                     ['xxx'],
 
722
                     ['yyy', 'zzz'],
 
723
                     ['<<<<', 'xxx', '====', 'yyy', 'zzz', '>>>>'])
 
724
 
 
725
    def testNonClashInsert(self):
 
726
        self.doMerge(['aaa'],
 
727
                     ['xxx', 'aaa'],
 
728
                     ['yyy', 'zzz'],
 
729
                     ['<<<<', 'xxx', 'aaa', '====', 'yyy', 'zzz', '>>>>'])
 
730
 
 
731
        self.doMerge(['aaa'],
 
732
                     ['aaa'],
 
733
                     ['yyy', 'zzz'],
 
734
                     ['yyy', 'zzz'])
 
735
 
 
736
 
 
737
    def testDeleteAndModify(self):
 
738
        """Clashing delete and modification.
 
739
 
 
740
        If one side modifies a region and the other deletes it then
 
741
        there should be a conflict with one side blank.
 
742
        """
 
743
 
 
744
        #######################################
 
745
        # skippd, not working yet
 
746
        return
 
747
        
 
748
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
749
                     ['aaa', 'ddd', 'ccc'],
 
750
                     ['aaa', 'ccc'],
 
751
                     ['<<<<', 'aaa', '====', '>>>>', 'ccc'])
 
752
    
 
753
 
 
754
 
 
755
def testweave():
 
756
    import testsweet
 
757
    from unittest import TestSuite, TestLoader
 
758
    import testweave
 
759
 
 
760
    tl = TestLoader()
 
761
    suite = TestSuite()
 
762
    suite.addTest(tl.loadTestsFromModule(testweave))
 
763
    
 
764
    return int(not testsweet.run_suite(suite)) # for shell 0=true
 
765
 
 
766
 
 
767
if __name__ == '__main__':
 
768
    import sys
 
769
    sys.exit(testweave())
 
770