/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2484.1.12 by John Arbash Meinel
Switch the layout to use a matching _knit_load_data_py.py and _knit_load_data_c.pyx
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""Tests for Knit data structure"""
18
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
19
from cStringIO import StringIO
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
20
import difflib
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
21
import gzip
22
import sha
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
23
import sys
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
24
2196.2.5 by John Arbash Meinel
Add an exception class when the knit index storage method is unknown, and properly test for it
25
from bzrlib import (
26
    errors,
2484.1.5 by John Arbash Meinel
Simplistic implementations of custom parsers for options and parents
27
    generate_ids,
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
28
    knit,
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
29
    pack,
2196.2.5 by John Arbash Meinel
Add an exception class when the knit index storage method is unknown, and properly test for it
30
    )
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
31
from bzrlib.errors import (
32
    RevisionAlreadyPresent,
33
    KnitHeaderError,
34
    RevisionNotPresent,
35
    NoSuchFile,
36
    )
2592.3.1 by Robert Collins
Allow giving KnitVersionedFile an index object to use rather than implicitly creating one.
37
from bzrlib.index import *
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
38
from bzrlib.knit import (
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
39
    AnnotatedKnitContent,
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
40
    KnitContent,
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
41
    KnitGraphIndex,
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
42
    KnitVersionedFile,
43
    KnitPlainFactory,
44
    KnitAnnotateFactory,
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
45
    _KnitAccess,
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
46
    _KnitData,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
47
    _KnitIndex,
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
48
    _PackAccess,
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
49
    PlainKnitContent,
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
50
    _StreamAccess,
51
    _StreamIndex,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
52
    WeaveToKnit,
2520.4.41 by Aaron Bentley
Accelerate mpdiff generation
53
    KnitSequenceMatcher,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
54
    )
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
55
from bzrlib.osutils import split_lines
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
56
from bzrlib.tests import (
57
    Feature,
58
    TestCase,
59
    TestCaseWithMemoryTransport,
60
    TestCaseWithTransport,
61
    )
2745.5.3 by Robert Collins
* Move transport logging into a new transport class
62
from bzrlib.transport import get_transport
1563.2.13 by Robert Collins
InterVersionedFile implemented.
63
from bzrlib.transport.memory import MemoryTransport
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
64
from bzrlib.tuned_gzip import GzipFile
2535.3.15 by Andrew Bennetts
Add KnitVersionedFile.get_stream_as_bytes, start smart implementation of RemoteRepository.get_data_stream.
65
from bzrlib.util import bencode
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
66
from bzrlib.weave import Weave
67
68
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
69
class _CompiledKnitFeature(Feature):
70
71
    def _probe(self):
72
        try:
2484.1.12 by John Arbash Meinel
Switch the layout to use a matching _knit_load_data_py.py and _knit_load_data_c.pyx
73
            import bzrlib._knit_load_data_c
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
74
        except ImportError:
75
            return False
76
        return True
77
78
    def feature_name(self):
2484.1.12 by John Arbash Meinel
Switch the layout to use a matching _knit_load_data_py.py and _knit_load_data_c.pyx
79
        return 'bzrlib._knit_load_data_c'
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
80
81
CompiledKnitFeature = _CompiledKnitFeature()
82
83
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
84
class KnitContentTestsMixin(object):
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
85
86
    def test_constructor(self):
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
87
        content = self._make_content([])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
88
89
    def test_text(self):
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
90
        content = self._make_content([])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
91
        self.assertEqual(content.text(), [])
92
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
93
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
94
        self.assertEqual(content.text(), ["text1", "text2"])
95
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
96
    def test_copy(self):
97
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
98
        copy = content.copy()
99
        self.assertIsInstance(copy, content.__class__)
100
        self.assertEqual(copy.annotate(), content.annotate())
101
102
    def assertDerivedBlocksEqual(self, source, target, noeol=False):
103
        """Assert that the derived matching blocks match real output"""
104
        source_lines = source.splitlines(True)
105
        target_lines = target.splitlines(True)
106
        def nl(line):
107
            if noeol and not line.endswith('\n'):
108
                return line + '\n'
109
            else:
110
                return line
111
        source_content = self._make_content([(None, nl(l)) for l in source_lines])
112
        target_content = self._make_content([(None, nl(l)) for l in target_lines])
113
        line_delta = source_content.line_delta(target_content)
114
        delta_blocks = list(KnitContent.get_line_delta_blocks(line_delta,
115
            source_lines, target_lines))
116
        matcher = KnitSequenceMatcher(None, source_lines, target_lines)
117
        matcher_blocks = list(list(matcher.get_matching_blocks()))
118
        self.assertEqual(matcher_blocks, delta_blocks)
119
120
    def test_get_line_delta_blocks(self):
121
        self.assertDerivedBlocksEqual('a\nb\nc\n', 'q\nc\n')
122
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1)
123
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1A)
124
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1B)
125
        self.assertDerivedBlocksEqual(TEXT_1B, TEXT_1A)
126
        self.assertDerivedBlocksEqual(TEXT_1A, TEXT_1B)
127
        self.assertDerivedBlocksEqual(TEXT_1A, '')
128
        self.assertDerivedBlocksEqual('', TEXT_1A)
129
        self.assertDerivedBlocksEqual('', '')
130
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\nd')
131
132
    def test_get_line_delta_blocks_noeol(self):
133
        """Handle historical knit deltas safely
134
135
        Some existing knit deltas don't consider the last line to differ
136
        when the only difference whether it has a final newline.
137
138
        New knit deltas appear to always consider the last line to differ
139
        in this case.
