/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: Ian Clatworthy
  • Date: 2007-09-03 12:32:14 UTC
  • mfrom: (2659.3.10 precommit)
  • mto: This revision was merged to the branch mainline in revision 2790.
  • Revision ID: ian.clatworthy@internode.on.net-20070903123214-kgrq7hubbtkmkn7i
(Nam Nguyen) Pre-commit hook

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005 Canonical Ltd
 
2
#
 
3
# Authors:
 
4
#   Johan Rydberg <jrydberg@gnu.org>
 
5
#
 
6
# This program is free software; you can redistribute it and/or modify
 
7
# it under the terms of the GNU General Public License as published by
 
8
# the Free Software Foundation; either version 2 of the License, or
 
9
# (at your option) any later version.
 
10
#
 
11
# This program is distributed in the hope that it will be useful,
 
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
14
# GNU General Public License for more details.
 
15
#
 
16
# You should have received a copy of the GNU General Public License
 
17
# along with this program; if not, write to the Free Software
 
18
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
19
 
 
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 StringIO import StringIO
 
25
 
 
26
import bzrlib
 
27
from bzrlib import (
 
28
    errors,
 
29
    osutils,
 
30
    progress,
 
31
    )
 
32
from bzrlib.errors import (
 
33
                           RevisionNotPresent, 
 
34
                           RevisionAlreadyPresent,
 
35
                           WeaveParentMismatch
 
36
                           )
 
37
from bzrlib.knit import (
 
38
    KnitVersionedFile,
 
39
    KnitAnnotateFactory,
 
40
    KnitPlainFactory,
 
41
    )
 
42
from bzrlib.tests import TestCaseWithMemoryTransport, TestSkipped
 
43
from bzrlib.tests.HTTPTestUtil import TestCaseWithWebserver
 
44
from bzrlib.trace import mutter
 
45
from bzrlib.transport import get_transport
 
46
from bzrlib.transport.memory import MemoryTransport
 
47
from bzrlib.tsort import topo_sort
 
48
import bzrlib.versionedfile as versionedfile
 
49
from bzrlib.weave import WeaveFile
 
50
from bzrlib.weavefile import read_weave, write_weave
 
51
 
 
52
 
 
53
class VersionedFileTestMixIn(object):
 
54
    """A mixin test class for testing VersionedFiles.
 
55
 
 
56
    This is not an adaptor-style test at this point because
 
57
    theres no dynamic substitution of versioned file implementations,
 
58
    they are strictly controlled by their owning repositories.
 
59
    """
 
60
 
 
61
    def test_add(self):
 
62
        f = self.get_file()
 
63
        f.add_lines('r0', [], ['a\n', 'b\n'])
 
64
        f.add_lines('r1', ['r0'], ['b\n', 'c\n'])
 
65
        def verify_file(f):
 
66
            versions = f.versions()
 
67
            self.assertTrue('r0' in versions)
 
68
            self.assertTrue('r1' in versions)
 
69
            self.assertEquals(f.get_lines('r0'), ['a\n', 'b\n'])
 
70
            self.assertEquals(f.get_text('r0'), 'a\nb\n')
 
71
            self.assertEquals(f.get_lines('r1'), ['b\n', 'c\n'])
 
72
            self.assertEqual(2, len(f))
 
73
            self.assertEqual(2, f.num_versions())
 
74
    
 
75
            self.assertRaises(RevisionNotPresent,
 
76
                f.add_lines, 'r2', ['foo'], [])
 
77
            self.assertRaises(RevisionAlreadyPresent,
 
78
                f.add_lines, 'r1', [], [])
 
79
        verify_file(f)
 
80
        # this checks that reopen with create=True does not break anything.
 
81
        f = self.reopen_file(create=True)
 
82
        verify_file(f)
 
83
 
 
84
    def test_adds_with_parent_texts(self):
 
85
        f = self.get_file()
 
86
        parent_texts = {}
 
87
        parent_texts['r0'] = f.add_lines('r0', [], ['a\n', 'b\n'])
 
88
        try:
 
89
            parent_texts['r1'] = f.add_lines_with_ghosts('r1',
 
90
                                                         ['r0', 'ghost'], 
 
91
                                                         ['b\n', 'c\n'],
 
92
                                                         parent_texts=parent_texts)
 
93
        except NotImplementedError:
 
94
            # if the format doesn't support ghosts, just add normally.
 
95
            parent_texts['r1'] = f.add_lines('r1',
 
96
                                             ['r0'], 
 
97
                                             ['b\n', 'c\n'],
 
98
                                             parent_texts=parent_texts)
 
99
        f.add_lines('r2', ['r1'], ['c\n', 'd\n'], parent_texts=parent_texts)
 
100
        self.assertNotEqual(None, parent_texts['r0'])
 
101
        self.assertNotEqual(None, parent_texts['r1'])
 
102
        def verify_file(f):
 
103
            versions = f.versions()
 
104
            self.assertTrue('r0' in versions)
 
105
            self.assertTrue('r1' in versions)
 
106
            self.assertTrue('r2' in versions)
 
107
            self.assertEquals(f.get_lines('r0'), ['a\n', 'b\n'])
 
108
            self.assertEquals(f.get_lines('r1'), ['b\n', 'c\n'])
 
109
            self.assertEquals(f.get_lines('r2'), ['c\n', 'd\n'])
 
110
            self.assertEqual(3, f.num_versions())
 
111
            origins = f.annotate('r1')
 
112
            self.assertEquals(origins[0][0], 'r0')
 
113
            self.assertEquals(origins[1][0], 'r1')
 
114
            origins = f.annotate('r2')
 
115
            self.assertEquals(origins[0][0], 'r1')
 
116
            self.assertEquals(origins[1][0], 'r2')
 
117
 
 
118
        verify_file(f)
 
119
        f = self.reopen_file()
 
120
        verify_file(f)
 
121
 
 
122
    def test_add_unicode_content(self):
 
123
        # unicode content is not permitted in versioned files. 
 
124
        # versioned files version sequences of bytes only.
 
125
        vf = self.get_file()
 
126
        self.assertRaises(errors.BzrBadParameterUnicode,
 
127
            vf.add_lines, 'a', [], ['a\n', u'b\n', 'c\n'])
 
128
        self.assertRaises(
 
129
            (errors.BzrBadParameterUnicode, NotImplementedError),
 
130
            vf.add_lines_with_ghosts, 'a', [], ['a\n', u'b\n', 'c\n'])
 
131
 
 
132
    def test_add_follows_left_matching_blocks(self):
 
133
        """If we change left_matching_blocks, delta changes
 
134
 
 
135
        Note: There are multiple correct deltas in this case, because
 
136
        we start with 1 "a" and we get 3.
 
137
        """
 
138
        vf = self.get_file()
 
139
        if isinstance(vf, WeaveFile):
 
140
            raise TestSkipped("WeaveFile ignores left_matching_blocks")
 
141
        vf.add_lines('1', [], ['a\n'])
 
142
        vf.add_lines('2', ['1'], ['a\n', 'a\n', 'a\n'],
 
143
                     left_matching_blocks=[(0, 0, 1), (1, 3, 0)])
 
144
        self.assertEqual([(1, 1, 2, [('2', 'a\n'), ('2', 'a\n')])],
 
145
                         vf.get_delta('2')[3])
 
146
        vf.add_lines('3', ['1'], ['a\n', 'a\n', 'a\n'],
 
147
                     left_matching_blocks=[(0, 2, 1), (1, 3, 0)])
 
148
        self.assertEqual([(0, 0, 2, [('3', 'a\n'), ('3', 'a\n')])],
 
149
                         vf.get_delta('3')[3])
 
150
 
 
151
    def test_inline_newline_throws(self):
 
152
        # \r characters are not permitted in lines being added
 
153
        vf = self.get_file()
 
154
        self.assertRaises(errors.BzrBadParameterContainsNewline, 
 
155
            vf.add_lines, 'a', [], ['a\n\n'])
 
156
        self.assertRaises(
 
157
            (errors.BzrBadParameterContainsNewline, NotImplementedError),
 
158
            vf.add_lines_with_ghosts, 'a', [], ['a\n\n'])
 
159
        # but inline CR's are allowed
 
