/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: Aaron Bentley
  • Date: 2007-08-16 05:37:08 UTC
  • mto: This revision was merged to the branch mainline in revision 2735.
  • Revision ID: aaron.bentley@utoronto.ca-20070816053708-3zot9t5j8rvgpho3
rename extract_files_bytest to iter_files_bytes, fix build_tree / progress

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