140
        """
141
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\nd\n', noeol=True)
142
        self.assertDerivedBlocksEqual('a\nb\nc\nd\n', 'a\nb\nc', noeol=True)
143
        self.assertDerivedBlocksEqual('a\nb\nc\n', 'a\nb\nc', noeol=True)
144
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\n', noeol=True)
145
146
147
class TestPlainKnitContent(TestCase, KnitContentTestsMixin):
148
149
    def _make_content(self, lines):
150
        annotated_content = AnnotatedKnitContent(lines)
151
        return PlainKnitContent(annotated_content.text(), 'bogus')
152
153
    def test_annotate(self):
154
        content = self._make_content([])
155
        self.assertEqual(content.annotate(), [])
156
157
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
158
        self.assertEqual(content.annotate(),
159
            [("bogus", "text1"), ("bogus", "text2")])
160
161
    def test_annotate_iter(self):
162
        content = self._make_content([])
163
        it = content.annotate_iter()
164
        self.assertRaises(StopIteration, it.next)
165
166
        content = self._make_content([("bogus", "text1"), ("bogus", "text2")])
167
        it = content.annotate_iter()
168
        self.assertEqual(it.next(), ("bogus", "text1"))
169
        self.assertEqual(it.next(), ("bogus", "text2"))
170
        self.assertRaises(StopIteration, it.next)
171
172
    def test_line_delta(self):
173
        content1 = self._make_content([("", "a"), ("", "b")])
174
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
175
        self.assertEqual(content1.line_delta(content2),
176
            [(1, 2, 2, ["a", "c"])])
177
178
    def test_line_delta_iter(self):
179
        content1 = self._make_content([("", "a"), ("", "b")])
180
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
181
        it = content1.line_delta_iter(content2)
182
        self.assertEqual(it.next(), (1, 2, 2, ["a", "c"]))
183
        self.assertRaises(StopIteration, it.next)
184
185
186
class TestAnnotatedKnitContent(TestCase, KnitContentTestsMixin):
187
188
    def _make_content(self, lines):
189
        return AnnotatedKnitContent(lines)
190
191
    def test_annotate(self):
192
        content = self._make_content([])
193
        self.assertEqual(content.annotate(), [])
194
195
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
196
        self.assertEqual(content.annotate(),
197
            [("origin1", "text1"), ("origin2", "text2")])
198
199
    def test_annotate_iter(self):
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
200
        content = self._make_content([])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
201
        it = content.annotate_iter()
202
        self.assertRaises(StopIteration, it.next)
203
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
204
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
205
        it = content.annotate_iter()
206
        self.assertEqual(it.next(), ("origin1", "text1"))
207
        self.assertEqual(it.next(), ("origin2", "text2"))
208
        self.assertRaises(StopIteration, it.next)
209
210
    def test_line_delta(self):
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
211
        content1 = self._make_content([("", "a"), ("", "b")])
212
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
213
        self.assertEqual(content1.line_delta(content2),
214
            [(1, 2, 2, [("", "a"), ("", "c")])])
215
216
    def test_line_delta_iter(self):
2794.1.2 by Robert Collins
Nuke versioned file add/get delta support, allowing easy simplification of unannotated Content, reducing memory copies and friction during commit on unannotated texts.
217
        content1 = self._make_content([("", "a"), ("", "b")])
218
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
219
        it = content1.line_delta_iter(content2)
220
        self.assertEqual(it.next(), (1, 2, 2, [("", "a"), ("", "c")]))
221
        self.assertRaises(StopIteration, it.next)
222
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
223
224
class MockTransport(object):
225
226
    def __init__(self, file_lines=None):
227
        self.file_lines = file_lines
228
        self.calls = []
2196.2.3 by John Arbash Meinel
Update tests and code to pass after merging bzr.dev
229
        # We have no base directory for the MockTransport
230
        self.base = ''
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
231
232
    def get(self, filename):
233
        if self.file_lines is None:
234
            raise NoSuchFile(filename)
235
        else:
236
            return StringIO("\n".join(self.file_lines))
237
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
238
    def readv(self, relpath, offsets):
239
        fp = self.get(relpath)
240
        for offset, size in offsets:
241
            fp.seek(offset)
242
            yield offset, fp.read(size)
243
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
244
    def __getattr__(self, name):
245
        def queue_call(*args, **kwargs):
246
            self.calls.append((name, args, kwargs))
247
        return queue_call
248
249
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
250
class KnitRecordAccessTestsMixin(object):
251
    """Tests for getting and putting knit records."""
252
253
    def assertAccessExists(self, access):
254
        """Ensure the data area for access has been initialised/exists."""
255
        raise NotImplementedError(self.assertAccessExists)
256
257
    def test_add_raw_records(self):
258
        """Add_raw_records adds records retrievable later."""
259
        access = self.get_access()
260
        memos = access.add_raw_records([10], '1234567890')
261
        self.assertEqual(['1234567890'], list(access.get_raw_records(memos)))
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
262
 
263
    def test_add_several_raw_records(self):
264
        """add_raw_records with many records and read some back."""
265
        access = self.get_access()
266
        memos = access.add_raw_records([10, 2, 5], '12345678901234567')
267
        self.assertEqual(['1234567890', '12', '34567'],
268
            list(access.get_raw_records(memos)))
269
        self.assertEqual(['1234567890'],
270
            list(access.get_raw_records(memos[0:1])))
271
        self.assertEqual(['12'],
272
            list(access.get_raw_records(memos[1:2])))
273
        self.assertEqual(['34567'],
274
            list(access.get_raw_records(memos[2:3])))
275
        self.assertEqual(['1234567890', '34567'],
276
            list(access.get_raw_records(memos[0:1] + memos[2:3])))
277
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
278
    def test_create(self):
279
        """create() should make a file on disk."""
280
        access = self.get_access()
281
        access.create()
282
        self.assertAccessExists(access)
283
284
    def test_open_file(self):
285
        """open_file never errors."""
286
        access = self.get_access()
287
        access.open_file()
288
289
290
class TestKnitKnitAccess(TestCaseWithMemoryTransport, KnitRecordAccessTestsMixin):
291
    """Tests for the .kndx implementation."""
292
293
    def assertAccessExists(self, access):
294
        self.assertNotEqual(None, access.open_file())
295
296
    def get_access(self):
297
        """Get a .knit style access instance."""
298
        access = _KnitAccess(self.get_transport(), "foo.knit", None, None,
299
            False, False)
300
        return access
301
    
302
303
class TestPackKnitAccess(TestCaseWithMemoryTransport, KnitRecordAccessTestsMixin):
304
    """Tests for the pack based access."""
305
306
    def assertAccessExists(self, access):
307
        # as pack based access has no backing unless an index maps data, this
308
        # is a no-op.
309
        pass
310
311
    def get_access(self):
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
312
        return self._get_access()[0]
313
314
    def _get_access(self, packname='packfile', index='FOO'):
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
315
        transport = self.get_transport()
316
        def write_data(bytes):
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
317
            transport.append_bytes(packname, bytes)
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
318
        writer = pack.ContainerWriter(write_data)
319
        writer.begin()
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
320
        indices = {index:(transport, packname)}
321
        access = _PackAccess(indices, writer=(writer, index))
322
        return access, writer
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
323
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
324
    def test_read_from_several_packs(self):
325
        access, writer = self._get_access()
326
        memos = []
327
        memos.extend(access.add_raw_records([10], '1234567890'))
328
        writer.end()
329
        access, writer = self._get_access('pack2', 'FOOBAR')
330
        memos.extend(access.add_raw_records([5], '12345'))
331
        writer.end()
332
        access, writer = self._get_access('pack3', 'BAZ')
333
        memos.extend(access.add_raw_records([5], 'alpha'))
334
        writer.end()
335
        transport = self.get_transport()
336
        access = _PackAccess({"FOO":(transport, 'packfile'),
337
            "FOOBAR":(transport, 'pack2'),
338
            "BAZ":(transport, 'pack3')})
339
        self.assertEqual(['1234567890', '12345', 'alpha'],
340
            list(access.get_raw_records(memos)))
341
        self.assertEqual(['1234567890'],
342
            list(access.get_raw_records(memos[0:1])))
343
        self.assertEqual(['12345'],
344
            list(access.get_raw_records(memos[1:2])))
345
        self.assertEqual(['alpha'],
346
            list(access.get_raw_records(memos[2:3])))
347
        self.assertEqual(['1234567890', 'alpha'],
348
            list(access.get_raw_records(memos[0:1] + memos[2:3])))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
349
2592.3.70 by Robert Collins
Allow setting a writer after creating a knit._PackAccess object.
350
    def test_set_writer(self):
351
        """The writer should be settable post construction."""
352
        access = _PackAccess({})
353
        transport = self.get_transport()
354
        packname = 'packfile'
355
        index = 'foo'
356
        def write_data(bytes):
357
            transport.append_bytes(packname, bytes)
358
        writer = pack.ContainerWriter(write_data)
359
        writer.begin()
360
        access.set_writer(writer, index, (transport, packname))
361
        memos = access.add_raw_records([10], '1234567890')
362
        writer.end()
363
        self.assertEqual(['1234567890'], list(access.get_raw_records(memos)))
364
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
365
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
366
class LowLevelKnitDataTests(TestCase):
367
368
    def create_gz_content(self, text):
369
        sio = StringIO()
370
        gz_file = gzip.GzipFile(mode='wb', fileobj=sio)
371
        gz_file.write(text)
372
        gz_file.close()
373
        return sio.getvalue()
374
375
    def test_valid_knit_data(self):
376
        sha1sum = sha.new('foo\nbar\n').hexdigest()
377
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
378
                                        'foo\n'
379
                                        'bar\n'
380
                                        'end rev-id-1\n'
381
                                        % (sha1sum,))
382
        transport = MockTransport([gz_txt])
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
383
        access = _KnitAccess(transport, 'filename', None, None, False, False)
384
        data = _KnitData(access=access)
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
385
        records = [('rev-id-1', (None, 0, len(gz_txt)))]
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
386
387
        contents = data.read_records(records)
388
        self.assertEqual({'rev-id-1':(['foo\n', 'bar\n'], sha1sum)}, contents)
389
390
        raw_contents = list(data.read_records_iter_raw(records))
391
        self.assertEqual([('rev-id-1', gz_txt)], raw_contents)
392
393
    def test_not_enough_lines(self):
394
        sha1sum = sha.new('foo\n').hexdigest()
395
        # record says 2 lines data says 1
396
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
397
                                        'foo\n'
398
                                        'end rev-id-1\n'
399
                                        % (sha1sum,))
400
        transport = MockTransport([gz_txt])
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
401
        access = _KnitAccess(transport, 'filename', None, None, False, False)
402
        data = _KnitData(access=access)
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
403
        records = [('rev-id-1', (None, 0, len(gz_txt)))]
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
404
        self.assertRaises(errors.KnitCorrupt, data.read_records, records)
405
406
        # read_records_iter_raw won't detect that sort of mismatch/corruption
407
        raw_contents = list(data.read_records_iter_raw(records))
408
        self.assertEqual([('rev-id-1', gz_txt)], raw_contents)
409
410
    def test_too_many_lines(self):
411
        sha1sum = sha.new('foo\nbar\n').hexdigest()
412
        # record says 1 lines data says 2
413
        gz_txt = self.create_gz_content('version rev-id-1 1 %s\n'
414
                                        'foo\n'
415
                                        'bar\n'
416
                                        'end rev-id-1\n'
417
                                        % (sha1sum,))
418
        transport = MockTransport([gz_txt])
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
419
        access = _KnitAccess(transport, 'filename', None, None, False, False)
420
        data = _KnitData(access=access)
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
421
        records = [('rev-id-1', (None, 0, len(gz_txt)))]
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
422
        self.assertRaises(errors.KnitCorrupt, data.read_records, records)
423
424
        # read_records_iter_raw won't detect that sort of mismatch/corruption
425
        raw_contents = list(data.read_records_iter_raw(records))
426
        self.assertEqual([('rev-id-1', gz_txt)], raw_contents)
427
428
    def test_mismatched_version_id(self):
429
        sha1sum = sha.new('foo\nbar\n').hexdigest()
430
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
431
                                        'foo\n'
432
                                        'bar\n'
433
                                        'end rev-id-1\n'
434
                                        % (sha1sum,))
435
        transport = MockTransport([gz_txt])
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
436
        access = _KnitAccess(transport, 'filename', None, None, False, False)
437
        data = _KnitData(access=access)
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
438
        # We are asking for rev-id-2, but the data is rev-id-1
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
439
        records = [('rev-id-2', (None, 0, len(gz_txt)))]
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
440
        self.assertRaises(errors.KnitCorrupt, data.read_records, records)
441
442
        # read_records_iter_raw will notice if we request the wrong version.
443
        self.assertRaises(errors.KnitCorrupt, list,
444
                          data.read_records_iter_raw(records))
445
446
    def test_uncompressed_data(self):
447
        sha1sum = sha.new('foo\nbar\n').hexdigest()
448
        txt = ('version rev-id-1 2 %s\n'
449
               'foo\n'
450
               'bar\n'
451
               'end rev-id-1\n'
452
               % (sha1sum,))
453
        transport = MockTransport([txt])
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
454
        access = _KnitAccess(transport, 'filename', None, None, False, False)
455
        data = _KnitData(access=access)
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
456
        records = [('rev-id-1', (None, 0, len(txt)))]
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
457
458
        # We don't have valid gzip data ==> corrupt
459
        self.assertRaises(errors.KnitCorrupt, data.read_records, records)
460
461
        # read_records_iter_raw will notice the bad data
462
        self.assertRaises(errors.KnitCorrupt, list,
463
                          data.read_records_iter_raw(records))
464
465
    def test_corrupted_data(self):
466
        sha1sum = sha.new('foo\nbar\n').hexdigest()
467
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
468
                                        'foo\n'
469
                                        'bar\n'
470
                                        'end rev-id-1\n'
471
                                        % (sha1sum,))
472
        # Change 2 bytes in the middle to \xff
473
        gz_txt = gz_txt[:10] + '\xff\xff' + gz_txt[12:]
474
        transport = MockTransport([gz_txt])
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
475
        access = _KnitAccess(transport, 'filename', None, None, False, False)
476
        data = _KnitData(access=access)
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
477
        records = [('rev-id-1', (None, 0, len(gz_txt)))]
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
478
479
        self.assertRaises(errors.KnitCorrupt, data.read_records, records)
480
481
        # read_records_iter_raw will notice if we request the wrong version.
482
        self.assertRaises(errors.KnitCorrupt, list,
483
                          data.read_records_iter_raw(records))
484
485
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
486
class LowLevelKnitIndexTests(TestCase):
487
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
488
    def get_knit_index(self, *args, **kwargs):
489
        orig = knit._load_data
490
        def reset():
491
            knit._load_data = orig
492
        self.addCleanup(reset)
2484.1.12 by John Arbash Meinel
Switch the layout to use a matching _knit_load_data_py.py and _knit_load_data_c.pyx
493
        from bzrlib._knit_load_data_py import _load_data_py
494
        knit._load_data = _load_data_py
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
495
        return _KnitIndex(*args, **kwargs)
496
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
497
    def test_no_such_file(self):
498
        transport = MockTransport()
499
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
500
        self.assertRaises(NoSuchFile, self.get_knit_index,
501
                          transport, "filename", "r")
502
        self.assertRaises(NoSuchFile, self.get_knit_index,
503
                          transport, "filename", "w", create=False)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
504
505
    def test_create_file(self):
506
        transport = MockTransport()
507
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
508
        index = self.get_knit_index(transport, "filename", "w",
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
509
            file_mode="wb", create=True)
510
        self.assertEqual(
511
                ("put_bytes_non_atomic",
512
                    ("filename", index.HEADER), {"mode": "wb"}),
513
                transport.calls.pop(0))
514
515
    def test_delay_create_file(self):
516
        transport = MockTransport()
517
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
518
        index = self.get_knit_index(transport, "filename", "w",
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
519
            create=True, file_mode="wb", create_parent_dir=True,
520
            delay_create=True, dir_mode=0777)
521
        self.assertEqual([], transport.calls)
522
523
        index.add_versions([])
524
        name, (filename, f), kwargs = transport.calls.pop(0)
525
        self.assertEqual("put_file_non_atomic", name)
526
        self.assertEqual(
527
            {"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
528
            kwargs)
529
        self.assertEqual("filename", filename)
530
        self.assertEqual(index.HEADER, f.read())
531
532
        index.add_versions([])
533
        self.assertEqual(("append_bytes", ("filename", ""), {}),
534
            transport.calls.pop(0))
535
536
    def test_read_utf8_version_id(self):
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
537
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
538
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
539
        transport = MockTransport([
540
            _KnitIndex.HEADER,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
541
            '%s option 0 1 :' % (utf8_revision_id,)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
542
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
543
        index = self.get_knit_index(transport, "filename", "r")
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
544
        # _KnitIndex is a private class, and deals in utf8 revision_ids, not
545
        # Unicode revision_ids.
546
        self.assertTrue(index.has_version(utf8_revision_id))
547
        self.assertFalse(index.has_version(unicode_revision_id))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
548
549
    def test_read_utf8_parents(self):
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
550
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
551
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
552
        transport = MockTransport([
553
            _KnitIndex.HEADER,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
554
            "version option 0 1 .%s :" % (utf8_revision_id,)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
555
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
556
        index = self.get_knit_index(transport, "filename", "r")
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
557
        self.assertEqual([utf8_revision_id],
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
558
            index.get_parents_with_ghosts("version"))
559
560
    def test_read_ignore_corrupted_lines(self):
561
        transport = MockTransport([
562
            _KnitIndex.HEADER,
563
            "corrupted",
564
            "corrupted options 0 1 .b .c ",
565
            "version options 0 1 :"
566
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
567
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
568
        self.assertEqual(1, index.num_versions())
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
569
        self.assertTrue(index.has_version("version"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
570
571
    def test_read_corrupted_header(self):
2196.2.3 by John Arbash Meinel
Update tests and code to pass after merging bzr.dev
572
        transport = MockTransport(['not a bzr knit index header\n'])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
573
        self.assertRaises(KnitHeaderError,
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
574
            self.get_knit_index, transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
575
576
    def test_read_duplicate_entries(self):
577
        transport = MockTransport([
578
            _KnitIndex.HEADER,
579
            "parent options 0 1 :",
580
            "version options1 0 1 0 :",
581
            "version options2 1 2 .other :",
582
            "version options3 3 4 0 .other :"
583
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
584
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
585
        self.assertEqual(2, index.num_versions())
2592.3.8 by Robert Collins
Remove unneeded pulib method lookup on private class _KnitIndex.
586
        # check that the index used is the first one written. (Specific
587
        # to KnitIndex style indices.
588
        self.assertEqual("1", index._version_list_to_index(["version"]))
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
589
        self.assertEqual((None, 3, 4), index.get_position("version"))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
590
        self.assertEqual(["options3"], index.get_options("version"))
591
        self.assertEqual(["parent", "other"],
592
            index.get_parents_with_ghosts("version"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
593
594
    def test_read_compressed_parents(self):
595
        transport = MockTransport([
596
            _KnitIndex.HEADER,
597
            "a option 0 1 :",
598
            "b option 0 1 0 :",
599
            "c option 0 1 1 0 :",
600
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
601
        index = self.get_knit_index(transport, "filename", "r")
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
602
        self.assertEqual(["a"], index.get_parents("b"))
603
        self.assertEqual(["b", "a"], index.get_parents("c"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
604
605
    def test_write_utf8_version_id(self):
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
606
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
607
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
608
        transport = MockTransport([
609
            _KnitIndex.HEADER
610
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
611
        index = self.get_knit_index(transport, "filename", "r")
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
612
        index.add_version(utf8_revision_id, ["option"], (None, 0, 1), [])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
613
        self.assertEqual(("append_bytes", ("filename",
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
614
            "\n%s option 0 1  :" % (utf8_revision_id,)),
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
615
            {}),
616
            transport.calls.pop(0))
617
618
    def test_write_utf8_parents(self):
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
619
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
620
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
621
        transport = MockTransport([
622
            _KnitIndex.HEADER
623
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
624
        index = self.get_knit_index(transport, "filename", "r")
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
625
        index.add_version("version", ["option"], (None, 0, 1), [utf8_revision_id])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
626
        self.assertEqual(("append_bytes", ("filename",
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
627
            "\nversion option 0 1 .%s :" % (utf8_revision_id,)),
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
628
            {}),
629
            transport.calls.pop(0))
630
631
    def test_get_graph(self):
632
        transport = MockTransport()
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
633
        index = self.get_knit_index(transport, "filename", "w", create=True)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
634
        self.assertEqual([], index.get_graph())
635
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
636
        index.add_version("a", ["option"], (None, 0, 1), ["b"])
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
637
        self.assertEqual([("a", ["b"])], index.get_graph())
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
638
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
639
        index.add_version("c", ["option"], (None, 0, 1), ["d"])
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
640
        self.assertEqual([("a", ["b"]), ("c", ["d"])],
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
641
            sorted(index.get_graph()))
642
643
    def test_get_ancestry(self):
644
        transport = MockTransport([
645
            _KnitIndex.HEADER,
646
            "a option 0 1 :",
647
            "b option 0 1 0 .e :",
648
            "c option 0 1 1 0 :",
649
            "d option 0 1 2 .f :"
650
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
651
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
652
653
        self.assertEqual([], index.get_ancestry([]))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
654
        self.assertEqual(["a"], index.get_ancestry(["a"]))
655
        self.assertEqual(["a", "b"], index.get_ancestry(["b"]))
656
        self.assertEqual(["a", "b", "c"], index.get_ancestry(["c"]))
657
        self.assertEqual(["a", "b", "c", "d"], index.get_ancestry(["d"]))
658
        self.assertEqual(["a", "b"], index.get_ancestry(["a", "b"]))
659
        self.assertEqual(["a", "b", "c"], index.get_ancestry(["a", "c"]))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
660
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
661
        self.assertRaises(RevisionNotPresent, index.get_ancestry, ["e"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
662
663
    def test_get_ancestry_with_ghosts(self):
664
        transport = MockTransport([
665
            _KnitIndex.HEADER,
666
            "a option 0 1 :",
667
            "b option 0 1 0 .e :",
668
            "c option 0 1 0 .f .g :",
669
            "d option 0 1 2 .h .j .k :"
670
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
671
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
672
673
        self.assertEqual([], index.get_ancestry_with_ghosts([]))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
674
        self.assertEqual(["a"], index.get_ancestry_with_ghosts(["a"]))
675
        self.assertEqual(["a", "e", "b"],
676
            index.get_ancestry_with_ghosts(["b"]))
677
        self.assertEqual(["a", "g", "f", "c"],
678
            index.get_ancestry_with_ghosts(["c"]))
679
        self.assertEqual(["a", "g", "f", "c", "k", "j", "h", "d"],
680
            index.get_ancestry_with_ghosts(["d"]))
681
        self.assertEqual(["a", "e", "b"],
682
            index.get_ancestry_with_ghosts(["a", "b"]))
683
        self.assertEqual(["a", "g", "f", "c"],
684
            index.get_ancestry_with_ghosts(["a", "c"]))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
685
        self.assertEqual(
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
686
            ["a", "g", "f", "c", "e", "b", "k", "j", "h", "d"],
687
            index.get_ancestry_with_ghosts(["b", "d"]))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
688
689
        self.assertRaises(RevisionNotPresent,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
690
            index.get_ancestry_with_ghosts, ["e"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
691
2592.3.43 by Robert Collins
A knit iter_parents API.
692
    def test_iter_parents(self):
693
        transport = MockTransport()
694
        index = self.get_knit_index(transport, "filename", "w", create=True)
695
        # no parents
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
696
        index.add_version('r0', ['option'], (None, 0, 1), [])
2592.3.43 by Robert Collins
A knit iter_parents API.
697
        # 1 parent
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
698
        index.add_version('r1', ['option'], (None, 0, 1), ['r0'])
2592.3.43 by Robert Collins
A knit iter_parents API.
699
        # 2 parents
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
700
        index.add_version('r2', ['option'], (None, 0, 1), ['r1', 'r0'])
2592.3.43 by Robert Collins
A knit iter_parents API.
701
        # XXX TODO a ghost
702
        # cases: each sample data individually:
703
        self.assertEqual(set([('r0', ())]),
704
            set(index.iter_parents(['r0'])))
705
        self.assertEqual(set([('r1', ('r0', ))]),
706
            set(index.iter_parents(['r1'])))
707
        self.assertEqual(set([('r2', ('r1', 'r0'))]),
708
            set(index.iter_parents(['r2'])))
709
        # no nodes returned for a missing node
710
        self.assertEqual(set(),
711
            set(index.iter_parents(['missing'])))
712
        # 1 node returned with missing nodes skipped
713
        self.assertEqual(set([('r1', ('r0', ))]),
714
            set(index.iter_parents(['ghost1', 'r1', 'ghost'])))
715
        # 2 nodes returned
716
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
717
            set(index.iter_parents(['r0', 'r1'])))
718
        # 2 nodes returned, missing skipped
719
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
720
            set(index.iter_parents(['a', 'r0', 'b', 'r1', 'c'])))
721
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
722
    def test_num_versions(self):
723
        transport = MockTransport([
724
            _KnitIndex.HEADER
725
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
726
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
727
728
        self.assertEqual(0, index.num_versions())
729
        self.assertEqual(0, len(index))
730
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
731
        index.add_version("a", ["option"], (None, 0, 1), [])
732
        self.assertEqual(1, index.num_versions())
733
        self.assertEqual(1, len(index))
734
735
        index.add_version("a", ["option2"], (None, 1, 2), [])
736
        self.assertEqual(1, index.num_versions())
737
        self.assertEqual(1, len(index))
738
739
        index.add_version("b", ["option"], (None, 0, 1), [])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
740
        self.assertEqual(2, index.num_versions())
741
        self.assertEqual(2, len(index))
742
743
    def test_get_versions(self):
744
        transport = MockTransport([
745
            _KnitIndex.HEADER
746
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
747
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
748
749
        self.assertEqual([], index.get_versions())
750
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
751
        index.add_version("a", ["option"], (None, 0, 1), [])
752
        self.assertEqual(["a"], index.get_versions())
753
754
        index.add_version("a", ["option"], (None, 0, 1), [])
755
        self.assertEqual(["a"], index.get_versions())
756
757
        index.add_version("b", ["option"], (None, 0, 1), [])
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
758
        self.assertEqual(["a", "b"], index.get_versions())
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
759
760
    def test_add_version(self):
761
        transport = MockTransport([
762
            _KnitIndex.HEADER
763
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
764
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
765
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
766
        index.add_version("a", ["option"], (None, 0, 1), ["b"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
767
        self.assertEqual(("append_bytes",
768
            ("filename", "\na option 0 1 .b :"),
769
            {}), transport.calls.pop(0))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
770
        self.assertTrue(index.has_version("a"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
771
        self.assertEqual(1, index.num_versions())
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
772
        self.assertEqual((None, 0, 1), index.get_position("a"))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
773
        self.assertEqual(["option"], index.get_options("a"))
774
        self.assertEqual(["b"], index.get_parents_with_ghosts("a"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
775
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
776
        index.add_version("a", ["opt"], (None, 1, 2), ["c"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
777
        self.assertEqual(("append_bytes",
778
            ("filename", "\na opt 1 2 .c :"),
779
            {}), transport.calls.pop(0))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
780
        self.assertTrue(index.has_version("a"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
781
        self.assertEqual(1, index.num_versions())
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
782
        self.assertEqual((None, 1, 2), index.get_position("a"))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
783
        self.assertEqual(["opt"], index.get_options("a"))
784
        self.assertEqual(["c"], index.get_parents_with_ghosts("a"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
785
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
786
        index.add_version("b", ["option"], (None, 2, 3), ["a"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
787
        self.assertEqual(("append_bytes",
788
            ("filename", "\nb option 2 3 0 :"),
789
            {}), transport.calls.pop(0))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
790
        self.assertTrue(index.has_version("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
791
        self.assertEqual(2, index.num_versions())
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
792
        self.assertEqual((None, 2, 3), index.get_position("b"))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
793
        self.assertEqual(["option"], index.get_options("b"))
794
        self.assertEqual(["a"], index.get_parents_with_ghosts("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
795
796
    def test_add_versions(self):
797
        transport = MockTransport([
798
            _KnitIndex.HEADER
799
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
800
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
801
802
        index.add_versions([
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
803
            ("a", ["option"], (None, 0, 1), ["b"]),
804
            ("a", ["opt"], (None, 1, 2), ["c"]),
805
            ("b", ["option"], (None, 2, 3), ["a"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
806
            ])
807
        self.assertEqual(("append_bytes", ("filename",
808
            "\na option 0 1 .b :"
809
            "\na opt 1 2 .c :"
810
            "\nb option 2 3 0 :"
811
            ), {}), transport.calls.pop(0))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
812
        self.assertTrue(index.has_version("a"))
813
        self.assertTrue(index.has_version("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
814
        self.assertEqual(2, index.num_versions())
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
815
        self.assertEqual((None, 1, 2), index.get_position("a"))
816
        self.assertEqual((None, 2, 3), index.get_position("b"))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
817
        self.assertEqual(["opt"], index.get_options("a"))
818
        self.assertEqual(["option"], index.get_options("b"))
819
        self.assertEqual(["c"], index.get_parents_with_ghosts("a"))
820
        self.assertEqual(["a"], index.get_parents_with_ghosts("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
821
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
822
    def test_add_versions_random_id_is_accepted(self):
823
        transport = MockTransport([
824
            _KnitIndex.HEADER
825
            ])
826
        index = self.get_knit_index(transport, "filename", "r")
827
828
        index.add_versions([
829
            ("a", ["option"], (None, 0, 1), ["b"]),
830
            ("a", ["opt"], (None, 1, 2), ["c"]),
831
            ("b", ["option"], (None, 2, 3), ["a"])
832
            ], random_id=True)
833
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
834
    def test_delay_create_and_add_versions(self):
835
        transport = MockTransport()
836
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
837
        index = self.get_knit_index(transport, "filename", "w",
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
838
            create=True, file_mode="wb", create_parent_dir=True,
839
            delay_create=True, dir_mode=0777)
840
        self.assertEqual([], transport.calls)
841
842
        index.add_versions([
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
843
            ("a", ["option"], (None, 0, 1), ["b"]),
844
            ("a", ["opt"], (None, 1, 2), ["c"]),
845
            ("b", ["option"], (None, 2, 3), ["a"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
846
            ])
847
        name, (filename, f), kwargs = transport.calls.pop(0)
848
        self.assertEqual("put_file_non_atomic", name)
849
        self.assertEqual(
850
            {"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
851
            kwargs)
852
        self.assertEqual("filename", filename)
853
        self.assertEqual(
854
            index.HEADER +
855
            "\na option 0 1 .b :"
856
            "\na opt 1 2 .c :"
857
            "\nb option 2 3 0 :",
858
            f.read())
859
860
    def test_has_version(self):
861
        transport = MockTransport([
862
            _KnitIndex.HEADER,
863
            "a option 0 1 :"
864
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
865
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
866
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
867
        self.assertTrue(index.has_version("a"))
868
        self.assertFalse(index.has_version("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
869
870
    def test_get_position(self):
871
        transport = MockTransport([
872
            _KnitIndex.HEADER,
873
            "a option 0 1 :",
874
            "b option 1 2 :"
875
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
876
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
877
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
878
        self.assertEqual((None, 0, 1), index.get_position("a"))
879
        self.assertEqual((None, 1, 2), index.get_position("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
880
881
    def test_get_method(self):
882
        transport = MockTransport([
883
            _KnitIndex.HEADER,
884
            "a fulltext,unknown 0 1 :",
885
            "b unknown,line-delta 1 2 :",
886
            "c bad 3 4 :"
887
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
888
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
889
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
890
        self.assertEqual("fulltext", index.get_method("a"))
891
        self.assertEqual("line-delta", index.get_method("b"))
892
        self.assertRaises(errors.KnitIndexUnknownMethod, index.get_method, "c")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
893
894
    def test_get_options(self):
895
        transport = MockTransport([
896
            _KnitIndex.HEADER,
897
            "a opt1 0 1 :",
898
            "b opt2,opt3 1 2 :"
899
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
900
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
901
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
902
        self.assertEqual(["opt1"], index.get_options("a"))
903
        self.assertEqual(["opt2", "opt3"], index.get_options("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
904
905
    def test_get_parents(self):
906
        transport = MockTransport([
907
            _KnitIndex.HEADER,
908
            "a option 0 1 :",
909
            "b option 1 2 0 .c :",
910
            "c option 1 2 1 0 .e :"
911
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
912
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
913
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
914
        self.assertEqual([], index.get_parents("a"))
915
        self.assertEqual(["a", "c"], index.get_parents("b"))
916
        self.assertEqual(["b", "a"], index.get_parents("c"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
917
918
    def test_get_parents_with_ghosts(self):
919
        transport = MockTransport([
920
            _KnitIndex.HEADER,
921
            "a option 0 1 :",
922
            "b option 1 2 0 .c :",
923
            "c option 1 2 1 0 .e :"
924
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
925
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
926
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
927
        self.assertEqual([], index.get_parents_with_ghosts("a"))
928
        self.assertEqual(["a", "c"], index.get_parents_with_ghosts("b"))
929
        self.assertEqual(["b", "a", "e"],
930
            index.get_parents_with_ghosts("c"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
931
932
    def test_check_versions_present(self):
933
        transport = MockTransport([
934
            _KnitIndex.HEADER,
935
            "a option 0 1 :",
936
            "b option 0 1 :"
937
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
938
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
939
940
        check = index.check_versions_present
941
942
        check([])
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
943
        check(["a"])
944
        check(["b"])
945
        check(["a", "b"])
946
        self.assertRaises(RevisionNotPresent, check, ["c"])
947
        self.assertRaises(RevisionNotPresent, check, ["a", "b", "c"])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
948
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
949
    def test_impossible_parent(self):
950
        """Test we get KnitCorrupt if the parent couldn't possibly exist."""