160
        vf.add_lines('a', [], ['a\r\n'])
 
161
        try:
 
162
            vf.add_lines_with_ghosts('b', [], ['a\r\n'])
 
163
        except NotImplementedError:
 
164
            pass
 
165
 
 
166
    def test_add_reserved(self):
 
167
        vf = self.get_file()
 
168
        self.assertRaises(errors.ReservedId,
 
169
            vf.add_lines, 'a:', [], ['a\n', 'b\n', 'c\n'])
 
170
 
 
171
        self.assertRaises(errors.ReservedId,
 
172
            vf.add_delta, 'a:', [], None, 'sha1', False, ((0, 0, 0, []),))
 
173
 
 
174
    def test_get_reserved(self):
 
175
        vf = self.get_file()
 
176
        self.assertRaises(errors.ReservedId, vf.get_delta, 'b:')
 
177
        self.assertRaises(errors.ReservedId, vf.get_texts, ['b:'])
 
178
        self.assertRaises(errors.ReservedId, vf.get_lines, 'b:')
 
179
        self.assertRaises(errors.ReservedId, vf.get_text, 'b:')
 
180
 
 
181
    def test_get_delta(self):
 
182
        f = self.get_file()
 
183
        sha1s = self._setup_for_deltas(f)
 
184
        expected_delta = (None, '6bfa09d82ce3e898ad4641ae13dd4fdb9cf0d76b', False, 
 
185
                          [(0, 0, 1, [('base', 'line\n')])])
 
186
        self.assertEqual(expected_delta, f.get_delta('base'))
 
187
        next_parent = 'base'
 
188
        text_name = 'chain1-'
 
189
        for depth in range(26):
 
190
            new_version = text_name + '%s' % depth
 
