/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 bzrlib/tests/test_versionedfile.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2008-06-05 03:02:10 UTC
  • mfrom: (3472.1.1 ianc-integration)
  • Revision ID: pqm@pqm.ubuntu.com-20080605030210-xwokghqkg4sqo1xy
Isolate the test HTTPServer from chdir calls (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005 by Canonical Ltd
 
1
# Copyright (C) 2005 Canonical Ltd
2
2
#
3
3
# Authors:
4
4
#   Johan Rydberg <jrydberg@gnu.org>
7
7
# it under the terms of the GNU General Public License as published by
8
8
# the Free Software Foundation; either version 2 of the License, or
9
9
# (at your option) any later version.
10
 
 
 
10
#
11
11
# This program is distributed in the hope that it will be useful,
12
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
14
# GNU General Public License for more details.
15
 
 
 
15
#
16
16
# You should have received a copy of the GNU General Public License
17
17
# along with this program; if not, write to the Free Software
18
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
19
 
20
20
 
 
21
# TODO: might be nice to create a versionedfile with some type of corruption
 
22
# considered typical and check that it can be detected/corrected.
 
23
 
 
24
from itertools import chain
 
25
from StringIO import StringIO
 
26
 
21
27
import bzrlib
22
 
import bzrlib.errors as errors
 
28
from bzrlib import (
 
29
    errors,
 
30
    osutils,
 
31
    progress,
 
32
    )
23
33
from bzrlib.errors import (
24
 
                           RevisionNotPresent, 
 
34
                           RevisionNotPresent,
25
35
                           RevisionAlreadyPresent,
26
36
                           WeaveParentMismatch
27
37
                           )
28
 
from bzrlib.knit import KnitVersionedFile, \
29
 
     KnitAnnotateFactory
30
 
from bzrlib.tests import TestCaseWithTransport
 
38
from bzrlib import knit as _mod_knit
 
39
from bzrlib.knit import (
 
40
    make_file_knit,
 
41
    KnitAnnotateFactory,
 
42
    KnitPlainFactory,
 
43
    )
 
44
from bzrlib.symbol_versioning import one_four, one_five
 
45
from bzrlib.tests import TestCaseWithMemoryTransport, TestSkipped
 
46
from bzrlib.tests.http_utils import TestCaseWithWebserver
31
47
from bzrlib.trace import mutter
32
48
from bzrlib.transport import get_transport
33
49
from bzrlib.transport.memory import MemoryTransport
 
50
from bzrlib.tsort import topo_sort
 
51
from bzrlib.tuned_gzip import GzipFile
34
52
import bzrlib.versionedfile as versionedfile
35
53
from bzrlib.weave import WeaveFile
36
 
from bzrlib.weavefile import read_weave
 
54
from bzrlib.weavefile import read_weave, write_weave
 
55
 
 
56
 
 
57
def get_diamond_vf(f, trailing_eol=True, left_only=False):
 
58
    """Get a diamond graph to exercise deltas and merges.
 
59
    
 
60
    :param trailing_eol: If True end the last line with \n.
 
61
    """
 
62
    parents = {
 
63
        'origin': (),
 
64
        'base': (('origin',),),
 
65
        'left': (('base',),),
 
66
        'right': (('base',),),
 
67
        'merged': (('left',), ('right',)),
 
68
        }
 
69
    # insert a diamond graph to exercise deltas and merges.
 
70
    if trailing_eol:
 
71
        last_char = '\n'
 
72
    else:
 
73
        last_char = ''
 
74
    f.add_lines('origin', [], ['origin' + last_char])
 
75
    f.add_lines('base', ['origin'], ['base' + last_char])
 
76
    f.add_lines('left', ['base'], ['base\n', 'left' + last_char])
 
77
    if not left_only:
 
78
        f.add_lines('right', ['base'],
 
79
            ['base\n', 'right' + last_char])
 
80
        f.add_lines('merged', ['left', 'right'],
 
81
            ['base\n', 'left\n', 'right\n', 'merged' + last_char])
 
82
    return f, parents
37
83
 
38
84
 
39
85
class VersionedFileTestMixIn(object):
44
90
    they are strictly controlled by their owning repositories.
45
91
    """
46
92
 
 
93
    def get_transaction(self):
 
94
        if not hasattr(self, '_transaction'):
 
95
            self._transaction = None
 
96
        return self._transaction
 
97
 
47
98
    def test_add(self):
48
99
        f = self.get_file()
49
100
        f.add_lines('r0', [], ['a\n', 'b\n'])
63
114
            self.assertRaises(RevisionAlreadyPresent,
64
115
                f.add_lines, 'r1', [], [])
65
116
        verify_file(f)
66
 
        f = self.reopen_file()
 
117
        # this checks that reopen with create=True does not break anything.
 
118
        f = self.reopen_file(create=True)
67
119
        verify_file(f)
68
120
 
 
121
    def test_get_record_stream_empty(self):
 
122
        """get_record_stream is a replacement for get_data_stream."""
 
123
        f = self.get_file()
 
124
        entries = f.get_record_stream([], 'unordered', False)
 
125
        self.assertEqual([], list(entries))
 
126
 
 
127
    def assertValidStorageKind(self, storage_kind):
 
128
        """Assert that storage_kind is a valid storage_kind."""
 
129
        self.assertSubset([storage_kind],
 
130
            ['mpdiff', 'knit-annotated-ft', 'knit-annotated-delta',
 
131
             'knit-ft', 'knit-delta', 'fulltext', 'knit-annotated-ft-gz',
 
132
             'knit-annotated-delta-gz', 'knit-ft-gz', 'knit-delta-gz'])
 
133
 
 
134
    def capture_stream(self, f, entries, on_seen, parents):
 
135
        """Capture a stream for testing."""
 
136
        for factory in entries:
 
137
            on_seen(factory.key)
 
138
            self.assertValidStorageKind(factory.storage_kind)
 
139
            self.assertEqual(f.get_sha1s([factory.key[0]])[0], factory.sha1)
 
140
            self.assertEqual(parents[factory.key[0]], factory.parents)
 
141
            self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
 
142
                str)
 
143
 
 
144
    def test_get_record_stream_interface(self):
 
145
        """Each item in a stream has to provide a regular interface."""
 
146
        f, parents = get_diamond_vf(self.get_file())
 
147
        entries = f.get_record_stream(['merged', 'left', 'right', 'base'],
 
148
            'unordered', False)
 
149
        seen = set()
 
150
        self.capture_stream(f, entries, seen.add, parents)
 
151
        self.assertEqual(set([('base',), ('left',), ('right',), ('merged',)]),
 
152
            seen)
 
153
 
 
154
    def test_get_record_stream_interface_ordered(self):
 
155
        """Each item in a stream has to provide a regular interface."""
 
156
        f, parents = get_diamond_vf(self.get_file())
 
157
        entries = f.get_record_stream(['merged', 'left', 'right', 'base'],
 
158
            'topological', False)
 
159
        seen = []
 
160
        self.capture_stream(f, entries, seen.append, parents)
 
161
        self.assertSubset([tuple(seen)],
 
162
            (
 
163
             (('base',), ('left',), ('right',), ('merged',)),
 
164
             (('base',), ('right',), ('left',), ('merged',)),
 
165
            ))
 
166
 
 
167
    def test_get_record_stream_interface_ordered_with_delta_closure(self):
 
168
        """Each item in a stream has to provide a regular interface."""
 
169
        f, parents = get_diamond_vf(self.get_file())
 
170
        entries = f.get_record_stream(['merged', 'left', 'right', 'base'],
 
171
            'topological', True)
 
172
        seen = []
 
173
        for factory in entries:
 
174
            seen.append(factory.key)
 
175
            self.assertValidStorageKind(factory.storage_kind)
 
176
            self.assertEqual(f.get_sha1s([factory.key[0]])[0], factory.sha1)
 
177
            self.assertEqual(parents[factory.key[0]], factory.parents)
 
178
            self.assertEqual(f.get_text(factory.key[0]),
 
179
                factory.get_bytes_as('fulltext'))
 
180
            self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
 
181
                str)
 
182
        self.assertSubset([tuple(seen)],
 
183
            (
 
184
             (('base',), ('left',), ('right',), ('merged',)),
 
185
             (('base',), ('right',), ('left',), ('merged',)),
 
186
            ))
 
187
 
 
188
    def test_get_record_stream_unknown_storage_kind_raises(self):
 
189
        """Asking for a storage kind that the stream cannot supply raises."""
 
190
        f, parents = get_diamond_vf(self.get_file())
 
191
        entries = f.get_record_stream(['merged', 'left', 'right', 'base'],
 
192
            'unordered', False)
 
193
        # We track the contents because we should be able to try, fail a
 
194
        # particular kind and then ask for one that works and continue.
 
195
        seen = set()
 
196
        for factory in entries:
 
197
            seen.add(factory.key)
 
198
            self.assertValidStorageKind(factory.storage_kind)
 
199
            self.assertEqual(f.get_sha1s([factory.key[0]])[0], factory.sha1)
 
200
            self.assertEqual(parents[factory.key[0]], factory.parents)
 
201
            # currently no stream emits mpdiff
 
202
            self.assertRaises(errors.UnavailableRepresentation,
 
203
                factory.get_bytes_as, 'mpdiff')
 
204
            self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
 
205
                str)
 
206
        self.assertEqual(set([('base',), ('left',), ('right',), ('merged',)]),
 
207
            seen)
 
208
 
 
209
    def test_get_record_stream_missing_records_are_absent(self):
 
210
        f, parents = get_diamond_vf(self.get_file())
 
211
        entries = f.get_record_stream(['merged', 'left', 'right', 'or', 'base'],
 
212
            'unordered', False)
 
213
        self.assertAbsentRecord(f, parents, entries)
 
214
        entries = f.get_record_stream(['merged', 'left', 'right', 'or', 'base'],
 
215
            'topological', False)
 
216
        self.assertAbsentRecord(f, parents, entries)
 
217
 
 
218
    def assertAbsentRecord(self, f, parents, entries):
 
219
        """Helper for test_get_record_stream_missing_records_are_absent."""
 
220
        seen = set()
 
221
        for factory in entries:
 
222
            seen.add(factory.key)
 
223
            if factory.key == ('or',):
 
224
                self.assertEqual('absent', factory.storage_kind)
 
225
                self.assertEqual(None, factory.sha1)
 
226
                self.assertEqual(None, factory.parents)
 
227
            else:
 
228
                self.assertValidStorageKind(factory.storage_kind)
 
229
                self.assertEqual(f.get_sha1s([factory.key[0]])[0], factory.sha1)
 
230
                self.assertEqual(parents[factory.key[0]], factory.parents)
 
231
                self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
 
232
                    str)
 
233
        self.assertEqual(
 
234
            set([('base',), ('left',), ('right',), ('merged',), ('or',)]),
 
235
            seen)
 
236
 
 
237
    def test_filter_absent_records(self):
 
238
        """Requested missing records can be filter trivially."""
 
239
        f, parents = get_diamond_vf(self.get_file())
 
240
        entries = f.get_record_stream(['merged', 'left', 'right', 'extra', 'base'],
 
241
            'unordered', False)
 
242
        seen = set()
 
243
        self.capture_stream(f, versionedfile.filter_absent(entries), seen.add,
 
244
            parents)
 
245
        self.assertEqual(set([('base',), ('left',), ('right',), ('merged',)]),
 
246
            seen)
 
247
 
 
248
    def test_insert_record_stream_empty(self):
 
249
        """Inserting an empty record stream should work."""
 
250
        f = self.get_file()
 
251
        stream = []
 
252
        f.insert_record_stream([])
 
253
 
 
254
    def assertIdenticalVersionedFile(self, left, right):
 
255
        """Assert that left and right have the same contents."""
 
256
        self.assertEqual(set(left.versions()), set(right.versions()))
 
257
        self.assertEqual(left.get_parent_map(left.versions()),
 
258
            right.get_parent_map(right.versions()))
 
259
        for v in left.versions():
 
260
            self.assertEqual(left.get_text(v), right.get_text(v))
 
261
 
 
262
    def test_insert_record_stream_fulltexts(self):
 
263
        """Any file should accept a stream of fulltexts."""
 
264
        f = self.get_file()
 
265
        weave_vf = WeaveFile('source', get_transport(self.get_url('.')),
 
266
            create=True, get_scope=self.get_transaction)
 
267
        source, _ = get_diamond_vf(weave_vf)
 
268
        stream = source.get_record_stream(source.versions(), 'topological',
 
269
            False)
 
270
        f.insert_record_stream(stream)
 
271
        self.assertIdenticalVersionedFile(f, source)
 
272
 
 
273
    def test_insert_record_stream_fulltexts_noeol(self):
 
274
        """Any file should accept a stream of fulltexts."""
 
275
        f = self.get_file()
 
276
        weave_vf = WeaveFile('source', get_transport(self.get_url('.')),
 
277
            create=True, get_scope=self.get_transaction)
 
278
        source, _ = get_diamond_vf(weave_vf, trailing_eol=False)
 
279
        stream = source.get_record_stream(source.versions(), 'topological',
 
280
            False)
 
281
        f.insert_record_stream(stream)
 
282
        self.assertIdenticalVersionedFile(f, source)
 
283
 
 
284
    def test_insert_record_stream_annotated_knits(self):
 
285
        """Any file should accept a stream from plain knits."""
 
286
        f = self.get_file()
 
287
        source = make_file_knit('source', get_transport(self.get_url('.')),
 
288
            create=True)
 
289
        get_diamond_vf(source)
 
290
        stream = source.get_record_stream(source.versions(), 'topological',
 
291
            False)
 
292
        f.insert_record_stream(stream)
 
293
        self.assertIdenticalVersionedFile(f, source)
 
294
 
 
295
    def test_insert_record_stream_annotated_knits_noeol(self):
 
296
        """Any file should accept a stream from plain knits."""
 
297
        f = self.get_file()
 
298
        source = make_file_knit('source', get_transport(self.get_url('.')),
 
299
            create=True)
 
300
        get_diamond_vf(source, trailing_eol=False)
 
301
        stream = source.get_record_stream(source.versions(), 'topological',
 
302
            False)
 
303
        f.insert_record_stream(stream)
 
304
        self.assertIdenticalVersionedFile(f, source)
 
305
 
 
306
    def test_insert_record_stream_plain_knits(self):
 
307
        """Any file should accept a stream from plain knits."""
 
308
        f = self.get_file()
 
309
        source = make_file_knit('source', get_transport(self.get_url('.')),
 
310
            create=True, factory=KnitPlainFactory())
 
311
        get_diamond_vf(source)
 
312
        stream = source.get_record_stream(source.versions(), 'topological',
 
313
            False)
 
314
        f.insert_record_stream(stream)
 
315
        self.assertIdenticalVersionedFile(f, source)
 
316
 
 
317
    def test_insert_record_stream_plain_knits_noeol(self):
 
318
        """Any file should accept a stream from plain knits."""
 
319
        f = self.get_file()
 
320
        source = make_file_knit('source', get_transport(self.get_url('.')),
 
321
            create=True, factory=KnitPlainFactory())
 
322
        get_diamond_vf(source, trailing_eol=False)
 
323
        stream = source.get_record_stream(source.versions(), 'topological',
 
324
            False)
 
325
        f.insert_record_stream(stream)
 
326
        self.assertIdenticalVersionedFile(f, source)
 
327
 
 
328
    def test_insert_record_stream_existing_keys(self):
 
329
        """Inserting keys already in a file should not error."""
 
330
        f = self.get_file()
 
331
        source = make_file_knit('source', get_transport(self.get_url('.')),
 
332
            create=True, factory=KnitPlainFactory())
 
333
        get_diamond_vf(source)
 
334
        # insert some keys into f.
 
335
        get_diamond_vf(f, left_only=True)
 
336
        stream = source.get_record_stream(source.versions(), 'topological',
 
337
            False)
 
338
        f.insert_record_stream(stream)
 
339
        self.assertIdenticalVersionedFile(f, source)
 
340
 
 
341
    def test_insert_record_stream_missing_keys(self):
 
342
        """Inserting a stream with absent keys should raise an error."""
 
343
        f = self.get_file()
 
344
        source = make_file_knit('source', get_transport(self.get_url('.')),
 
345
            create=True, factory=KnitPlainFactory())
 
346
        stream = source.get_record_stream(['missing'], 'topological',
 
347
            False)
 
348
        self.assertRaises(errors.RevisionNotPresent, f.insert_record_stream,
 
349
            stream)
 
350
 
 
351
    def test_insert_record_stream_out_of_order(self):
 
352
        """An out of order stream can either error or work."""
 
353
        f, parents = get_diamond_vf(self.get_file())
 
354
        origin_entries = f.get_record_stream(['origin'], 'unordered', False)
 
355
        end_entries = f.get_record_stream(['merged', 'left'],
 
356
            'topological', False)
 
357
        start_entries = f.get_record_stream(['right', 'base'],
 
358
            'topological', False)
 
359
        entries = chain(origin_entries, end_entries, start_entries)
 
360
        target = self.get_file('target')
 
361
        try:
 
362
            target.insert_record_stream(entries)
 
363
        except RevisionNotPresent:
 
364
            # Must not have corrupted the file.
 
365
            target.check()
 
366
        else:
 
367
            self.assertIdenticalVersionedFile(f, target)
 
368
 
 
369
    def test_insert_record_stream_delta_missing_basis_no_corruption(self):
 
370
        """Insertion where a needed basis is not included aborts safely."""
 
371
        # Annotated source - deltas can be used in any knit.
 
372
        source = make_file_knit('source', get_transport(self.get_url('.')),
 
373
            create=True)
 
374
        get_diamond_vf(source)
 
375
        entries = source.get_record_stream(['origin', 'merged'], 'unordered', False)
 
376
        f = self.get_file()
 
377
        self.assertRaises(RevisionNotPresent, f.insert_record_stream, entries)
 
378
        f.check()
 
379
        self.assertFalse(f.has_version('merged'))
 
380
 
69
381
    def test_adds_with_parent_texts(self):
70
382
        f = self.get_file()
71
383
        parent_texts = {}
72
 
        parent_texts['r0'] = f.add_lines('r0', [], ['a\n', 'b\n'])
 
384
        _, _, parent_texts['r0'] = f.add_lines('r0', [], ['a\n', 'b\n'])
73
385
        try:
74
 
            parent_texts['r1'] = f.add_lines_with_ghosts('r1',
75
 
                                                         ['r0', 'ghost'], 
76
 
                                                         ['b\n', 'c\n'],
77
 
                                                         parent_texts=parent_texts)
 
386
            _, _, parent_texts['r1'] = f.add_lines_with_ghosts('r1',
 
387
                ['r0', 'ghost'], ['b\n', 'c\n'], parent_texts=parent_texts)
78
388
        except NotImplementedError:
79
389
            # if the format doesn't support ghosts, just add normally.
80
 
            parent_texts['r1'] = f.add_lines('r1',
81
 
                                             ['r0'], 
82
 
                                             ['b\n', 'c\n'],
83
 
                                             parent_texts=parent_texts)
 
390
            _, _, parent_texts['r1'] = f.add_lines('r1',
 
391
                ['r0'], ['b\n', 'c\n'], parent_texts=parent_texts)
84
392
        f.add_lines('r2', ['r1'], ['c\n', 'd\n'], parent_texts=parent_texts)
85
393
        self.assertNotEqual(None, parent_texts['r0'])
86
394
        self.assertNotEqual(None, parent_texts['r1'])
104
412
        f = self.reopen_file()
105
413
        verify_file(f)
106
414
 
107
 
    def test_get_delta(self):
108
 
        f = self.get_file()
109
 
        sha1s = self._setup_for_deltas(f)
110
 
        expected_delta = (None, '6bfa09d82ce3e898ad4641ae13dd4fdb9cf0d76b', False, 
111
 
                          [(0, 0, 1, [('base', 'line\n')])])
112
 
        self.assertEqual(expected_delta, f.get_delta('base'))
113
 
        next_parent = 'base'
114
 
        text_name = 'chain1-'
115
 
        for depth in range(26):
116
 
            new_version = text_name + '%s' % depth
117
 
            expected_delta = (next_parent, sha1s[depth], 
118
 
                              False,
119
 
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
120
 
            self.assertEqual(expected_delta, f.get_delta(new_version))
121
 
            next_parent = new_version
122
 
        next_parent = 'base'
123
 
        text_name = 'chain2-'
124
 
        for depth in range(26):
125
 
            new_version = text_name + '%s' % depth
126
 
            expected_delta = (next_parent, sha1s[depth], False,
127
 
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
128
 
            self.assertEqual(expected_delta, f.get_delta(new_version))
129
 
            next_parent = new_version
130
 
        # smoke test for eol support
131
 
        expected_delta = ('base', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True, [])
132
 
        self.assertEqual(['line'], f.get_lines('noeol'))
133
 
        self.assertEqual(expected_delta, f.get_delta('noeol'))
134
 
 
135
 
    def test_get_deltas(self):
136
 
        f = self.get_file()
137
 
        sha1s = self._setup_for_deltas(f)
138
 
        deltas = f.get_deltas(f.versions())
139
 
        expected_delta = (None, '6bfa09d82ce3e898ad4641ae13dd4fdb9cf0d76b', False, 
140
 
                          [(0, 0, 1, [('base', 'line\n')])])
141
 
        self.assertEqual(expected_delta, deltas['base'])
142
 
        next_parent = 'base'
143
 
        text_name = 'chain1-'
144
 
        for depth in range(26):
145
 
            new_version = text_name + '%s' % depth
146
 
            expected_delta = (next_parent, sha1s[depth], 
147
 
                              False,
148
 
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
149
 
            self.assertEqual(expected_delta, deltas[new_version])
150
 
            next_parent = new_version
151
 
        next_parent = 'base'
152
 
        text_name = 'chain2-'
153
 
        for depth in range(26):
154
 
            new_version = text_name + '%s' % depth
155
 
            expected_delta = (next_parent, sha1s[depth], False,
156
 
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
157
 
            self.assertEqual(expected_delta, deltas[new_version])
158
 
            next_parent = new_version
159
 
        # smoke tests for eol support
160
 
        expected_delta = ('base', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True, [])
161
 
        self.assertEqual(['line'], f.get_lines('noeol'))
162
 
        self.assertEqual(expected_delta, deltas['noeol'])
163
 
        # smoke tests for eol support - two noeol in a row same content
164
 
        expected_deltas = (('noeol', '3ad7ee82dbd8f29ecba073f96e43e414b3f70a4d', True, 
165
 
                          [(0, 1, 2, [(u'noeolsecond', 'line\n'), (u'noeolsecond', 'line\n')])]),
166
 
                          ('noeol', '3ad7ee82dbd8f29ecba073f96e43e414b3f70a4d', True, 
167
 
                           [(0, 0, 1, [('noeolsecond', 'line\n')]), (1, 1, 0, [])]))
168
 
        self.assertEqual(['line\n', 'line'], f.get_lines('noeolsecond'))
169
 
        self.assertTrue(deltas['noeolsecond'] in expected_deltas)
170
 
        # two no-eol in a row, different content
171
 
        expected_delta = ('noeolsecond', '8bb553a84e019ef1149db082d65f3133b195223b', True, 
172
 
                          [(1, 2, 1, [(u'noeolnotshared', 'phone\n')])])
173
 
        self.assertEqual(['line\n', 'phone'], f.get_lines('noeolnotshared'))
174
 
        self.assertEqual(expected_delta, deltas['noeolnotshared'])
175
 
        # eol folling a no-eol with content change
176
 
        expected_delta = ('noeol', 'a61f6fb6cfc4596e8d88c34a308d1e724caf8977', False, 
177
 
                          [(0, 1, 1, [(u'eol', 'phone\n')])])
178
 
        self.assertEqual(['phone\n'], f.get_lines('eol'))
179
 
        self.assertEqual(expected_delta, deltas['eol'])
180
 
        # eol folling a no-eol with content change
181
 
        expected_delta = ('noeol', '6bfa09d82ce3e898ad4641ae13dd4fdb9cf0d76b', False, 
182
 
                          [(0, 1, 1, [(u'eolline', 'line\n')])])
183
 
        self.assertEqual(['line\n'], f.get_lines('eolline'))
184
 
        self.assertEqual(expected_delta, deltas['eolline'])
185
 
        # eol with no parents
186
 
        expected_delta = (None, '264f39cab871e4cfd65b3a002f7255888bb5ed97', True, 
187
 
                          [(0, 0, 1, [(u'noeolbase', 'line\n')])])
188
 
        self.assertEqual(['line'], f.get_lines('noeolbase'))
189
 
        self.assertEqual(expected_delta, deltas['noeolbase'])
190
 
        # eol with two parents, in inverse insertion order
191
 
        expected_deltas = (('noeolbase', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True,
192
 
                            [(0, 1, 1, [(u'eolbeforefirstparent', 'line\n')])]),
193
 
                           ('noeolbase', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True,
194
 
                            [(0, 1, 1, [(u'eolbeforefirstparent', 'line\n')])]))
195
 
        self.assertEqual(['line'], f.get_lines('eolbeforefirstparent'))
196
 
        #self.assertTrue(deltas['eolbeforefirstparent'] in expected_deltas)
 
415
    def test_add_unicode_content(self):
 
416
        # unicode content is not permitted in versioned files. 
 
417
        # versioned files version sequences of bytes only.
 
418
        vf = self.get_file()
 
419
        self.assertRaises(errors.BzrBadParameterUnicode,
 
420
            vf.add_lines, 'a', [], ['a\n', u'b\n', 'c\n'])
 
421
        self.assertRaises(
 
422
            (errors.BzrBadParameterUnicode, NotImplementedError),
 
423
            vf.add_lines_with_ghosts, 'a', [], ['a\n', u'b\n', 'c\n'])
 
424
 
 
425
    def test_add_follows_left_matching_blocks(self):
 
426
        """If we change left_matching_blocks, delta changes
 
427
 
 
428
        Note: There are multiple correct deltas in this case, because
 
429
        we start with 1 "a" and we get 3.
 
430
        """
 
431
        vf = self.get_file()
 
432
        if isinstance(vf, WeaveFile):
 
433
            raise TestSkipped("WeaveFile ignores left_matching_blocks")
 
434
        vf.add_lines('1', [], ['a\n'])
 
435
        vf.add_lines('2', ['1'], ['a\n', 'a\n', 'a\n'],
 
436
                     left_matching_blocks=[(0, 0, 1), (1, 3, 0)])
 
437
        self.assertEqual(['a\n', 'a\n', 'a\n'], vf.get_lines('2'))
 
438
        vf.add_lines('3', ['1'], ['a\n', 'a\n', 'a\n'],
 
439
                     left_matching_blocks=[(0, 2, 1), (1, 3, 0)])
 
440
        self.assertEqual(['a\n', 'a\n', 'a\n'], vf.get_lines('3'))
 
441
 
 
442
    def test_inline_newline_throws(self):
 
443
        # \r characters are not permitted in lines being added
 
444
        vf = self.get_file()
 
445
        self.assertRaises(errors.BzrBadParameterContainsNewline, 
 
446
            vf.add_lines, 'a', [], ['a\n\n'])
 
447
        self.assertRaises(
 
448
            (errors.BzrBadParameterContainsNewline, NotImplementedError),
 
449
            vf.add_lines_with_ghosts, 'a', [], ['a\n\n'])
 
450
        # but inline CR's are allowed
 
451
        vf.add_lines('a', [], ['a\r\n'])
 
452
        try:
 
453
            vf.add_lines_with_ghosts('b', [], ['a\r\n'])
 
454
        except NotImplementedError:
 
455
            pass
 
456
 
 
457
    def test_add_reserved(self):
 
458
        vf = self.get_file()
 
459
        self.assertRaises(errors.ReservedId,
 
460
            vf.add_lines, 'a:', [], ['a\n', 'b\n', 'c\n'])
 
461
 
 
462
    def test_add_lines_nostoresha(self):
 
463
        """When nostore_sha is supplied using old content raises."""
 
464
        vf = self.get_file()
 
465
        empty_text = ('a', [])
 
466
        sample_text_nl = ('b', ["foo\n", "bar\n"])
 
467
        sample_text_no_nl = ('c', ["foo\n", "bar"])
 
468
        shas = []
 
469
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
 
470
            sha, _, _ = vf.add_lines(version, [], lines)
 
471
            shas.append(sha)
 
472
        # we now have a copy of all the lines in the vf.
 
473
        for sha, (version, lines) in zip(
 
474
            shas, (empty_text, sample_text_nl, sample_text_no_nl)):
 
475
            self.assertRaises(errors.ExistingContent,
 
476
                vf.add_lines, version + "2", [], lines,
 
477
                nostore_sha=sha)
 
478
            # and no new version should have been added.
 
479
            self.assertRaises(errors.RevisionNotPresent, vf.get_lines,
 
480
                version + "2")
 
481
 
 
482
    def test_add_lines_with_ghosts_nostoresha(self):
 
483
        """When nostore_sha is supplied using old content raises."""
 
484
        vf = self.get_file()
 
485
        empty_text = ('a', [])
 
486
        sample_text_nl = ('b', ["foo\n", "bar\n"])
 
487
        sample_text_no_nl = ('c', ["foo\n", "bar"])
 
488
        shas = []
 
489
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
 
490
            sha, _, _ = vf.add_lines(version, [], lines)
 
491
            shas.append(sha)
 
492
        # we now have a copy of all the lines in the vf.
 
493
        # is the test applicable to this vf implementation?
 
494
        try:
 
495
            vf.add_lines_with_ghosts('d', [], [])
 
496
        except NotImplementedError:
 
497
            raise TestSkipped("add_lines_with_ghosts is optional")
 
498
        for sha, (version, lines) in zip(
 
499
            shas, (empty_text, sample_text_nl, sample_text_no_nl)):
 
500
            self.assertRaises(errors.ExistingContent,
 
501
                vf.add_lines_with_ghosts, version + "2", [], lines,
 
502
                nostore_sha=sha)
 
503
            # and no new version should have been added.
 
504
            self.assertRaises(errors.RevisionNotPresent, vf.get_lines,
 
505
                version + "2")
 
506
 
 
507
    def test_add_lines_return_value(self):
 
508
        # add_lines should return the sha1 and the text size.
 
509
        vf = self.get_file()
 
510
        empty_text = ('a', [])
 
511
        sample_text_nl = ('b', ["foo\n", "bar\n"])
 
512
        sample_text_no_nl = ('c', ["foo\n", "bar"])
 
513
        # check results for the three cases:
 
514
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
 
515
            # the first two elements are the same for all versioned files:
 
516
            # - the digest and the size of the text. For some versioned files
 
517
            #   additional data is returned in additional tuple elements.
 
518
            result = vf.add_lines(version, [], lines)
 
519
            self.assertEqual(3, len(result))
 
520
            self.assertEqual((osutils.sha_strings(lines), sum(map(len, lines))),
 
521
                result[0:2])
 
522
        # parents should not affect the result:
 
523
        lines = sample_text_nl[1]
 
524
        self.assertEqual((osutils.sha_strings(lines), sum(map(len, lines))),
 
525
            vf.add_lines('d', ['b', 'c'], lines)[0:2])
 
526
 
 
527
    def test_get_reserved(self):
 
528
        vf = self.get_file()
 
529
        self.assertRaises(errors.ReservedId, vf.get_texts, ['b:'])
 
530
        self.assertRaises(errors.ReservedId, vf.get_lines, 'b:')
 
531
        self.assertRaises(errors.ReservedId, vf.get_text, 'b:')
 
532
 
 
533
    def test_make_mpdiffs(self):
 
534
        from bzrlib import multiparent
 
535
        vf = self.get_file('foo')
 
536
        sha1s = self._setup_for_deltas(vf)
 
537
        new_vf = self.get_file('bar')
 
538
        for version in multiparent.topo_iter(vf):
 
539
            mpdiff = vf.make_mpdiffs([version])[0]
 
540
            new_vf.add_mpdiffs([(version, vf.get_parent_map([version])[version],
 
541
                                 vf.get_sha1s([version])[0], mpdiff)])
 
542
            self.assertEqualDiff(vf.get_text(version),
 
543
                                 new_vf.get_text(version))
197
544
 
198
545
    def _setup_for_deltas(self, f):
199
 
        self.assertRaises(errors.RevisionNotPresent, f.get_delta, 'base')
 
546
        self.assertFalse(f.has_version('base'))
200
547
        # add texts that should trip the knit maximum delta chain threshold
201
548
        # as well as doing parallel chains of data in knits.
202
549
        # this is done by two chains of 25 insertions
265
612
            next_parent = new_version
266
613
        return sha1s
267
614
 
268
 
    def test_add_delta(self):
269
 
        # tests for the add-delta facility.
270
 
        # at this point, optimising for speed, we assume no checks when deltas are inserted.
271
 
        # this may need to be revisited.
272
 
        source = self.get_file('source')
273
 
        source.add_lines('base', [], ['line\n'])
274
 
        next_parent = 'base'
275
 
        text_name = 'chain1-'
276
 
        text = ['line\n']
277
 
        for depth in range(26):
278
 
            new_version = text_name + '%s' % depth
279
 
            text = text + ['line\n']
280
 
            source.add_lines(new_version, [next_parent], text)
281
 
            next_parent = new_version
282
 
        next_parent = 'base'
283
 
        text_name = 'chain2-'
284
 
        text = ['line\n']
285
 
        for depth in range(26):
286
 
            new_version = text_name + '%s' % depth
287
 
            text = text + ['line\n']
288
 
            source.add_lines(new_version, [next_parent], text)
289
 
            next_parent = new_version
290
 
        source.add_lines('noeol', ['base'], ['line'])
291
 
        
292
 
        target = self.get_file('target')
293
 
        for version in source.versions():
294
 
            parent, sha1, noeol, delta = source.get_delta(version)
295
 
            target.add_delta(version,
296
 
                             source.get_parents(version),
297
 
                             parent,
298
 
                             sha1,
299
 
                             noeol,
300
 
                             delta)
301
 
        self.assertRaises(RevisionAlreadyPresent,
302
 
                          target.add_delta, 'base', [], None, '', False, [])
303
 
        for version in source.versions():
304
 
            self.assertEqual(source.get_lines(version),
305
 
                             target.get_lines(version))
306
 
 
307
615
    def test_ancestry(self):
308
616
        f = self.get_file()
309
617
        self.assertEqual([], f.get_ancestry([]))
332
640
        self.assertRaises(RevisionNotPresent,
333
641
            f.get_ancestry, ['rM', 'rX'])
334
642
 
 
643
        self.assertEqual(set(f.get_ancestry('rM')),
 
644
            set(f.get_ancestry('rM', topo_sorted=False)))
 
645
 
335
646
    def test_mutate_after_finish(self):
 
647
        self._transaction = 'before'
336
648
        f = self.get_file()
337
 
        f.transaction_finished()
338
 
        self.assertRaises(errors.OutSideTransaction, f.add_delta, '', [], '', '', False, [])
 
649
        self._transaction = 'after'
339
650
        self.assertRaises(errors.OutSideTransaction, f.add_lines, '', [], [])
340
651
        self.assertRaises(errors.OutSideTransaction, f.add_lines_with_ghosts, '', [], [])
341
 
        self.assertRaises(errors.OutSideTransaction, f.fix_parents, '', [])
342
 
        self.assertRaises(errors.OutSideTransaction, f.join, '')
343
 
        self.assertRaises(errors.OutSideTransaction, f.clone_text, 'base', 'bar', ['foo'])
 
652
        self.assertRaises(errors.OutSideTransaction, self.applyDeprecated,
 
653
            one_five, f.join, '')
344
654
        
345
 
    def test_clear_cache(self):
346
 
        f = self.get_file()
347
 
        # on a new file it should not error
348
 
        f.clear_cache()
349
 
        # and after adding content, doing a clear_cache and a get should work.
350
 
        f.add_lines('0', [], ['a'])
351
 
        f.clear_cache()
352
 
        self.assertEqual(['a'], f.get_lines('0'))
353
 
 
354
 
    def test_clone_text(self):
355
 
        f = self.get_file()
356
 
        f.add_lines('r0', [], ['a\n', 'b\n'])
357
 
        f.clone_text('r1', 'r0', ['r0'])
358
 
        def verify_file(f):
359
 
            self.assertEquals(f.get_lines('r1'), f.get_lines('r0'))
360
 
            self.assertEquals(f.get_lines('r1'), ['a\n', 'b\n'])
361
 
            self.assertEquals(f.get_parents('r1'), ['r0'])
362
 
    
363
 
            self.assertRaises(RevisionNotPresent,
364
 
                f.clone_text, 'r2', 'rX', [])
365
 
            self.assertRaises(RevisionAlreadyPresent,
366
 
                f.clone_text, 'r1', 'r0', [])
367
 
        verify_file(f)
368
 
        verify_file(self.reopen_file())
369
 
 
370
 
    def test_create_empty(self):
371
 
        f = self.get_file()
372
 
        f.add_lines('0', [], ['a\n'])
373
 
        new_f = f.create_empty('t', MemoryTransport())
374
 
        # smoke test, specific types should check it is honoured correctly for
375
 
        # non type attributes
376
 
        self.assertEqual([], new_f.versions())
377
 
        self.assertTrue(isinstance(new_f, f.__class__))
378
 
 
379
655
    def test_copy_to(self):
380
656
        f = self.get_file()
381
657
        f.add_lines('0', [], ['a\n'])
382
658
        t = MemoryTransport()
383
659
        f.copy_to('foo', t)
384
 
        for suffix in f.__class__.get_suffixes():
 
660
        for suffix in self.get_factory().get_suffixes():
385
661
            self.assertTrue(t.has('foo' + suffix))
386
662
 
387
663
    def test_get_suffixes(self):
388
664
        f = self.get_file()
389
 
        # should be the same
390
 
        self.assertEqual(f.__class__.get_suffixes(), f.__class__.get_suffixes())
391
665
        # and should be a list
392
 
        self.assertTrue(isinstance(f.__class__.get_suffixes(), list))
393
 
 
394
 
    def test_get_graph(self):
395
 
        f = self.get_file()
396
 
        f.add_lines('v1', [], ['hello\n'])
397
 
        f.add_lines('v2', ['v1'], ['hello\n', 'world\n'])
398
 
        f.add_lines('v3', ['v2'], ['hello\n', 'cruel\n', 'world\n'])
399
 
        self.assertEqual({'v1': [],
400
 
                          'v2': ['v1'],
401
 
                          'v3': ['v2']},
402
 
                         f.get_graph())
403
 
 
404
 
    def test_get_parents(self):
 
666
        self.assertTrue(isinstance(self.get_factory().get_suffixes(), list))
 
667
 
 
668
    def test_get_parent_map(self):
405
669
        f = self.get_file()
406
670
        f.add_lines('r0', [], ['a\n', 'b\n'])
407
 
        f.add_lines('r1', [], ['a\n', 'b\n'])
 
671
        self.assertEqual(
 
672
            {'r0':()}, f.get_parent_map(['r0']))
 
673
        f.add_lines('r1', ['r0'], ['a\n', 'b\n'])
 
674
        self.assertEqual(
 
675
            {'r1':('r0',)}, f.get_parent_map(['r1']))
 
676
        self.assertEqual(
 
677
            {'r0':(),
 
678
             'r1':('r0',)},
 
679
            f.get_parent_map(['r0', 'r1']))
408
680
        f.add_lines('r2', [], ['a\n', 'b\n'])
409
681
        f.add_lines('r3', [], ['a\n', 'b\n'])
410
682
        f.add_lines('m', ['r0', 'r1', 'r2', 'r3'], ['a\n', 'b\n'])
411
 
        self.assertEquals(f.get_parents('m'), ['r0', 'r1', 'r2', 'r3'])
412
 
 
413
 
        self.assertRaises(RevisionNotPresent,
414
 
            f.get_parents, 'y')
 
683
        self.assertEqual(
 
684
            {'m':('r0', 'r1', 'r2', 'r3')}, f.get_parent_map(['m']))
 
685
        self.assertEqual({}, f.get_parent_map('y'))
 
686
        self.assertEqual(
 
687
            {'r0':(),
 
688
             'r1':('r0',)},
 
689
            f.get_parent_map(['r0', 'y', 'r1']))
415
690
 
416
691
    def test_annotate(self):
417
692
        f = self.get_file()
424
699
        self.assertRaises(RevisionNotPresent,
425
700
            f.annotate, 'foo')
426
701
 
427
 
    def test_walk(self):
428
 
        # tests that walk returns all the inclusions for the requested
429
 
        # revisions as well as the revisions changes themselves.
430
 
        f = self.get_file('1')
431
 
        f.add_lines('r0', [], ['a\n', 'b\n'])
432
 
        f.add_lines('r1', ['r0'], ['c\n', 'b\n'])
433
 
        f.add_lines('rX', ['r1'], ['d\n', 'b\n'])
434
 
        f.add_lines('rY', ['r1'], ['c\n', 'e\n'])
435
 
 
436
 
        lines = {}
437
 
        for lineno, insert, dset, text in f.walk(['rX', 'rY']):
438
 
            lines[text] = (insert, dset)
439
 
 
440
 
        self.assertTrue(lines['a\n'], ('r0', set(['r1'])))
441
 
        self.assertTrue(lines['b\n'], ('r0', set(['rY'])))
442
 
        self.assertTrue(lines['c\n'], ('r1', set(['rX'])))
443
 
        self.assertTrue(lines['d\n'], ('rX', set([])))
444
 
        self.assertTrue(lines['e\n'], ('rY', set([])))
445
 
 
446
702
    def test_detection(self):
447
703
        # Test weaves detect corruption.
448
704
        #
477
733
        # versions in the weave 
478
734
        # the ordering here is to make a tree so that dumb searches have
479
735
        # more changes to muck up.
 
736
 
 
737
        class InstrumentedProgress(progress.DummyProgress):
 
738
 
 
739
            def __init__(self):
 
740
 
 
741
                progress.DummyProgress.__init__(self)
 
742
                self.updates = []
 
743
 
 
744
            def update(self, msg=None, current=None, total=None):
 
745
                self.updates.append((msg, current, total))
 
746
 
480
747
        vf = self.get_file()
481
748
        # add a base to get included
482
749
        vf.add_lines('base', [], ['base\n'])
490
757
        vf.add_lines('otherchild',
491
758
                     ['lancestor', 'base'],
492
759
                     ['base\n', 'lancestor\n', 'otherchild\n'])
493
 
        def iter_with_versions(versions):
 
760
        def iter_with_versions(versions, expected):
494
761
            # now we need to see what lines are returned, and how often.
495
 
            lines = {'base\n':0,
496
 
                     'lancestor\n':0,
497
 
                     'rancestor\n':0,
498
 
                     'child\n':0,
499
 
                     'otherchild\n':0,
500
 
                     }
 
762
            lines = {}
 
763
            progress = InstrumentedProgress()
501
764
            # iterate over the lines
502
 
            for line in vf.iter_lines_added_or_present_in_versions(versions):
 
765
            for line in vf.iter_lines_added_or_present_in_versions(versions,
 
766
                pb=progress):
 
767
                lines.setdefault(line, 0)
503
768
                lines[line] += 1
 
769
            if []!= progress.updates:
 
770
                self.assertEqual(expected, progress.updates)
504
771
            return lines
505
 
        lines = iter_with_versions(['child', 'otherchild'])
 
772
        lines = iter_with_versions(['child', 'otherchild'],
 
773
                                   [('Walking content.', 0, 2),
 
774
                                    ('Walking content.', 1, 2),
 
775
                                    ('Walking content.', 2, 2)])
506
776
        # we must see child and otherchild
507
 
        self.assertTrue(lines['child\n'] > 0)
508
 
        self.assertTrue(lines['otherchild\n'] > 0)
 
777
        self.assertTrue(lines[('child\n', 'child')] > 0)
 
778
        self.assertTrue(lines[('otherchild\n', 'otherchild')] > 0)
509
779
        # we dont care if we got more than that.
510
780
        
511
781
        # test all lines
512
 
        lines = iter_with_versions(None)
 
782
        lines = iter_with_versions(None, [('Walking content.', 0, 5),
 
783
                                          ('Walking content.', 1, 5),
 
784
                                          ('Walking content.', 2, 5),
 
785
                                          ('Walking content.', 3, 5),
 
786
                                          ('Walking content.', 4, 5),
 
787
                                          ('Walking content.', 5, 5)])
513
788
        # all lines must be seen at least once
514
 
        self.assertTrue(lines['base\n'] > 0)
515
 
        self.assertTrue(lines['lancestor\n'] > 0)
516
 
        self.assertTrue(lines['rancestor\n'] > 0)
517
 
        self.assertTrue(lines['child\n'] > 0)
518
 
        self.assertTrue(lines['otherchild\n'] > 0)
519
 
 
520
 
    def test_fix_parents(self):
521
 
        # some versioned files allow incorrect parents to be corrected after
522
 
        # insertion - this may not fix ancestry..
523
 
        # if they do not supported, they just do not implement it.
524
 
        # we test this as an interface test to ensure that those that *do*
525
 
        # implementent it get it right.
526
 
        vf = self.get_file()
527
 
        vf.add_lines('notbase', [], [])
528
 
        vf.add_lines('base', [], [])
529
 
        try:
530
 
            vf.fix_parents('notbase', ['base'])
531
 
        except NotImplementedError:
532
 
            return
533
 
        self.assertEqual(['base'], vf.get_parents('notbase'))
534
 
        # open again, check it stuck.
535
 
        vf = self.get_file()
536
 
        self.assertEqual(['base'], vf.get_parents('notbase'))
537
 
 
538
 
    def test_fix_parents_with_ghosts(self):
539
 
        # when fixing parents, ghosts that are listed should not be ghosts
540
 
        # anymore.
541
 
        vf = self.get_file()
542
 
 
543
 
        try:
544
 
            vf.add_lines_with_ghosts('notbase', ['base', 'stillghost'], [])
545
 
        except NotImplementedError:
546
 
            return
547
 
        vf.add_lines('base', [], [])
548
 
        vf.fix_parents('notbase', ['base', 'stillghost'])
549
 
        self.assertEqual(['base'], vf.get_parents('notbase'))
550
 
        # open again, check it stuck.
551
 
        vf = self.get_file()
552
 
        self.assertEqual(['base'], vf.get_parents('notbase'))
553
 
        # and check the ghosts
554
 
        self.assertEqual(['base', 'stillghost'],
555
 
                         vf.get_parents_with_ghosts('notbase'))
 
789
        self.assertTrue(lines[('base\n', 'base')] > 0)
 
790
        self.assertTrue(lines[('lancestor\n', 'lancestor')] > 0)
 
791
        self.assertTrue(lines[('rancestor\n', 'rancestor')] > 0)
 
792
        self.assertTrue(lines[('child\n', 'child')] > 0)
 
793
        self.assertTrue(lines[('otherchild\n', 'otherchild')] > 0)
556
794
 
557
795
    def test_add_lines_with_ghosts(self):
558
796
        # some versioned file formats allow lines to be added with parent
561
799
        # add_lines_with_ghosts api.
562
800
        vf = self.get_file()
563
801
        # add a revision with ghost parents
 
802
        # The preferred form is utf8, but we should translate when needed
 
803
        parent_id_unicode = u'b\xbfse'
 
804
        parent_id_utf8 = parent_id_unicode.encode('utf8')
564
805
        try:
565
 
            vf.add_lines_with_ghosts(u'notbxbfse', [u'b\xbfse'], [])
 
806
            vf.add_lines_with_ghosts('notbxbfse', [parent_id_utf8], [])
566
807
        except NotImplementedError:
567
808
            # check the other ghost apis are also not implemented
568
 
            self.assertRaises(NotImplementedError, vf.has_ghost, 'foo')
569
809
            self.assertRaises(NotImplementedError, vf.get_ancestry_with_ghosts, ['foo'])
570
810
            self.assertRaises(NotImplementedError, vf.get_parents_with_ghosts, 'foo')
571
 
            self.assertRaises(NotImplementedError, vf.get_graph_with_ghosts)
572
811
            return
 
812
        vf = self.reopen_file()
573
813
        # test key graph related apis: getncestry, _graph, get_parents
574
814
        # has_version
575
815
        # - these are ghost unaware and must not be reflect ghosts
576
 
        self.assertEqual([u'notbxbfse'], vf.get_ancestry(u'notbxbfse'))
577
 
        self.assertEqual([], vf.get_parents(u'notbxbfse'))
578
 
        self.assertEqual({u'notbxbfse':[]}, vf.get_graph())
579
 
        self.assertFalse(vf.has_version(u'b\xbfse'))
 
816
        self.assertEqual(['notbxbfse'], vf.get_ancestry('notbxbfse'))
 
817
        self.assertFalse(vf.has_version(parent_id_utf8))
580
818
        # we have _with_ghost apis to give us ghost information.
581
 
        self.assertEqual([u'b\xbfse', u'notbxbfse'], vf.get_ancestry_with_ghosts([u'notbxbfse']))
582
 
        self.assertEqual([u'b\xbfse'], vf.get_parents_with_ghosts(u'notbxbfse'))
583
 
        self.assertEqual({u'notbxbfse':[u'b\xbfse']}, vf.get_graph_with_ghosts())
584
 
        self.assertTrue(vf.has_ghost(u'b\xbfse'))
 
819
        self.assertEqual([parent_id_utf8, 'notbxbfse'], vf.get_ancestry_with_ghosts(['notbxbfse']))
 
820
        self.assertEqual([parent_id_utf8], vf.get_parents_with_ghosts('notbxbfse'))
585
821
        # if we add something that is a ghost of another, it should correct the
586
822
        # results of the prior apis
587
 
        vf.add_lines(u'b\xbfse', [], [])
588
 
        self.assertEqual([u'b\xbfse', u'notbxbfse'], vf.get_ancestry([u'notbxbfse']))
589
 
        self.assertEqual([u'b\xbfse'], vf.get_parents(u'notbxbfse'))
590
 
        self.assertEqual({u'b\xbfse':[],
591
 
                          u'notbxbfse':[u'b\xbfse'],
592
 
                          },
593
 
                         vf.get_graph())
594
 
        self.assertTrue(vf.has_version(u'b\xbfse'))
 
823
        vf.add_lines(parent_id_utf8, [], [])
 
824
        self.assertEqual([parent_id_utf8, 'notbxbfse'], vf.get_ancestry(['notbxbfse']))
 
825
        self.assertEqual({'notbxbfse':(parent_id_utf8,)},
 
826
            vf.get_parent_map(['notbxbfse']))
 
827
        self.assertTrue(vf.has_version(parent_id_utf8))
595
828
        # we have _with_ghost apis to give us ghost information.
596
 
        self.assertEqual([u'b\xbfse', u'notbxbfse'], vf.get_ancestry_with_ghosts([u'notbxbfse']))
597
 
        self.assertEqual([u'b\xbfse'], vf.get_parents_with_ghosts(u'notbxbfse'))
598
 
        self.assertEqual({u'b\xbfse':[],
599
 
                          u'notbxbfse':[u'b\xbfse'],
600
 
                          },
601
 
                         vf.get_graph_with_ghosts())
602
 
        self.assertFalse(vf.has_ghost(u'b\xbfse'))
 
829
        self.assertEqual([parent_id_utf8, 'notbxbfse'],
 
830
            vf.get_ancestry_with_ghosts(['notbxbfse']))
 
831
        self.assertEqual([parent_id_utf8], vf.get_parents_with_ghosts('notbxbfse'))
603
832
 
604
833
    def test_add_lines_with_ghosts_after_normal_revs(self):
605
834
        # some versioned file formats allow lines to be added with parent
609
838
        vf = self.get_file()
610
839
        # probe for ghost support
611
840
        try:
612
 
            vf.has_ghost('hoo')
 
841
            vf.add_lines_with_ghosts('base', [], ['line\n', 'line_b\n'])
613
842
        except NotImplementedError:
614
843
            return
615
 
        vf.add_lines_with_ghosts('base', [], ['line\n', 'line_b\n'])
616
844
        vf.add_lines_with_ghosts('references_ghost',
617
845
                                 ['base', 'a_ghost'],
618
846
                                 ['line\n', 'line_b\n', 'line_c\n'])
626
854
        factory = self.get_factory()
627
855
        vf = factory('id', transport, 0777, create=True, access_mode='w')
628
856
        vf = factory('id', transport, access_mode='r')
629
 
        self.assertRaises(errors.ReadOnlyError, vf.add_delta, '', [], '', '', False, [])
630
857
        self.assertRaises(errors.ReadOnlyError, vf.add_lines, 'base', [], [])
631
858
        self.assertRaises(errors.ReadOnlyError,
632
859
                          vf.add_lines_with_ghosts,
633
860
                          'base',
634
861
                          [],
635
862
                          [])
636
 
        self.assertRaises(errors.ReadOnlyError, vf.fix_parents, 'base', [])
637
 
        self.assertRaises(errors.ReadOnlyError, vf.join, 'base')
638
 
        self.assertRaises(errors.ReadOnlyError, vf.clone_text, 'base', 'bar', ['foo'])
 
863
        self.assertRaises(errors.ReadOnlyError, self.applyDeprecated, one_five,
 
864
            vf.join, 'base')
 
865
    
 
866
    def test_get_sha1s(self):
 
867
        # check the sha1 data is available
 
868
        vf = self.get_file()
 
869
        # a simple file
 
870
        vf.add_lines('a', [], ['a\n'])
 
871
        # the same file, different metadata
 
872
        vf.add_lines('b', ['a'], ['a\n'])
 
873
        # a file differing only in last newline.
 
874
        vf.add_lines('c', [], ['a'])
 
875
        self.assertEqual(['3f786850e387550fdab836ed7e6dc881de23001b',
 
876
                          '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8',
 
877
                          '3f786850e387550fdab836ed7e6dc881de23001b'],
 
878
                          vf.get_sha1s(['a', 'c', 'b']))
639
879
        
640
880
 
641
 
class TestWeave(TestCaseWithTransport, VersionedFileTestMixIn):
 
881
class TestWeave(TestCaseWithMemoryTransport, VersionedFileTestMixIn):
642
882
 
643
883
    def get_file(self, name='foo'):
644
 
        return WeaveFile(name, get_transport(self.get_url('.')), create=True)
 
884
        return WeaveFile(name, get_transport(self.get_url('.')), create=True,
 
885
            get_scope=self.get_transaction)
645
886
 
646
887
    def get_file_corrupted_text(self):
647
 
        w = WeaveFile('foo', get_transport(self.get_url('.')), create=True)
 
888
        w = WeaveFile('foo', get_transport(self.get_url('.')), create=True,
 
889
            get_scope=self.get_transaction)
648
890
        w.add_lines('v1', [], ['hello\n'])
649
891
        w.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
650
892
        
677
919
        w._sha1s[1] =  'f0f265c6e75f1c8f9ab76dcf85528352c5f215ef'
678
920
        return w
679
921
 
680
 
    def reopen_file(self, name='foo'):
681
 
        return WeaveFile(name, get_transport(self.get_url('.')))
 
922
    def reopen_file(self, name='foo', create=False):
 
923
        return WeaveFile(name, get_transport(self.get_url('.')), create=create,
 
924
            get_scope=self.get_transaction)
682
925
 
683
926
    def test_no_implicit_create(self):
684
927
        self.assertRaises(errors.NoSuchFile,
685
928
                          WeaveFile,
686
929
                          'foo',
687
 
                          get_transport(self.get_url('.')))
 
930
                          get_transport(self.get_url('.')),
 
931
                          get_scope=self.get_transaction)
688
932
 
689
933
    def get_factory(self):
690
934
        return WeaveFile
691
935
 
692
936
 
693
 
class TestKnit(TestCaseWithTransport, VersionedFileTestMixIn):
 
937
class TestKnit(TestCaseWithMemoryTransport, VersionedFileTestMixIn):
694
938
 
695
 
    def get_file(self, name='foo'):
696
 
        return KnitVersionedFile(name, get_transport(self.get_url('.')),
697
 
                                 delta=True, create=True)
 
939
    def get_file(self, name='foo', create=True):
 
940
        return make_file_knit(name, get_transport(self.get_url('.')),
 
941
            delta=True, create=True, get_scope=self.get_transaction)
698
942
 
699
943
    def get_factory(self):
700
 
        return KnitVersionedFile
 
944
        return make_file_knit
701
945
 
702
946
    def get_file_corrupted_text(self):
703
947
        knit = self.get_file()
705
949
        knit.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
706
950
        return knit
707
951
 
708
 
    def reopen_file(self, name='foo'):
709
 
        return KnitVersionedFile(name, get_transport(self.get_url('.')), delta=True)
 
952
    def reopen_file(self, name='foo', create=False):
 
953
        return self.get_file(name, create)
710
954
 
711
955
    def test_detection(self):
712
 
        print "TODO for merging: create a corrupted knit."
713
956
        knit = self.get_file()
714
957
        knit.check()
715
958
 
716
959
    def test_no_implicit_create(self):
717
 
        self.assertRaises(errors.NoSuchFile,
718
 
                          KnitVersionedFile,
719
 
                          'foo',
720
 
                          get_transport(self.get_url('.')))
 
960
        self.assertRaises(errors.NoSuchFile, self.get_factory(), 'foo',
 
961
            get_transport(self.get_url('.')))
 
962
 
 
963
 
 
964
class TestPlaintextKnit(TestKnit):
 
965
    """Test a knit with no cached annotations"""
 
966
 
 
967
    def get_file(self, name='foo', create=True):
 
968
        return make_file_knit(name, get_transport(self.get_url('.')),
 
969
            delta=True, create=create, get_scope=self.get_transaction,
 
970
            factory=_mod_knit.KnitPlainFactory())
 
971
 
 
972
 
 
973
class TestPlanMergeVersionedFile(TestCaseWithMemoryTransport):
 
974
 
 
975
    def setUp(self):
 
976
        TestCaseWithMemoryTransport.setUp(self)
 
977
        self.vf1 = make_file_knit('root', self.get_transport(), create=True)
 
978
        self.vf2 = make_file_knit('root', self.get_transport(), create=True)
 
979
        self.plan_merge_vf = versionedfile._PlanMergeVersionedFile('root',
 
980
            [self.vf1, self.vf2])
 
981
 
 
982
    def test_add_lines(self):
 
983
        self.plan_merge_vf.add_lines('a:', [], [])
 
984
        self.assertRaises(ValueError, self.plan_merge_vf.add_lines, 'a', [],
 
985
                          [])
 
986
        self.assertRaises(ValueError, self.plan_merge_vf.add_lines, 'a:', None,
 
987
                          [])
 
988
        self.assertRaises(ValueError, self.plan_merge_vf.add_lines, 'a:', [],
 
989
                          None)
 
990
 
 
991
    def test_ancestry(self):
 
992
        self.vf1.add_lines('A', [], [])
 
993
        self.vf1.add_lines('B', ['A'], [])
 
994
        self.plan_merge_vf.add_lines('C:', ['B'], [])
 
995
        self.plan_merge_vf.add_lines('D:', ['C:'], [])
 
996
        self.assertEqual(set(['A', 'B', 'C:', 'D:']),
 
997
            self.plan_merge_vf.get_ancestry('D:', topo_sorted=False))
 
998
 
 
999
    def setup_abcde(self):
 
1000
        self.vf1.add_lines('A', [], ['a'])
 
1001
        self.vf1.add_lines('B', ['A'], ['b'])
 
1002
        self.vf2.add_lines('C', [], ['c'])
 
1003
        self.vf2.add_lines('D', ['C'], ['d'])
 
1004
        self.plan_merge_vf.add_lines('E:', ['B', 'D'], ['e'])
 
1005
 
 
1006
    def test_ancestry_uses_all_versionedfiles(self):
 
1007
        self.setup_abcde()
 
1008
        self.assertEqual(set(['A', 'B', 'C', 'D', 'E:']),
 
1009
            self.plan_merge_vf.get_ancestry('E:', topo_sorted=False))
 
1010
 
 
1011
    def test_ancestry_raises_revision_not_present(self):
 
1012
        error = self.assertRaises(errors.RevisionNotPresent,
 
1013
                                  self.plan_merge_vf.get_ancestry, 'E:', False)
 
1014
        self.assertContainsRe(str(error), '{E:} not present in "root"')
 
1015
 
 
1016
    def test_get_parents(self):
 
1017
        self.setup_abcde()
 
1018
        self.assertEqual({'B':('A',)}, self.plan_merge_vf.get_parent_map(['B']))
 
1019
        self.assertEqual({'D':('C',)}, self.plan_merge_vf.get_parent_map(['D']))
 
1020
        self.assertEqual({'E:':('B', 'D')},
 
1021
            self.plan_merge_vf.get_parent_map(['E:']))
 
1022
        self.assertEqual({}, self.plan_merge_vf.get_parent_map(['F']))
 
1023
        self.assertEqual({
 
1024
                'B':('A',),
 
1025
                'D':('C',),
 
1026
                'E:':('B', 'D'),
 
1027
                }, self.plan_merge_vf.get_parent_map(['B', 'D', 'E:', 'F']))
 
1028
 
 
1029
    def test_get_lines(self):
 
1030
        self.setup_abcde()
 
1031
        self.assertEqual(['a'], self.plan_merge_vf.get_lines('A'))
 
1032
        self.assertEqual(['c'], self.plan_merge_vf.get_lines('C'))
 
1033
        self.assertEqual(['e'], self.plan_merge_vf.get_lines('E:'))
 
1034
        error = self.assertRaises(errors.RevisionNotPresent,
 
1035
                                  self.plan_merge_vf.get_lines, 'F')
 
1036
        self.assertContainsRe(str(error), '{F} not present in "root"')
721
1037
 
722
1038
 
723
1039
class InterString(versionedfile.InterVersionedFile):
738
1054
# if we make the registry a separate class though we still need to 
739
1055
# test the behaviour in the active registry to catch failure-to-handle-
740
1056
# stange-objects
741
 
class TestInterVersionedFile(TestCaseWithTransport):
 
1057
class TestInterVersionedFile(TestCaseWithMemoryTransport):
742
1058
 
743
1059
    def test_get_default_inter_versionedfile(self):
744
1060
        # test that the InterVersionedFile.get(a, b) probes
783
1099
            versionedfile.InterVersionedFile.unregister_optimiser(InterString)
784
1100
        # now we should get the default InterVersionedFile object again.
785
1101
        self.assertGetsDefaultInterVersionedFile(dummy_a, dummy_b)
 
1102
 
 
1103
 
 
1104
class TestReadonlyHttpMixin(object):
 
1105
 
 
1106
    def get_transaction(self):
 
1107
        return 1
 
1108
 
 
1109
    def test_readonly_http_works(self):
 
1110
        # we should be able to read from http with a versioned file.
 
1111
        vf = self.get_file()
 
1112
        # try an empty file access
 
1113
        readonly_vf = self.get_factory()('foo', get_transport(self.get_readonly_url('.')))
 
1114
        self.assertEqual([], readonly_vf.versions())
 
1115
        # now with feeling.
 
1116
        vf.add_lines('1', [], ['a\n'])
 
1117
        vf.add_lines('2', ['1'], ['b\n', 'a\n'])
 
1118
        readonly_vf = self.get_factory()('foo', get_transport(self.get_readonly_url('.')))
 
1119
        self.assertEqual(['1', '2'], vf.versions())
 
1120
        for version in readonly_vf.versions():
 
1121
            readonly_vf.get_lines(version)
 
1122
 
 
1123
 
 
1124
class TestWeaveHTTP(TestCaseWithWebserver, TestReadonlyHttpMixin):
 
1125
 
 
1126
    def get_file(self):
 
1127
        return WeaveFile('foo', get_transport(self.get_url('.')), create=True,
 
1128
            get_scope=self.get_transaction)
 
1129
 
 
1130
    def get_factory(self):
 
1131
        return WeaveFile
 
1132
 
 
1133
 
 
1134
class TestKnitHTTP(TestCaseWithWebserver, TestReadonlyHttpMixin):
 
1135
 
 
1136
    def get_file(self):
 
1137
        return make_file_knit('foo', get_transport(self.get_url('.')),
 
1138
            delta=True, create=True, get_scope=self.get_transaction)
 
1139
 
 
1140
    def get_factory(self):
 
1141
        return make_file_knit
 
1142
 
 
1143
 
 
1144
class MergeCasesMixin(object):
 
1145
 
 
1146
    def doMerge(self, base, a, b, mp):
 
1147
        from cStringIO import StringIO
 
1148
        from textwrap import dedent
 
1149
 
 
1150
        def addcrlf(x):
 
1151
            return x + '\n'
 
1152
        
 
1153
        w = self.get_file()
 
1154
        w.add_lines('text0', [], map(addcrlf, base))
 
1155
        w.add_lines('text1', ['text0'], map(addcrlf, a))
 
1156
        w.add_lines('text2', ['text0'], map(addcrlf, b))
 
1157
 
 
1158
        self.log_contents(w)
 
1159
 
 
1160
        self.log('merge plan:')
 
1161
        p = list(w.plan_merge('text1', 'text2'))
 
1162
        for state, line in p:
 
1163
            if line:
 
1164
                self.log('%12s | %s' % (state, line[:-1]))
 
1165
 
 
1166
        self.log('merge:')
 
1167
        mt = StringIO()
 
1168
        mt.writelines(w.weave_merge(p))
 
1169
        mt.seek(0)
 
1170
        self.log(mt.getvalue())
 
1171
 
 
1172
        mp = map(addcrlf, mp)
 
1173
        self.assertEqual(mt.readlines(), mp)
 
1174
        
 
1175
        
 
1176
    def testOneInsert(self):
 
1177
        self.doMerge([],
 
1178
                     ['aa'],
 
1179
                     [],
 
1180
                     ['aa'])
 
1181
 
 
1182
    def testSeparateInserts(self):
 
1183
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
1184
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
1185
                     ['aaa', 'bbb', 'yyy', 'ccc'],
 
1186
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
1187
 
 
1188
    def testSameInsert(self):
 
1189
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
1190
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
1191
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'],
 
1192
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
1193
    overlappedInsertExpected = ['aaa', 'xxx', 'yyy', 'bbb']
 
1194
    def testOverlappedInsert(self):
 
1195
        self.doMerge(['aaa', 'bbb'],
 
1196
                     ['aaa', 'xxx', 'yyy', 'bbb'],
 
1197
                     ['aaa', 'xxx', 'bbb'], self.overlappedInsertExpected)
 
1198
 
 
1199
        # really it ought to reduce this to 
 
1200
        # ['aaa', 'xxx', 'yyy', 'bbb']
 
1201
 
 
1202
 
 
1203
    def testClashReplace(self):
 
1204
        self.doMerge(['aaa'],
 
1205
                     ['xxx'],
 
1206
                     ['yyy', 'zzz'],
 
1207
                     ['<<<<<<< ', 'xxx', '=======', 'yyy', 'zzz', 
 
1208
                      '>>>>>>> '])
 
1209
 
 
1210
    def testNonClashInsert1(self):
 
1211
        self.doMerge(['aaa'],
 
1212
                     ['xxx', 'aaa'],
 
1213
                     ['yyy', 'zzz'],
 
1214
                     ['<<<<<<< ', 'xxx', 'aaa', '=======', 'yyy', 'zzz', 
 
1215
                      '>>>>>>> '])
 
1216
 
 
1217
    def testNonClashInsert2(self):
 
1218
        self.doMerge(['aaa'],
 
1219
                     ['aaa'],
 
1220
                     ['yyy', 'zzz'],
 
1221
                     ['yyy', 'zzz'])
 
1222
 
 
1223
 
 
1224
    def testDeleteAndModify(self):
 
1225
        """Clashing delete and modification.
 
1226
 
 
1227
        If one side modifies a region and the other deletes it then
 
1228
        there should be a conflict with one side blank.
 
1229
        """
 
1230
 
 
1231
        #######################################
 
1232
        # skippd, not working yet
 
1233
        return
 
1234
        
 
1235
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
1236
                     ['aaa', 'ddd', 'ccc'],
 
1237
                     ['aaa', 'ccc'],
 
1238
                     ['<<<<<<<< ', 'aaa', '=======', '>>>>>>> ', 'ccc'])
 
1239
 
 
1240
    def _test_merge_from_strings(self, base, a, b, expected):
 
1241
        w = self.get_file()
 
1242
        w.add_lines('text0', [], base.splitlines(True))
 
1243
        w.add_lines('text1', ['text0'], a.splitlines(True))
 
1244
        w.add_lines('text2', ['text0'], b.splitlines(True))
 
1245
        self.log('merge plan:')
 
1246
        p = list(w.plan_merge('text1', 'text2'))
 
1247
        for state, line in p:
 
1248
            if line:
 
1249
                self.log('%12s | %s' % (state, line[:-1]))
 
1250
        self.log('merge result:')
 
1251
        result_text = ''.join(w.weave_merge(p))
 
1252
        self.log(result_text)
 
1253
        self.assertEqualDiff(result_text, expected)
 
1254
 
 
1255
    def test_weave_merge_conflicts(self):
 
1256
        # does weave merge properly handle plans that end with unchanged?
 
1257
        result = ''.join(self.get_file().weave_merge([('new-a', 'hello\n')]))
 
1258
        self.assertEqual(result, 'hello\n')
 
1259
 
 
1260
    def test_deletion_extended(self):
 
1261
        """One side deletes, the other deletes more.
 
1262
        """
 
1263
        base = """\
 
1264
            line 1
 
1265
            line 2
 
1266
            line 3
 
1267
            """
 
1268
        a = """\
 
1269
            line 1
 
1270
            line 2
 
1271
            """
 
1272
        b = """\
 
1273
            line 1
 
1274
            """
 
1275
        result = """\
 
1276
            line 1
 
1277
            """
 
1278
        self._test_merge_from_strings(base, a, b, result)
 
1279
 
 
1280
    def test_deletion_overlap(self):
 
1281
        """Delete overlapping regions with no other conflict.
 
1282
 
 
1283
        Arguably it'd be better to treat these as agreement, rather than 
 
1284
        conflict, but for now conflict is safer.
 
1285
        """
 
1286
        base = """\
 
1287
            start context
 
1288
            int a() {}
 
1289
            int b() {}
 
1290
            int c() {}
 
1291
            end context
 
1292
            """
 
1293
        a = """\
 
1294
            start context
 
1295
            int a() {}
 
1296
            end context
 
1297
            """
 
1298
        b = """\
 
1299
            start context
 
1300
            int c() {}
 
1301
            end context
 
1302
            """
 
1303
        result = """\
 
1304
            start context
 
1305
<<<<<<< 
 
1306
            int a() {}
 
1307
=======
 
1308
            int c() {}
 
1309
>>>>>>> 
 
1310
            end context
 
1311
            """
 
1312
        self._test_merge_from_strings(base, a, b, result)
 
1313
 
 
1314
    def test_agreement_deletion(self):
 
1315
        """Agree to delete some lines, without conflicts."""
 
1316
        base = """\
 
1317
            start context
 
1318
            base line 1
 
1319
            base line 2
 
1320
            end context
 
1321
            """
 
1322
        a = """\
 
1323
            start context
 
1324
            base line 1
 
1325
            end context
 
1326
            """
 
1327
        b = """\
 
1328
            start context
 
1329
            base line 1
 
1330
            end context
 
1331
            """
 
1332
        result = """\
 
1333
            start context
 
1334
            base line 1
 
1335
            end context
 
1336
            """
 
1337
        self._test_merge_from_strings(base, a, b, result)
 
1338
 
 
1339
    def test_sync_on_deletion(self):
 
1340
        """Specific case of merge where we can synchronize incorrectly.
 
1341
        
 
1342
        A previous version of the weave merge concluded that the two versions
 
1343
        agreed on deleting line 2, and this could be a synchronization point.
 
1344
        Line 1 was then considered in isolation, and thought to be deleted on 
 
1345
        both sides.
 
1346
 
 
1347
        It's better to consider the whole thing as a disagreement region.
 
1348
        """
 
1349
        base = """\
 
1350
            start context
 
1351
            base line 1
 
1352
            base line 2
 
1353
            end context
 
1354
            """
 
1355
        a = """\
 
1356
            start context
 
1357
            base line 1
 
1358
            a's replacement line 2
 
1359
            end context
 
1360
            """
 
1361
        b = """\
 
1362
            start context
 
1363
            b replaces
 
1364
            both lines
 
1365
            end context
 
1366
            """
 
1367
        result = """\
 
1368
            start context
 
1369
<<<<<<< 
 
1370
            base line 1
 
1371
            a's replacement line 2
 
1372
=======
 
1373
            b replaces
 
1374
            both lines
 
1375
>>>>>>> 
 
1376
            end context
 
1377
            """
 
1378
        self._test_merge_from_strings(base, a, b, result)
 
1379
 
 
1380
 
 
1381
class TestKnitMerge(TestCaseWithMemoryTransport, MergeCasesMixin):
 
1382
 
 
1383
    def get_file(self, name='foo'):
 
1384
        return make_file_knit(name, get_transport(self.get_url('.')),
 
1385
                                 delta=True, create=True)
 
1386
 
 
1387
    def log_contents(self, w):
 
1388
        pass
 
1389
 
 
1390
 
 
1391
class TestWeaveMerge(TestCaseWithMemoryTransport, MergeCasesMixin):
 
1392
 
 
1393
    def get_file(self, name='foo'):
 
1394
        return WeaveFile(name, get_transport(self.get_url('.')), create=True)
 
1395
 
 
1396
    def log_contents(self, w):
 
1397
        self.log('weave is:')
 
1398
        tmpf = StringIO()
 
1399
        write_weave(w, tmpf)
 
1400
        self.log(tmpf.getvalue())
 
1401
 
 
1402
    overlappedInsertExpected = ['aaa', '<<<<<<< ', 'xxx', 'yyy', '=======', 
 
1403
                                'xxx', '>>>>>>> ', 'bbb']
 
1404
 
 
1405
 
 
1406
class TestContentFactoryAdaption(TestCaseWithMemoryTransport):
 
1407
 
 
1408
    def test_select_adaptor(self):
 
1409
        """Test expected adapters exist."""
 
1410
        # One scenario for each lookup combination we expect to use.
 
1411
        # Each is source_kind, requested_kind, adapter class
 
1412
        scenarios = [
 
1413
            ('knit-delta-gz', 'fulltext', _mod_knit.DeltaPlainToFullText),
 
1414
            ('knit-ft-gz', 'fulltext', _mod_knit.FTPlainToFullText),
 
1415
            ('knit-annotated-delta-gz', 'knit-delta-gz',
 
1416
                _mod_knit.DeltaAnnotatedToUnannotated),
 
1417
            ('knit-annotated-delta-gz', 'fulltext',
 
1418
                _mod_knit.DeltaAnnotatedToFullText),
 
1419
            ('knit-annotated-ft-gz', 'knit-ft-gz',
 
1420
                _mod_knit.FTAnnotatedToUnannotated),
 
1421
            ('knit-annotated-ft-gz', 'fulltext',
 
1422
                _mod_knit.FTAnnotatedToFullText),
 
1423
            ]
 
1424
        for source, requested, klass in scenarios:
 
1425
            adapter_factory = versionedfile.adapter_registry.get(
 
1426
                (source, requested))
 
1427
            adapter = adapter_factory(None)
 
1428
            self.assertIsInstance(adapter, klass)
 
1429
 
 
1430
    def get_knit(self, annotated=True):
 
1431
        if annotated:
 
1432
            factory = KnitAnnotateFactory()
 
1433
        else:
 
1434
            factory = KnitPlainFactory()
 
1435
        return make_file_knit('knit', self.get_transport('.'), delta=True,
 
1436
            create=True, factory=factory)
 
1437
 
 
1438
    def helpGetBytes(self, f, ft_adapter, delta_adapter):
 
1439
        """Grab the interested adapted texts for tests."""
 
1440
        # origin is a fulltext
 
1441
        entries = f.get_record_stream(['origin'], 'unordered', False)
 
1442
        base = entries.next()
 
1443
        ft_data = ft_adapter.get_bytes(base, base.get_bytes_as(base.storage_kind))
 
1444
        # merged is both a delta and multiple parents.
 
1445
        entries = f.get_record_stream(['merged'], 'unordered', False)
 
1446
        merged = entries.next()
 
1447
        delta_data = delta_adapter.get_bytes(merged,
 
1448
            merged.get_bytes_as(merged.storage_kind))
 
1449
        return ft_data, delta_data
 
1450
 
 
1451
    def test_deannotation_noeol(self):
 
1452
        """Test converting annotated knits to unannotated knits."""
 
1453
        # we need a full text, and a delta
 
1454
        f, parents = get_diamond_vf(self.get_knit(), trailing_eol=False)
 
1455
        ft_data, delta_data = self.helpGetBytes(f,
 
1456
            _mod_knit.FTAnnotatedToUnannotated(None),
 
1457
            _mod_knit.DeltaAnnotatedToUnannotated(None))
 
1458
        self.assertEqual(
 
1459
            'version origin 1 b284f94827db1fa2970d9e2014f080413b547a7e\n'
 
1460
            'origin\n'
 
1461
            'end origin\n',
 
1462
            GzipFile(mode='rb', fileobj=StringIO(ft_data)).read())
 
1463
        self.assertEqual(
 
1464
            'version merged 4 32c2e79763b3f90e8ccde37f9710b6629c25a796\n'
 
1465
            '1,2,3\nleft\nright\nmerged\nend merged\n',
 
1466
            GzipFile(mode='rb', fileobj=StringIO(delta_data)).read())
 
1467
 
 
1468
    def test_deannotation(self):
 
1469
        """Test converting annotated knits to unannotated knits."""
 
1470
        # we need a full text, and a delta
 
1471
        f, parents = get_diamond_vf(self.get_knit())
 
1472
        ft_data, delta_data = self.helpGetBytes(f,
 
1473
            _mod_knit.FTAnnotatedToUnannotated(None),
 
1474
            _mod_knit.DeltaAnnotatedToUnannotated(None))
 
1475
        self.assertEqual(
 
1476
            'version origin 1 00e364d235126be43292ab09cb4686cf703ddc17\n'
 
1477
            'origin\n'
 
1478
            'end origin\n',
 
1479
            GzipFile(mode='rb', fileobj=StringIO(ft_data)).read())
 
1480
        self.assertEqual(
 
1481
            'version merged 3 ed8bce375198ea62444dc71952b22cfc2b09226d\n'
 
1482
            '2,2,2\nright\nmerged\nend merged\n',
 
1483
            GzipFile(mode='rb', fileobj=StringIO(delta_data)).read())
 
1484
 
 
1485
    def test_annotated_to_fulltext_no_eol(self):
 
1486
        """Test adapting annotated knits to full texts (for -> weaves)."""
 
1487
        # we need a full text, and a delta
 
1488
        f, parents = get_diamond_vf(self.get_knit(), trailing_eol=False)
 
1489
        # Reconstructing a full text requires a backing versioned file, and it
 
1490
        # must have the base lines requested from it.
 
1491
        logged_vf = versionedfile.RecordingVersionedFileDecorator(f)
 
1492
        ft_data, delta_data = self.helpGetBytes(f,
 
1493
            _mod_knit.FTAnnotatedToFullText(None),
 
1494
            _mod_knit.DeltaAnnotatedToFullText(logged_vf))
 
1495
        self.assertEqual('origin', ft_data)
 
1496
        self.assertEqual('base\nleft\nright\nmerged', delta_data)
 
1497
        self.assertEqual([('get_lines', 'left')], logged_vf.calls)
 
1498
 
 
1499
    def test_annotated_to_fulltext(self):
 
1500
        """Test adapting annotated knits to full texts (for -> weaves)."""
 
1501
        # we need a full text, and a delta
 
1502
        f, parents = get_diamond_vf(self.get_knit())
 
1503
        # Reconstructing a full text requires a backing versioned file, and it
 
1504
        # must have the base lines requested from it.
 
1505
        logged_vf = versionedfile.RecordingVersionedFileDecorator(f)
 
1506
        ft_data, delta_data = self.helpGetBytes(f,
 
1507
            _mod_knit.FTAnnotatedToFullText(None),
 
1508
            _mod_knit.DeltaAnnotatedToFullText(logged_vf))
 
1509
        self.assertEqual('origin\n', ft_data)
 
1510
        self.assertEqual('base\nleft\nright\nmerged\n', delta_data)
 
1511
        self.assertEqual([('get_lines', 'left')], logged_vf.calls)
 
1512
 
 
1513
    def test_unannotated_to_fulltext(self):
 
1514
        """Test adapting unannotated knits to full texts.
 
1515
        
 
1516
        This is used for -> weaves, and for -> annotated knits.
 
1517
        """
 
1518
        # we need a full text, and a delta
 
1519
        f, parents = get_diamond_vf(self.get_knit(annotated=False))
 
1520
        # Reconstructing a full text requires a backing versioned file, and it
 
1521
        # must have the base lines requested from it.
 
1522
        logged_vf = versionedfile.RecordingVersionedFileDecorator(f)
 
1523
        ft_data, delta_data = self.helpGetBytes(f,
 
1524
            _mod_knit.FTPlainToFullText(None),
 
1525
            _mod_knit.DeltaPlainToFullText(logged_vf))
 
1526
        self.assertEqual('origin\n', ft_data)
 
1527
        self.assertEqual('base\nleft\nright\nmerged\n', delta_data)
 
1528
        self.assertEqual([('get_lines', 'left')], logged_vf.calls)
 
1529
 
 
1530
    def test_unannotated_to_fulltext_no_eol(self):
 
1531
        """Test adapting unannotated knits to full texts.
 
1532
        
 
1533
        This is used for -> weaves, and for -> annotated knits.
 
1534
        """
 
1535
        # we need a full text, and a delta
 
1536
        f, parents = get_diamond_vf(self.get_knit(annotated=False),
 
1537
            trailing_eol=False)
 
1538
        # Reconstructing a full text requires a backing versioned file, and it
 
1539
        # must have the base lines requested from it.
 
1540
        logged_vf = versionedfile.RecordingVersionedFileDecorator(f)
 
1541
        ft_data, delta_data = self.helpGetBytes(f,
 
1542
            _mod_knit.FTPlainToFullText(None),
 
1543
            _mod_knit.DeltaPlainToFullText(logged_vf))
 
1544
        self.assertEqual('origin', ft_data)
 
1545
        self.assertEqual('base\nleft\nright\nmerged', delta_data)
 
1546
        self.assertEqual([('get_lines', 'left')], logged_vf.calls)
 
1547