951
        transport = MockTransport([
952
            _KnitIndex.HEADER,
953
            "a option 0 1 :",
954
            "b option 0 1 4 :"  # We don't have a 4th record
955
            ])
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
956
        try:
957
            self.assertRaises(errors.KnitCorrupt,
958
                              self.get_knit_index, transport, 'filename', 'r')
959
        except TypeError, e:
960
            if (str(e) == ('exceptions must be strings, classes, or instances,'
961
                           ' not exceptions.IndexError')
962
                and sys.version_info[0:2] >= (2,5)):
963
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
964
                                  ' raising new style exceptions with python'
965
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
966
            else:
967
                raise
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
968
969
    def test_corrupted_parent(self):
970
        transport = MockTransport([
971
            _KnitIndex.HEADER,
972
            "a option 0 1 :",
973
            "b option 0 1 :",
974
            "c option 0 1 1v :", # Can't have a parent of '1v'
975
            ])
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
976
        try:
977
            self.assertRaises(errors.KnitCorrupt,
978
                              self.get_knit_index, transport, 'filename', 'r')
979
        except TypeError, e:
980
            if (str(e) == ('exceptions must be strings, classes, or instances,'
981
                           ' not exceptions.ValueError')
982
                and sys.version_info[0:2] >= (2,5)):
983
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
984
                                  ' raising new style exceptions with python'
985
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
986
            else:
987
                raise
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
988
989
    def test_corrupted_parent_in_list(self):
990
        transport = MockTransport([
991
            _KnitIndex.HEADER,
992
            "a option 0 1 :",
993
            "b option 0 1 :",
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
994
            "c option 0 1 1 v :", # Can't have a parent of 'v'
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
995
            ])
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
996
        try:
997
            self.assertRaises(errors.KnitCorrupt,
998
                              self.get_knit_index, transport, 'filename', 'r')
999
        except TypeError, e:
1000
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1001
                           ' not exceptions.ValueError')
1002
                and sys.version_info[0:2] >= (2,5)):
1003
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1004
                                  ' raising new style exceptions with python'
1005
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1006
            else:
1007
                raise
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1008
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1009
    def test_invalid_position(self):
1010
        transport = MockTransport([
1011
            _KnitIndex.HEADER,
1012
            "a option 1v 1 :",
1013
            ])
1014
        try:
1015
            self.assertRaises(errors.KnitCorrupt,
1016
                              self.get_knit_index, transport, 'filename', 'r')
1017
        except TypeError, e:
1018
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1019
                           ' not exceptions.ValueError')
1020
                and sys.version_info[0:2] >= (2,5)):
1021
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1022
                                  ' raising new style exceptions with python'
1023
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1024
            else:
1025
                raise
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1026
1027
    def test_invalid_size(self):
1028
        transport = MockTransport([
1029
            _KnitIndex.HEADER,
1030
            "a option 1 1v :",
1031
            ])
1032
        try:
1033
            self.assertRaises(errors.KnitCorrupt,
1034
                              self.get_knit_index, transport, 'filename', 'r')
1035
        except TypeError, e:
1036
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1037
                           ' not exceptions.ValueError')
1038
                and sys.version_info[0:2] >= (2,5)):
1039
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1040
                                  ' raising new style exceptions with python'
1041
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1042
            else:
1043
                raise
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1044
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1045
    def test_short_line(self):
1046
        transport = MockTransport([
1047
            _KnitIndex.HEADER,
1048
            "a option 0 10  :",
1049
            "b option 10 10 0", # This line isn't terminated, ignored
1050
            ])
1051
        index = self.get_knit_index(transport, "filename", "r")
1052
        self.assertEqual(['a'], index.get_versions())
1053
1054
    def test_skip_incomplete_record(self):
1055
        # A line with bogus data should just be skipped
1056
        transport = MockTransport([
1057
            _KnitIndex.HEADER,
1058
            "a option 0 10  :",
1059
            "b option 10 10 0", # This line isn't terminated, ignored
1060
            "c option 20 10 0 :", # Properly terminated, and starts with '\n'
1061
            ])
1062
        index = self.get_knit_index(transport, "filename", "r")
1063
        self.assertEqual(['a', 'c'], index.get_versions())
1064
1065
    def test_trailing_characters(self):
1066
        # A line with bogus data should just be skipped
1067
        transport = MockTransport([
1068
            _KnitIndex.HEADER,
1069
            "a option 0 10  :",
1070
            "b option 10 10 0 :a", # This line has extra trailing characters
1071
            "c option 20 10 0 :", # Properly terminated, and starts with '\n'
1072
            ])
1073
        index = self.get_knit_index(transport, "filename", "r")
1074
        self.assertEqual(['a', 'c'], index.get_versions())
1075
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1076
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1077
class LowLevelKnitIndexTests_c(LowLevelKnitIndexTests):
1078
1079
    _test_needs_features = [CompiledKnitFeature]
1080
1081
    def get_knit_index(self, *args, **kwargs):
1082
        orig = knit._load_data
1083
        def reset():
1084
            knit._load_data = orig
1085
        self.addCleanup(reset)
2484.1.12 by John Arbash Meinel
Switch the layout to use a matching _knit_load_data_py.py and _knit_load_data_c.pyx
1086
        from bzrlib._knit_load_data_c import _load_data_c
1087
        knit._load_data = _load_data_c
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1088
        return _KnitIndex(*args, **kwargs)
1089
1090
1091
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
1092
class KnitTests(TestCaseWithTransport):
1093
    """Class containing knit test helper routines."""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1094
2535.3.27 by Andrew Bennetts
Merge from bzr.dev.
1095
    def make_test_knit(self, annotate=False, delay_create=False, index=None,
1096
                       name='test'):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1097
        if not annotate:
1098
            factory = KnitPlainFactory()
1099
        else:
1100
            factory = None
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1101
        return KnitVersionedFile(name, get_transport('.'), access_mode='w',
1946.2.1 by John Arbash Meinel
2 changes to knits. Delay creating the .knit or .kndx file until we have actually tried to write data. Because of this, we must allow the Knit to create the prefix directories
1102
                                 factory=factory, create=True,
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
1103
                                 delay_create=delay_create, index=index)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1104
2535.3.53 by Andrew Bennetts
Remove get_stream_as_bytes from KnitVersionedFile's API, make it a function in knitrepo.py instead.
1105
    def assertRecordContentEqual(self, knit, version_id, candidate_content):
1106
        """Assert that some raw record content matches the raw record content
1107
        for a particular version_id in the given knit.
1108
        """
1109
        index_memo = knit._index.get_position(version_id)
1110
        record = (version_id, index_memo)
1111
        [(_, expected_content)] = list(knit._data.read_records_iter_raw([record]))
1112
        self.assertEqual(expected_content, candidate_content)
1113
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
1114
1115
class BasicKnitTests(KnitTests):
1116
1117
    def add_stock_one_and_one_a(self, k):
1118
        k.add_lines('text-1', [], split_lines(TEXT_1))
1119
        k.add_lines('text-1a', ['text-1'], split_lines(TEXT_1A))
1120
1121
    def test_knit_constructor(self):
1122
        """Construct empty k"""
1123
        self.make_test_knit()
1124
2592.3.1 by Robert Collins
Allow giving KnitVersionedFile an index object to use rather than implicitly creating one.
1125
    def test_make_explicit_index(self):
1126
        """We can supply an index to use."""
1127
        knit = KnitVersionedFile('test', get_transport('.'),
1128
            index='strangelove')
1129
        self.assertEqual(knit._index, 'strangelove')
1130
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1131
    def test_knit_add(self):
1132
        """Store one text in knit and retrieve"""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1133
        k = self.make_test_knit()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1134
        k.add_lines('text-1', [], split_lines(TEXT_1))
1135
        self.assertTrue(k.has_version('text-1'))
1136
        self.assertEqualDiff(''.join(k.get_lines('text-1')), TEXT_1)
1137
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1138
    def test_newline_empty_lines(self):
1139
        # ensure that ["\n"] round trips ok.
1140
        knit = self.make_test_knit()
1141
        knit.add_lines('a', [], ["\n"])
1142
        knit.add_lines_with_ghosts('b', [], ["\n"])
1143
        self.assertEqual(["\n"], knit.get_lines('a'))
1144
        self.assertEqual(["\n"], knit.get_lines('b'))
1145
        self.assertEqual(['fulltext'], knit._index.get_options('a'))
1146
        self.assertEqual(['fulltext'], knit._index.get_options('b'))
1147
        knit.add_lines('c', ['a'], ["\n"])
1148
        knit.add_lines_with_ghosts('d', ['b'], ["\n"])
1149
        self.assertEqual(["\n"], knit.get_lines('c'))
1150
        self.assertEqual(["\n"], knit.get_lines('d'))
1151
        self.assertEqual(['line-delta'], knit._index.get_options('c'))
1152
        self.assertEqual(['line-delta'], knit._index.get_options('d'))
1153
1154
    def test_empty_lines(self):
1155
        # bizarrely, [] is not listed as having no-eol. 
1156
        knit = self.make_test_knit()
1157
        knit.add_lines('a', [], [])
1158
        knit.add_lines_with_ghosts('b', [], [])
1159
        self.assertEqual([], knit.get_lines('a'))
1160
        self.assertEqual([], knit.get_lines('b'))
1161
        self.assertEqual(['fulltext'], knit._index.get_options('a'))
1162
        self.assertEqual(['fulltext'], knit._index.get_options('b'))
1163
        knit.add_lines('c', ['a'], [])
1164
        knit.add_lines_with_ghosts('d', ['b'], [])
1165
        self.assertEqual([], knit.get_lines('c'))
1166
        self.assertEqual([], knit.get_lines('d'))
1167
        self.assertEqual(['line-delta'], knit._index.get_options('c'))
1168
        self.assertEqual(['line-delta'], knit._index.get_options('d'))
1169
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1170
    def test_knit_reload(self):
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1171
        # test that the content in a reloaded knit is correct
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1172
        k = self.make_test_knit()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1173
        k.add_lines('text-1', [], split_lines(TEXT_1))