191
            expected_delta = (next_parent, sha1s[depth], 
 
192
                              False,
 
193
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
 
194
            self.assertEqual(expected_delta, f.get_delta(new_version))
 
195
            next_parent = new_version
 
196
        next_parent = 'base'
 
197
        text_name = 'chain2-'
 
198
        for depth in range(26):
 
199
            new_version = text_name + '%s' % depth
 
200
            expected_delta = (next_parent, sha1s[depth], False,
 
201
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
 
202
            self.assertEqual(expected_delta, f.get_delta(new_version))
 
203
            next_parent = new_version
 
204
        # smoke test for eol support
 
205
        expected_delta = ('base', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True, [])
 
206
        self.assertEqual(['line'], f.get_lines('noeol'))
 
207
        self.assertEqual(expected_delta, f.get_delta('noeol'))
 
208
 
 
209
    def test_get_deltas(self):
 
210
        f = self.get_file()
 
211
        sha1s = self._setup_for_deltas(f)
 
212
        deltas = f.get_deltas(f.versions())
 
213
        expected_delta = (None, '6bfa09d82ce3e898ad4641ae13dd4fdb9cf0d76b', False, 
 
214
                          [(0, 0, 1, [('base', 'line\n')])])
 
215
        self.assertEqual(expected_delta, deltas['base'])
 
216
        next_parent = 'base'
 
217
        text_name = 'chain1-'
 
218
        for depth in range(26):
 
219
            new_version = text_name + '%s' % depth
 
220
            expected_delta = (next_parent, sha1s[depth], 
 
221
                              False,
 
222
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
 
223
            self.assertEqual(expected_delta, deltas[new_version])
 
224
            next_parent = new_version
 
225
        next_parent = 'base'
 
226
        text_name = 'chain2-'
 
227
        for depth in range(26):
 
228
            new_version = text_name + '%s' % depth
 
229
            expected_delta = (next_parent, sha1s[depth], False,
 
230
                              [(depth + 1, depth + 1, 1, [(new_version, 'line\n')])])
 
231
            self.assertEqual(expected_delta, deltas[new_version])
 
232
            next_parent = new_version
 
233
        # smoke tests for eol support
 
234
        expected_delta = ('base', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True, [])
 
235
        self.assertEqual(['line'], f.get_lines('noeol'))
 
236
        self.assertEqual(expected_delta, deltas['noeol'])
 
237
        # smoke tests for eol support - two noeol in a row same content
 
238
        expected_deltas = (('noeol', '3ad7ee82dbd8f29ecba073f96e43e414b3f70a4d', True, 
 
239
                          [(0, 1, 2, [('noeolsecond', 'line\n'), ('noeolsecond', 'line\n')])]),
 
240
                          ('noeol', '3ad7ee82dbd8f29ecba073f96e43e414b3f70a4d', True, 
 
241
                           [(0, 0, 1, [('noeolsecond', 'line\n')]), (1, 1, 0, [])]))
 
242
        self.assertEqual(['line\n', 'line'], f.get_lines('noeolsecond'))
 
243
        self.assertTrue(deltas['noeolsecond'] in expected_deltas)
 
244
        # two no-eol in a row, different content
 
245
        expected_delta = ('noeolsecond', '8bb553a84e019ef1149db082d65f3133b195223b', True, 
 
246
                          [(1, 2, 1, [('noeolnotshared', 'phone\n')])])
 
247
        self.assertEqual(['line\n', 'phone'], f.get_lines('noeolnotshared'))
 
248
        self.assertEqual(expected_delta, deltas['noeolnotshared'])
 
249
        # eol folling a no-eol with content change
 
250
        expected_delta = ('noeol', 'a61f6fb6cfc4596e8d88c34a308d1e724caf8977', False, 
 
251
                          [(0, 1, 1, [('eol', 'phone\n')])])
 
252
        self.assertEqual(['phone\n'], f.get_lines('eol'))
 
253
        self.assertEqual(expected_delta, deltas['eol'])
 
254
        # eol folling a no-eol with content change
 
255
        expected_delta = ('noeol', '6bfa09d82ce3e898ad4641ae13dd4fdb9cf0d76b', False, 
 
256
                          [(0, 1, 1, [('eolline', 'line\n')])])
 
257
        self.assertEqual(['line\n'], f.get_lines('eolline'))
 
258
        self.assertEqual(expected_delta, deltas['eolline'])
 
259
        # eol with no parents
 
260
        expected_delta = (None, '264f39cab871e4cfd65b3a002f7255888bb5ed97', True, 
 
261
                          [(0, 0, 1, [('noeolbase', 'line\n')])])
 
262
        self.assertEqual(['line'], f.get_lines('noeolbase'))
 
263
        self.assertEqual(expected_delta, deltas['noeolbase'])
 
264
        # eol with two parents, in inverse insertion order
 
265
        expected_deltas = (('noeolbase', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True,
 
266
                            [(0, 1, 1, [('eolbeforefirstparent', 'line\n')])]),
 
267
                           ('noeolbase', '264f39cab871e4cfd65b3a002f7255888bb5ed97', True,
 
268
                            [(0, 1, 1, [('eolbeforefirstparent', 'line\n')])]))
 
269
        self.assertEqual(['line'], f.get_lines('eolbeforefirstparent'))
 
270
        #self.assertTrue(deltas['eolbeforefirstparent'] in expected_deltas)
 
271
 
 
272
    def test_make_mpdiffs(self):
 
273
        from bzrlib import multiparent
 
274
        vf = self.get_file('foo')
 
275
        sha1s = self._setup_for_deltas(vf)
 
276
        new_vf = self.get_file('bar')
 
277
        for version in multiparent.topo_iter(vf):
 
278
            mpdiff = vf.make_mpdiffs([version])[0]
 
279
            new_vf.add_mpdiffs([(version, vf.get_parents(version),
 
280
                                 vf.get_sha1(version), mpdiff)])
 
281
            self.assertEqualDiff(vf.get_text(version),
 
282
                                 new_vf.get_text(version))
 
283
 
 
284
    def _setup_for_deltas(self, f):
 
285
        self.assertRaises(errors.RevisionNotPresent, f.get_delta, 'base')
 
286
        # add texts that should trip the knit maximum delta chain threshold
 
287
        # as well as doing parallel chains of data in knits.
 
288
        # this is done by two chains of 25 insertions
 
289
        f.add_lines('base', [], ['line\n'])
 
290
        f.add_lines('noeol', ['base'], ['line'])
 
291
        # detailed eol tests:
 
292
        # shared last line with parent no-eol
 
293
        f.add_lines('noeolsecond', ['noeol'], ['line\n', 'line'])
 
294
        # differing last line with parent, both no-eol
 
295
        f.add_lines('noeolnotshared', ['noeolsecond'], ['line\n', 'phone'])
 
296
        # add eol following a noneol parent, change content
 
297
        f.add_lines('eol', ['noeol'], ['phone\n'])
 
298
        # add eol following a noneol parent, no change content
 
299
        f.add_lines('eolline', ['noeol'], ['line\n'])
 
300
        # noeol with no parents:
 
301
        f.add_lines('noeolbase', [], ['line'])
 
302
        # noeol preceeding its leftmost parent in the output:
 
303
        # this is done by making it a merge of two parents with no common
 
304
        # anestry: noeolbase and noeol with the 
 
305
        # later-inserted parent the leftmost.
 
306
        f.add_lines('eolbeforefirstparent', ['noeolbase', 'noeol'], ['line'])
 
307
        # two identical eol texts
 
308
        f.add_lines('noeoldup', ['noeol'], ['line'])
 
309
        next_parent = 'base'
 
310
        text_name = 'chain1-'
 
311
        text = ['line\n']
 
312
        sha1s = {0 :'da6d3141cb4a5e6f464bf6e0518042ddc7bfd079',
 
313
                 1 :'45e21ea146a81ea44a821737acdb4f9791c8abe7',
 
314
                 2 :'e1f11570edf3e2a070052366c582837a4fe4e9fa',
 
315
                 3 :'26b4b8626da827088c514b8f9bbe4ebf181edda1',
 
316
                 4 :'e28a5510be25ba84d31121cff00956f9970ae6f6',
 
317
                 5 :'d63ec0ce22e11dcf65a931b69255d3ac747a318d',
 
318
                 6 :'2c2888d288cb5e1d98009d822fedfe6019c6a4ea',
 
319
                 7 :'95c14da9cafbf828e3e74a6f016d87926ba234ab',
 
320
                 8 :'779e9a0b28f9f832528d4b21e17e168c67697272',
 
321
                 9 :'1f8ff4e5c6ff78ac106fcfe6b1e8cb8740ff9a8f',
 
322
                 10:'131a2ae712cf51ed62f143e3fbac3d4206c25a05',
 
323
                 11:'c5a9d6f520d2515e1ec401a8f8a67e6c3c89f199',
 
324
                 12:'31a2286267f24d8bedaa43355f8ad7129509ea85',
 
325
                 13:'dc2a7fe80e8ec5cae920973973a8ee28b2da5e0a',
 
326
                 14:'2c4b1736566b8ca6051e668de68650686a3922f2',
 
327
                 15:'5912e4ecd9b0c07be4d013e7e2bdcf9323276cde',
 
328
                 16:'b0d2e18d3559a00580f6b49804c23fea500feab3',
 
329
                 17:'8e1d43ad72f7562d7cb8f57ee584e20eb1a69fc7',
 
330
                 18:'5cf64a3459ae28efa60239e44b20312d25b253f3',
 
331
                 19:'1ebed371807ba5935958ad0884595126e8c4e823',
 
332
                 20:'2aa62a8b06fb3b3b892a3292a068ade69d5ee0d3',
 
333
                 21:'01edc447978004f6e4e962b417a4ae1955b6fe5d',
 
334
                 22:'d8d8dc49c4bf0bab401e0298bb5ad827768618bb',
 
335
                 23:'c21f62b1c482862983a8ffb2b0c64b3451876e3f',
 
336
                 24:'c0593fe795e00dff6b3c0fe857a074364d5f04fc',
 
337
                 25:'dd1a1cf2ba9cc225c3aff729953e6364bf1d1855',
 
338
                 }
 
339
        for depth in range(26):
 
340
            new_version = text_name + '%s' % depth
 
341
            text = text + ['line\n']
 
342
            f.add_lines(new_version, [next_parent], text)
 
343
            next_parent = new_version
 
344
        next_parent = 'base'
 
345
        text_name = 'chain2-'
 
346
        text = ['line\n']
 
347
        for depth in range(26):
 
348
            new_version = text_name + '%s' % depth
 
349
            text = text + ['line\n']
 
350
            f.add_lines(new_version, [next_parent], text)
 
351
            next_parent = new_version
 
352
        return sha1s
 
353
 
 
354
    def test_add_delta(self):
 
355
        # tests for the add-delta facility.
 
356
        # at this point, optimising for speed, we assume no checks when deltas are inserted.
 
357
        # this may need to be revisited.
 
358
        source = self.get_file('source')
 
359
        source.add_lines('base', [], ['line\n'])
 
360
        next_parent = 'base'
 
361
        text_name = 'chain1-'
 
362
        text = ['line\n']
 
363
        for depth in range(26):
 
364
            new_version = text_name + '%s' % depth
 
365
            text = text + ['line\n']
 
366
            source.add_lines(new_version, [next_parent], text)
 
367
            next_parent = new_version
 
368
        next_parent = 'base'
 
369
        text_name = 'chain2-'
 
370
        text = ['line\n']
 
371
        for depth in range(26):
 
372
            new_version = text_name + '%s' % depth
 
373
            text = text + ['line\n']
 
374
            source.add_lines(new_version, [next_parent], text)
 
375
            next_parent = new_version
 
376
        source.add_lines('noeol', ['base'], ['line'])
 
377
        
 
378
        target = self.get_file('target')
 
379
        for version in source.versions():
 
380
            parent, sha1, noeol, delta = source.get_delta(version)
 
381
            target.add_delta(version,
 
382
                             source.get_parents(version),
 
383
                             parent,
 
384
                             sha1,
 
385
                             noeol,
 
386
                             delta)
 
387
        self.assertRaises(RevisionAlreadyPresent,
 
388
                          target.add_delta, 'base', [], None, '', False, [])
 
389
        for version in source.versions():
 
390
            self.assertEqual(source.get_lines(version),
 
391
                             target.get_lines(version))
 
392
 
 
393
    def test_ancestry(self):
 
394
        f = self.get_file()
 
395
        self.assertEqual([], f.get_ancestry([]))
 
396
        f.add_lines('r0', [], ['a\n', 'b\n'])
 
397
        f.add_lines('r1', ['r0'], ['b\n', 'c\n'])
 
398
        f.add_lines('r2', ['r0'], ['b\n', 'c\n'])
 
399
        f.add_lines('r3', ['r2'], ['b\n', 'c\n'])
 
400
        f.add_lines('rM', ['r1', 'r2'], ['b\n', 'c\n'])
 
401
        self.assertEqual([], f.get_ancestry([]))
 
402
        versions = f.get_ancestry(['rM'])
 
403
        # there are some possibilities:
 
404
        # r0 r1 r2 rM r3
 
405
        # r0 r1 r2 r3 rM
 
406
        # etc
 
407
        # so we check indexes
 
408
        r0 = versions.index('r0')
 
409
        r1 = versions.index('r1')
 
410
        r2 = versions.index('r2')
 
411
        self.assertFalse('r3' in versions)
 
412
        rM = versions.index('rM')
 
413
        self.assertTrue(r0 < r1)
 
414
        self.assertTrue(r0 < r2)
 
415
        self.assertTrue(r1 < rM)
 
416
        self.assertTrue(r2 < rM)
 
417
 
 
418
        self.assertRaises(RevisionNotPresent,
 
419
            f.get_ancestry, ['rM', 'rX'])
 
420
 
 
421
        self.assertEqual(set(f.get_ancestry('rM')),
 
422
            set(f.get_ancestry('rM', topo_sorted=False)))
 
423
 
 
424
    def test_mutate_after_finish(self):
 
425
        f = self.get_file()
 
426
        f.transaction_finished()
 
427
        self.assertRaises(errors.OutSideTransaction, f.add_delta, '', [], '', '', False, [])
 
428
        self.assertRaises(errors.OutSideTransaction, f.add_lines, '', [], [])
 
429
        self.assertRaises(errors.OutSideTransaction, f.add_lines_with_ghosts, '', [], [])
 
430
        self.assertRaises(errors.OutSideTransaction, f.fix_parents, '', [])
 
431
        self.assertRaises(errors.OutSideTransaction, f.join, '')
 
432
        self.assertRaises(errors.OutSideTransaction, f.clone_text, 'base', 'bar', ['foo'])
 
433
        
 
434
    def test_clear_cache(self):
 
435
        f = self.get_file()
 
436
        # on a new file it should not error
 
437
        f.clear_cache()
 
438
        # and after adding content, doing a clear_cache and a get should work.
 
439
        f.add_lines('0', [], ['a'])
 
440
        f.clear_cache()
 
441
        self.assertEqual(['a'], f.get_lines('0'))
 
442
 
 
443
    def test_clone_text(self):
 
444
        f = self.get_file()
 
445
        f.add_lines('r0', [], ['a\n', 'b\n'])
 
446
        f.clone_text('r1', 'r0', ['r0'])
 
447
        def verify_file(f):
 
448
            self.assertEquals(f.get_lines('r1'), f.get_lines('r0'))
 
449
            self.assertEquals(f.get_lines('r1'), ['a\n', 'b\n'])
 
450
            self.assertEquals(f.get_parents('r1'), ['r0'])
 
451
    
 
452
            self.assertRaises(RevisionNotPresent,
 
453
                f.clone_text, 'r2', 'rX', [])
 
454
            self.assertRaises(RevisionAlreadyPresent,
 
455
                f.clone_text, 'r1', 'r0', [])
 
456
        verify_file(f)
 
457
        verify_file(self.reopen_file())
 
458
 
 
459
    def test_create_empty(self):
 
460
        f = self.get_file()
 
461
        f.add_lines('0', [], ['a\n'])
 
462
        new_f = f.create_empty('t', MemoryTransport())
 
463
        # smoke test, specific types should check it is honoured correctly for
 
464
        # non type attributes
 
465
        self.assertEqual([], new_f.versions())
 
466
        self.assertTrue(isinstance(new_f, f.__class__))
 
467
 
 
468
    def test_copy_to(self):
 
469
        f = self.get_file()
 
470
        f.add_lines('0', [], ['a\n'])
 
471
        t = MemoryTransport()
 
472
        f.copy_to('foo', t)
 
473
        for suffix in f.__class__.get_suffixes():
 
474
            self.assertTrue(t.has('foo' + suffix))
 
475
 
 
476
    def test_get_suffixes(self):
 
477
        f = self.get_file()
 
478
        # should be the same
 
479
        self.assertEqual(f.__class__.get_suffixes(), f.__class__.get_suffixes())
 
480
        # and should be a list
 
481
        self.assertTrue(isinstance(f.__class__.get_suffixes(), list))
 
482
 
 
483
    def build_graph(self, file, graph):
 
484
        for node in topo_sort(graph.items()):
 
485
            file.add_lines(node, graph[node], [])
 
486
 
 
487
    def test_get_graph(self):
 
488
        f = self.get_file()
 
489
        graph = {
 
490
            'v1': (),
 
491
            'v2': ('v1', ),
 
492
            'v3': ('v2', )}
 
493
        self.build_graph(f, graph)
 
494
        self.assertEqual(graph, f.get_graph())
 
495
    
 
496
    def test_get_graph_partial(self):
 
497
        f = self.get_file()
 
498
        complex_graph = {}
 
499
        simple_a = {
 
500
            'c': (),
 
501
            'b': ('c', ),
 
502
            'a': ('b', ),
 
503
            }
 
504
        complex_graph.update(simple_a)
 
505
        simple_b = {
 
506
            'c': (),
 
507
            'b': ('c', ),
 
508
            }
 
509
        complex_graph.update(simple_b)
 
510
        simple_gam = {
 
511
            'c': (),
 
512
            'oo': (),
 
513
            'bar': ('oo', 'c'),
 
514
            'gam': ('bar', ),
 
515
            }
 
516
        complex_graph.update(simple_gam)
 
517
        simple_b_gam = {}
 
518
        simple_b_gam.update(simple_gam)
 
519
        simple_b_gam.update(simple_b)
 
520
        self.build_graph(f, complex_graph)
 
521
        self.assertEqual(simple_a, f.get_graph(['a']))
 
522
        self.assertEqual(simple_b, f.get_graph(['b']))
 
523
        self.assertEqual(simple_gam, f.get_graph(['gam']))
 
524
        self.assertEqual(simple_b_gam, f.get_graph(['b', 'gam']))
 
525
 
 
526
    def test_get_parents(self):
 
527
        f = self.get_file()
 
528
        f.add_lines('r0', [], ['a\n', 'b\n'])
 
529
        f.add_lines('r1', [], ['a\n', 'b\n'])
 
530
        f.add_lines('r2', [], ['a\n', 'b\n'])
 
531
        f.add_lines('r3', [], ['a\n', 'b\n'])
 
532
        f.add_lines('m', ['r0', 'r1', 'r2', 'r3'], ['a\n', 'b\n'])
 
533
        self.assertEquals(f.get_parents('m'), ['r0', 'r1', 'r2', 'r3'])
 
534
 
 
535
        self.assertRaises(RevisionNotPresent,
 
536
            f.get_parents, 'y')
 
537
 
 
538
    def test_annotate(self):
 
539
        f = self.get_file()
 
540
        f.add_lines('r0', [], ['a\n', 'b\n'])
 
541
        f.add_lines('r1', ['r0'], ['c\n', 'b\n'])
 
542
        origins = f.annotate('r1')
 
543
        self.assertEquals(origins[0][0], 'r1')
 
544
        self.assertEquals(origins[1][0], 'r0')
 
545
 
 
546
        self.assertRaises(RevisionNotPresent,
 
547
            f.annotate, 'foo')
 
548
 
 
549
    def test_detection(self):
 
550
        # Test weaves detect corruption.
 
551
        #
 
552
        # Weaves contain a checksum of their texts.
 
553
        # When a text is extracted, this checksum should be
 
554
        # verified.
 
555
 
 
556
        w = self.get_file_corrupted_text()
 
557
 
 
558
        self.assertEqual('hello\n', w.get_text('v1'))
 
559
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_text, 'v2')
 
560
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_lines, 'v2')
 
561
        self.assertRaises(errors.WeaveInvalidChecksum, w.check)
 
562
 
 
563
        w = self.get_file_corrupted_checksum()
 
564
 
 
565
        self.assertEqual('hello\n', w.get_text('v1'))
 
566
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_text, 'v2')
 
567
        self.assertRaises(errors.WeaveInvalidChecksum, w.get_lines, 'v2')
 
568
        self.assertRaises(errors.WeaveInvalidChecksum, w.check)
 
569
 
 
570
    def get_file_corrupted_text(self):
 
571
        """Return a versioned file with corrupt text but valid metadata."""
 
572
        raise NotImplementedError(self.get_file_corrupted_text)
 
573
 
 
574
    def reopen_file(self, name='foo'):
 
575
        """Open the versioned file from disk again."""
 
576
        raise NotImplementedError(self.reopen_file)
 
577
 
 
578
    def test_iter_parents(self):
 
579
        """iter_parents returns the parents for many nodes."""
 
580
        f = self.get_file()
 
581
        # sample data:
 
582
        # no parents
 
583
        f.add_lines('r0', [], ['a\n', 'b\n'])
 
584
        # 1 parents
 
585
        f.add_lines('r1', ['r0'], ['a\n', 'b\n'])
 
586
        # 2 parents
 
587
        f.add_lines('r2', ['r1', 'r0'], ['a\n', 'b\n'])
 
588
        # XXX TODO a ghost
 
589
        # cases: each sample data individually:
 
590
        self.assertEqual(set([('r0', ())]),
 
591
            set(f.iter_parents(['r0'])))
 
592
        self.assertEqual(set([('r1', ('r0', ))]),
 
593
            set(f.iter_parents(['r1'])))
 
594
        self.assertEqual(set([('r2', ('r1', 'r0'))]),
 
595
            set(f.iter_parents(['r2'])))
 
596
        # no nodes returned for a missing node
 
597
        self.assertEqual(set(),
 
598
            set(f.iter_parents(['missing'])))
 
599
        # 1 node returned with missing nodes skipped
 
600
        self.assertEqual(set([('r1', ('r0', ))]),
 
601
            set(f.iter_parents(['ghost1', 'r1', 'ghost'])))
 