1174
        del k
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1175
        k2 = KnitVersionedFile('test', get_transport('.'), access_mode='r', factory=KnitPlainFactory(), create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1176
        self.assertTrue(k2.has_version('text-1'))
1177
        self.assertEqualDiff(''.join(k2.get_lines('text-1')), TEXT_1)
1178
1179
    def test_knit_several(self):
1180
        """Store several texts in a knit"""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1181
        k = self.make_test_knit()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1182
        k.add_lines('text-1', [], split_lines(TEXT_1))
1183
        k.add_lines('text-2', [], split_lines(TEXT_2))
1184
        self.assertEqualDiff(''.join(k.get_lines('text-1')), TEXT_1)
1185
        self.assertEqualDiff(''.join(k.get_lines('text-2')), TEXT_2)
1186
        
1187
    def test_repeated_add(self):
1188
        """Knit traps attempt to replace existing version"""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1189
        k = self.make_test_knit()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1190
        k.add_lines('text-1', [], split_lines(TEXT_1))
1191
        self.assertRaises(RevisionAlreadyPresent, 
1192
                k.add_lines,
1193
                'text-1', [], split_lines(TEXT_1))
1194
1195
    def test_empty(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1196
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1197
        k.add_lines('text-1', [], [])
1198
        self.assertEquals(k.get_lines('text-1'), [])
1199
1200
    def test_incomplete(self):
1201
        """Test if texts without a ending line-end can be inserted and
1202
        extracted."""
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1203
        k = KnitVersionedFile('test', get_transport('.'), delta=False, create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1204
        k.add_lines('text-1', [], ['a\n',    'b'  ])
1205
        k.add_lines('text-2', ['text-1'], ['a\rb\n', 'b\n'])
1666.1.6 by Robert Collins
Make knit the default format.
1206
        # reopening ensures maximum room for confusion
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1207
        k = KnitVersionedFile('test', get_transport('.'), delta=False, create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1208
        self.assertEquals(k.get_lines('text-1'), ['a\n',    'b'  ])
1209
        self.assertEquals(k.get_lines('text-2'), ['a\rb\n', 'b\n'])
1210
1211
    def test_delta(self):
1212
        """Expression of knit delta as lines"""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1213
        k = self.make_test_knit()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1214
        td = list(line_delta(TEXT_1.splitlines(True),
1215
                             TEXT_1A.splitlines(True)))
1216
        self.assertEqualDiff(''.join(td), delta_1_1a)
1217
        out = apply_line_delta(TEXT_1.splitlines(True), td)
1218
        self.assertEqualDiff(''.join(out), TEXT_1A)
1219
1220
    def test_add_with_parents(self):
1221
        """Store in knit with parents"""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1222
        k = self.make_test_knit()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1223
        self.add_stock_one_and_one_a(k)
1224
        self.assertEquals(k.get_parents('text-1'), [])
1225
        self.assertEquals(k.get_parents('text-1a'), ['text-1'])
1226
1227
    def test_ancestry(self):
1228
        """Store in knit with parents"""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1229
        k = self.make_test_knit()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1230
        self.add_stock_one_and_one_a(k)
1231
        self.assertEquals(set(k.get_ancestry(['text-1a'])), set(['text-1a', 'text-1']))
1232
1233
    def test_add_delta(self):
1234
        """Store in knit with parents"""
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1235
        k = KnitVersionedFile('test', get_transport('.'), factory=KnitPlainFactory(),
1563.2.25 by Robert Collins
Merge in upstream.
1236
            delta=True, create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1237
        self.add_stock_one_and_one_a(k)
1596.2.7 by Robert Collins
Remove the requirement for reannotation in knit joins.
1238
        k.clear_cache()
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1239
        self.assertEqualDiff(''.join(k.get_lines('text-1a')), TEXT_1A)
1240
2592.3.21 by Robert Collins
Test using a KnitGraphIndex for storage.
1241
    def test_add_delta_knit_graph_index(self):
1242
        """Does adding work with a KnitGraphIndex."""
1243
        index = InMemoryGraphIndex(2)
1244
        knit_index = KnitGraphIndex(index, add_callback=index.add_nodes,
1245
            deltas=True)
1246
        k = KnitVersionedFile('test', get_transport('.'),
1247
            delta=True, create=True, index=knit_index)
1248
        self.add_stock_one_and_one_a(k)
1249
        k.clear_cache()
1250
        self.assertEqualDiff(''.join(k.get_lines('text-1a')), TEXT_1A)
1251
        # check the index had the right data added.
1252
        self.assertEqual(set([
2624.2.14 by Robert Collins
Add source index to the index iteration API to allow mapping back to the origin of retrieved data.
1253
            (index, ('text-1', ), ' 0 127', ((), ())),
1254
            (index, ('text-1a', ), ' 127 140', ((('text-1', ),), (('text-1', ),))),
2592.3.21 by Robert Collins
Test using a KnitGraphIndex for storage.
1255
            ]), set(index.iter_all_entries()))
1256
        # we should not have a .kndx file
1257
        self.assertFalse(get_transport('.').has('test.kndx'))
1258
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1259
    def test_annotate(self):
1260
        """Annotations"""
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1261
        k = KnitVersionedFile('knit', get_transport('.'), factory=KnitAnnotateFactory(),
1563.2.25 by Robert Collins
Merge in upstream.
1262
            delta=True, create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1263
        self.insert_and_test_small_annotate(k)
1264
1265
    def insert_and_test_small_annotate(self, k):
1266
        """test annotation with k works correctly."""
1267
        k.add_lines('text-1', [], ['a\n', 'b\n'])
1268
        k.add_lines('text-2', ['text-1'], ['a\n', 'c\n'])
1269
1270
        origins = k.annotate('text-2')
1271
        self.assertEquals(origins[0], ('text-1', 'a\n'))
1272
        self.assertEquals(origins[1], ('text-2', 'c\n'))
1273
1274
    def test_annotate_fulltext(self):
1275
        """Annotations"""
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1276
        k = KnitVersionedFile('knit', get_transport('.'), factory=KnitAnnotateFactory(),
1563.2.25 by Robert Collins
Merge in upstream.
1277
            delta=False, create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1278
        self.insert_and_test_small_annotate(k)
1279
1280
    def test_annotate_merge_1(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1281
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1282
        k.add_lines('text-a1', [], ['a\n', 'b\n'])
1283
        k.add_lines('text-a2', [], ['d\n', 'c\n'])
1284
        k.add_lines('text-am', ['text-a1', 'text-a2'], ['d\n', 'b\n'])
1285
        origins = k.annotate('text-am')
1286
        self.assertEquals(origins[0], ('text-a2', 'd\n'))
1287
        self.assertEquals(origins[1], ('text-a1', 'b\n'))
1288
1289
    def test_annotate_merge_2(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1290
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1291
        k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1292
        k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
1293
        k.add_lines('text-am', ['text-a1', 'text-a2'], ['a\n', 'y\n', 'c\n'])
1294
        origins = k.annotate('text-am')
1295
        self.assertEquals(origins[0], ('text-a1', 'a\n'))
1296
        self.assertEquals(origins[1], ('text-a2', 'y\n'))
1297
        self.assertEquals(origins[2], ('text-a1', 'c\n'))
1298
1299
    def test_annotate_merge_9(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1300
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1301
        k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1302
        k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
1303
        k.add_lines('text-am', ['text-a1', 'text-a2'], ['k\n', 'y\n', 'c\n'])
1304
        origins = k.annotate('text-am')
1305
        self.assertEquals(origins[0], ('text-am', 'k\n'))
1306
        self.assertEquals(origins[1], ('text-a2', 'y\n'))
1307
        self.assertEquals(origins[2], ('text-a1', 'c\n'))
1308
1309
    def test_annotate_merge_3(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1310
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1311
        k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1312
        k.add_lines('text-a2', [] ,['x\n', 'y\n', 'z\n'])
1313
        k.add_lines('text-am', ['text-a1', 'text-a2'], ['k\n', 'y\n', 'z\n'])
1314
        origins = k.annotate('text-am')
1315
        self.assertEquals(origins[0], ('text-am', 'k\n'))
1316
        self.assertEquals(origins[1], ('text-a2', 'y\n'))
1317
        self.assertEquals(origins[2], ('text-a2', 'z\n'))
1318
1319
    def test_annotate_merge_4(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1320
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1321
        k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1322
        k.add_lines('text-a2', [], ['x\n', 'y\n', 'z\n'])
1323
        k.add_lines('text-a3', ['text-a1'], ['a\n', 'b\n', 'p\n'])
1324
        k.add_lines('text-am', ['text-a2', 'text-a3'], ['a\n', 'b\n', 'z\n'])
1325
        origins = k.annotate('text-am')
1326
        self.assertEquals(origins[0], ('text-a1', 'a\n'))
1327
        self.assertEquals(origins[1], ('text-a1', 'b\n'))
1328
        self.assertEquals(origins[2], ('text-a2', 'z\n'))
1329
1330
    def test_annotate_merge_5(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1331
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1332
        k.add_lines('text-a1', [], ['a\n', 'b\n', 'c\n'])
1333
        k.add_lines('text-a2', [], ['d\n', 'e\n', 'f\n'])
1334
        k.add_lines('text-a3', [], ['x\n', 'y\n', 'z\n'])
1335
        k.add_lines('text-am',
1336
                    ['text-a1', 'text-a2', 'text-a3'],
1337
                    ['a\n', 'e\n', 'z\n'])
1338
        origins = k.annotate('text-am')
1339
        self.assertEquals(origins[0], ('text-a1', 'a\n'))
1340
        self.assertEquals(origins[1], ('text-a2', 'e\n'))
1341
        self.assertEquals(origins[2], ('text-a3', 'z\n'))
1342
1343
    def test_annotate_file_cherry_pick(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1344
        k = self.make_test_knit(True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1345
        k.add_lines('text-1', [], ['a\n', 'b\n', 'c\n'])
1346
        k.add_lines('text-2', ['text-1'], ['d\n', 'e\n', 'f\n'])
1347
        k.add_lines('text-3', ['text-2', 'text-1'], ['a\n', 'b\n', 'c\n'])
1348
        origins = k.annotate('text-3')
1349
        self.assertEquals(origins[0], ('text-1', 'a\n'))
1350
        self.assertEquals(origins[1], ('text-1', 'b\n'))
1351
        self.assertEquals(origins[2], ('text-1', 'c\n'))
1352
2851.4.6 by Ian Clatworthy
review tweaks
1353
    def _test_join_with_factories(self, k1_factory, k2_factory):
2851.4.1 by Ian Clatworthy
Support joining plain knits to annotated knits and vice versa
1354
        k1 = KnitVersionedFile('test1', get_transport('.'), factory=k1_factory, create=True)
1355
        k1.add_lines('text-a', [], ['a1\n', 'a2\n', 'a3\n'])
1356
        k1.add_lines('text-b', ['text-a'], ['a1\n', 'b2\n', 'a3\n'])
1357
        k1.add_lines('text-c', [], ['c1\n', 'c2\n', 'c3\n'])
1358
        k1.add_lines('text-d', ['text-c'], ['c1\n', 'd2\n', 'd3\n'])
1359
        k1.add_lines('text-m', ['text-b', 'text-d'], ['a1\n', 'b2\n', 'd3\n'])
1360
        k2 = KnitVersionedFile('test2', get_transport('.'), factory=k2_factory, create=True)
2851.4.6 by Ian Clatworthy
review tweaks
1361
        count = k2.join(k1, version_ids=['text-m'])
1362
        self.assertEquals(count, 5)
1363
        self.assertTrue(k2.has_version('text-a'))
1364
        self.assertTrue(k2.has_version('text-c'))
1365
        origins = k2.annotate('text-m')
1366
        self.assertEquals(origins[0], ('text-a', 'a1\n'))
1367
        self.assertEquals(origins[1], ('text-b', 'b2\n'))
1368
        self.assertEquals(origins[2], ('text-d', 'd3\n'))
2851.4.1 by Ian Clatworthy
Support joining plain knits to annotated knits and vice versa
1369
1370
    def test_knit_join_plain_to_plain(self):
1371
        """Test joining a plain knit with a plain knit."""
2851.4.6 by Ian Clatworthy
review tweaks
1372
        self._test_join_with_factories(KnitPlainFactory(), KnitPlainFactory())
2851.4.1 by Ian Clatworthy
Support joining plain knits to annotated knits and vice versa
1373
1374
    def test_knit_join_anno_to_anno(self):
1375
        """Test joining an annotated knit with an annotated knit."""
2851.4.6 by Ian Clatworthy
review tweaks
1376
        self._test_join_with_factories(None, None)
2851.4.1 by Ian Clatworthy
Support joining plain knits to annotated knits and vice versa
1377
1378
    def test_knit_join_anno_to_plain(self):
1379
        """Test joining an annotated knit with a plain knit."""
2851.4.6 by Ian Clatworthy
review tweaks
1380
        self._test_join_with_factories(None, KnitPlainFactory())
2851.4.1 by Ian Clatworthy
Support joining plain knits to annotated knits and vice versa
1381
1382
    def test_knit_join_plain_to_anno(self):
1383
        """Test joining a plain knit with an annotated knit."""
2851.4.6 by Ian Clatworthy
review tweaks
1384
        self._test_join_with_factories(KnitPlainFactory(), None)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1385
1386
    def test_reannotate(self):
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1387
        k1 = KnitVersionedFile('knit1', get_transport('.'),
1563.2.25 by Robert Collins
Merge in upstream.
1388
                               factory=KnitAnnotateFactory(), create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1389
        # 0
1390
        k1.add_lines('text-a', [], ['a\n', 'b\n'])
1391
        # 1
1392
        k1.add_lines('text-b', ['text-a'], ['a\n', 'c\n'])
1393
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1394
        k2 = KnitVersionedFile('test2', get_transport('.'),
1563.2.25 by Robert Collins
Merge in upstream.
1395
                               factory=KnitAnnotateFactory(), create=True)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1396
        k2.join(k1, version_ids=['text-b'])
1397
1398
        # 2
1399
        k1.add_lines('text-X', ['text-b'], ['a\n', 'b\n'])
1400
        # 2
1401
        k2.add_lines('text-c', ['text-b'], ['z\n', 'c\n'])
1402
        # 3
1403
        k2.add_lines('text-Y', ['text-b'], ['b\n', 'c\n'])
1404
1405
        # test-c will have index 3
1406
        k1.join(k2, version_ids=['text-c'])
1407
1408
        lines = k1.get_lines('text-c')
1409
        self.assertEquals(lines, ['z\n', 'c\n'])
1410
1411
        origins = k1.annotate('text-c')
1594.2.24 by Robert Collins
Make use of the transaction finalisation warning support to implement in-knit caching.
1412
        self.assertEquals(origins[0], ('text-c', 'z\n'))
1413
        self.assertEquals(origins[1], ('text-b', 'c\n'))
1414
1756.3.4 by Aaron Bentley
Fix bug getting texts when line deltas were reused
1415
    def test_get_line_delta_texts(self):
1416
        """Make sure we can call get_texts on text with reused line deltas"""
1417
        k1 = KnitVersionedFile('test1', get_transport('.'), 
1418
                               factory=KnitPlainFactory(), create=True)
1419
        for t in range(3):
1420
            if t == 0:
1421
                parents = []
1422
            else:
1423
                parents = ['%d' % (t-1)]
1424
            k1.add_lines('%d' % t, parents, ['hello\n'] * t)
1425
        k1.get_texts(('%d' % t) for t in range(3))
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
1426
        
1427
    def test_iter_lines_reads_in_order(self):
2745.5.3 by Robert Collins
* Move transport logging into a new transport class
1428
        instrumented_t = get_transport('trace+memory:///')
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
1429
        k1 = KnitVersionedFile('id', instrumented_t, create=True, delta=True)
2745.5.3 by Robert Collins
* Move transport logging into a new transport class
1430
        self.assertEqual([('get', 'id.kndx',)], instrumented_t._activity)
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
1431
        # add texts with no required ordering
1432
        k1.add_lines('base', [], ['text\n'])
1433
        k1.add_lines('base2', [], ['text2\n'])
1434
        k1.clear_cache()
2745.5.4 by Robert Collins
Review feedback.
1435
        # clear the logged activity, but preserve the list instance in case of
1436
        # clones pointing at it.
2745.5.3 by Robert Collins
* Move transport logging into a new transport class
1437
        del instrumented_t._activity[:]
1594.3.1 by Robert Collins
Merge transaction finalisation and ensure iter_lines_added_or_present in knits does a old-to-new read in the knit.
1438
        # request a last-first iteration
2745.5.3 by Robert Collins
* Move transport logging into a new transport class
1439
        results = list(k1.iter_lines_added_or_present_in_versions(
1440
            ['base2', 'base']))
2745.5.6 by Robert Collins
Fix knit test fallout from final readv api change.
1441
        self.assertEqual(
1442
            [('readv', 'id.knit', [(0, 87), (87, 89)], False, None)],
2745.5.3 by Robert Collins
* Move transport logging into a new transport class
1443
            instrumented_t._activity)
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
1444
        self.assertEqual([('text\n', 'base'), ('text2\n', 'base2')], results)
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1445
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1446
    def test_create_empty_annotated(self):
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1447
        k1 = self.make_test_knit(True)
1563.2.13 by Robert Collins
InterVersionedFile implemented.
1448
        # 0
1449
        k1.add_lines('text-a', [], ['a\n', 'b\n'])
1450
        k2 = k1.create_empty('t', MemoryTransport())
1451
        self.assertTrue(isinstance(k2.factory, KnitAnnotateFactory))
1452
        self.assertEqual(k1.delta, k2.delta)
1453
        # the generic test checks for empty content and file class
1454
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1455
    def test_knit_format(self):
1456
        # this tests that a new knit index file has the expected content
1457
        # and that is writes the data we expect as records are added.
1458
        knit = self.make_test_knit(True)
1946.2.1 by John Arbash Meinel
2 changes to knits. Delay creating the .knit or .kndx file until we have actually tried to write data. Because of this, we must allow the Knit to create the prefix directories
1459
        # Now knit files are not created until we first add data to them
1666.1.6 by Robert Collins
Make knit the default format.
1460
        self.assertFileEqual("# bzr knit index 8\n", 'test.kndx')
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1461
        knit.add_lines_with_ghosts('revid', ['a_ghost'], ['a\n'])
1462
        self.assertFileEqual(
1666.1.6 by Robert Collins
Make knit the default format.
1463
            "# bzr knit index 8\n"
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1464
            "\n"
1465
            "revid fulltext 0 84 .a_ghost :",
1466
            'test.kndx')
1467
        knit.add_lines_with_ghosts('revid2', ['revid'], ['a\n'])
1468
        self.assertFileEqual(
1666.1.6 by Robert Collins
Make knit the default format.
1469
            "# bzr knit index 8\n"
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1470
            "\nrevid fulltext 0 84 .a_ghost :"
1471
            "\nrevid2 line-delta 84 82 0 :",
1472
            'test.kndx')
1473
        # we should be able to load this file again
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1474
        knit = KnitVersionedFile('test', get_transport('.'), access_mode='r')
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1475
        self.assertEqual(['revid', 'revid2'], knit.versions())
1476
        # write a short write to the file and ensure that its ignored
2484.1.23 by John Arbash Meinel
When we append a new line, don't use text mode
1477
        indexfile = file('test.kndx', 'ab')
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1478
        indexfile.write('\nrevid3 line-delta 166 82 1 2 3 4 5 .phwoar:demo ')
1479
        indexfile.close()
1480
        # we should be able to load this file again
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1481
        knit = KnitVersionedFile('test', get_transport('.'), access_mode='w')
1654.1.5 by Robert Collins
Merge partial index write support for knits, adding a test case per review comments.
1482
        self.assertEqual(['revid', 'revid2'], knit.versions())
1483
        # and add a revision with the same id the failed write had
1484
        knit.add_lines('revid3', ['revid2'], ['a\n'])
1485
        # and when reading it revid3 should now appear.
1685.1.39 by John Arbash Meinel
Updating test_knit to not instantiate a LocalTransport directly.
1486
        knit = KnitVersionedFile('test', get_transport('.'), access_mode='r')
1654.1.5 by Robert Collins
Merge partial index write support for knits, adding a test case per review comments.
1487
        self.assertEqual(['revid', 'revid2', 'revid3'], knit.versions())
1488
        self.assertEqual(['revid2'], knit.get_parents('revid3'))
1489
1946.2.1 by John Arbash Meinel
2 changes to knits. Delay creating the .knit or .kndx file until we have actually tried to write data. Because of this, we must allow the Knit to create the prefix directories
1490
    def test_delay_create(self):
1491
        """Test that passing delay_create=True creates files late"""
1492
        knit = self.make_test_knit(annotate=True, delay_create=True)
1493
        self.failIfExists('test.knit')
1494
        self.failIfExists('test.kndx')
1495
        knit.add_lines_with_ghosts('revid', ['a_ghost'], ['a\n'])
1496
        self.failUnlessExists('test.knit')
1497
        self.assertFileEqual(
1498
            "# bzr knit index 8\n"
1499
            "\n"
1500
            "revid fulltext 0 84 .a_ghost :",
1501
            'test.kndx')
1502
1946.2.2 by John Arbash Meinel
test delay_create does the right thing
1503
    def test_create_parent_dir(self):
1504
        """create_parent_dir can create knits in nonexistant dirs"""
1505
        # Has no effect if we don't set 'delay_create'
1506
        trans = get_transport('.')
1507
        self.assertRaises(NoSuchFile, KnitVersionedFile, 'dir/test',
1508
                          trans, access_mode='w', factory=None,
1509
                          create=True, create_parent_dir=True)
1510
        # Nothing should have changed yet
1511
        knit = KnitVersionedFile('dir/test', trans, access_mode='w',
1512
                                 factory=None, create=True,
1513
                                 create_parent_dir=True,
1514
                                 delay_create=True)
1515
        self.failIfExists('dir/test.knit')
1516
        self.failIfExists('dir/test.kndx')
1517
        self.failIfExists('dir')
1518
        knit.add_lines('revid', [], ['a\n'])
1519
        self.failUnlessExists('dir')
1520
        self.failUnlessExists('dir/test.knit')
1521
        self.assertFileEqual(
1522
            "# bzr knit index 8\n"
1523
            "\n"
1524
            "revid fulltext 0 84  :",
1525
            'dir/test.kndx')
1526
1946.2.13 by John Arbash Meinel
Test that passing modes does the right thing for knits.
1527
    def test_create_mode_700(self):
1528
        trans = get_transport('.')
1529
        if not trans._can_roundtrip_unix_modebits():
1530
            # Can't roundtrip, so no need to run this test
1531
            return
1532
        knit = KnitVersionedFile('dir/test', trans, access_mode='w',
1533
                                 factory=None, create=True,
1534
                                 create_parent_dir=True,
1535
                                 delay_create=True,
1536
                                 file_mode=0600,
1537
                                 dir_mode=0700)
1538
        knit.add_lines('revid', [], ['a\n'])
1539
        self.assertTransportMode(trans, 'dir', 0700)
1540
        self.assertTransportMode(trans, 'dir/test.knit', 0600)
1541
        self.assertTransportMode(trans, 'dir/test.kndx', 0600)
1542
1543
    def test_create_mode_770(self):
1544
        trans = get_transport('.')
1545
        if not trans._can_roundtrip_unix_modebits():
1546
            # Can't roundtrip, so no need to run this test
1547
            return
1548
        knit = KnitVersionedFile('dir/test', trans, access_mode='w',
1549
                                 factory=None, create=True,
1550
                                 create_parent_dir=True,
1551
                                 delay_create=True,
1552
                                 file_mode=0660,
1553
                                 dir_mode=0770)
1554
        knit.add_lines('revid', [], ['a\n'])
1555
        self.assertTransportMode(trans, 'dir', 0770)
1556
        self.assertTransportMode(trans, 'dir/test.knit', 0660)
1557
        self.assertTransportMode(trans, 'dir/test.kndx', 0660)
1558
1559
    def test_create_mode_777(self):
1560
        trans = get_transport('.')
1561
        if not trans._can_roundtrip_unix_modebits():
1562
            # Can't roundtrip, so no need to run this test
1563
            return
1564
        knit = KnitVersionedFile('dir/test', trans, access_mode='w',
1565
                                 factory=None, create=True,
1566
                                 create_parent_dir=True,
1567
                                 delay_create=True,
1568
                                 file_mode=0666,
1569
                                 dir_mode=0777)
1570
        knit.add_lines('revid', [], ['a\n'])
1571
        self.assertTransportMode(trans, 'dir', 0777)
1572
        self.assertTransportMode(trans, 'dir/test.knit', 0666)
1573
        self.assertTransportMode(trans, 'dir/test.kndx', 0666)
1574
1664.2.1 by Aaron Bentley
Start work on plan_merge test
1575
    def test_plan_merge(self):
1576
        my_knit = self.make_test_knit(annotate=True)
1577
        my_knit.add_lines('text1', [], split_lines(TEXT_1))
1578
        my_knit.add_lines('text1a', ['text1'], split_lines(TEXT_1A))
1579
        my_knit.add_lines('text1b', ['text1'], split_lines(TEXT_1B))
1664.2.3 by Aaron Bentley
Add failing test case
1580
        plan = list(my_knit.plan_merge('text1a', 'text1b'))
1664.2.6 by Aaron Bentley
Got plan-merge passing tests
1581
        for plan_line, expected_line in zip(plan, AB_MERGE):
1582
            self.assertEqual(plan_line, expected_line)
1641.1.2 by Robert Collins
Change knit index files to be robust in the presence of partial writes.
1583
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1584
    def test_get_stream_empty(self):
1585
        """Get a data stream for an empty knit file."""
1586
        k1 = self.make_test_knit()
1587
        format, data_list, reader_callable = k1.get_data_stream([])
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1588
        self.assertEqual('knit-plain', format)
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1589
        self.assertEqual([], data_list)
1590
        content = reader_callable(None)
1591
        self.assertEqual('', content)
1592
        self.assertIsInstance(content, str)
1593
1594
    def test_get_stream_one_version(self):
1595
        """Get a data stream for a single record out of a knit containing just
1596
        one record.
1597
        """
1598
        k1 = self.make_test_knit()
1599
        test_data = [
1600
            ('text-a', [], TEXT_1),
1601
            ]
1602
        expected_data_list = [
1603
            # version, options, length, parents
1604
            ('text-a', ['fulltext'], 122, []),
1605
           ]
1606
        for version_id, parents, lines in test_data:
1607
            k1.add_lines(version_id, parents, split_lines(lines))
1608
1609
        format, data_list, reader_callable = k1.get_data_stream(['text-a'])
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1610
        self.assertEqual('knit-plain', format)
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1611
        self.assertEqual(expected_data_list, data_list)
1612
        # There's only one record in the knit, so the content should be the
1613
        # entire knit data file's contents.
2535.3.36 by Andrew Bennetts
Merge bzr.dev
1614
        self.assertEqual(k1.transport.get_bytes(k1._data._access._filename),
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1615
                         reader_callable(None))
1616
        
1617
    def test_get_stream_get_one_version_of_many(self):
1618
        """Get a data stream for just one version out of a knit containing many
1619
        versions.
1620
        """
1621
        k1 = self.make_test_knit()
1622
        # Insert the same data as test_knit_join, as they seem to cover a range
1623
        # of cases (no parents, one parent, multiple parents).
1624
        test_data = [
1625
            ('text-a', [], TEXT_1),
1626
            ('text-b', ['text-a'], TEXT_1),
1627
            ('text-c', [], TEXT_1),
1628
            ('text-d', ['text-c'], TEXT_1),
1629
            ('text-m', ['text-b', 'text-d'], TEXT_1),
1630
            ]
1631
        expected_data_list = [
1632
            # version, options, length, parents
1633
            ('text-m', ['line-delta'], 84, ['text-b', 'text-d']),
1634
            ]
1635
        for version_id, parents, lines in test_data:
1636
            k1.add_lines(version_id, parents, split_lines(lines))
1637
1638
        format, data_list, reader_callable = k1.get_data_stream(['text-m'])
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1639
        self.assertEqual('knit-plain', format)
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1640
        self.assertEqual(expected_data_list, data_list)
1641
        self.assertRecordContentEqual(k1, 'text-m', reader_callable(None))
1642
        
3023.2.2 by Martin Pool
Fix KnitVersionedFile.get_data_stream to not assume .versions() is sorted. (lp:165106)
1643
    def test_get_data_stream_unordered_index(self):
1644
        """Get a data stream when the knit index reports versions out of order.
1645
1646
        https://bugs.launchpad.net/bzr/+bug/164637
1647
        """
1648
        k1 = self.make_test_knit()
1649
        test_data = [
1650
            ('text-a', [], TEXT_1),
1651
            ('text-b', ['text-a'], TEXT_1),
1652
            ('text-c', [], TEXT_1),
1653
            ('text-d', ['text-c'], TEXT_1),
1654
            ('text-m', ['text-b', 'text-d'], TEXT_1),
1655
            ]
1656
        for version_id, parents, lines in test_data:
1657
            k1.add_lines(version_id, parents, split_lines(lines))
1658
        # monkey-patch versions method to return out of order, as if coming
1659
        # from multiple independently indexed packs
1660
        original_versions = k1.versions
1661
        k1.versions = lambda: reversed(original_versions())
1662
        expected_data_list = [
1663
            ('text-a', ['fulltext'], 122, []),
1664
            ('text-b', ['line-delta'], 84, ['text-a'])]
1665
        # now check the fulltext is first and the delta second
1666
        format, data_list, _ = k1.get_data_stream(['text-a', 'text-b'])
1667
        self.assertEqual('knit-plain', format)
1668
        self.assertEqual(expected_data_list, data_list)
1669
        # and that's true if we ask for them in the opposite order too
1670
        format, data_list, _ = k1.get_data_stream(['text-b', 'text-a'])
1671
        self.assertEqual(expected_data_list, data_list)
1672
        # also try requesting more versions
1673
        format, data_list, _ = k1.get_data_stream([
1674
            'text-m', 'text-b', 'text-a'])
1675
        self.assertEqual([
1676
            ('text-a', ['fulltext'], 122, []),
1677
            ('text-b', ['line-delta'], 84, ['text-a']),
1678
            ('text-m', ['line-delta'], 84, ['text-b', 'text-d']),
1679
            ], data_list)
1680
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1681
    def test_get_stream_ghost_parent(self):
1682
        """Get a data stream for a version with a ghost parent."""
1683
        k1 = self.make_test_knit()
1684
        # Test data
1685
        k1.add_lines('text-a', [], split_lines(TEXT_1))
1686
        k1.add_lines_with_ghosts('text-b', ['text-a', 'text-ghost'],
1687
                                 split_lines(TEXT_1))
1688
        # Expected data
1689
        expected_data_list = [
1690
            # version, options, length, parents
1691
            ('text-b', ['line-delta'], 84, ['text-a', 'text-ghost']),
1692
            ]
1693
        
1694
        format, data_list, reader_callable = k1.get_data_stream(['text-b'])
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1695
        self.assertEqual('knit-plain', format)
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1696
        self.assertEqual(expected_data_list, data_list)
1697
        self.assertRecordContentEqual(k1, 'text-b', reader_callable(None))
1698
    
1699
    def test_get_stream_get_multiple_records(self):
1700
        """Get a stream for multiple records of a knit."""
1701
        k1 = self.make_test_knit()
1702
        # Insert the same data as test_knit_join, as they seem to cover a range
1703
        # of cases (no parents, one parent, multiple parents).
1704
        test_data = [
1705
            ('text-a', [], TEXT_1),
1706
            ('text-b', ['text-a'], TEXT_1),
1707
            ('text-c', [], TEXT_1),
1708
            ('text-d', ['text-c'], TEXT_1),
1709
            ('text-m', ['text-b', 'text-d'], TEXT_1),
1710
            ]
3023.2.3 by Martin Pool
Update tests for new ordering of results from get_data_stream - the order is not defined by the interface, but is stable
1711
        for version_id, parents, lines in test_data:
1712
            k1.add_lines(version_id, parents, split_lines(lines))
1713
1714
        # This test is actually a bit strict as the order in which they're
1715
        # returned is not defined.  This matches the current (deterministic)
1716
        # behaviour.
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1717
        expected_data_list = [
1718
            # version, options, length, parents
3023.2.3 by Martin Pool
Update tests for new ordering of results from get_data_stream - the order is not defined by the interface, but is stable
1719
            ('text-d', ['line-delta'], 84, ['text-c']),
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1720
            ('text-b', ['line-delta'], 84, ['text-a']),
1721
            ]
1722
        # Note that even though we request the revision IDs in a particular
1723
        # order, the data stream may return them in any order it likes.  In this
1724
        # case, they'll be in the order they were inserted into the knit.
1725
        format, data_list, reader_callable = k1.get_data_stream(
1726
            ['text-d', 'text-b'])
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1727
        self.assertEqual('knit-plain', format)
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1728
        self.assertEqual(expected_data_list, data_list)
3023.2.3 by Martin Pool
Update tests for new ordering of results from get_data_stream - the order is not defined by the interface, but is stable
1729
        # must match order they're returned
1730
        self.assertRecordContentEqual(k1, 'text-d', reader_callable(84))
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1731
        self.assertRecordContentEqual(k1, 'text-b', reader_callable(84))
1732
        self.assertEqual('', reader_callable(None),
1733
                         "There should be no more bytes left to read.")
1734
1735
    def test_get_stream_all(self):
1736
        """Get a data stream for all the records in a knit.
1737
1738
        This exercises fulltext records, line-delta records, records with
1739
        various numbers of parents, and reading multiple records out of the
1740
        callable.  These cases ought to all be exercised individually by the
1741
        other test_get_stream_* tests; this test is basically just paranoia.
1742
        """
1743
        k1 = self.make_test_knit()
1744
        # Insert the same data as test_knit_join, as they seem to cover a range
1745
        # of cases (no parents, one parent, multiple parents).
1746
        test_data = [
1747
            ('text-a', [], TEXT_1),
1748
            ('text-b', ['text-a'], TEXT_1),
1749
            ('text-c', [], TEXT_1),
1750
            ('text-d', ['text-c'], TEXT_1),
1751
            ('text-m', ['text-b', 'text-d'], TEXT_1),
1752
           ]
3023.2.3 by Martin Pool
Update tests for new ordering of results from get_data_stream - the order is not defined by the interface, but is stable
1753
        for version_id, parents, lines in test_data:
1754
            k1.add_lines(version_id, parents, split_lines(lines))
1755
1756
        # This test is actually a bit strict as the order in which they're
1757
        # returned is not defined.  This matches the current (deterministic)
1758
        # behaviour.
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1759
        expected_data_list = [
1760
            # version, options, length, parents
1761
            ('text-a', ['fulltext'], 122, []),
1762
            ('text-b', ['line-delta'], 84, ['text-a']),
3023.2.3 by Martin Pool
Update tests for new ordering of results from get_data_stream - the order is not defined by the interface, but is stable
1763
            ('text-m', ['line-delta'], 84, ['text-b', 'text-d']),
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1764
            ('text-c', ['fulltext'], 121, []),
1765
            ('text-d', ['line-delta'], 84, ['text-c']),
1766
            ]
1767
        format, data_list, reader_callable = k1.get_data_stream(
1768
            ['text-a', 'text-b', 'text-c', 'text-d', 'text-m'])
2535.3.17 by Andrew Bennetts
[broken] Closer to a working Repository.fetch_revisions smart request.
1769
        self.assertEqual('knit-plain', format)
2535.3.3 by Andrew Bennetts
Add Knit.get_data_stream.
1770
        self.assertEqual(expected_data_list, data_list)
1771
        for version_id, options, length, parents in expected_data_list:
1772
            bytes = reader_callable(length)
1773
            self.assertRecordContentEqual(k1, version_id, bytes)
1774
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1775
    def assertKnitFilesEqual(self, knit1, knit2):
1776
        """Assert that the contents of the index and data files of two knits are
1777
        equal.
1778
        """
1779
        self.assertEqual(
2535.3.36 by Andrew Bennetts
Merge bzr.dev
1780
            knit1.transport.get_bytes(knit1._data._access._filename),
1781
            knit2.transport.get_bytes(knit2._data._access._filename))
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1782
        self.assertEqual(
1783
            knit1.transport.get_bytes(knit1._index._filename),
1784
            knit2.transport.get_bytes(knit2._index._filename))
1785
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1786
    def assertKnitValuesEqual(self, left, right):
3052.2.5 by Andrew Bennetts
Address the rest of the review comments from John and myself.
1787
        """Assert that the texts, annotations and graph of left and right are
1788
        the same.
1789
        """
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1790
        self.assertEqual(set(left.versions()), set(right.versions()))
1791
        for version in left.versions():
1792
            self.assertEqual(left.get_parents_with_ghosts(version),
1793
                right.get_parents_with_ghosts(version))
1794
            self.assertEqual(left.get_lines(version),
1795
                right.get_lines(version))
1796
            self.assertEqual(left.annotate(version),
1797
                right.annotate(version))
1798
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1799
    def test_insert_data_stream_empty(self):
1800
        """Inserting a data stream with no records should not put any data into
1801
        the knit.
1802
        """
1803
        k1 = self.make_test_knit()
1804
        k1.insert_data_stream(
1805
            (k1.get_format_signature(), [], lambda ignored: ''))
2535.3.36 by Andrew Bennetts
Merge bzr.dev
1806
        self.assertEqual('', k1.transport.get_bytes(k1._data._access._filename),
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1807
                         "The .knit should be completely empty.")
1808
        self.assertEqual(k1._index.HEADER,
1809
                         k1.transport.get_bytes(k1._index._filename),
1810
                         "The .kndx should have nothing apart from the header.")
1811
1812
    def test_insert_data_stream_one_record(self):
1813
        """Inserting a data stream with one record from a knit with one record
1814
        results in byte-identical files.
1815
        """
1816
        source = self.make_test_knit(name='source')
1817
        source.add_lines('text-a', [], split_lines(TEXT_1))
1818
        data_stream = source.get_data_stream(['text-a'])
1819
        target = self.make_test_knit(name='target')
1820
        target.insert_data_stream(data_stream)
1821
        self.assertKnitFilesEqual(source, target)
1822
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1823
    def test_insert_data_stream_annotated_unannotated(self):
1824
        """Inserting an annotated datastream to an unannotated knit works."""
1825
        # case one - full texts.
1826
        source = self.make_test_knit(name='source', annotate=True)
1827
        target = self.make_test_knit(name='target', annotate=False)
1828
        source.add_lines('text-a', [], split_lines(TEXT_1))
1829
        target.insert_data_stream(source.get_data_stream(['text-a']))
1830
        self.assertKnitValuesEqual(source, target)
1831
        # case two - deltas.
1832
        source.add_lines('text-b', ['text-a'], split_lines(TEXT_2))
1833
        target.insert_data_stream(source.get_data_stream(['text-b']))
1834
        self.assertKnitValuesEqual(source, target)
1835
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
1836
    def test_insert_data_stream_unannotated_annotated(self):
1837
        """Inserting an unannotated datastream to an annotated knit works."""
1838
        # case one - full texts.
1839
        source = self.make_test_knit(name='source', annotate=False)
1840
        target = self.make_test_knit(name='target', annotate=True)
1841
        source.add_lines('text-a', [], split_lines(TEXT_1))
1842
        target.insert_data_stream(source.get_data_stream(['text-a']))
1843
        self.assertKnitValuesEqual(source, target)
1844
        # case two - deltas.
1845
        source.add_lines('text-b', ['text-a'], split_lines(TEXT_2))
1846
        target.insert_data_stream(source.get_data_stream(['text-b']))
1847
        self.assertKnitValuesEqual(source, target)
1848
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1849
    def test_insert_data_stream_records_already_present(self):
1850
        """Insert a data stream where some records are alreday present in the
1851
        target, and some not.  Only the new records are inserted.
1852
        """
1853
        source = self.make_test_knit(name='source')
1854
        target = self.make_test_knit(name='target')
1855
        # Insert 'text-a' into both source and target
1856
        source.add_lines('text-a', [], split_lines(TEXT_1))
1857
        target.insert_data_stream(source.get_data_stream(['text-a']))
1858
        # Insert 'text-b' into just the source.
1859
        source.add_lines('text-b', ['text-a'], split_lines(TEXT_1))
1860
        # Get a data stream of both text-a and text-b, and insert it.
1861
        data_stream = source.get_data_stream(['text-a', 'text-b'])
1862
        target.insert_data_stream(data_stream)
1863
        # The source and target will now be identical.  This means the text-a
1864
        # record was not added a second time.
1865
        self.assertKnitFilesEqual(source, target)
1866
1867
    def test_insert_data_stream_multiple_records(self):
1868
        """Inserting a data stream of all records from a knit with multiple
1869
        records results in byte-identical files.
1870
        """
1871
        source = self.make_test_knit(name='source')
1872
        source.add_lines('text-a', [], split_lines(TEXT_1))
1873
        source.add_lines('text-b', ['text-a'], split_lines(TEXT_1))
1874
        source.add_lines('text-c', [], split_lines(TEXT_1))
1875
        data_stream = source.get_data_stream(['text-a', 'text-b', 'text-c'])
1876
        
1877
        target = self.make_test_knit(name='target')
1878
        target.insert_data_stream(data_stream)
1879
        
1880
        self.assertKnitFilesEqual(source, target)
1881
1882
    def test_insert_data_stream_ghost_parent(self):
1883
        """Insert a data stream with a record that has a ghost parent."""
1884
        # Make a knit with a record, text-a, that has a ghost parent.
1885
        source = self.make_test_knit(name='source')
1886
        source.add_lines_with_ghosts('text-a', ['text-ghost'],
1887
                                     split_lines(TEXT_1))
1888
        data_stream = source.get_data_stream(['text-a'])
1889
1890
        target = self.make_test_knit(name='target')
1891
        target.insert_data_stream(data_stream)
1892
1893
        self.assertKnitFilesEqual(source, target)
1894
1895
        # The target knit object is in a consistent state, i.e. the record we
1896
        # just added is immediately visible.
1897
        self.assertTrue(target.has_version('text-a'))
1898
        self.assertTrue(target.has_ghost('text-ghost'))
1899
        self.assertEqual(split_lines(TEXT_1), target.get_lines('text-a'))
1900
1901
    def test_insert_data_stream_inconsistent_version_lines(self):
1902
        """Inserting a data stream which has different content for a version_id
1903
        than already exists in the knit will raise KnitCorrupt.
1904
        """
1905
        source = self.make_test_knit(name='source')
1906
        target = self.make_test_knit(name='target')
1907
        # Insert a different 'text-a' into both source and target
1908
        source.add_lines('text-a', [], split_lines(TEXT_1))
1909
        target.add_lines('text-a', [], split_lines(TEXT_2))
1910
        # Insert a data stream with conflicting content into the target
1911
        data_stream = source.get_data_stream(['text-a'])
1912
        self.assertRaises(
1913
            errors.KnitCorrupt, target.insert_data_stream, data_stream)
1914
1915
    def test_insert_data_stream_inconsistent_version_parents(self):
1916
        """Inserting a data stream which has different parents for a version_id
1917
        than already exists in the knit will raise KnitCorrupt.
1918
        """
1919
        source = self.make_test_knit(name='source')
1920
        target = self.make_test_knit(name='target')
1921
        # Insert a different 'text-a' into both source and target.  They differ
1922
        # only by the parents list, the content is the same.
1923
        source.add_lines_with_ghosts('text-a', [], split_lines(TEXT_1))
1924
        target.add_lines_with_ghosts('text-a', ['a-ghost'], split_lines(TEXT_1))
1925
        # Insert a data stream with conflicting content into the target
1926
        data_stream = source.get_data_stream(['text-a'])
1927
        self.assertRaises(
1928
            errors.KnitCorrupt, target.insert_data_stream, data_stream)
1929
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1930
    def test_insert_data_stream_unknown_format(self):
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1931
        """A data stream in a different format to the target knit cannot be
1932
        inserted.
1933
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1934
        It will raise KnitDataStreamUnknown because the fallback code will fail
1935
        to make a knit. In future we may need KnitDataStreamIncompatible again,
1936
        for more exotic cases.
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1937
        """
1938
        data_stream = ('fake-format-signature', [], lambda _: '')
1939
        target = self.make_test_knit(name='target')
1940
        self.assertRaises(
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1941
            errors.KnitDataStreamUnknown,
2535.3.4 by Andrew Bennetts
Simple implementation of Knit.insert_data_stream.
1942
            target.insert_data_stream, data_stream)
1943
2535.3.5 by Andrew Bennetts
Batch writes as much as possible in insert_data_stream.
1944
    #  * test that a stream of "already present version, then new version"
1945
    #    inserts correctly.
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1946
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1947
1948
    def assertMadeStreamKnit(self, source_knit, versions, target_knit):
1949
        """Assert that a knit made from a stream is as expected."""
1950
        a_stream = source_knit.get_data_stream(versions)
1951
        expected_data = a_stream[2](None)
1952
        a_stream = source_knit.get_data_stream(versions)
1953
        a_knit = target_knit._knit_from_datastream(a_stream)
1954
        self.assertEqual(source_knit.factory.__class__,
1955
            a_knit.factory.__class__)
1956
        self.assertIsInstance(a_knit._data._access, _StreamAccess)
1957
        self.assertIsInstance(a_knit._index, _StreamIndex)
1958
        self.assertEqual(a_knit._index.data_list, a_stream[1])
1959
        self.assertEqual(a_knit._data._access.data, expected_data)
1960
        self.assertEqual(a_knit.filename, target_knit.filename)
1961
        self.assertEqual(a_knit.transport, target_knit.transport)
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
1962
        self.assertEqual(a_knit._index, a_knit._data._access.stream_index)
1963
        self.assertEqual(target_knit, a_knit._data._access.backing_knit)
1964
        self.assertIsInstance(a_knit._data._access.orig_factory,
1965
            source_knit.factory.__class__)
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
1966
1967
    def test__knit_from_data_stream_empty(self):
1968
        """Create a knit object from a datastream."""
1969
        annotated = self.make_test_knit(name='source', annotate=True)
1970
        plain = self.make_test_knit(name='target', annotate=False)
1971
        # case 1: annotated source
1972
        self.assertMadeStreamKnit(annotated, [], annotated)
1973
        self.assertMadeStreamKnit(annotated, [], plain)
1974
        # case 2: plain source
1975
        self.assertMadeStreamKnit(plain, [], annotated)
1976
        self.assertMadeStreamKnit(plain, [], plain)
1977
1978
    def test__knit_from_data_stream_unknown_format(self):
1979
        annotated = self.make_test_knit(name='source', annotate=True)
1980
        self.assertRaises(errors.KnitDataStreamUnknown,
1981
            annotated._knit_from_datastream, ("unknown", None, None))
1982
1983
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
1984
TEXT_1 = """\
1985
Banana cup cakes:
1986
1987
- bananas
1988
- eggs
1989
- broken tea cups
1990
"""
1991
1992
TEXT_1A = """\
1993
Banana cup cake recipe
1994
(serves 6)
1995
1996
- bananas
1997
- eggs
1998
- broken tea cups
1999
- self-raising flour
2000
"""
2001
1664.2.1 by Aaron Bentley
Start work on plan_merge test
2002
TEXT_1B = """\
2003
Banana cup cake recipe
2004
2005
- bananas (do not use plantains!!!)
2006
- broken tea cups
2007
- flour
2008
"""
2009
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2010
delta_1_1a = """\
2011
0,1,2
2012
Banana cup cake recipe
2013
(serves 6)
2014
5,5,1
2015
- self-raising flour
2016
"""
2017
2018
TEXT_2 = """\
2019
Boeuf bourguignon
2020
2021
- beef
2022
- red wine
2023
- small onions
2024
- carrot
2025
- mushrooms
2026
"""
2027
1664.2.3 by Aaron Bentley
Add failing test case
2028
AB_MERGE_TEXT="""unchanged|Banana cup cake recipe
2029
new-a|(serves 6)
2030
unchanged|
2031
killed-b|- bananas
2032
killed-b|- eggs
2033
new-b|- bananas (do not use plantains!!!)
2034
unchanged|- broken tea cups
2035
new-a|- self-raising flour
1664.2.6 by Aaron Bentley
Got plan-merge passing tests
2036
new-b|- flour
2037
"""
1664.2.3 by Aaron Bentley
Add failing test case
2038
AB_MERGE=[tuple(l.split('|')) for l in AB_MERGE_TEXT.splitlines(True)]
2039
2040
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
2041
def line_delta(from_lines, to_lines):
2042
    """Generate line-based delta from one text to another"""
2043
    s = difflib.SequenceMatcher(None, from_lines, to_lines)
2044
    for op in s.get_opcodes():
2045
        if op[0] == 'equal':
2046
            continue
2047
        yield '%d,%d,%d\n' % (op[1], op[2], op[4]-op[3])
2048
        for i in range(op[3], op[4]):
2049
            yield to_lines[i]
2050
2051
2052
def apply_line_delta(basis_lines, delta_lines):
2053
    """Apply a line-based perfect diff
2054
    
2055
    basis_lines -- text to apply the patch to
2056
    delta_lines -- diff instructions and content
2057
    """
2058
    out = basis_lines[:]
2059
    i = 0
2060
    offset = 0
2061
    while i < len(delta_lines):
2062
        l = delta_lines[i]
2063
        a, b, c = map(long, l.split(','))
2064
        i = i + 1
2065
        out[offset+a:offset+b] = delta_lines[i:i+c]
2066
        i = i + c
2067
        offset = offset + (b - a) + c
2068
    return out
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
2069
2070
2071
class TestWeaveToKnit(KnitTests):
2072
2073
    def test_weave_to_knit_matches(self):
2074
        # check that the WeaveToKnit is_compatible function
2075
        # registers True for a Weave to a Knit.
2076
        w = Weave()
2077
        k = self.make_test_knit()
2078
        self.failUnless(WeaveToKnit.is_compatible(w, k))
2079
        self.failIf(WeaveToKnit.is_compatible(k, w))
2080
        self.failIf(WeaveToKnit.is_compatible(w, w))
2081
        self.failIf(WeaveToKnit.is_compatible(k, k))
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
2082
2083
2084
class TestKnitCaching(KnitTests):
2085
    
2850.1.1 by Robert Collins
* ``KnitVersionedFile.add*`` will no longer cache added records even when
2086
    def create_knit(self):
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
2087
        k = self.make_test_knit(True)
2088
        k.add_lines('text-1', [], split_lines(TEXT_1))
2089
        k.add_lines('text-2', [], split_lines(TEXT_2))
2090
        return k
2091
2092
    def test_no_caching(self):
2093
        k = self.create_knit()
2094
        # Nothing should be cached without setting 'enable_cache'
2095
        self.assertEqual({}, k._data._cache)
2096
2097
    def test_cache_data_read_raw(self):
2098
        k = self.create_knit()
2099
2100
        # Now cache and read
2101
        k.enable_cache()
2102
2103
        def read_one_raw(version):
2104
            pos_map = k._get_components_positions([version])
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2105
            method, index_memo, next = pos_map[version]
2106
            lst = list(k._data.read_records_iter_raw([(version, index_memo)]))
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
2107
            self.assertEqual(1, len(lst))
2108
            return lst[0]
2109
2110
        val = read_one_raw('text-1')
1863.1.8 by John Arbash Meinel
Removing disk-backed-cache
2111
        self.assertEqual({'text-1':val[1]}, k._data._cache)
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
2112
2113
        k.clear_cache()
2114
        # After clear, new reads are not cached
2115
        self.assertEqual({}, k._data._cache)
2116
2117
        val2 = read_one_raw('text-1')
2118
        self.assertEqual(val, val2)
2119
        self.assertEqual({}, k._data._cache)
2120
2121
    def test_cache_data_read(self):
2122
        k = self.create_knit()
2123
2124
        def read_one(version):
2125
            pos_map = k._get_components_positions([version])
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2126
            method, index_memo, next = pos_map[version]
2127
            lst = list(k._data.read_records_iter([(version, index_memo)]))
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
2128
            self.assertEqual(1, len(lst))
2129
            return lst[0]
2130
2131
        # Now cache and read
2132
        k.enable_cache()
2133
2134
        val = read_one('text-2')
2135
        self.assertEqual(['text-2'], k._data._cache.keys())
2136
        self.assertEqual('text-2', val[0])
2137
        content, digest = k._data._parse_record('text-2',
2138
                                                k._data._cache['text-2'])
2139
        self.assertEqual(content, val[1])
2140
        self.assertEqual(digest, val[2])
2141
2142
        k.clear_cache()
2143
        self.assertEqual({}, k._data._cache)
2144
2145
        val2 = read_one('text-2')
2146
        self.assertEqual(val, val2)
2147
        self.assertEqual({}, k._data._cache)
2148
2149
    def test_cache_read(self):
2150
        k = self.create_knit()
2151
        k.enable_cache()
2152
2153
        text = k.get_text('text-1')
2154
        self.assertEqual(TEXT_1, text)
2155
        self.assertEqual(['text-1'], k._data._cache.keys())
2156
2157
        k.clear_cache()
2158
        self.assertEqual({}, k._data._cache)
2159
2160
        text = k.get_text('text-1')
2161
        self.assertEqual(TEXT_1, text)
2162
        self.assertEqual({}, k._data._cache)
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
2163
2164
2165
class TestKnitIndex(KnitTests):
2166
2167
    def test_add_versions_dictionary_compresses(self):
2168
        """Adding versions to the index should update the lookup dict"""
2169
        knit = self.make_test_knit()
2170
        idx = knit._index
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2171
        idx.add_version('a-1', ['fulltext'], (None, 0, 0), [])
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
2172
        self.check_file_contents('test.kndx',
2173
            '# bzr knit index 8\n'
2174
            '\n'
2175
            'a-1 fulltext 0 0  :'
2176
            )
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2177
        idx.add_versions([('a-2', ['fulltext'], (None, 0, 0), ['a-1']),
2178
                          ('a-3', ['fulltext'], (None, 0, 0), ['a-2']),
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
2179
                         ])
2180
        self.check_file_contents('test.kndx',
2181
            '# bzr knit index 8\n'
2182
            '\n'
2183
            'a-1 fulltext 0 0  :\n'
2184
            'a-2 fulltext 0 0 0 :\n'
2185
            'a-3 fulltext 0 0 1 :'
2186
            )
2187
        self.assertEqual(['a-1', 'a-2', 'a-3'], idx._history)
2188
        self.assertEqual({'a-1':('a-1', ['fulltext'], 0, 0, [], 0),
2189
                          'a-2':('a-2', ['fulltext'], 0, 0, ['a-1'], 1),
2190
                          'a-3':('a-3', ['fulltext'], 0, 0, ['a-2'], 2),
2191
                         }, idx._cache)
2192
2193
    def test_add_versions_fails_clean(self):
2194
        """If add_versions fails in the middle, it restores a pristine state.
2195
2196
        Any modifications that are made to the index are reset if all versions
2197
        cannot be added.
2198
        """
2199
        # This cheats a little bit by passing in a generator which will
2200
        # raise an exception before the processing finishes
2201
        # Other possibilities would be to have an version with the wrong number
2202
        # of entries, or to make the backing transport unable to write any
2203
        # files.
2204
2205
        knit = self.make_test_knit()
2206
        idx = knit._index
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2207
        idx.add_version('a-1', ['fulltext'], (None, 0, 0), [])
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
2208
2209
        class StopEarly(Exception):
2210
            pass
2211
2212
        def generate_failure():
2213
            """Add some entries and then raise an exception"""
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2214
            yield ('a-2', ['fulltext'], (None, 0, 0), ['a-1'])
2215
            yield ('a-3', ['fulltext'], (None, 0, 0), ['a-2'])
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
2216
            raise StopEarly()
2217
2218
        # Assert the pre-condition
2219
        self.assertEqual(['a-1'], idx._history)
2220
        self.assertEqual({'a-1':('a-1', ['fulltext'], 0, 0, [], 0)}, idx._cache)
2221
2222
        self.assertRaises(StopEarly, idx.add_versions, generate_failure())
2223
2224
        # And it shouldn't be modified
2225
        self.assertEqual(['a-1'], idx._history)
2226
        self.assertEqual({'a-1':('a-1', ['fulltext'], 0, 0, [], 0)}, idx._cache)
2171.1.1 by John Arbash Meinel
Knit index files should ignore empty indexes rather than consider them corrupt.
2227
2228
    def test_knit_index_ignores_empty_files(self):
2229
        # There was a race condition in older bzr, where a ^C at the right time
2230
        # could leave an empty .kndx file, which bzr would later claim was a
2231
        # corrupted file since the header was not present. In reality, the file
2232
        # just wasn't created, so it should be ignored.
2233
        t = get_transport('.')
2234
        t.put_bytes('test.kndx', '')
2235
2236
        knit = self.make_test_knit()
2237
2238
    def test_knit_index_checks_header(self):
2239
        t = get_transport('.')
2240
        t.put_bytes('test.kndx', '# not really a knit header\n\n')
2241
2196.2.1 by John Arbash Meinel
Merge Dmitry's optimizations and minimize the actual diff.
2242
        self.assertRaises(KnitHeaderError, self.make_test_knit)
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2243
2244
2245
class TestGraphIndexKnit(KnitTests):
2246
    """Tests for knits using a GraphIndex rather than a KnitIndex."""
2247
2248
    def make_g_index(self, name, ref_lists=0, nodes=[]):
2249
        builder = GraphIndexBuilder(ref_lists)
2250
        for node, references, value in nodes:
2251
            builder.add_node(node, references, value)
2252
        stream = builder.finish()
2253
        trans = self.get_transport()
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
2254
        size = trans.put_file(name, stream)
2255
        return GraphIndex(trans, name, size)
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2256
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2257
    def two_graph_index(self, deltas=False, catch_adds=False):
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2258
        """Build a two-graph index.
2259
2260
        :param deltas: If true, use underlying indices with two node-ref
2261
            lists and 'parent' set to a delta-compressed against tail.
2262
        """
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2263
        # build a complex graph across several indices.
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2264
        if deltas:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2265
            # delta compression inn the index
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2266
            index1 = self.make_g_index('1', 2, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2267
                (('tip', ), 'N0 100', ([('parent', )], [], )),
2268
                (('tail', ), '', ([], []))])
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2269
            index2 = self.make_g_index('2', 2, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2270
                (('parent', ), ' 100 78', ([('tail', ), ('ghost', )], [('tail', )])),
2271
                (('separate', ), '', ([], []))])
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2272
        else:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2273
            # just blob location and graph in the index.
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2274
            index1 = self.make_g_index('1', 1, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2275
                (('tip', ), 'N0 100', ([('parent', )], )),
2276
                (('tail', ), '', ([], ))])
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2277
            index2 = self.make_g_index('2', 1, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2278
                (('parent', ), ' 100 78', ([('tail', ), ('ghost', )], )),
2279
                (('separate', ), '', ([], ))])
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2280
        combined_index = CombinedGraphIndex([index1, index2])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2281
        if catch_adds:
2282
            self.combined_index = combined_index
2283
            self.caught_entries = []
2284
            add_callback = self.catch_add
2285
        else:
2286
            add_callback = None
2287
        return KnitGraphIndex(combined_index, deltas=deltas,
2288
            add_callback=add_callback)
2592.3.4 by Robert Collins
Implement get_ancestry/get_ancestry_with_ghosts for KnitGraphIndex.
2289
2290
    def test_get_graph(self):
2291
        index = self.two_graph_index()
2592.3.2 by Robert Collins
Implement a get_graph for a new KnitGraphIndex that will implement a KnitIndex on top of the GraphIndex API.
2292
        self.assertEqual(set([
2293
            ('tip', ('parent', )),
2294
            ('tail', ()),
2295
            ('parent', ('tail', 'ghost')),
2296
            ('separate', ()),
2297
            ]), set(index.get_graph()))
2592.3.4 by Robert Collins
Implement get_ancestry/get_ancestry_with_ghosts for KnitGraphIndex.
2298
2299
    def test_get_ancestry(self):
2592.3.30 by Robert Collins
Make GraphKnitIndex get_ancestry the same as regular knits.
2300
        # get_ancestry is defined as eliding ghosts, not erroring.
2301
        index = self.two_graph_index()
2592.3.4 by Robert Collins
Implement get_ancestry/get_ancestry_with_ghosts for KnitGraphIndex.
2302
        self.assertEqual([], index.get_ancestry([]))
2303
        self.assertEqual(['separate'], index.get_ancestry(['separate']))
2304
        self.assertEqual(['tail'], index.get_ancestry(['tail']))
2305
        self.assertEqual(['tail', 'parent'], index.get_ancestry(['parent']))
2306
        self.assertEqual(['tail', 'parent', 'tip'], index.get_ancestry(['tip']))
2307
        self.assertTrue(index.get_ancestry(['tip', 'separate']) in
2308
            (['tail', 'parent', 'tip', 'separate'],
2309
             ['separate', 'tail', 'parent', 'tip'],
2310
            ))
2311
        # and without topo_sort
2312
        self.assertEqual(set(['separate']),
2313
            set(index.get_ancestry(['separate'], topo_sorted=False)))
2314
        self.assertEqual(set(['tail']),
2315
            set(index.get_ancestry(['tail'], topo_sorted=False)))
2316
        self.assertEqual(set(['tail', 'parent']),
2317
            set(index.get_ancestry(['parent'], topo_sorted=False)))
2318
        self.assertEqual(set(['tail', 'parent', 'tip']),
2319
            set(index.get_ancestry(['tip'], topo_sorted=False)))
2320
        self.assertEqual(set(['separate', 'tail', 'parent', 'tip']),
2321
            set(index.get_ancestry(['tip', 'separate'])))
2592.3.30 by Robert Collins
Make GraphKnitIndex get_ancestry the same as regular knits.
2322
        # asking for a ghost makes it go boom.
2323
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry, ['ghost'])
2592.3.4 by Robert Collins
Implement get_ancestry/get_ancestry_with_ghosts for KnitGraphIndex.
2324
2325
    def test_get_ancestry_with_ghosts(self):
2326
        index = self.two_graph_index()
2327
        self.assertEqual([], index.get_ancestry_with_ghosts([]))
2328
        self.assertEqual(['separate'], index.get_ancestry_with_ghosts(['separate']))
2329
        self.assertEqual(['tail'], index.get_ancestry_with_ghosts(['tail']))
2330
        self.assertTrue(index.get_ancestry_with_ghosts(['parent']) in
2331
            (['tail', 'ghost', 'parent'],
2332
             ['ghost', 'tail', 'parent'],
2333
            ))
2334
        self.assertTrue(index.get_ancestry_with_ghosts(['tip']) in
2335
            (['tail', 'ghost', 'parent', 'tip'],
2336
             ['ghost', 'tail', 'parent', 'tip'],
2337
            ))
2338
        self.assertTrue(index.get_ancestry_with_ghosts(['tip', 'separate']) in
2339
            (['tail', 'ghost', 'parent', 'tip', 'separate'],
2340
             ['ghost', 'tail', 'parent', 'tip', 'separate'],
2341
             ['separate', 'tail', 'ghost', 'parent', 'tip'],
2342
             ['separate', 'ghost', 'tail', 'parent', 'tip'],
2343
            ))
2592.3.30 by Robert Collins
Make GraphKnitIndex get_ancestry the same as regular knits.
2344
        # asking for a ghost makes it go boom.
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2345
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry_with_ghosts, ['ghost'])
2592.3.5 by Robert Collins
Implement KnitGraphIndex.num_versions.
2346
2347
    def test_num_versions(self):
2348
        index = self.two_graph_index()
2349
        self.assertEqual(4, index.num_versions())
2592.3.6 by Robert Collins
Implement KnitGraphIndex.get_versions.
2350
2351
    def test_get_versions(self):
2352
        index = self.two_graph_index()
2353
        self.assertEqual(set(['tail', 'tip', 'parent', 'separate']),
2354
            set(index.get_versions()))
2355
2592.3.9 by Robert Collins
Implement KnitGraphIndex.has_version.
2356
    def test_has_version(self):
2357
        index = self.two_graph_index()
2358
        self.assertTrue(index.has_version('tail'))
2359
        self.assertFalse(index.has_version('ghost'))
2360
2592.3.10 by Robert Collins
Implement KnitGraphIndex.get_position.
2361
    def test_get_position(self):
2362
        index = self.two_graph_index()
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2363
        self.assertEqual((index._graph_index._indices[0], 0, 100), index.get_position('tip'))
2364
        self.assertEqual((index._graph_index._indices[1], 100, 78), index.get_position('parent'))
2592.3.10 by Robert Collins
Implement KnitGraphIndex.get_position.
2365
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2366
    def test_get_method_deltas(self):
2367
        index = self.two_graph_index(deltas=True)
2592.3.11 by Robert Collins
Implement KnitGraphIndex.get_method.
2368
        self.assertEqual('fulltext', index.get_method('tip'))
2369
        self.assertEqual('line-delta', index.get_method('parent'))
2370
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
2371
    def test_get_method_no_deltas(self):
2372
        # check that the parent-history lookup is ignored with deltas=False.
2373
        index = self.two_graph_index(deltas=False)
2374
        self.assertEqual('fulltext', index.get_method('tip'))
2375
        self.assertEqual('fulltext', index.get_method('parent'))
2376
2592.3.14 by Robert Collins
Implement KnitGraphIndex.get_options.
2377
    def test_get_options_deltas(self):
2378
        index = self.two_graph_index(deltas=True)
2658.2.1 by Robert Collins
Fix mismatch between KnitGraphIndex and KnitIndex in get_options.
2379
        self.assertEqual(['fulltext', 'no-eol'], index.get_options('tip'))
2380
        self.assertEqual(['line-delta'], index.get_options('parent'))
2592.3.14 by Robert Collins
Implement KnitGraphIndex.get_options.
2381
2382
    def test_get_options_no_deltas(self):
2383
        # check that the parent-history lookup is ignored with deltas=False.
2384
        index = self.two_graph_index(deltas=False)
2658.2.1 by Robert Collins
Fix mismatch between KnitGraphIndex and KnitIndex in get_options.
2385
        self.assertEqual(['fulltext', 'no-eol'], index.get_options('tip'))
2386
        self.assertEqual(['fulltext'], index.get_options('parent'))
2592.3.14 by Robert Collins
Implement KnitGraphIndex.get_options.
2387
2592.3.15 by Robert Collins
Implement KnitGraphIndex.get_parents/get_parents_with_ghosts.
2388
    def test_get_parents(self):
2389
        # get_parents ignores ghosts
2390
        index = self.two_graph_index()
2592.3.43 by Robert Collins
A knit iter_parents API.
2391
        self.assertEqual(('tail', ), index.get_parents('parent'))
2392
        # and errors on ghosts.
2393
        self.assertRaises(errors.RevisionNotPresent,
2394
            index.get_parents, 'ghost')
2592.3.15 by Robert Collins
Implement KnitGraphIndex.get_parents/get_parents_with_ghosts.
2395
2396
    def test_get_parents_with_ghosts(self):
2397
        index = self.two_graph_index()
2398
        self.assertEqual(('tail', 'ghost'), index.get_parents_with_ghosts('parent'))
2592.3.43 by Robert Collins
A knit iter_parents API.
2399
        # and errors on ghosts.
2400
        self.assertRaises(errors.RevisionNotPresent,
2401
            index.get_parents_with_ghosts, 'ghost')
2592.3.15 by Robert Collins
Implement KnitGraphIndex.get_parents/get_parents_with_ghosts.
2402
2592.3.16 by Robert Collins
Implement KnitGraphIndex.check_versions_present.
2403
    def test_check_versions_present(self):
2404
        # ghosts should not be considered present
2405
        index = self.two_graph_index()
2406
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
2407
            ['ghost'])
2408
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
2409
            ['tail', 'ghost'])
2410
        index.check_versions_present(['tail', 'separate'])
2592.3.14 by Robert Collins
Implement KnitGraphIndex.get_options.
2411
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2412
    def catch_add(self, entries):
2413
        self.caught_entries.append(entries)
2414
2415
    def test_add_no_callback_errors(self):
2416
        index = self.two_graph_index()
2417
        self.assertRaises(errors.ReadOnlyError, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2418
            'new', 'fulltext,no-eol', (None, 50, 60), ['separate'])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2419
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2420
    def test_add_version_smoke(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2421
        index = self.two_graph_index(catch_adds=True)
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2422
        index.add_version('new', 'fulltext,no-eol', (None, 50, 60), ['separate'])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2423
        self.assertEqual([[(('new', ), 'N50 60', ((('separate',),),))]],
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2424
            self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2425
2426
    def test_add_version_delta_not_delta_index(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2427
        index = self.two_graph_index(catch_adds=True)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2428
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2429
            'new', 'no-eol,line-delta', (None, 0, 100), ['parent'])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2430
        self.assertEqual([], self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2431
2432
    def test_add_version_same_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2433
        index = self.two_graph_index(catch_adds=True)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2434
        # options can be spelt two different ways
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2435
        index.add_version('tip', 'fulltext,no-eol', (None, 0, 100), ['parent'])
2436
        index.add_version('tip', 'no-eol,fulltext', (None, 0, 100), ['parent'])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2437
        # but neither should have added data.
2438
        self.assertEqual([[], []], self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2439
        
2440
    def test_add_version_different_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2441
        index = self.two_graph_index(deltas=True, catch_adds=True)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2442
        # change options
2443
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2444
            'tip', 'no-eol,line-delta', (None, 0, 100), ['parent'])
2445
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2446
            'tip', 'line-delta,no-eol', (None, 0, 100), ['parent'])
2447
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2448
            'tip', 'fulltext', (None, 0, 100), ['parent'])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2449
        # position/length
2450
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2451
            'tip', 'fulltext,no-eol', (None, 50, 100), ['parent'])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2452
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2453
            'tip', 'fulltext,no-eol', (None, 0, 1000), ['parent'])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2454
        # parents
2455
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2456
            'tip', 'fulltext,no-eol', (None, 0, 100), [])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2457
        self.assertEqual([], self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2458
        
2459
    def test_add_versions_nodeltas(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2460
        index = self.two_graph_index(catch_adds=True)
2461
        index.add_versions([
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2462
                ('new', 'fulltext,no-eol', (None, 50, 60), ['separate']),
2463
                ('new2', 'fulltext', (None, 0, 6), ['new']),
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2464
                ])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2465
        self.assertEqual([(('new', ), 'N50 60', ((('separate',),),)),
2466
            (('new2', ), ' 0 6', ((('new',),),))],
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2467
            sorted(self.caught_entries[0]))
2468
        self.assertEqual(1, len(self.caught_entries))
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2469
2470
    def test_add_versions_deltas(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2471
        index = self.two_graph_index(deltas=True, catch_adds=True)
2472
        index.add_versions([
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2473
                ('new', 'fulltext,no-eol', (None, 50, 60), ['separate']),
2474
                ('new2', 'line-delta', (None, 0, 6), ['new']),
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2475
                ])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2476
        self.assertEqual([(('new', ), 'N50 60', ((('separate',),), ())),
2477
            (('new2', ), ' 0 6', ((('new',),), (('new',),), ))],
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2478
            sorted(self.caught_entries[0]))
2479
        self.assertEqual(1, len(self.caught_entries))
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2480
2481
    def test_add_versions_delta_not_delta_index(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2482
        index = self.two_graph_index(catch_adds=True)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2483
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2484
            [('new', 'no-eol,line-delta', (None, 0, 100), ['parent'])])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2485
        self.assertEqual([], self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2486
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2487
    def test_add_versions_random_id_accepted(self):
2488
        index = self.two_graph_index(catch_adds=True)
2489
        index.add_versions([], random_id=True)
2490
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2491
    def test_add_versions_same_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2492
        index = self.two_graph_index(catch_adds=True)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2493
        # options can be spelt two different ways
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2494
        index.add_versions([('tip', 'fulltext,no-eol', (None, 0, 100), ['parent'])])
2495
        index.add_versions([('tip', 'no-eol,fulltext', (None, 0, 100), ['parent'])])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2496
        # but neither should have added data.
2497
        self.assertEqual([[], []], self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2498
        
2499
    def test_add_versions_different_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2500
        index = self.two_graph_index(deltas=True, catch_adds=True)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2501
        # change options
2502
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2503
            [('tip', 'no-eol,line-delta', (None, 0, 100), ['parent'])])
2504
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2505
            [('tip', 'line-delta,no-eol', (None, 0, 100), ['parent'])])
2506
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2507
            [('tip', 'fulltext', (None, 0, 100), ['parent'])])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2508
        # position/length
2509
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2510
            [('tip', 'fulltext,no-eol', (None, 50, 100), ['parent'])])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2511
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2512
            [('tip', 'fulltext,no-eol', (None, 0, 1000), ['parent'])])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2513
        # parents
2514
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2515
            [('tip', 'fulltext,no-eol', (None, 0, 100), [])])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
2516
        # change options in the second record
2517
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2518
            [('tip', 'fulltext,no-eol', (None, 0, 100), ['parent']),
2519
             ('tip', 'no-eol,line-delta', (None, 0, 100), ['parent'])])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
2520
        self.assertEqual([], self.caught_entries)
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2521
2592.3.43 by Robert Collins
A knit iter_parents API.
2522
    def test_iter_parents(self):
2523
        index1 = self.make_g_index('1', 1, [
2524
        # no parents
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2525
            (('r0', ), 'N0 100', ([], )),
2592.3.43 by Robert Collins
A knit iter_parents API.
2526
        # 1 parent
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2527
            (('r1', ), '', ([('r0', )], ))])
2592.3.43 by Robert Collins
A knit iter_parents API.
2528
        index2 = self.make_g_index('2', 1, [
2529
        # 2 parents
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2530
            (('r2', ), 'N0 100', ([('r1', ), ('r0', )], )),
2592.3.43 by Robert Collins
A knit iter_parents API.
2531
            ])
2532
        combined_index = CombinedGraphIndex([index1, index2])
2533
        index = KnitGraphIndex(combined_index)
2534
        # XXX TODO a ghost
2535
        # cases: each sample data individually:
2536
        self.assertEqual(set([('r0', ())]),
2537
            set(index.iter_parents(['r0'])))
2538
        self.assertEqual(set([('r1', ('r0', ))]),
2539
            set(index.iter_parents(['r1'])))
2540
        self.assertEqual(set([('r2', ('r1', 'r0'))]),
2541
            set(index.iter_parents(['r2'])))
2542
        # no nodes returned for a missing node
2543
        self.assertEqual(set(),
2544
            set(index.iter_parents(['missing'])))
2545
        # 1 node returned with missing nodes skipped
2546
        self.assertEqual(set([('r1', ('r0', ))]),
2547
            set(index.iter_parents(['ghost1', 'r1', 'ghost'])))
2548
        # 2 nodes returned
2549
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
2550
            set(index.iter_parents(['r0', 'r1'])))
2551
        # 2 nodes returned, missing skipped
2552
        self.assertEqual(set([('r0', ()), ('r1', ('r0', ))]),
2553
            set(index.iter_parents(['a', 'r0', 'b', 'r1', 'c'])))
2554
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2555
2556
class TestNoParentsGraphIndexKnit(KnitTests):
2557
    """Tests for knits using KnitGraphIndex with no parents."""
2558
2559
    def make_g_index(self, name, ref_lists=0, nodes=[]):
2560
        builder = GraphIndexBuilder(ref_lists)
2561
        for node, references in nodes:
2562
            builder.add_node(node, references)
2563
        stream = builder.finish()
2564
        trans = self.get_transport()
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
2565
        size = trans.put_file(name, stream)
2566
        return GraphIndex(trans, name, size)
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2567
2568
    def test_parents_deltas_incompatible(self):
2569
        index = CombinedGraphIndex([])
2570
        self.assertRaises(errors.KnitError, KnitGraphIndex, index,
2571
            deltas=True, parents=False)
2572
2573
    def two_graph_index(self, catch_adds=False):
2574
        """Build a two-graph index.
2575
2576
        :param deltas: If true, use underlying indices with two node-ref
2577
            lists and 'parent' set to a delta-compressed against tail.
2578
        """
2579
        # put several versions in the index.
2580
        index1 = self.make_g_index('1', 0, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2581
            (('tip', ), 'N0 100'),
2582
            (('tail', ), '')])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2583
        index2 = self.make_g_index('2', 0, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2584
            (('parent', ), ' 100 78'),
2585
            (('separate', ), '')])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2586
        combined_index = CombinedGraphIndex([index1, index2])
2587
        if catch_adds:
2588
            self.combined_index = combined_index
2589
            self.caught_entries = []
2590
            add_callback = self.catch_add
2591
        else:
2592
            add_callback = None
2593
        return KnitGraphIndex(combined_index, parents=False,
2594
            add_callback=add_callback)
2595
2596
    def test_get_graph(self):
2597
        index = self.two_graph_index()
2598
        self.assertEqual(set([
2599
            ('tip', ()),
2600
            ('tail', ()),
2601
            ('parent', ()),
2602
            ('separate', ()),
2603
            ]), set(index.get_graph()))
2604
2605
    def test_get_ancestry(self):
2606
        # with no parents, ancestry is always just the key.
2607
        index = self.two_graph_index()
2608
        self.assertEqual([], index.get_ancestry([]))
2609
        self.assertEqual(['separate'], index.get_ancestry(['separate']))
2610
        self.assertEqual(['tail'], index.get_ancestry(['tail']))
2611
        self.assertEqual(['parent'], index.get_ancestry(['parent']))
2612
        self.assertEqual(['tip'], index.get_ancestry(['tip']))
2613
        self.assertTrue(index.get_ancestry(['tip', 'separate']) in
2614
            (['tip', 'separate'],
2615
             ['separate', 'tip'],
2616
            ))
2617
        # asking for a ghost makes it go boom.
2618
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry, ['ghost'])
2619
2620
    def test_get_ancestry_with_ghosts(self):