602
        # 2 nodes returned
 
603
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
 
604
            set(f.iter_parents(['r0', 'r1'])))
 
605
        # 2 nodes returned, missing skipped
 
606
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
 
607
            set(f.iter_parents(['a', 'r0', 'b', 'r1', 'c'])))
 
608
 
 
609
    def test_iter_lines_added_or_present_in_versions(self):
 
610
        # test that we get at least an equalset of the lines added by
 
611
        # versions in the weave 
 
612
        # the ordering here is to make a tree so that dumb searches have
 
613
        # more changes to muck up.
 
614
 
 
615
        class InstrumentedProgress(progress.DummyProgress):
 
616
 
 
617
            def __init__(self):
 
618
 
 
619
                progress.DummyProgress.__init__(self)
 
620
                self.updates = []
 
621
 
 
622
            def update(self, msg=None, current=None, total=None):
 
623
                self.updates.append((msg, current, total))
 
624
 
 
625
        vf = self.get_file()
 
626
        # add a base to get included
 
627
        vf.add_lines('base', [], ['base\n'])
 
628
        # add a ancestor to be included on one side
 
629
        vf.add_lines('lancestor', [], ['lancestor\n'])
 
630
        # add a ancestor to be included on the other side
 
631
        vf.add_lines('rancestor', ['base'], ['rancestor\n'])
 
632
        # add a child of rancestor with no eofile-nl
 
633
        vf.add_lines('child', ['rancestor'], ['base\n', 'child\n'])
 
634
        # add a child of lancestor and base to join the two roots
 
635
        vf.add_lines('otherchild',
 
636
                     ['lancestor', 'base'],
 
637
                     ['base\n', 'lancestor\n', 'otherchild\n'])
 
638
        def iter_with_versions(versions, expected):
 
639
            # now we need to see what lines are returned, and how often.
 
640
            lines = {'base\n':0,
 
641
                     'lancestor\n':0,
 
642
                     'rancestor\n':0,
 
643
                     'child\n':0,
 
644
                     'otherchild\n':0,
 
645
                     }
 
646
            progress = InstrumentedProgress()
 
647
            # iterate over the lines
 
648
            for line in vf.iter_lines_added_or_present_in_versions(versions, 
 
649
                pb=progress):
 
650
                lines[line] += 1
 
651
            if []!= progress.updates: 
 
652
                self.assertEqual(expected, progress.updates)
 
653
            return lines
 
654
        lines = iter_with_versions(['child', 'otherchild'],
 
655
                                   [('Walking content.', 0, 2),
 
656
                                    ('Walking content.', 1, 2),
 
657
                                    ('Walking content.', 2, 2)])
 
658
        # we must see child and otherchild
 
659
        self.assertTrue(lines['child\n'] > 0)
 
660
        self.assertTrue(lines['otherchild\n'] > 0)
 
661
        # we dont care if we got more than that.
 
662
        
 
663
        # test all lines
 
664
        lines = iter_with_versions(None, [('Walking content.', 0, 5),
 
665
                                          ('Walking content.', 1, 5),
 
666
                                          ('Walking content.', 2, 5),
 
667
                                          ('Walking content.', 3, 5),
 
668
                                          ('Walking content.', 4, 5),
 
669
                                          ('Walking content.', 5, 5)])
 
670
        # all lines must be seen at least once
 
671
        self.assertTrue(lines['base\n'] > 0)
 
672
        self.assertTrue(lines['lancestor\n'] > 0)
 
673
        self.assertTrue(lines['rancestor\n'] > 0)
 
674
        self.assertTrue(lines['child\n'] > 0)
 
675
        self.assertTrue(lines['otherchild\n'] > 0)
 
676
 
 
677
    def test_fix_parents(self):
 
678
        # some versioned files allow incorrect parents to be corrected after
 
679
        # insertion - this may not fix ancestry..
 
680
        # if they do not supported, they just do not implement it.
 
681
        # we test this as an interface test to ensure that those that *do*
 
682
        # implementent it get it right.
 
683
        vf = self.get_file()
 
684
        vf.add_lines('notbase', [], [])
 
685
        vf.add_lines('base', [], [])
 
686
        try:
 
687
            vf.fix_parents('notbase', ['base'])
 
688
        except NotImplementedError:
 
689
            return
 
690
        self.assertEqual(['base'], vf.get_parents('notbase'))
 
691
        # open again, check it stuck.
 
692
        vf = self.get_file()
 
693
        self.assertEqual(['base'], vf.get_parents('notbase'))
 
694
 
 
695
    def test_fix_parents_with_ghosts(self):
 
696
        # when fixing parents, ghosts that are listed should not be ghosts
 
697
        # anymore.
 
698
        vf = self.get_file()
 
699
 
 
700
        try:
 
701
            vf.add_lines_with_ghosts('notbase', ['base', 'stillghost'], [])
 
702
        except NotImplementedError:
 
703
            return
 
704
        vf.add_lines('base', [], [])
 
705
        vf.fix_parents('notbase', ['base', 'stillghost'])
 
706
        self.assertEqual(['base'], vf.get_parents('notbase'))
 
707
        # open again, check it stuck.
 
708
        vf = self.get_file()
 
709
        self.assertEqual(['base'], vf.get_parents('notbase'))
 
710
        # and check the ghosts
 
711
        self.assertEqual(['base', 'stillghost'],
 
712
                         vf.get_parents_with_ghosts('notbase'))
 
713
 
 
714
    def test_add_lines_with_ghosts(self):
 
715
        # some versioned file formats allow lines to be added with parent
 
716
        # information that is > than that in the format. Formats that do
 
717
        # not support this need to raise NotImplementedError on the
 
718
        # add_lines_with_ghosts api.
 
719
        vf = self.get_file()
 
720
        # add a revision with ghost parents
 
721
        # The preferred form is utf8, but we should translate when needed
 
722
        parent_id_unicode = u'b\xbfse'
 
723
        parent_id_utf8 = parent_id_unicode.encode('utf8')
 
724
        try:
 
725
            vf.add_lines_with_ghosts('notbxbfse', [parent_id_utf8], [])
 
726
        except NotImplementedError:
 
727
            # check the other ghost apis are also not implemented
 
728
            self.assertRaises(NotImplementedError, vf.has_ghost, 'foo')
 
729
            self.assertRaises(NotImplementedError, vf.get_ancestry_with_ghosts, ['foo'])
 
730
            self.assertRaises(NotImplementedError, vf.get_parents_with_ghosts, 'foo')
 
731
            self.assertRaises(NotImplementedError, vf.get_graph_with_ghosts)
 
732
            return
 
733
        vf = self.reopen_file()
 
734
        # test key graph related apis: getncestry, _graph, get_parents
 
735
        # has_version
 
736
        # - these are ghost unaware and must not be reflect ghosts
 
737
        self.assertEqual(['notbxbfse'], vf.get_ancestry('notbxbfse'))
 
738
        self.assertEqual([], vf.get_parents('notbxbfse'))
 
739
        self.assertEqual({'notbxbfse':()}, vf.get_graph())
 
740
        self.assertFalse(self.callDeprecated([osutils._revision_id_warning],
 
741
                         vf.has_version, parent_id_unicode))
 
742
        self.assertFalse(vf.has_version(parent_id_utf8))
 
743
        # we have _with_ghost apis to give us ghost information.
 
744
        self.assertEqual([parent_id_utf8, 'notbxbfse'], vf.get_ancestry_with_ghosts(['notbxbfse']))
 
745
        self.assertEqual([parent_id_utf8], vf.get_parents_with_ghosts('notbxbfse'))
 
746
        self.assertEqual({'notbxbfse':[parent_id_utf8]}, vf.get_graph_with_ghosts())
 
747
        self.assertTrue(self.callDeprecated([osutils._revision_id_warning],
 
748
                        vf.has_ghost, parent_id_unicode))
 
749
        self.assertTrue(vf.has_ghost(parent_id_utf8))
 
750
        # if we add something that is a ghost of another, it should correct the
 
751
        # results of the prior apis
 
752
        self.callDeprecated([osutils._revision_id_warning],
 
753
                            vf.add_lines, parent_id_unicode, [], [])
 
754
        self.assertEqual([parent_id_utf8, 'notbxbfse'], vf.get_ancestry(['notbxbfse']))
 
755
        self.assertEqual([parent_id_utf8], vf.get_parents('notbxbfse'))
 
756
        self.assertEqual({parent_id_utf8:(),
 
757
                          'notbxbfse':(parent_id_utf8, ),
 
758
                          },
 
759
                         vf.get_graph())
 
760
        self.assertTrue(self.callDeprecated([osutils._revision_id_warning],
 
761
                        vf.has_version, parent_id_unicode))
 
762
        self.assertTrue(vf.has_version(parent_id_utf8))
 
763
        # we have _with_ghost apis to give us ghost information.
 
764
        self.assertEqual([parent_id_utf8, 'notbxbfse'], vf.get_ancestry_with_ghosts(['notbxbfse']))
 
765
        self.assertEqual([parent_id_utf8], vf.get_parents_with_ghosts('notbxbfse'))
 
766
        self.assertEqual({parent_id_utf8:[],
 
767
                          'notbxbfse':[parent_id_utf8],
 
768
                          },
 
769
                         vf.get_graph_with_ghosts())
 
770
        self.assertFalse(self.callDeprecated([osutils._revision_id_warning],
 
771
                         vf.has_ghost, parent_id_unicode))
 
772
        self.assertFalse(vf.has_ghost(parent_id_utf8))
 
773
 
 
774
    def test_add_lines_with_ghosts_after_normal_revs(self):
 
775
        # some versioned file formats allow lines to be added with parent
 
776
        # information that is > than that in the format. Formats that do
 
777
        # not support this need to raise NotImplementedError on the
 
778
        # add_lines_with_ghosts api.
 
779
        vf = self.get_file()
 
780
        # probe for ghost support
 
781
        try:
 
782
            vf.has_ghost('hoo')
 
783
        except NotImplementedError:
 
784
            return
 
785
        vf.add_lines_with_ghosts('base', [], ['line\n', 'line_b\n'])
 
786
        vf.add_lines_with_ghosts('references_ghost',
 
787
                                 ['base', 'a_ghost'],
 
788
                                 ['line\n', 'line_b\n', 'line_c\n'])
 
789
        origins = vf.annotate('references_ghost')
 
790
        self.assertEquals(('base', 'line\n'), origins[0])
 
791
        self.assertEquals(('base', 'line_b\n'), origins[1])
 
792
        self.assertEquals(('references_ghost', 'line_c\n'), origins[2])
 
793
 
 
794
    def test_readonly_mode(self):
 
795
        transport = get_transport(self.get_url('.'))
 
796
        factory = self.get_factory()
 
797
        vf = factory('id', transport, 0777, create=True, access_mode='w')
 
798
        vf = factory('id', transport, access_mode='r')
 
799
        self.assertRaises(errors.ReadOnlyError, vf.add_delta, '', [], '', '', False, [])
 
800
        self.assertRaises(errors.ReadOnlyError, vf.add_lines, 'base', [], [])
 
801
        self.assertRaises(errors.ReadOnlyError,
 
802
                          vf.add_lines_with_ghosts,
 
803
                          'base',
 
804
                          [],
 
805
                          [])
 
806
        self.assertRaises(errors.ReadOnlyError, vf.fix_parents, 'base', [])
 
807
        self.assertRaises(errors.ReadOnlyError, vf.join, 'base')
 
808
        self.assertRaises(errors.ReadOnlyError, vf.clone_text, 'base', 'bar', ['foo'])
 
809
    
 
810
    def test_get_sha1(self):
 
811
        # check the sha1 data is available
 
812
        vf = self.get_file()
 
813
        # a simple file
 
814
        vf.add_lines('a', [], ['a\n'])
 
815
        # the same file, different metadata
 
816
        vf.add_lines('b', ['a'], ['a\n'])
 
817
        # a file differing only in last newline.
 
818
        vf.add_lines('c', [], ['a'])
 
819
        self.assertEqual(
 
820
            '3f786850e387550fdab836ed7e6dc881de23001b', vf.get_sha1('a'))
 
821
        self.assertEqual(
 
822
            '3f786850e387550fdab836ed7e6dc881de23001b', vf.get_sha1('b'))
 
823
        self.assertEqual(
 
824
            '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8', vf.get_sha1('c'))
 
825
 
 
826
        self.assertEqual(['3f786850e387550fdab836ed7e6dc881de23001b',
 
827
                          '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8',
 
828
                          '3f786850e387550fdab836ed7e6dc881de23001b'],
 
829
                          vf.get_sha1s(['a', 'c', 'b']))
 
830
        
 
831
 
 
832
class TestWeave(TestCaseWithMemoryTransport, VersionedFileTestMixIn):
 
833
 
 
834
    def get_file(self, name='foo'):
 
835
        return WeaveFile(name, get_transport(self.get_url('.')), create=True)
 
836
 
 
837
    def get_file_corrupted_text(self):
 
838
        w = WeaveFile('foo', get_transport(self.get_url('.')), create=True)
 
839
        w.add_lines('v1', [], ['hello\n'])
 
840
        w.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
 
841
        
 
842
        # We are going to invasively corrupt the text
 
843
        # Make sure the internals of weave are the same
 
844
        self.assertEqual([('{', 0)
 
845
                        , 'hello\n'
 
846
                        , ('}', None)
 
847
                        , ('{', 1)
 
848
                        , 'there\n'
 
849
                        , ('}', None)
 
850
                        ], w._weave)
 
851
        
 
852
        self.assertEqual(['f572d396fae9206628714fb2ce00f72e94f2258f'
 
853
                        , '90f265c6e75f1c8f9ab76dcf85528352c5f215ef'
 
854
                        ], w._sha1s)
 
855
        w.check()
 
856
        
 
857
        # Corrupted
 
858
        w._weave[4] = 'There\n'
 
859
        return w
 
860
 
 
861
    def get_file_corrupted_checksum(self):
 
862
        w = self.get_file_corrupted_text()
 
863
        # Corrected
 
864
        w._weave[4] = 'there\n'
 
865
        self.assertEqual('hello\nthere\n', w.get_text('v2'))
 
866
        
 
867
        #Invalid checksum, first digit changed
 
868
        w._sha1s[1] =  'f0f265c6e75f1c8f9ab76dcf85528352c5f215ef'
 
869
        return w
 
870
 
 
871
    def reopen_file(self, name='foo', create=False):
 
872
        return WeaveFile(name, get_transport(self.get_url('.')), create=create)
 
873
 
 
874
    def test_no_implicit_create(self):
 
875
        self.assertRaises(errors.NoSuchFile,
 
876
                          WeaveFile,
 
877
                          'foo',
 
878
                          get_transport(self.get_url('.')))
 
879
 
 
880
    def get_factory(self):
 
881
        return WeaveFile
 
882
 
 
883
 
 
884
class TestKnit(TestCaseWithMemoryTransport, VersionedFileTestMixIn):
 
885
 
 
886
    def get_file(self, name='foo'):
 
887
        return self.get_factory()(name, get_transport(self.get_url('.')),
 
888
                                  delta=True, create=True)
 
889
 
 
890
    def get_factory(self):
 
891
        return KnitVersionedFile
 
892
 
 
893
    def get_file_corrupted_text(self):
 
894
        knit = self.get_file()
 
895
        knit.add_lines('v1', [], ['hello\n'])
 
896
        knit.add_lines('v2', ['v1'], ['hello\n', 'there\n'])
 
897
        return knit
 
898
 
 
899
    def reopen_file(self, name='foo', create=False):
 
900
        return self.get_factory()(name, get_transport(self.get_url('.')),
 
901
            delta=True,
 
902
            create=create)
 
903
 
 
904
    def test_detection(self):
 
905
        knit = self.get_file()
 
906
        knit.check()
 
907
 
 
908
    def test_no_implicit_create(self):
 
909
        self.assertRaises(errors.NoSuchFile,
 
910
                          KnitVersionedFile,
 
911
                          'foo',
 
912
                          get_transport(self.get_url('.')))
 
913
 
 
914
 
 
915
class TestPlaintextKnit(TestKnit):
 
916
    """Test a knit with no cached annotations"""
 
917
 
 
918
    def _factory(self, name, transport, file_mode=None, access_mode=None,
 
919
                 delta=True, create=False):
 