2621
        index = self.two_graph_index()
2622
        self.assertEqual([], index.get_ancestry_with_ghosts([]))
2623
        self.assertEqual(['separate'], index.get_ancestry_with_ghosts(['separate']))
2624
        self.assertEqual(['tail'], index.get_ancestry_with_ghosts(['tail']))
2625
        self.assertEqual(['parent'], index.get_ancestry_with_ghosts(['parent']))
2626
        self.assertEqual(['tip'], index.get_ancestry_with_ghosts(['tip']))
2627
        self.assertTrue(index.get_ancestry_with_ghosts(['tip', 'separate']) in
2628
            (['tip', 'separate'],
2629
             ['separate', 'tip'],
2630
            ))
2631
        # asking for a ghost makes it go boom.
2632
        self.assertRaises(errors.RevisionNotPresent, index.get_ancestry_with_ghosts, ['ghost'])
2633
2634
    def test_num_versions(self):
2635
        index = self.two_graph_index()
2636
        self.assertEqual(4, index.num_versions())
2637
2638
    def test_get_versions(self):
2639
        index = self.two_graph_index()
2640
        self.assertEqual(set(['tail', 'tip', 'parent', 'separate']),
2641
            set(index.get_versions()))
2642
2643
    def test_has_version(self):
2644
        index = self.two_graph_index()