920
        return KnitVersionedFile(name, transport, file_mode, access_mode,
 
921
                                 KnitPlainFactory(), delta=delta,
 
922
                                 create=create)
 
923
 
 
924
    def get_factory(self):
 
925
        return self._factory
 
926
 
 
927
 
 
928
class InterString(versionedfile.InterVersionedFile):
 
929
    """An inter-versionedfile optimised code path for strings.
 
930
 
 
931
    This is for use during testing where we use strings as versionedfiles
 
932
    so that none of the default regsitered interversionedfile classes will
 
933
    match - which lets us test the match logic.
 
934
    """
 
935
 
 
936
    @staticmethod
 
937
    def is_compatible(source, target):
 
938
        """InterString is compatible with strings-as-versionedfiles."""
 
939
        return isinstance(source, str) and isinstance(target, str)
 
940
 
 
941
 
 
942
# TODO this and the InterRepository core logic should be consolidatable
 
943
# if we make the registry a separate class though we still need to 
 
944
# test the behaviour in the active registry to catch failure-to-handle-
 
945
# stange-objects
 
946
class TestInterVersionedFile(TestCaseWithMemoryTransport):
 
947
 
 
948
    def test_get_default_inter_versionedfile(self):
 
949
        # test that the InterVersionedFile.get(a, b) probes
 
950
        # for a class where is_compatible(a, b) returns
 
951
        # true and returns a default interversionedfile otherwise.
 
952
        # This also tests that the default registered optimised interversionedfile
 
953
        # classes do not barf inappropriately when a surprising versionedfile type
 
954
        # is handed to them.
 
955
        dummy_a = "VersionedFile 1."
 
956
        dummy_b = "VersionedFile 2."
 
957
        self.assertGetsDefaultInterVersionedFile(dummy_a, dummy_b)
 
958
 
 
959
    def assertGetsDefaultInterVersionedFile(self, a, b):
 
960
        """Asserts that InterVersionedFile.get(a, b) -> the default."""
 
961
        inter = versionedfile.InterVersionedFile.get(a, b)
 
962
        self.assertEqual(versionedfile.InterVersionedFile,
 
963
                         inter.__class__)
 
964
        self.assertEqual(a, inter.source)
 
965
        self.assertEqual(b, inter.target)
 
966
 
 
967
    def test_register_inter_versionedfile_class(self):
 
968
        # test that a optimised code path provider - a
 
969
        # InterVersionedFile subclass can be registered and unregistered
 
970
        # and that it is correctly selected when given a versionedfile
 
971
        # pair that it returns true on for the is_compatible static method
 
972
        # check
 
973
        dummy_a = "VersionedFile 1."
 
974
        dummy_b = "VersionedFile 2."
 
975
        versionedfile.InterVersionedFile.register_optimiser(InterString)
 
976
        try:
 
977
            # we should get the default for something InterString returns False
 
978
            # to
 
979
            self.assertFalse(InterString.is_compatible(dummy_a, None))
 
980
            self.assertGetsDefaultInterVersionedFile(dummy_a, None)
 
981
            # and we should get an InterString for a pair it 'likes'
 
982
            self.assertTrue(InterString.is_compatible(dummy_a, dummy_b))
 
983
            inter = versionedfile.InterVersionedFile.get(dummy_a, dummy_b)
 
984
            self.assertEqual(InterString, inter.__class__)
 
985
            self.assertEqual(dummy_a, inter.source)
 
986
            self.assertEqual(dummy_b, inter.target)
 
987
        finally:
 
988
            versionedfile.InterVersionedFile.unregister_optimiser(InterString)
 
989
        # now we should get the default InterVersionedFile object again.
 
990
        self.assertGetsDefaultInterVersionedFile(dummy_a, dummy_b)
 
991
 
 
992
 
 
993
class TestReadonlyHttpMixin(object):
 
994
 
 
995
    def test_readonly_http_works(self):
 
996
        # we should be able to read from http with a versioned file.
 
997
        vf = self.get_file()
 
998
        # try an empty file access
 
999
        readonly_vf = self.get_factory()('foo', get_transport(self.get_readonly_url('.')))
 
1000
        self.assertEqual([], readonly_vf.versions())
 
1001
        # now with feeling.
 
1002
        vf.add_lines('1', [], ['a\n'])
 
1003
        vf.add_lines('2', ['1'], ['b\n', 'a\n'])
 
1004
        readonly_vf = self.get_factory()('foo', get_transport(self.get_readonly_url('.')))
 
1005
        self.assertEqual(['1', '2'], vf.versions())
 
1006
        for version in readonly_vf.versions():
 
1007
            readonly_vf.get_lines(version)
 
1008
 
 
1009
 
 
1010
class TestWeaveHTTP(TestCaseWithWebserver, TestReadonlyHttpMixin):
 
1011
 
 
1012
    def get_file(self):
 
1013
        return WeaveFile('foo', get_transport(self.get_url('.')), create=True)
 
1014
 
 
1015
    def get_factory(self):
 
1016
        return WeaveFile
 
1017
 
 
1018
 
 
1019
class TestKnitHTTP(TestCaseWithWebserver, TestReadonlyHttpMixin):
 
1020
 
 
1021
    def get_file(self):
 
1022
        return KnitVersionedFile('foo', get_transport(self.get_url('.')),
 
1023
                                 delta=True, create=True)
 
1024
 
 
1025
    def get_factory(self):
 
1026
        return KnitVersionedFile
 
1027
 
 
1028
 
 
1029
class MergeCasesMixin(object):
 
1030
 
 
1031
    def doMerge(self, base, a, b, mp):
 
1032
        from cStringIO import StringIO
 
1033
        from textwrap import dedent
 
1034
 
 
1035
        def addcrlf(x):
 
1036
            return x + '\n'
 
1037
        
 
1038
        w = self.get_file()
 
1039
        w.add_lines('text0', [], map(addcrlf, base))
 
1040
        w.add_lines('text1', ['text0'], map(addcrlf, a))
 
1041
        w.add_lines('text2', ['text0'], map(addcrlf, b))
 
1042
 
 
1043
        self.log_contents(w)
 
1044
 
 
1045
        self.log('merge plan:')
 
1046
        p = list(w.plan_merge('text1', 'text2'))
 
1047
        for state, line in p:
 
1048
            if line:
 
1049
                self.log('%12s | %s' % (state, line[:-1]))
 
1050
 
 
1051
        self.log('merge:')
 
1052
        mt = StringIO()
 
1053
        mt.writelines(w.weave_merge(p))
 
1054
        mt.seek(0)
 
1055
        self.log(mt.getvalue())
 
1056
 
 
1057
        mp = map(addcrlf, mp)
 
1058
        self.assertEqual(mt.readlines(), mp)
 
1059
        
 
1060
        
 
1061
    def testOneInsert(self):
 
1062
        self.doMerge([],
 
1063
                     ['aa'],
 
1064
                     [],
 
1065
                     ['aa'])
 
1066
 
 
1067
    def testSeparateInserts(self):
 
1068
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
1069
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
1070
                     ['aaa', 'bbb', 'yyy', 'ccc'],
 
1071
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
1072
 
 
1073
    def testSameInsert(self):
 
1074
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
1075
                     ['aaa', 'xxx', 'bbb', 'ccc'],
 
1076
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'],
 
1077
                     ['aaa', 'xxx', 'bbb', 'yyy', 'ccc'])
 
1078
    overlappedInsertExpected = ['aaa', 'xxx', 'yyy', 'bbb']
 
1079
    def testOverlappedInsert(self):
 
1080
        self.doMerge(['aaa', 'bbb'],
 
1081
                     ['aaa', 'xxx', 'yyy', 'bbb'],
 
1082
                     ['aaa', 'xxx', 'bbb'], self.overlappedInsertExpected)
 
1083
 
 
1084
        # really it ought to reduce this to 
 
1085
        # ['aaa', 'xxx', 'yyy', 'bbb']
 
1086
 
 
1087
 
 
1088
    def testClashReplace(self):
 
1089
        self.doMerge(['aaa'],
 
1090
                     ['xxx'],
 
1091
                     ['yyy', 'zzz'],
 
1092
                     ['<<<<<<< ', 'xxx', '=======', 'yyy', 'zzz', 
 
1093
                      '>>>>>>> '])
 
1094
 
 
1095
    def testNonClashInsert1(self):
 
1096
        self.doMerge(['aaa'],
 
1097
                     ['xxx', 'aaa'],
 
1098
                     ['yyy', 'zzz'],
 
1099
                     ['<<<<<<< ', 'xxx', 'aaa', '=======', 'yyy', 'zzz', 
 
1100
                      '>>>>>>> '])
 
1101
 
 
1102
    def testNonClashInsert2(self):
 
1103
        self.doMerge(['aaa'],
 
1104
                     ['aaa'],
 
1105
                     ['yyy', 'zzz'],
 
1106
                     ['yyy', 'zzz'])
 
1107
 
 
1108
 
 
1109
    def testDeleteAndModify(self):
 
1110
        """Clashing delete and modification.
 
1111
 
 
1112
        If one side modifies a region and the other deletes it then
 
1113
        there should be a conflict with one side blank.
 
1114
        """
 
1115
 
 
1116
        #######################################
 
1117
        # skippd, not working yet
 
1118
        return
 
1119
        
 
1120
        self.doMerge(['aaa', 'bbb', 'ccc'],
 
1121
                     ['aaa', 'ddd', 'ccc'],
 
1122
                     ['aaa', 'ccc'],
 
1123
                     ['<<<<<<<< ', 'aaa', '=======', '>>>>>>> ', 'ccc'])
 
1124
 
 
1125
    def _test_merge_from_strings(self, base, a, b, expected):
 
1126
        w = self.get_file()
 
1127
        w.add_lines('text0', [], base.splitlines(True))
 
1128
        w.add_lines('text1', ['text0'], a.splitlines(True))
 
1129
        w.add_lines('text2', ['text0'], b.splitlines(True))
 
1130
        self.log('merge plan:')
 
1131
        p = list(w.plan_merge('text1', 'text2'))
 
1132
        for state, line in p:
 
1133
            if line:
 
1134
                self.log('%12s | %s' % (state, line[:-1]))
 
1135
        self.log('merge result:')
 
1136
        result_text = ''.join(w.weave_merge(p))
 
1137
        self.log(result_text)
 
1138
        self.assertEqualDiff(result_text, expected)
 
1139
 
 
1140
    def test_weave_merge_conflicts(self):
 
1141
        # does weave merge properly handle plans that end with unchanged?
 
1142
        result = ''.join(self.get_file().weave_merge([('new-a', 'hello\n')]))
 
1143
        self.assertEqual(result, 'hello\n')
 
1144
 
 
1145
    def test_deletion_extended(self):
 
1146
        """One side deletes, the other deletes more.
 
1147
        """
 
1148
        base = """\
 
1149
            line 1
 
1150
            line 2
 
1151
            line 3
 
1152
            """
 
1153
        a = """\
 
1154
            line 1
 
1155
            line 2
 
1156
            """
 
1157
        b = """\
 
1158
            line 1
 
1159
            """
 
1160
        result = """\
 
1161
            line 1
 
1162
            """
 
1163
        self._test_merge_from_strings(base, a, b, result)
 
1164
 
 
1165
    def test_deletion_overlap(self):
 
1166
        """Delete overlapping regions with no other conflict.
 
1167
 
 
1168
        Arguably it'd be better to treat these as agreement, rather than 
 
1169
        conflict, but for now conflict is safer.
 
1170
        """
 
1171
        base = """\
 
1172
            start context
 
1173
            int a() {}
 
1174
            int b() {}
 
1175
            int c() {}
 
1176
            end context
 
1177
            """
 
1178
        a = """\
 
1179
            start context
 
1180
            int a() {}
 
1181
            end context
 
1182
            """
 
1183
        b = """\
 
1184
            start context
 
1185
            int c() {}
 
1186
            end context
 
1187
            """
 
1188
        result = """\
 
1189
            start context
 
1190
<<<<<<< 
 
1191
            int a() {}
 
1192
=======
 
1193
            int c() {}
 
1194
>>>>>>> 
 
1195
            end context
 
1196
            """
 
1197
        self._test_merge_from_strings(base, a, b, result)
 
1198
 
 
1199
    def test_agreement_deletion(self):
 
1200
        """Agree to delete some lines, without conflicts."""
 
1201
        base = """\
 
1202
            start context
 
1203
            base line 1
 
1204
            base line 2
 
1205
            end context
 
1206
            """
 
1207
        a = """\
 
1208
            start context
 
1209
            base line 1
 
1210
            end context
 
1211
            """
 
1212
        b = """\
 
1213
            start context
 
1214
            base line 1
 
1215
            end context
 
1216
            """
 
1217
        result = """\
 
1218
            start context
 
1219
            base line 1
 
1220
            end context
 
1221
            """
 
1222
        self._test_merge_from_strings(base, a, b, result)
 
1223
 
 
1224
    def test_sync_on_deletion(self):
 
1225
        """Specific case of merge where we can synchronize incorrectly.
 
1226
        
 
1227
        A previous version of the weave merge concluded that the two versions
 
1228
        agreed on deleting line 2, and this could be a synchronization point.
 
1229
        Line 1 was then considered in isolation, and thought to be deleted on 
 
1230
        both sides.
 
1231
 
 
1232
        It's better to consider the whole thing as a disagreement region.
 
1233
        """
 
1234
        base = """\
 
1235
            start context
 
1236
            base line 1
 
1237
            base line 2
 
1238
            end context
 
1239
            """
 
1240
        a = """\
 
1241
            start context
 
1242
            base line 1
 
1243
            a's replacement line 2
 
1244
            end context
 
1245
            """
 
1246
        b = """\
 
1247
            start context
 
1248
            b replaces
 
1249
            both lines
 
1250
            end context
 
1251
            """
 
1252
        result = """\
 
1253
            start context
 
1254
<<<<<<< 
 
1255
            base line 1
 
1256
            a's replacement line 2
 
1257
=======
 
1258
            b replaces
 
1259
            both lines
 
1260
>>>>>>> 
 
1261
            end context
 
1262
            """
 
1263
        self._test_merge_from_strings(base, a, b, result)
 
1264
 
 
1265
 
 
1266
class TestKnitMerge(TestCaseWithMemoryTransport, MergeCasesMixin):
 
1267
 
 
1268
    def get_file(self, name='foo'):
 
1269
        return KnitVersionedFile(name, get_transport(self.get_url('.')),
 
1270
                                 delta=True, create=True)
 
1271
 
 
1272
    def log_contents(self, w):
 
1273
        pass
 
1274
 
 
1275
 
 
1276
class TestWeaveMerge(TestCaseWithMemoryTransport, MergeCasesMixin):
 
1277
 
 
1278
    def get_file(self, name='foo'):
 
1279
        return WeaveFile(name, get_transport(self.get_url('.')), create=True)
 
1280
 
 
1281
    def log_contents(self, w):
 
1282
        self.log('weave is:')
 
1283
        tmpf = StringIO()
 
1284
        write_weave(w, tmpf)
 
1285
        self.log(tmpf.getvalue())
 
1286
 
 
1287
    overlappedInsertExpected = ['aaa', '<<<<<<< ', 'xxx', 'yyy', '=======', 
 
1288
                                'xxx', '>>>>>>> ', 'bbb']
 
1289
 
 
1290
 
 
1291
class TestFormatSignatures(TestCaseWithMemoryTransport):
 
1292
 
 
1293
    def get_knit_file(self, name, annotated):
 
1294
        if annotated:
 
1295
            factory = KnitAnnotateFactory()
 
1296
        else:
 
1297
            factory = KnitPlainFactory()
 
1298
        return KnitVersionedFile(
 
1299
            name, get_transport(self.get_url('.')), create=True,
 
1300
            factory=factory)
 
1301
 
 
1302
    def test_knit_format_signatures(self):
 
1303
        """Different formats of knit have different signature strings."""
 
1304
        knit = self.get_knit_file('a', True)
 
1305
        self.assertEqual('knit-annotated', knit.get_format_signature())
 
1306
        knit = self.get_knit_file('p', False)
 
1307
        self.assertEqual('knit-plain', knit.get_format_signature())
 
1308