2645
        self.assertTrue(index.has_version('tail'))
2646
        self.assertFalse(index.has_version('ghost'))
2647
2648
    def test_get_position(self):
2649
        index = self.two_graph_index()
2592.3.71 by Robert Collins
Basic version of knit-based repository operating, many tests failing.
2650
        self.assertEqual((index._graph_index._indices[0], 0, 100), index.get_position('tip'))
2651
        self.assertEqual((index._graph_index._indices[1], 100, 78), index.get_position('parent'))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2652
2653
    def test_get_method(self):
2654
        index = self.two_graph_index()
2655
        self.assertEqual('fulltext', index.get_method('tip'))
2658.2.1 by Robert Collins
Fix mismatch between KnitGraphIndex and KnitIndex in get_options.
2656
        self.assertEqual(['fulltext'], index.get_options('parent'))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2657
2658
    def test_get_options(self):
2659
        index = self.two_graph_index()
2658.2.1 by Robert Collins
Fix mismatch between KnitGraphIndex and KnitIndex in get_options.
2660
        self.assertEqual(['fulltext', 'no-eol'], index.get_options('tip'))
2661
        self.assertEqual(['fulltext'], index.get_options('parent'))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2662
2663
    def test_get_parents(self):
2664
        index = self.two_graph_index()
2665
        self.assertEqual((), index.get_parents('parent'))
2592.3.43 by Robert Collins
A knit iter_parents API.
2666
        # and errors on ghosts.
2667
        self.assertRaises(errors.RevisionNotPresent,
2668
            index.get_parents, 'ghost')
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2669
2670
    def test_get_parents_with_ghosts(self):
2671
        index = self.two_graph_index()
2672
        self.assertEqual((), index.get_parents_with_ghosts('parent'))
2592.3.43 by Robert Collins
A knit iter_parents API.
2673
        # and errors on ghosts.
2674
        self.assertRaises(errors.RevisionNotPresent,
2675
            index.get_parents_with_ghosts, 'ghost')
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2676
2677
    def test_check_versions_present(self):
2678
        index = self.two_graph_index()
2679
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
2680
            ['missing'])
2681
        self.assertRaises(RevisionNotPresent, index.check_versions_present,
2682
            ['tail', 'missing'])
2683
        index.check_versions_present(['tail', 'separate'])
2684
2685
    def catch_add(self, entries):
2686
        self.caught_entries.append(entries)
2687
2688
    def test_add_no_callback_errors(self):
2689
        index = self.two_graph_index()
2690
        self.assertRaises(errors.ReadOnlyError, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2691
            'new', 'fulltext,no-eol', (None, 50, 60), ['separate'])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2692
2693
    def test_add_version_smoke(self):
2694
        index = self.two_graph_index(catch_adds=True)
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2695
        index.add_version('new', 'fulltext,no-eol', (None, 50, 60), [])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2696
        self.assertEqual([[(('new', ), 'N50 60')]],
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2697
            self.caught_entries)
2698
2699
    def test_add_version_delta_not_delta_index(self):
2700
        index = self.two_graph_index(catch_adds=True)
2701
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2702
            'new', 'no-eol,line-delta', (None, 0, 100), [])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2703
        self.assertEqual([], self.caught_entries)
2704
2705
    def test_add_version_same_dup(self):
2706
        index = self.two_graph_index(catch_adds=True)
2707
        # options can be spelt two different ways
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2708
        index.add_version('tip', 'fulltext,no-eol', (None, 0, 100), [])
2709
        index.add_version('tip', 'no-eol,fulltext', (None, 0, 100), [])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2710
        # but neither should have added data.
2711
        self.assertEqual([[], []], self.caught_entries)
2712
        
2713
    def test_add_version_different_dup(self):
2714
        index = self.two_graph_index(catch_adds=True)
2715
        # change options
2716
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2717
            'tip', 'no-eol,line-delta', (None, 0, 100), [])
2718
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2719
            'tip', 'line-delta,no-eol', (None, 0, 100), [])
2720
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2721
            'tip', 'fulltext', (None, 0, 100), [])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2722
        # position/length
2723
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2724
            'tip', 'fulltext,no-eol', (None, 50, 100), [])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2725
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2726
            'tip', 'fulltext,no-eol', (None, 0, 1000), [])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2727
        # parents
2728
        self.assertRaises(errors.KnitCorrupt, index.add_version,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2729
            'tip', 'fulltext,no-eol', (None, 0, 100), ['parent'])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2730
        self.assertEqual([], self.caught_entries)
2731
        
2732
    def test_add_versions(self):
2733
        index = self.two_graph_index(catch_adds=True)
2734
        index.add_versions([
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2735
                ('new', 'fulltext,no-eol', (None, 50, 60), []),
2736
                ('new2', 'fulltext', (None, 0, 6), []),
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2737
                ])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2738
        self.assertEqual([(('new', ), 'N50 60'), (('new2', ), ' 0 6')],
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2739
            sorted(self.caught_entries[0]))
2740
        self.assertEqual(1, len(self.caught_entries))
2741
2742
    def test_add_versions_delta_not_delta_index(self):
2743
        index = self.two_graph_index(catch_adds=True)
2744
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2745
            [('new', 'no-eol,line-delta', (None, 0, 100), ['parent'])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2746
        self.assertEqual([], self.caught_entries)
2747
2748
    def test_add_versions_parents_not_parents_index(self):
2749
        index = self.two_graph_index(catch_adds=True)
2750
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2751
            [('new', 'no-eol,fulltext', (None, 0, 100), ['parent'])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2752
        self.assertEqual([], self.caught_entries)
2753
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2754
    def test_add_versions_random_id_accepted(self):
2755
        index = self.two_graph_index(catch_adds=True)
2756
        index.add_versions([], random_id=True)
2757
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2758
    def test_add_versions_same_dup(self):
2759
        index = self.two_graph_index(catch_adds=True)
2760
        # options can be spelt two different ways
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2761
        index.add_versions([('tip', 'fulltext,no-eol', (None, 0, 100), [])])
2762
        index.add_versions([('tip', 'no-eol,fulltext', (None, 0, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2763
        # but neither should have added data.
2764
        self.assertEqual([[], []], self.caught_entries)
2765
        
2766
    def test_add_versions_different_dup(self):
2767
        index = self.two_graph_index(catch_adds=True)
2768
        # change options
2769
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2770
            [('tip', 'no-eol,line-delta', (None, 0, 100), [])])
2771
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2772
            [('tip', 'line-delta,no-eol', (None, 0, 100), [])])
2773
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2774
            [('tip', 'fulltext', (None, 0, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2775
        # position/length
2776
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2777
            [('tip', 'fulltext,no-eol', (None, 50, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2778
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2779
            [('tip', 'fulltext,no-eol', (None, 0, 1000), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2780
        # parents
2781
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2782
            [('tip', 'fulltext,no-eol', (None, 0, 100), ['parent'])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2783
        # change options in the second record
2784
        self.assertRaises(errors.KnitCorrupt, index.add_versions,
2670.2.2 by Robert Collins
* In ``bzrlib.knit`` the internal interface has been altered to use
2785
            [('tip', 'fulltext,no-eol', (None, 0, 100), []),
2786
             ('tip', 'no-eol,line-delta', (None, 0, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2787
        self.assertEqual([], self.caught_entries)
2788
2592.3.43 by Robert Collins
A knit iter_parents API.
2789
    def test_iter_parents(self):
2790
        index = self.two_graph_index()
2791
        self.assertEqual(set([
2792
            ('tip', ()), ('tail', ()), ('parent', ()), ('separate', ())
2793
            ]),
2794
            set(index.iter_parents(['tip', 'tail', 'ghost', 'parent', 'separate'])))
2795
        self.assertEqual(set([('tip', ())]),
2796
            set(index.iter_parents(['tip'])))
2797
        self.assertEqual(set(),
2798
            set(index.iter_parents([])))
3015.2.19 by Robert Collins
Don't include the pack container length in the lengths given by get_data_stream.
2799
2800
2801
class TestPackKnits(KnitTests):
2802
    """Tests that use a _PackAccess and KnitGraphIndex."""
2803
2804
    def test_get_data_stream_packs_ignores_pack_overhead(self):
2805
        # Packs have an encoding overhead that should not be included in the
2806
        # 'size' field of a data stream, because it is not returned by the
2807
        # raw_reading functions - it is why index_memo's are opaque, and
2808
        # get_data_stream was abusing this.
2809
        packname = 'test.pack'
2810
        transport = self.get_transport()
2811
        def write_data(bytes):
2812
            transport.append_bytes(packname, bytes)
2813
        writer = pack.ContainerWriter(write_data)
2814
        writer.begin()
2815
        index = InMemoryGraphIndex(2)
2816
        knit_index = KnitGraphIndex(index, add_callback=index.add_nodes,
2817
            deltas=True)
2818
        indices = {index:(transport, packname)}
2819
        access = _PackAccess(indices, writer=(writer, index))
2820
        k = KnitVersionedFile('test', get_transport('.'),
2821
            delta=True, create=True, index=knit_index, access_method=access)
2822
        # insert something into the knit
2823
        k.add_lines('text-1', [], ["foo\n"])
2824
        # get a data stream for it
2825
        stream = k.get_data_stream(['text-1'])
2826
        # if the stream has been incorrectly assembled, we will get a short read
2827
        # reading from the stream (as streams have no trailer)
2828
        expected_length = stream[1][0][2]
2829
        # we use -1 to do the read, so that if a trailer is added this test
2830
        # will fail and we'll adjust it to handle that case correctly, rather
2831
        # than allowing an over-read that is bogus.
2832
        self.assertEqual(expected_length, len(stream[2](-1)))
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2833
2834
2835
class Test_StreamIndex(KnitTests):
2836
2837
    def get_index(self, knit, stream):
2838
        """Get a _StreamIndex from knit and stream."""
2839
        return knit._knit_from_datastream(stream)._index
2840
2841
    def assertIndexVersions(self, knit, versions):
2842
        """Check that the _StreamIndex versions are those of the stream."""
2843
        index = self.get_index(knit, knit.get_data_stream(versions))
2844
        self.assertEqual(set(index.get_versions()), set(versions))
2845
        # check we didn't get duplicates
2846
        self.assertEqual(len(index.get_versions()), len(versions))
2847
2848
    def assertIndexAncestry(self, knit, ancestry_versions, versions, result):
2849
        """Check the result of a get_ancestry call on knit."""
2850
        index = self.get_index(knit, knit.get_data_stream(versions))
3052.2.4 by Andrew Bennetts
Some tweaks suggested by John's review.
2851
        self.assertEqual(
2852
            set(result),
2853
            set(index.get_ancestry(ancestry_versions, False)))
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2854
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2855
    def assertIterParents(self, knit, versions, parent_versions, result):
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2856
        """Check the result of an iter_parents call on knit."""
2857
        index = self.get_index(knit, knit.get_data_stream(versions))
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2858
        self.assertEqual(result, index.iter_parents(parent_versions))
2859
2860
    def assertGetMethod(self, knit, versions, version, result):
2861
        index = self.get_index(knit, knit.get_data_stream(versions))
2862
        self.assertEqual(result, index.get_method(version))
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2863
2864
    def assertGetOptions(self, knit, version, options):
2865
        index = self.get_index(knit, knit.get_data_stream(version))
2866
        self.assertEqual(options, index.get_options(version))
2867
2868
    def assertGetPosition(self, knit, versions, version, result):
2869
        index = self.get_index(knit, knit.get_data_stream(versions))
3052.2.5 by Andrew Bennetts
Address the rest of the review comments from John and myself.
2870
        if result[1] is None:
2871
            result = (result[0], index, result[2], result[3])
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2872
        self.assertEqual(result, index.get_position(version))
2873
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2874
    def assertGetParentsWithGhosts(self, knit, versions, version, parents):
2875
        index = self.get_index(knit, knit.get_data_stream(versions))
2876
        self.assertEqual(parents, index.get_parents_with_ghosts(version))
2877
2878
    def make_knit_with_4_versions_2_dags(self):
2879
        knit = self.make_test_knit()
2880
        knit.add_lines('a', [], ["foo"])
2881
        knit.add_lines('b', [], [])
2882
        knit.add_lines('c', ['b', 'a'], [])
2883
        knit.add_lines_with_ghosts('d', ['e', 'f'], [])
2884
        return knit
2885
2886
    def test_versions(self):
2887
        """The versions of a StreamIndex are those of the datastream."""
2888
        knit = self.make_knit_with_4_versions_2_dags()
2889
        # ask for most permutations, which catches bugs like falling back to the
2890
        # target knit, or showing ghosts, etc.
2891
        self.assertIndexVersions(knit, [])
2892
        self.assertIndexVersions(knit, ['a'])
2893
        self.assertIndexVersions(knit, ['b'])
2894
        self.assertIndexVersions(knit, ['c'])
2895
        self.assertIndexVersions(knit, ['d'])
2896
        self.assertIndexVersions(knit, ['a', 'b'])
2897
        self.assertIndexVersions(knit, ['b', 'c'])
2898
        self.assertIndexVersions(knit, ['a', 'c'])
2899
        self.assertIndexVersions(knit, ['a', 'b', 'c'])
2900
        self.assertIndexVersions(knit, ['a', 'b', 'c', 'd'])
2901
2902
    def test_construct(self):
2903
        """Constructing a StreamIndex generates index data."""
2904
        data_list = [('text-a', ['fulltext'], 127, []),
2905
            ('text-b', ['option'], 128, ['text-c'])]
2906
        index = _StreamIndex(data_list)
2907
        self.assertEqual({'text-a':(['fulltext'], (0, 127), []),
2908
            'text-b':(['option'], (127, 127 + 128), ['text-c'])},
2909
            index._by_version)
2910
2911
    def test_get_ancestry(self):
2912
        knit = self.make_knit_with_4_versions_2_dags()
2913
        self.assertIndexAncestry(knit, ['a'], ['a'], ['a'])
2914
        self.assertIndexAncestry(knit, ['b'], ['b'], ['b'])
2915
        self.assertIndexAncestry(knit, ['c'], ['c'], ['c'])
2916
        self.assertIndexAncestry(knit, ['c'], ['a', 'b', 'c'],
3052.2.4 by Andrew Bennetts
Some tweaks suggested by John's review.
2917
            set(['a', 'b', 'c']))
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2918
        self.assertIndexAncestry(knit, ['c', 'd'], ['a', 'b', 'c', 'd'],
3052.2.4 by Andrew Bennetts
Some tweaks suggested by John's review.
2919
            set(['a', 'b', 'c', 'd']))
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2920
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2921
    def test_get_method(self):
2922
        knit = self.make_knit_with_4_versions_2_dags()
2923
        self.assertGetMethod(knit, ['a'], 'a', 'fulltext')
2924
        self.assertGetMethod(knit, ['c'], 'c', 'line-delta')
2925
        # get_method on a basis that is not in the datastream (but in the
2926
        # backing knit) returns 'fulltext', because thats what we'll create as
2927
        # we thunk across.
2928
        self.assertGetMethod(knit, ['c'], 'b', 'fulltext')
2929
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2930
    def test_iter_parents(self):
2931
        knit = self.make_knit_with_4_versions_2_dags()
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2932
        self.assertIterParents(knit, ['a'], ['a'], [('a', [])])
2933
        self.assertIterParents(knit, ['a', 'b'], ['a', 'b'],
2934
            [('a', []), ('b', [])])
2935
        self.assertIterParents(knit, ['a', 'b', 'c'], ['a', 'b', 'c'],
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2936
            [('a', []), ('b', []), ('c', ['b', 'a'])])
2937
        self.assertIterParents(knit, ['a', 'b', 'c', 'd'],
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2938
            ['a', 'b', 'c', 'd'],
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2939
            [('a', []), ('b', []), ('c', ['b', 'a']), ('d', ['e', 'f'])])
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2940
        self.assertIterParents(knit, ['c'], ['a', 'b', 'c'],
2941
            [('c', ['b', 'a'])])
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2942
2943
    def test_get_options(self):
2944
        knit = self.make_knit_with_4_versions_2_dags()
2945
        self.assertGetOptions(knit, 'a', ['no-eol', 'fulltext'])
2946
        self.assertGetOptions(knit, 'c', ['line-delta'])
2947
2948
    def test_get_parents_with_ghosts(self):
2949
        knit = self.make_knit_with_4_versions_2_dags()
2950
        self.assertGetParentsWithGhosts(knit, ['a'], 'a', [])
2951
        self.assertGetParentsWithGhosts(knit, ['c'], 'c', ['b', 'a'])
3052.2.4 by Andrew Bennetts
Some tweaks suggested by John's review.
2952
        self.assertGetParentsWithGhosts(knit, ['d'], 'd', ['e', 'f'])
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2953
2954
    def test_get_position(self):
2955
        knit = self.make_knit_with_4_versions_2_dags()
3052.2.6 by Andrew Bennetts
Fix typo in comment.
2956
        # get_position returns (thunk_flag, index(can be None), start, end) for
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2957
        # _StreamAccess to use.
3052.2.5 by Andrew Bennetts
Address the rest of the review comments from John and myself.
2958
        self.assertGetPosition(knit, ['a'], 'a', (False, None, 0, 78))
2959
        self.assertGetPosition(knit, ['a', 'c'], 'c', (False, None, 78, 156))
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2960
        # get_position on a text that is not in the datastream (but in the
3052.2.5 by Andrew Bennetts
Address the rest of the review comments from John and myself.
2961
        # backing knit) returns (True, 'versionid', None, None) - and then the
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2962
        # access object can construct the relevant data as needed.
3052.2.5 by Andrew Bennetts
Address the rest of the review comments from John and myself.
2963
        self.assertGetPosition(knit, ['a', 'c'], 'b', (True, 'b', None, None))
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
2964
2965
2966
class Test_StreamAccess(KnitTests):
3052.2.2 by Robert Collins
* Operations pulling data from a smart server where the underlying
2967
2968
    def get_index_access(self, knit, stream):
2969
        """Get a _StreamAccess from knit and stream."""
2970
        knit =  knit._knit_from_datastream(stream)
2971
        return knit._index, knit._data._access
2972
2973
    def assertGetRawRecords(self, knit, versions):
2974
        index, access = self.get_index_access(knit,
2975
            knit.get_data_stream(versions))
2976
        # check that every version asked for can be obtained from the resulting
2977
        # access object.
2978
        # batch
2979
        memos = []
2980
        for version in versions:
2981
            memos.append(knit._index.get_position(version))
2982
        original = {}
2983
        for version, data in zip(
2984
            versions, knit._data._access.get_raw_records(memos)):
2985
            original[version] = data
2986
        memos = []
2987
        for version in versions:
2988
            memos.append(index.get_position(version))
2989
        streamed = {}
2990
        for version, data in zip(versions, access.get_raw_records(memos)):
2991
            streamed[version] = data
2992
        self.assertEqual(original, streamed)
2993
        # individually
2994
        for version in versions:
2995
            data = list(access.get_raw_records(
2996
                [index.get_position(version)]))[0]
2997
            self.assertEqual(original[version], data)
2998
2999
    def make_knit_with_two_versions(self):
3000
        knit = self.make_test_knit()
3001
        knit.add_lines('a', [], ["foo"])
3002
        knit.add_lines('b', [], ["bar"])
3003
        return knit
3004
3005
    def test_get_raw_records(self):
3006
        knit = self.make_knit_with_two_versions()
3007
        self.assertGetRawRecords(knit, ['a', 'b'])
3008
        self.assertGetRawRecords(knit, ['a'])
3009
        self.assertGetRawRecords(knit, ['b'])
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
3010
    
3011
    def test_get_raw_record_from_backing_knit(self):
3012
        # the thunk layer should create an artificial A on-demand when needed.
3013
        source_knit = self.make_test_knit(name='plain', annotate=False)
3014
        target_knit = self.make_test_knit(name='annotated', annotate=True)
3015
        source_knit.add_lines("A", [], ["Foo\n"])
3016
        # Give the target A, so we can try to thunk across to it.
3017
        target_knit.join(source_knit)
3018
        index, access = self.get_index_access(target_knit,
3019
            source_knit.get_data_stream([]))
3052.2.5 by Andrew Bennetts
Address the rest of the review comments from John and myself.
3020
        raw_data = list(access.get_raw_records([(True, "A", None, None)]))[0]
3052.2.3 by Robert Collins
Handle insert_data_stream of an unannotated stream into an annotated knit.
3021
        df = GzipFile(mode='rb', fileobj=StringIO(raw_data))
3022
        self.assertEqual(
3023
            'version A 1 5d36b88bb697a2d778f024048bafabd443d74503\n'
3024
            'Foo\nend A\n',
3025
            df.read())
3026
3027
    def test_asking_for_thunk_stream_is_not_plain_errors(self):
3028
        knit = self.make_test_knit(name='annotated', annotate=True)
3029
        knit.add_lines("A", [], ["Foo\n"])
3030
        index, access = self.get_index_access(knit,
3031
            knit.get_data_stream([]))
3032
        self.assertRaises(errors.KnitCorrupt,
3052.2.5 by Andrew Bennetts
Address the rest of the review comments from John and myself.
3033
            list, access.get_raw_records([(True, "A", None, None)]))