~bzr-pqm/bzr/bzr.dev

4763.2.4 by John Arbash Meinel
merge bzr.2.1 in preparation for NEWS entry.
1
# Copyright (C) 2006-2010 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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
16
17
"""Tests for Knit data structure"""
18
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
19
from cStringIO import StringIO
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
20
import sys
1563.2.4 by Robert Collins
First cut at including the knit implementation of versioned_file.
21
2196.2.5 by John Arbash Meinel
Add an exception class when the knit index storage method is unknown, and properly test for it
22
from bzrlib import (
23
    errors,
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
24
    knit,
3350.8.12 by Robert Collins
Stacked make_mpdiffs.
25
    multiparent,
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
26
    osutils,
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
27
    pack,
4913.2.24 by John Arbash Meinel
Track down a few more import typos.
28
    tests,
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
29
    transport,
5279.1.1 by Andrew Bennetts
lazy_import most things in merge.py; add a few representative modules to the import tariff tests; tweak a couple of other modules so that patiencediff is not necessarily imported; remove a bunch of unused imports from test_knit.py.
30
    tuned_gzip,
2196.2.5 by John Arbash Meinel
Add an exception class when the knit index storage method is unknown, and properly test for it
31
    )
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
32
from bzrlib.errors import (
33
    KnitHeaderError,
34
    NoSuchFile,
35
    )
2592.3.1 by Robert Collins
Allow giving KnitVersionedFile an index object to use rather than implicitly creating one.
36
from bzrlib.index import *
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
37
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.
38
    AnnotatedKnitContent,
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
39
    KnitContent,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
40
    KnitVersionedFiles,
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.
41
    PlainKnitContent,
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
42
    _VFContentMapGenerator,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
43
    _DirectPackAccess,
44
    _KndxIndex,
45
    _KnitGraphIndex,
46
    _KnitKeyAccess,
47
    make_file_factory,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
48
    )
5279.1.1 by Andrew Bennetts
lazy_import most things in merge.py; add a few representative modules to the import tariff tests; tweak a couple of other modules so that patiencediff is not necessarily imported; remove a bunch of unused imports from test_knit.py.
49
from bzrlib.patiencediff import PatienceSequenceMatcher
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
50
from bzrlib.repofmt import pack_repo
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
51
from bzrlib.tests import (
52
    TestCase,
53
    TestCaseWithMemoryTransport,
54
    TestCaseWithTransport,
3787.1.1 by Robert Collins
Embed the failed text in sha1 knit errors.
55
    TestNotApplicable,
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
56
    )
3350.8.2 by Robert Collins
stacked get_parent_map.
57
from bzrlib.versionedfile import (
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
58
    AbsentContentFactory,
3350.8.2 by Robert Collins
stacked get_parent_map.
59
    ConstantMapper,
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
60
    network_bytes_to_kind_and_offset,
3350.8.2 by Robert Collins
stacked get_parent_map.
61
    RecordingVersionedFilesDecorator,
62
    )
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
63
64
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
65
compiled_knit_feature = tests.ModuleAvailableFeature(
66
                            'bzrlib._knit_load_data_pyx')
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
67
68
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.
69
class KnitContentTestsMixin(object):
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
70
71
    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.
72
        content = self._make_content([])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
73
74
    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.
75
        content = self._make_content([])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
76
        self.assertEqual(content.text(), [])
77
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.
78
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
79
        self.assertEqual(content.text(), ["text1", "text2"])
80
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.
81
    def test_copy(self):
82
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
83
        copy = content.copy()
84
        self.assertIsInstance(copy, content.__class__)
85
        self.assertEqual(copy.annotate(), content.annotate())
86
87
    def assertDerivedBlocksEqual(self, source, target, noeol=False):
88
        """Assert that the derived matching blocks match real output"""
89
        source_lines = source.splitlines(True)
90
        target_lines = target.splitlines(True)
91
        def nl(line):
92
            if noeol and not line.endswith('\n'):
93
                return line + '\n'
94
            else:
95
                return line
96
        source_content = self._make_content([(None, nl(l)) for l in source_lines])
97
        target_content = self._make_content([(None, nl(l)) for l in target_lines])
98
        line_delta = source_content.line_delta(target_content)
99
        delta_blocks = list(KnitContent.get_line_delta_blocks(line_delta,
100
            source_lines, target_lines))
5279.1.1 by Andrew Bennetts
lazy_import most things in merge.py; add a few representative modules to the import tariff tests; tweak a couple of other modules so that patiencediff is not necessarily imported; remove a bunch of unused imports from test_knit.py.
101
        matcher = PatienceSequenceMatcher(None, source_lines, target_lines)
102
        matcher_blocks = list(matcher.get_matching_blocks())
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.
103
        self.assertEqual(matcher_blocks, delta_blocks)
104
105
    def test_get_line_delta_blocks(self):
106
        self.assertDerivedBlocksEqual('a\nb\nc\n', 'q\nc\n')
107
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1)
108
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1A)
109
        self.assertDerivedBlocksEqual(TEXT_1, TEXT_1B)
110
        self.assertDerivedBlocksEqual(TEXT_1B, TEXT_1A)
111
        self.assertDerivedBlocksEqual(TEXT_1A, TEXT_1B)
112
        self.assertDerivedBlocksEqual(TEXT_1A, '')
113
        self.assertDerivedBlocksEqual('', TEXT_1A)
114
        self.assertDerivedBlocksEqual('', '')
115
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\nd')
116
117
    def test_get_line_delta_blocks_noeol(self):
118
        """Handle historical knit deltas safely
119
120
        Some existing knit deltas don't consider the last line to differ
121
        when the only difference whether it has a final newline.
122
123
        New knit deltas appear to always consider the last line to differ
124
        in this case.
125
        """
126
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\nd\n', noeol=True)
127
        self.assertDerivedBlocksEqual('a\nb\nc\nd\n', 'a\nb\nc', noeol=True)
128
        self.assertDerivedBlocksEqual('a\nb\nc\n', 'a\nb\nc', noeol=True)
129
        self.assertDerivedBlocksEqual('a\nb\nc', 'a\nb\nc\n', noeol=True)
130
131
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
132
TEXT_1 = """\
133
Banana cup cakes:
134
135
- bananas
136
- eggs
137
- broken tea cups
138
"""
139
140
TEXT_1A = """\
141
Banana cup cake recipe
142
(serves 6)
143
144
- bananas
145
- eggs
146
- broken tea cups
147
- self-raising flour
148
"""
149
150
TEXT_1B = """\
151
Banana cup cake recipe
152
153
- bananas (do not use plantains!!!)
154
- broken tea cups
155
- flour
156
"""
157
158
delta_1_1a = """\
159
0,1,2
160
Banana cup cake recipe
161
(serves 6)
162
5,5,1
163
- self-raising flour
164
"""
165
166
TEXT_2 = """\
167
Boeuf bourguignon
168
169
- beef
170
- red wine
171
- small onions
172
- carrot
173
- mushrooms
174
"""
175
176
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.
177
class TestPlainKnitContent(TestCase, KnitContentTestsMixin):
178
179
    def _make_content(self, lines):
180
        annotated_content = AnnotatedKnitContent(lines)
181
        return PlainKnitContent(annotated_content.text(), 'bogus')
182
183
    def test_annotate(self):
184
        content = self._make_content([])
185
        self.assertEqual(content.annotate(), [])
186
187
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
188
        self.assertEqual(content.annotate(),
189
            [("bogus", "text1"), ("bogus", "text2")])
190
191
    def test_line_delta(self):
192
        content1 = self._make_content([("", "a"), ("", "b")])
193
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
194
        self.assertEqual(content1.line_delta(content2),
195
            [(1, 2, 2, ["a", "c"])])
196
197
    def test_line_delta_iter(self):
198
        content1 = self._make_content([("", "a"), ("", "b")])
199
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
200
        it = content1.line_delta_iter(content2)
201
        self.assertEqual(it.next(), (1, 2, 2, ["a", "c"]))
202
        self.assertRaises(StopIteration, it.next)
203
204
205
class TestAnnotatedKnitContent(TestCase, KnitContentTestsMixin):
206
207
    def _make_content(self, lines):
208
        return AnnotatedKnitContent(lines)
209
210
    def test_annotate(self):
211
        content = self._make_content([])
212
        self.assertEqual(content.annotate(), [])
213
214
        content = self._make_content([("origin1", "text1"), ("origin2", "text2")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
215
        self.assertEqual(content.annotate(),
216
            [("origin1", "text1"), ("origin2", "text2")])
217
218
    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.
219
        content1 = self._make_content([("", "a"), ("", "b")])
220
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
221
        self.assertEqual(content1.line_delta(content2),
222
            [(1, 2, 2, [("", "a"), ("", "c")])])
223
224
    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.
225
        content1 = self._make_content([("", "a"), ("", "b")])
226
        content2 = self._make_content([("", "a"), ("", "a"), ("", "c")])
2151.1.1 by John Arbash Meinel
(Dmitry Vasiliev) Tune KnitContent and add tests
227
        it = content1.line_delta_iter(content2)
228
        self.assertEqual(it.next(), (1, 2, 2, [("", "a"), ("", "c")]))
229
        self.assertRaises(StopIteration, it.next)
230
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
231
232
class MockTransport(object):
233
234
    def __init__(self, file_lines=None):
235
        self.file_lines = file_lines
236
        self.calls = []
2196.2.3 by John Arbash Meinel
Update tests and code to pass after merging bzr.dev
237
        # We have no base directory for the MockTransport
238
        self.base = ''
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
239
240
    def get(self, filename):
241
        if self.file_lines is None:
242
            raise NoSuchFile(filename)
243
        else:
244
            return StringIO("\n".join(self.file_lines))
245
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
246
    def readv(self, relpath, offsets):
247
        fp = self.get(relpath)
248
        for offset, size in offsets:
249
            fp.seek(offset)
250
            yield offset, fp.read(size)
251
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
252
    def __getattr__(self, name):
253
        def queue_call(*args, **kwargs):
254
            self.calls.append((name, args, kwargs))
255
        return queue_call
256
257
3789.2.2 by John Arbash Meinel
Test that a readv() failing after yielding data will still raise Retry
258
class MockReadvFailingTransport(MockTransport):
259
    """Fail in the middle of a readv() result.
260
3789.2.3 by John Arbash Meinel
Change the mocking a bit, so we can be sure it is failing at the right time.
261
    This Transport will successfully yield the first two requested hunks, but
262
    raise NoSuchFile for the rest.
3789.2.2 by John Arbash Meinel
Test that a readv() failing after yielding data will still raise Retry
263
    """
264
265
    def readv(self, relpath, offsets):
3789.2.3 by John Arbash Meinel
Change the mocking a bit, so we can be sure it is failing at the right time.
266
        count = 0
3789.2.2 by John Arbash Meinel
Test that a readv() failing after yielding data will still raise Retry
267
        for result in MockTransport.readv(self, relpath, offsets):
3789.2.3 by John Arbash Meinel
Change the mocking a bit, so we can be sure it is failing at the right time.
268
            count += 1
269
            # we use 2 because the first offset is the pack header, the second
270
            # is the first actual content requset
271
            if count > 2:
3789.2.2 by John Arbash Meinel
Test that a readv() failing after yielding data will still raise Retry
272
                raise errors.NoSuchFile(relpath)
273
            yield result
274
275
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
276
class KnitRecordAccessTestsMixin(object):
277
    """Tests for getting and putting knit records."""
278
279
    def test_add_raw_records(self):
280
        """Add_raw_records adds records retrievable later."""
281
        access = self.get_access()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
282
        memos = access.add_raw_records([('key', 10)], '1234567890')
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
283
        self.assertEqual(['1234567890'], list(access.get_raw_records(memos)))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
284
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
285
    def test_add_several_raw_records(self):
286
        """add_raw_records with many records and read some back."""
287
        access = self.get_access()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
288
        memos = access.add_raw_records([('key', 10), ('key2', 2), ('key3', 5)],
289
            '12345678901234567')
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
290
        self.assertEqual(['1234567890', '12', '34567'],
291
            list(access.get_raw_records(memos)))
292
        self.assertEqual(['1234567890'],
293
            list(access.get_raw_records(memos[0:1])))
294
        self.assertEqual(['12'],
295
            list(access.get_raw_records(memos[1:2])))
296
        self.assertEqual(['34567'],
297
            list(access.get_raw_records(memos[2:3])))
298
        self.assertEqual(['1234567890', '34567'],
299
            list(access.get_raw_records(memos[0:1] + memos[2:3])))
300
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
301
302
class TestKnitKnitAccess(TestCaseWithMemoryTransport, KnitRecordAccessTestsMixin):
303
    """Tests for the .kndx implementation."""
304
305
    def get_access(self):
306
        """Get a .knit style access instance."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
307
        mapper = ConstantMapper("foo")
308
        access = _KnitKeyAccess(self.get_transport(), mapper)
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
309
        return access
3789.2.6 by John Arbash Meinel
Make _DirectPackAccess.reload_or_raise maintain the logic.
310
311
312
class _TestException(Exception):
313
    """Just an exception for local tests to use."""
314
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
315
316
class TestPackKnitAccess(TestCaseWithMemoryTransport, KnitRecordAccessTestsMixin):
317
    """Tests for the pack based access."""
318
319
    def get_access(self):
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
320
        return self._get_access()[0]
321
322
    def _get_access(self, packname='packfile', index='FOO'):
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
323
        transport = self.get_transport()
324
        def write_data(bytes):
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
325
            transport.append_bytes(packname, bytes)
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
326
        writer = pack.ContainerWriter(write_data)
327
        writer.begin()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
328
        access = _DirectPackAccess({})
329
        access.set_writer(writer, index, (transport, packname))
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
330
        return access, writer
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
331
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
332
    def make_pack_file(self):
333
        """Create a pack file with 2 records."""
334
        access, writer = self._get_access(packname='packname', index='foo')
335
        memos = []
336
        memos.extend(access.add_raw_records([('key1', 10)], '1234567890'))
337
        memos.extend(access.add_raw_records([('key2', 5)], '12345'))
338
        writer.end()
339
        return memos
340
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
341
    def make_vf_for_retrying(self):
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
342
        """Create 3 packs and a reload function.
343
344
        Originally, 2 pack files will have the data, but one will be missing.
345
        And then the third will be used in place of the first two if reload()
346
        is called.
347
348
        :return: (versioned_file, reload_counter)
349
            versioned_file  a KnitVersionedFiles using the packs for access
350
        """
4617.7.1 by Robert Collins
Lock the format knit retry tests depend on - knits aren't used for 2a formats.
351
        builder = self.make_branch_builder('.', format="1.9")
4454.3.59 by John Arbash Meinel
Track down why the annotate retry code was failing.
352
        builder.start_series()
353
        builder.build_snapshot('rev-1', None, [
354
            ('add', ('', 'root-id', 'directory', None)),
355
            ('add', ('file', 'file-id', 'file', 'content\nrev 1\n')),
356
            ])
357
        builder.build_snapshot('rev-2', ['rev-1'], [
358
            ('modify', ('file-id', 'content\nrev 2\n')),
359
            ])
360
        builder.build_snapshot('rev-3', ['rev-2'], [
361
            ('modify', ('file-id', 'content\nrev 3\n')),
362
            ])
363
        builder.finish_series()
364
        b = builder.get_branch()
365
        b.lock_write()
366
        self.addCleanup(b.unlock)
4145.1.6 by Robert Collins
More test fallout, but all caught now.
367
        # Pack these three revisions into another pack file, but don't remove
368
        # the originals
4454.3.59 by John Arbash Meinel
Track down why the annotate retry code was failing.
369
        repo = b.repository
4145.1.6 by Robert Collins
More test fallout, but all caught now.
370
        collection = repo._pack_collection
371
        collection.ensure_loaded()
372
        orig_packs = collection.packs
373
        packer = pack_repo.Packer(collection, orig_packs, '.testpack')
374
        new_pack = packer.pack()
375
        # forget about the new pack
376
        collection.reset()
377
        repo.refresh_data()
4454.3.59 by John Arbash Meinel
Track down why the annotate retry code was failing.
378
        vf = repo.revisions
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
379
        # Set up a reload() function that switches to using the new pack file
380
        new_index = new_pack.revision_index
381
        access_tuple = new_pack.access_tuple()
382
        reload_counter = [0, 0, 0]
383
        def reload():
384
            reload_counter[0] += 1
385
            if reload_counter[1] > 0:
386
                # We already reloaded, nothing more to do
387
                reload_counter[2] += 1
388
                return False
389
            reload_counter[1] += 1
390
            vf._index._graph_index._indices[:] = [new_index]
391
            vf._access._indices.clear()
392
            vf._access._indices[new_index] = access_tuple
393
            return True
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
394
        # Delete one of the pack files so the data will need to be reloaded. We
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
395
        # will delete the file with 'rev-2' in it
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
396
        trans, name = orig_packs[1].access_tuple()
397
        trans.delete(name)
398
        # We don't have the index trigger reloading because we want to test
399
        # that we reload when the .pack disappears
400
        vf._access._reload_func = reload
401
        return vf, reload_counter
402
3789.2.6 by John Arbash Meinel
Make _DirectPackAccess.reload_or_raise maintain the logic.
403
    def make_reload_func(self, return_val=True):
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
404
        reload_called = [0]
405
        def reload():
406
            reload_called[0] += 1
3789.2.6 by John Arbash Meinel
Make _DirectPackAccess.reload_or_raise maintain the logic.
407
            return return_val
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
408
        return reload_called, reload
409
3789.2.6 by John Arbash Meinel
Make _DirectPackAccess.reload_or_raise maintain the logic.
410
    def make_retry_exception(self):
411
        # We raise a real exception so that sys.exc_info() is properly
412
        # populated
413
        try:
414
            raise _TestException('foobar')
415
        except _TestException, e:
3789.2.29 by John Arbash Meinel
RetryWithNewPacks requires another argument.
416
            retry_exc = errors.RetryWithNewPacks(None, reload_occurred=False,
3789.2.6 by John Arbash Meinel
Make _DirectPackAccess.reload_or_raise maintain the logic.
417
                                                 exc_info=sys.exc_info())
418
        return retry_exc
419
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
420
    def test_read_from_several_packs(self):
421
        access, writer = self._get_access()
422
        memos = []
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
423
        memos.extend(access.add_raw_records([('key', 10)], '1234567890'))
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
424
        writer.end()
425
        access, writer = self._get_access('pack2', 'FOOBAR')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
426
        memos.extend(access.add_raw_records([('key', 5)], '12345'))
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
427
        writer.end()
428
        access, writer = self._get_access('pack3', 'BAZ')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
429
        memos.extend(access.add_raw_records([('key', 5)], 'alpha'))
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
430
        writer.end()
431
        transport = self.get_transport()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
432
        access = _DirectPackAccess({"FOO":(transport, 'packfile'),
2592.3.67 by Robert Collins
More tests for bzrlib.knit._PackAccess.
433
            "FOOBAR":(transport, 'pack2'),
434
            "BAZ":(transport, 'pack3')})
435
        self.assertEqual(['1234567890', '12345', 'alpha'],
436
            list(access.get_raw_records(memos)))
437
        self.assertEqual(['1234567890'],
438
            list(access.get_raw_records(memos[0:1])))
439
        self.assertEqual(['12345'],
440
            list(access.get_raw_records(memos[1:2])))
441
        self.assertEqual(['alpha'],
442
            list(access.get_raw_records(memos[2:3])))
443
        self.assertEqual(['1234567890', 'alpha'],
444
            list(access.get_raw_records(memos[0:1] + memos[2:3])))
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
445
2592.3.70 by Robert Collins
Allow setting a writer after creating a knit._PackAccess object.
446
    def test_set_writer(self):
447
        """The writer should be settable post construction."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
448
        access = _DirectPackAccess({})
2592.3.70 by Robert Collins
Allow setting a writer after creating a knit._PackAccess object.
449
        transport = self.get_transport()
450
        packname = 'packfile'
451
        index = 'foo'
452
        def write_data(bytes):
453
            transport.append_bytes(packname, bytes)
454
        writer = pack.ContainerWriter(write_data)
455
        writer.begin()
456
        access.set_writer(writer, index, (transport, packname))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
457
        memos = access.add_raw_records([('key', 10)], '1234567890')
2592.3.70 by Robert Collins
Allow setting a writer after creating a knit._PackAccess object.
458
        writer.end()
459
        self.assertEqual(['1234567890'], list(access.get_raw_records(memos)))
460
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
461
    def test_missing_index_raises_retry(self):
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
462
        memos = self.make_pack_file()
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
463
        transport = self.get_transport()
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
464
        reload_called, reload_func = self.make_reload_func()
465
        # Note that the index key has changed from 'foo' to 'bar'
466
        access = _DirectPackAccess({'bar':(transport, 'packname')},
467
                                   reload_func=reload_func)
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
468
        e = self.assertListRaises(errors.RetryWithNewPacks,
469
                                  access.get_raw_records, memos)
470
        # Because a key was passed in which does not match our index list, we
471
        # assume that the listing was already reloaded
472
        self.assertTrue(e.reload_occurred)
473
        self.assertIsInstance(e.exc_info, tuple)
474
        self.assertIs(e.exc_info[0], KeyError)
475
        self.assertIsInstance(e.exc_info[1], KeyError)
476
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
477
    def test_missing_index_raises_key_error_with_no_reload(self):
478
        memos = self.make_pack_file()
479
        transport = self.get_transport()
480
        # Note that the index key has changed from 'foo' to 'bar'
481
        access = _DirectPackAccess({'bar':(transport, 'packname')})
482
        e = self.assertListRaises(KeyError, access.get_raw_records, memos)
483
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
484
    def test_missing_file_raises_retry(self):
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
485
        memos = self.make_pack_file()
486
        transport = self.get_transport()
487
        reload_called, reload_func = self.make_reload_func()
488
        # Note that the 'filename' has been changed to 'different-packname'
489
        access = _DirectPackAccess({'foo':(transport, 'different-packname')},
490
                                   reload_func=reload_func)
491
        e = self.assertListRaises(errors.RetryWithNewPacks,
492
                                  access.get_raw_records, memos)
493
        # The file has gone missing, so we assume we need to reload
494
        self.assertFalse(e.reload_occurred)
495
        self.assertIsInstance(e.exc_info, tuple)
496
        self.assertIs(e.exc_info[0], errors.NoSuchFile)
497
        self.assertIsInstance(e.exc_info[1], errors.NoSuchFile)
498
        self.assertEqual('different-packname', e.exc_info[1].path)
499
500
    def test_missing_file_raises_no_such_file_with_no_reload(self):
501
        memos = self.make_pack_file()
502
        transport = self.get_transport()
503
        # Note that the 'filename' has been changed to 'different-packname'
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
504
        access = _DirectPackAccess({'foo':(transport, 'different-packname')})
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
505
        e = self.assertListRaises(errors.NoSuchFile,
3789.2.1 by John Arbash Meinel
_DirectPackAccess can now raise RetryWithNewPacks when we think something has happened.
506
                                  access.get_raw_records, memos)
507
3789.2.2 by John Arbash Meinel
Test that a readv() failing after yielding data will still raise Retry
508
    def test_failing_readv_raises_retry(self):
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
509
        memos = self.make_pack_file()
510
        transport = self.get_transport()
511
        failing_transport = MockReadvFailingTransport(
512
                                [transport.get_bytes('packname')])
513
        reload_called, reload_func = self.make_reload_func()
514
        access = _DirectPackAccess({'foo':(failing_transport, 'packname')},
515
                                   reload_func=reload_func)
516
        # Asking for a single record will not trigger the Mock failure
517
        self.assertEqual(['1234567890'],
518
            list(access.get_raw_records(memos[:1])))
519
        self.assertEqual(['12345'],
520
            list(access.get_raw_records(memos[1:2])))
521
        # A multiple offset readv() will fail mid-way through
522
        e = self.assertListRaises(errors.RetryWithNewPacks,
523
                                  access.get_raw_records, memos)
524
        # The file has gone missing, so we assume we need to reload
525
        self.assertFalse(e.reload_occurred)
526
        self.assertIsInstance(e.exc_info, tuple)
527
        self.assertIs(e.exc_info[0], errors.NoSuchFile)
528
        self.assertIsInstance(e.exc_info[1], errors.NoSuchFile)
529
        self.assertEqual('packname', e.exc_info[1].path)
530
531
    def test_failing_readv_raises_no_such_file_with_no_reload(self):
532
        memos = self.make_pack_file()
533
        transport = self.get_transport()
534
        failing_transport = MockReadvFailingTransport(
535
                                [transport.get_bytes('packname')])
536
        reload_called, reload_func = self.make_reload_func()
3789.2.2 by John Arbash Meinel
Test that a readv() failing after yielding data will still raise Retry
537
        access = _DirectPackAccess({'foo':(failing_transport, 'packname')})
3789.2.3 by John Arbash Meinel
Change the mocking a bit, so we can be sure it is failing at the right time.
538
        # Asking for a single record will not trigger the Mock failure
539
        self.assertEqual(['1234567890'],
540
            list(access.get_raw_records(memos[:1])))
541
        self.assertEqual(['12345'],
542
            list(access.get_raw_records(memos[1:2])))
543
        # A multiple offset readv() will fail mid-way through
3789.2.5 by John Arbash Meinel
Change _DirectPackAccess to only raise Retry when _reload_func is defined.
544
        e = self.assertListRaises(errors.NoSuchFile,
3789.2.2 by John Arbash Meinel
Test that a readv() failing after yielding data will still raise Retry
545
                                  access.get_raw_records, memos)
546
3789.2.6 by John Arbash Meinel
Make _DirectPackAccess.reload_or_raise maintain the logic.
547
    def test_reload_or_raise_no_reload(self):
548
        access = _DirectPackAccess({}, reload_func=None)
549
        retry_exc = self.make_retry_exception()
550
        # Without a reload_func, we will just re-raise the original exception
551
        self.assertRaises(_TestException, access.reload_or_raise, retry_exc)
552
553
    def test_reload_or_raise_reload_changed(self):
554
        reload_called, reload_func = self.make_reload_func(return_val=True)
555
        access = _DirectPackAccess({}, reload_func=reload_func)
556
        retry_exc = self.make_retry_exception()
557
        access.reload_or_raise(retry_exc)
558
        self.assertEqual([1], reload_called)
559
        retry_exc.reload_occurred=True
560
        access.reload_or_raise(retry_exc)
561
        self.assertEqual([2], reload_called)
562
563
    def test_reload_or_raise_reload_no_change(self):
564
        reload_called, reload_func = self.make_reload_func(return_val=False)
565
        access = _DirectPackAccess({}, reload_func=reload_func)
566
        retry_exc = self.make_retry_exception()
567
        # If reload_occurred is False, then we consider it an error to have
568
        # reload_func() return False (no changes).
569
        self.assertRaises(_TestException, access.reload_or_raise, retry_exc)
570
        self.assertEqual([1], reload_called)
571
        retry_exc.reload_occurred=True
572
        # If reload_occurred is True, then we assume nothing changed because
573
        # it had changed earlier, but didn't change again
574
        access.reload_or_raise(retry_exc)
575
        self.assertEqual([2], reload_called)
576
3789.2.13 by John Arbash Meinel
KnitVersionedFile.annotate() now retries when appropriate.
577
    def test_annotate_retries(self):
578
        vf, reload_counter = self.make_vf_for_retrying()
579
        # It is a little bit bogus to annotate the Revision VF, but it works,
580
        # as we have ancestry stored there
581
        key = ('rev-3',)
582
        reload_lines = vf.annotate(key)
583
        self.assertEqual([1, 1, 0], reload_counter)
584
        plain_lines = vf.annotate(key)
585
        self.assertEqual([1, 1, 0], reload_counter) # No extra reloading
586
        if reload_lines != plain_lines:
587
            self.fail('Annotation was not identical with reloading.')
588
        # Now delete the packs-in-use, which should trigger another reload, but
589
        # this time we just raise an exception because we can't recover
590
        for trans, name in vf._access._indices.itervalues():
591
            trans.delete(name)
592
        self.assertRaises(errors.NoSuchFile, vf.annotate, key)
593
        self.assertEqual([2, 1, 1], reload_counter)
594
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
595
    def test__get_record_map_retries(self):
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
596
        vf, reload_counter = self.make_vf_for_retrying()
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
597
        keys = [('rev-1',), ('rev-2',), ('rev-3',)]
3789.2.10 by John Arbash Meinel
The first function for KnitVersionedFiles can now retry on request.
598
        records = vf._get_record_map(keys)
599
        self.assertEqual(keys, sorted(records.keys()))
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
600
        self.assertEqual([1, 1, 0], reload_counter)
601
        # Now delete the packs-in-use, which should trigger another reload, but
602
        # this time we just raise an exception because we can't recover
603
        for trans, name in vf._access._indices.itervalues():
604
            trans.delete(name)
605
        self.assertRaises(errors.NoSuchFile, vf._get_record_map, keys)
606
        self.assertEqual([2, 1, 1], reload_counter)
607
608
    def test_get_record_stream_retries(self):
609
        vf, reload_counter = self.make_vf_for_retrying()
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
610
        keys = [('rev-1',), ('rev-2',), ('rev-3',)]
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
611
        record_stream = vf.get_record_stream(keys, 'topological', False)
612
        record = record_stream.next()
613
        self.assertEqual(('rev-1',), record.key)
614
        self.assertEqual([0, 0, 0], reload_counter)
615
        record = record_stream.next()
616
        self.assertEqual(('rev-2',), record.key)
617
        self.assertEqual([1, 1, 0], reload_counter)
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
618
        record = record_stream.next()
619
        self.assertEqual(('rev-3',), record.key)
620
        self.assertEqual([1, 1, 0], reload_counter)
3789.2.11 by John Arbash Meinel
KnitVersionedFile.get_record_stream now retries *and* fails correctly.
621
        # Now delete all pack files, and see that we raise the right error
622
        for trans, name in vf._access._indices.itervalues():
623
            trans.delete(name)
624
        self.assertListRaises(errors.NoSuchFile,
625
            vf.get_record_stream, keys, 'topological', False)
626
3789.2.12 by John Arbash Meinel
iter_lines_added_or_present now retries.
627
    def test_iter_lines_added_or_present_in_keys_retries(self):
628
        vf, reload_counter = self.make_vf_for_retrying()
629
        keys = [('rev-1',), ('rev-2',), ('rev-3',)]
630
        # Unfortunately, iter_lines_added_or_present_in_keys iterates the
631
        # result in random order (determined by the iteration order from a
632
        # set()), so we don't have any solid way to trigger whether data is
633
        # read before or after. However we tried to delete the middle node to
634
        # exercise the code well.
635
        # What we care about is that all lines are always yielded, but not
636
        # duplicated
637
        count = 0
638
        reload_lines = sorted(vf.iter_lines_added_or_present_in_keys(keys))
639
        self.assertEqual([1, 1, 0], reload_counter)
640
        # Now do it again, to make sure the result is equivalent
641
        plain_lines = sorted(vf.iter_lines_added_or_present_in_keys(keys))
642
        self.assertEqual([1, 1, 0], reload_counter) # No extra reloading
643
        self.assertEqual(plain_lines, reload_lines)
644
        self.assertEqual(21, len(plain_lines))
645
        # Now delete all pack files, and see that we raise the right error
646
        for trans, name in vf._access._indices.itervalues():
647
            trans.delete(name)
648
        self.assertListRaises(errors.NoSuchFile,
649
            vf.iter_lines_added_or_present_in_keys, keys)
650
        self.assertEqual([2, 1, 1], reload_counter)
651
3878.1.1 by John Arbash Meinel
KVF.get_record_stream('unordered') now returns the records based on I/O ordering.
652
    def test_get_record_stream_yields_disk_sorted_order(self):
653
        # if we get 'unordered' pick a semi-optimal order for reading. The
654
        # order should be grouped by pack file, and then by position in file
655
        repo = self.make_repository('test', format='pack-0.92')
656
        repo.lock_write()
657
        self.addCleanup(repo.unlock)
658
        repo.start_write_group()
659
        vf = repo.texts
660
        vf.add_lines(('f-id', 'rev-5'), [('f-id', 'rev-4')], ['lines\n'])
661
        vf.add_lines(('f-id', 'rev-1'), [], ['lines\n'])
662
        vf.add_lines(('f-id', 'rev-2'), [('f-id', 'rev-1')], ['lines\n'])
663
        repo.commit_write_group()
664
        # We inserted them as rev-5, rev-1, rev-2, we should get them back in
665
        # the same order
666
        stream = vf.get_record_stream([('f-id', 'rev-1'), ('f-id', 'rev-5'),
667
                                       ('f-id', 'rev-2')], 'unordered', False)
668
        keys = [r.key for r in stream]
669
        self.assertEqual([('f-id', 'rev-5'), ('f-id', 'rev-1'),
670
                          ('f-id', 'rev-2')], keys)
671
        repo.start_write_group()
672
        vf.add_lines(('f-id', 'rev-4'), [('f-id', 'rev-3')], ['lines\n'])
673
        vf.add_lines(('f-id', 'rev-3'), [('f-id', 'rev-2')], ['lines\n'])
674
        vf.add_lines(('f-id', 'rev-6'), [('f-id', 'rev-5')], ['lines\n'])
675
        repo.commit_write_group()
676
        # Request in random order, to make sure the output order isn't based on
677
        # the request
678
        request_keys = set(('f-id', 'rev-%d' % i) for i in range(1, 7))
679
        stream = vf.get_record_stream(request_keys, 'unordered', False)
680
        keys = [r.key for r in stream]
681
        # We want to get the keys back in disk order, but it doesn't matter
682
        # which pack we read from first. So this can come back in 2 orders
683
        alt1 = [('f-id', 'rev-%d' % i) for i in [4, 3, 6, 5, 1, 2]]
684
        alt2 = [('f-id', 'rev-%d' % i) for i in [5, 1, 2, 4, 3, 6]]
685
        if keys != alt1 and keys != alt2:
686
            self.fail('Returned key order did not match either expected order.'
687
                      ' expected %s or %s, not %s'
688
                      % (alt1, alt2, keys))
689
2592.3.66 by Robert Collins
Allow adaption of KnitData to pack files.
690
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
691
class LowLevelKnitDataTests(TestCase):
692
693
    def create_gz_content(self, text):
694
        sio = StringIO()
5279.1.1 by Andrew Bennetts
lazy_import most things in merge.py; add a few representative modules to the import tariff tests; tweak a couple of other modules so that patiencediff is not necessarily imported; remove a bunch of unused imports from test_knit.py.
695
        gz_file = tuned_gzip.GzipFile(mode='wb', fileobj=sio)
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
696
        gz_file.write(text)
697
        gz_file.close()
698
        return sio.getvalue()
699
3789.2.4 by John Arbash Meinel
Add a multiple-record test, though it isn't quite what we want for the readv tests.
700
    def make_multiple_records(self):
701
        """Create the content for multiple records."""
702
        sha1sum = osutils.sha('foo\nbar\n').hexdigest()
703
        total_txt = []
704
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
705
                                        'foo\n'
706
                                        'bar\n'
707
                                        'end rev-id-1\n'
708
                                        % (sha1sum,))
709
        record_1 = (0, len(gz_txt), sha1sum)
710
        total_txt.append(gz_txt)
711
        sha1sum = osutils.sha('baz\n').hexdigest()
712
        gz_txt = self.create_gz_content('version rev-id-2 1 %s\n'
713
                                        'baz\n'
714
                                        'end rev-id-2\n'
715
                                        % (sha1sum,))
716
        record_2 = (record_1[1], len(gz_txt), sha1sum)
717
        total_txt.append(gz_txt)
718
        return total_txt, record_1, record_2
719
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
720
    def test_valid_knit_data(self):
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
721
        sha1sum = osutils.sha('foo\nbar\n').hexdigest()
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
722
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
723
                                        'foo\n'
724
                                        'bar\n'
725
                                        'end rev-id-1\n'
726
                                        % (sha1sum,))
727
        transport = MockTransport([gz_txt])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
728
        access = _KnitKeyAccess(transport, ConstantMapper('filename'))
729
        knit = KnitVersionedFiles(None, access)
730
        records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
731
732
        contents = list(knit._read_records_iter(records))
733
        self.assertEqual([(('rev-id-1',), ['foo\n', 'bar\n'],
734
            '4e48e2c9a3d2ca8a708cb0cc545700544efb5021')], contents)
735
736
        raw_contents = list(knit._read_records_iter_raw(records))
737
        self.assertEqual([(('rev-id-1',), gz_txt, sha1sum)], raw_contents)
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
738
3789.2.4 by John Arbash Meinel
Add a multiple-record test, though it isn't quite what we want for the readv tests.
739
    def test_multiple_records_valid(self):
740
        total_txt, record_1, record_2 = self.make_multiple_records()
741
        transport = MockTransport([''.join(total_txt)])
742
        access = _KnitKeyAccess(transport, ConstantMapper('filename'))
743
        knit = KnitVersionedFiles(None, access)
744
        records = [(('rev-id-1',), (('rev-id-1',), record_1[0], record_1[1])),
745
                   (('rev-id-2',), (('rev-id-2',), record_2[0], record_2[1]))]
746
747
        contents = list(knit._read_records_iter(records))
748
        self.assertEqual([(('rev-id-1',), ['foo\n', 'bar\n'], record_1[2]),
749
                          (('rev-id-2',), ['baz\n'], record_2[2])],
750
                         contents)
751
752
        raw_contents = list(knit._read_records_iter_raw(records))
753
        self.assertEqual([(('rev-id-1',), total_txt[0], record_1[2]),
754
                          (('rev-id-2',), total_txt[1], record_2[2])],
755
                         raw_contents)
756
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
757
    def test_not_enough_lines(self):
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
758
        sha1sum = osutils.sha('foo\n').hexdigest()
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
759
        # record says 2 lines data says 1
760
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
761
                                        'foo\n'
762
                                        'end rev-id-1\n'
763
                                        % (sha1sum,))
764
        transport = MockTransport([gz_txt])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
765
        access = _KnitKeyAccess(transport, ConstantMapper('filename'))
766
        knit = KnitVersionedFiles(None, access)
767
        records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
768
        self.assertRaises(errors.KnitCorrupt, list,
769
            knit._read_records_iter(records))
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
770
771
        # read_records_iter_raw won't detect that sort of mismatch/corruption
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
772
        raw_contents = list(knit._read_records_iter_raw(records))
773
        self.assertEqual([(('rev-id-1',),  gz_txt, sha1sum)], raw_contents)
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
774
775
    def test_too_many_lines(self):
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
776
        sha1sum = osutils.sha('foo\nbar\n').hexdigest()
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
777
        # record says 1 lines data says 2
778
        gz_txt = self.create_gz_content('version rev-id-1 1 %s\n'
779
                                        'foo\n'
780
                                        'bar\n'
781
                                        'end rev-id-1\n'
782
                                        % (sha1sum,))
783
        transport = MockTransport([gz_txt])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
784
        access = _KnitKeyAccess(transport, ConstantMapper('filename'))
785
        knit = KnitVersionedFiles(None, access)
786
        records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
787
        self.assertRaises(errors.KnitCorrupt, list,
788
            knit._read_records_iter(records))
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
789
790
        # read_records_iter_raw won't detect that sort of mismatch/corruption
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
791
        raw_contents = list(knit._read_records_iter_raw(records))
792
        self.assertEqual([(('rev-id-1',), gz_txt, sha1sum)], raw_contents)
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
793
794
    def test_mismatched_version_id(self):
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
795
        sha1sum = osutils.sha('foo\nbar\n').hexdigest()
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
796
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
797
                                        'foo\n'
798
                                        'bar\n'
799
                                        'end rev-id-1\n'
800
                                        % (sha1sum,))
801
        transport = MockTransport([gz_txt])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
802
        access = _KnitKeyAccess(transport, ConstantMapper('filename'))
803
        knit = KnitVersionedFiles(None, access)
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
804
        # We are asking for rev-id-2, but the data is rev-id-1
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
805
        records = [(('rev-id-2',), (('rev-id-2',), 0, len(gz_txt)))]
806
        self.assertRaises(errors.KnitCorrupt, list,
807
            knit._read_records_iter(records))
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
808
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
809
        # read_records_iter_raw detects mismatches in the header
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
810
        self.assertRaises(errors.KnitCorrupt, list,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
811
            knit._read_records_iter_raw(records))
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
812
813
    def test_uncompressed_data(self):
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
814
        sha1sum = osutils.sha('foo\nbar\n').hexdigest()
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
815
        txt = ('version rev-id-1 2 %s\n'
816
               'foo\n'
817
               'bar\n'
818
               'end rev-id-1\n'
819
               % (sha1sum,))
820
        transport = MockTransport([txt])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
821
        access = _KnitKeyAccess(transport, ConstantMapper('filename'))
822
        knit = KnitVersionedFiles(None, access)
823
        records = [(('rev-id-1',), (('rev-id-1',), 0, len(txt)))]
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
824
825
        # We don't have valid gzip data ==> corrupt
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
826
        self.assertRaises(errors.KnitCorrupt, list,
827
            knit._read_records_iter(records))
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
828
829
        # read_records_iter_raw will notice the bad data
830
        self.assertRaises(errors.KnitCorrupt, list,
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
831
            knit._read_records_iter_raw(records))
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
832
833
    def test_corrupted_data(self):
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
834
        sha1sum = osutils.sha('foo\nbar\n').hexdigest()
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
835
        gz_txt = self.create_gz_content('version rev-id-1 2 %s\n'
836
                                        'foo\n'
837
                                        'bar\n'
838
                                        'end rev-id-1\n'
839
                                        % (sha1sum,))
840
        # Change 2 bytes in the middle to \xff
841
        gz_txt = gz_txt[:10] + '\xff\xff' + gz_txt[12:]
842
        transport = MockTransport([gz_txt])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
843
        access = _KnitKeyAccess(transport, ConstantMapper('filename'))
844
        knit = KnitVersionedFiles(None, access)
845
        records = [(('rev-id-1',), (('rev-id-1',), 0, len(gz_txt)))]
846
        self.assertRaises(errors.KnitCorrupt, list,
847
            knit._read_records_iter(records))
848
        # read_records_iter_raw will barf on bad gz data
849
        self.assertRaises(errors.KnitCorrupt, list,
850
            knit._read_records_iter_raw(records))
2329.1.1 by John Arbash Meinel
Update _KnitData parser to raise more helpful errors when it detects corruption.
851
852
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
853
class LowLevelKnitIndexTests(TestCase):
854
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
855
    def get_knit_index(self, transport, name, mode):
856
        mapper = ConstantMapper(name)
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
857
        from bzrlib._knit_load_data_py import _load_data_py
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
858
        self.overrideAttr(knit, '_load_data', _load_data_py)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
859
        allow_writes = lambda: 'w' in mode
860
        return _KndxIndex(transport, mapper, lambda:None, allow_writes, lambda:True)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
861
862
    def test_create_file(self):
863
        transport = MockTransport()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
864
        index = self.get_knit_index(transport, "filename", "w")
865
        index.keys()
866
        call = transport.calls.pop(0)
867
        # call[1][1] is a StringIO - we can't test it by simple equality.
868
        self.assertEqual('put_file_non_atomic', call[0])
869
        self.assertEqual('filename.kndx', call[1][0])
870
        # With no history, _KndxIndex writes a new index:
871
        self.assertEqual(_KndxIndex.HEADER,
872
            call[1][1].getvalue())
873
        self.assertEqual({'create_parent_dir': True}, call[2])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
874
875
    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
876
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
877
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
878
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
879
            _KndxIndex.HEADER,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
880
            '%s option 0 1 :' % (utf8_revision_id,)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
881
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
882
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
883
        # _KndxIndex is a private class, and deals in utf8 revision_ids, not
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
884
        # Unicode revision_ids.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
885
        self.assertEqual({(utf8_revision_id,):()},
886
            index.get_parent_map(index.keys()))
887
        self.assertFalse((unicode_revision_id,) in index.keys())
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
888
889
    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
890
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
891
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
892
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
893
            _KndxIndex.HEADER,
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
894
            "version option 0 1 .%s :" % (utf8_revision_id,)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
895
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
896
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
897
        self.assertEqual({("version",):((utf8_revision_id,),)},
898
            index.get_parent_map(index.keys()))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
899
900
    def test_read_ignore_corrupted_lines(self):
901
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
902
            _KndxIndex.HEADER,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
903
            "corrupted",
904
            "corrupted options 0 1 .b .c ",
905
            "version options 0 1 :"
906
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
907
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
908
        self.assertEqual(1, len(index.keys()))
909
        self.assertEqual(set([("version",)]), index.keys())
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
910
911
    def test_read_corrupted_header(self):
2196.2.3 by John Arbash Meinel
Update tests and code to pass after merging bzr.dev
912
        transport = MockTransport(['not a bzr knit index header\n'])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
913
        index = self.get_knit_index(transport, "filename", "r")
914
        self.assertRaises(KnitHeaderError, index.keys)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
915
916
    def test_read_duplicate_entries(self):
917
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
918
            _KndxIndex.HEADER,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
919
            "parent options 0 1 :",
920
            "version options1 0 1 0 :",
921
            "version options2 1 2 .other :",
922
            "version options3 3 4 0 .other :"
923
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
924
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
925
        self.assertEqual(2, len(index.keys()))
2592.3.8 by Robert Collins
Remove unneeded pulib method lookup on private class _KnitIndex.
926
        # check that the index used is the first one written. (Specific
927
        # to KnitIndex style indices.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
928
        self.assertEqual("1", index._dictionary_compress([("version",)]))
929
        self.assertEqual((("version",), 3, 4), index.get_position(("version",)))
930
        self.assertEqual(["options3"], index.get_options(("version",)))
931
        self.assertEqual({("version",):(("parent",), ("other",))},
932
            index.get_parent_map([("version",)]))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
933
934
    def test_read_compressed_parents(self):
935
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
936
            _KndxIndex.HEADER,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
937
            "a option 0 1 :",
938
            "b option 0 1 0 :",
939
            "c option 0 1 1 0 :",
940
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
941
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
942
        self.assertEqual({("b",):(("a",),), ("c",):(("b",), ("a",))},
943
            index.get_parent_map([("b",), ("c",)]))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
944
945
    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
946
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
947
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
948
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
949
            _KndxIndex.HEADER
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
950
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
951
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
952
        index.add_records([
953
            ((utf8_revision_id,), ["option"], ((utf8_revision_id,), 0, 1), [])])
954
        call = transport.calls.pop(0)
955
        # call[1][1] is a StringIO - we can't test it by simple equality.
956
        self.assertEqual('put_file_non_atomic', call[0])
957
        self.assertEqual('filename.kndx', call[1][0])
958
        # With no history, _KndxIndex writes a new index:
959
        self.assertEqual(_KndxIndex.HEADER +
960
            "\n%s option 0 1  :" % (utf8_revision_id,),
961
            call[1][1].getvalue())
962
        self.assertEqual({'create_parent_dir': True}, call[2])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
963
964
    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
965
        unicode_revision_id = u"version-\N{CYRILLIC CAPITAL LETTER A}"
966
        utf8_revision_id = unicode_revision_id.encode('utf-8')
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
967
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
968
            _KndxIndex.HEADER
969
            ])
970
        index = self.get_knit_index(transport, "filename", "r")
971
        index.add_records([
972
            (("version",), ["option"], (("version",), 0, 1), [(utf8_revision_id,)])])
973
        call = transport.calls.pop(0)
974
        # call[1][1] is a StringIO - we can't test it by simple equality.
975
        self.assertEqual('put_file_non_atomic', call[0])
976
        self.assertEqual('filename.kndx', call[1][0])
977
        # With no history, _KndxIndex writes a new index:
978
        self.assertEqual(_KndxIndex.HEADER +
979
            "\nversion option 0 1 .%s :" % (utf8_revision_id,),
980
            call[1][1].getvalue())
981
        self.assertEqual({'create_parent_dir': True}, call[2])
982
983
    def test_keys(self):
984
        transport = MockTransport([
985
            _KndxIndex.HEADER
986
            ])
987
        index = self.get_knit_index(transport, "filename", "r")
988
989
        self.assertEqual(set(), index.keys())
990
991
        index.add_records([(("a",), ["option"], (("a",), 0, 1), [])])
992
        self.assertEqual(set([("a",)]), index.keys())
993
994
        index.add_records([(("a",), ["option"], (("a",), 0, 1), [])])
995
        self.assertEqual(set([("a",)]), index.keys())
996
997
        index.add_records([(("b",), ["option"], (("b",), 0, 1), [])])
998
        self.assertEqual(set([("a",), ("b",)]), index.keys())
999
1000
    def add_a_b(self, index, random_id=None):
1001
        kwargs = {}
1002
        if random_id is not None:
1003
            kwargs["random_id"] = random_id
1004
        index.add_records([
1005
            (("a",), ["option"], (("a",), 0, 1), [("b",)]),
1006
            (("a",), ["opt"], (("a",), 1, 2), [("c",)]),
1007
            (("b",), ["option"], (("b",), 2, 3), [("a",)])
1008
            ], **kwargs)
1009
1010
    def assertIndexIsAB(self, index):
1011
        self.assertEqual({
1012
            ('a',): (('c',),),
1013
            ('b',): (('a',),),
1014
            },
1015
            index.get_parent_map(index.keys()))
1016
        self.assertEqual((("a",), 1, 2), index.get_position(("a",)))
1017
        self.assertEqual((("b",), 2, 3), index.get_position(("b",)))
1018
        self.assertEqual(["opt"], index.get_options(("a",)))
1019
1020
    def test_add_versions(self):
1021
        transport = MockTransport([
1022
            _KndxIndex.HEADER
1023
            ])
1024
        index = self.get_knit_index(transport, "filename", "r")
1025
1026
        self.add_a_b(index)
1027
        call = transport.calls.pop(0)
1028
        # call[1][1] is a StringIO - we can't test it by simple equality.
1029
        self.assertEqual('put_file_non_atomic', call[0])
1030
        self.assertEqual('filename.kndx', call[1][0])
1031
        # With no history, _KndxIndex writes a new index:
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1032
        self.assertEqual(
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1033
            _KndxIndex.HEADER +
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1034
            "\na option 0 1 .b :"
1035
            "\na opt 1 2 .c :"
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1036
            "\nb option 2 3 0 :",
1037
            call[1][1].getvalue())
1038
        self.assertEqual({'create_parent_dir': True}, call[2])
1039
        self.assertIndexIsAB(index)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1040
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
1041
    def test_add_versions_random_id_is_accepted(self):
1042
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1043
            _KndxIndex.HEADER
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
1044
            ])
1045
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1046
        self.add_a_b(index, random_id=True)
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
1047
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1048
    def test_delay_create_and_add_versions(self):
1049
        transport = MockTransport()
1050
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1051
        index = self.get_knit_index(transport, "filename", "w")
1052
        # dir_mode=0777)
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1053
        self.assertEqual([], transport.calls)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1054
        self.add_a_b(index)
1055
        #self.assertEqual(
1056
        #[    {"dir_mode": 0777, "create_parent_dir": True, "mode": "wb"},
1057
        #    kwargs)
1058
        # Two calls: one during which we load the existing index (and when its
1059
        # missing create it), then a second where we write the contents out.
1060
        self.assertEqual(2, len(transport.calls))
1061
        call = transport.calls.pop(0)
1062
        self.assertEqual('put_file_non_atomic', call[0])
1063
        self.assertEqual('filename.kndx', call[1][0])
1064
        # With no history, _KndxIndex writes a new index:
1065
        self.assertEqual(_KndxIndex.HEADER, call[1][1].getvalue())
1066
        self.assertEqual({'create_parent_dir': True}, call[2])
1067
        call = transport.calls.pop(0)
1068
        # call[1][1] is a StringIO - we can't test it by simple equality.
1069
        self.assertEqual('put_file_non_atomic', call[0])
1070
        self.assertEqual('filename.kndx', call[1][0])
1071
        # With no history, _KndxIndex writes a new index:
1072
        self.assertEqual(
1073
            _KndxIndex.HEADER +
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1074
            "\na option 0 1 .b :"
1075
            "\na opt 1 2 .c :"
1076
            "\nb option 2 3 0 :",
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1077
            call[1][1].getvalue())
1078
        self.assertEqual({'create_parent_dir': True}, call[2])
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1079
4039.3.5 by John Arbash Meinel
Add direct tests for _get_total_build_size.
1080
    def assertTotalBuildSize(self, size, keys, positions):
1081
        self.assertEqual(size,
1082
                         knit._get_total_build_size(None, keys, positions))
1083
1084
    def test__get_total_build_size(self):
1085
        positions = {
1086
            ('a',): (('fulltext', False), (('a',), 0, 100), None),
1087
            ('b',): (('line-delta', False), (('b',), 100, 21), ('a',)),
1088
            ('c',): (('line-delta', False), (('c',), 121, 35), ('b',)),
1089
            ('d',): (('line-delta', False), (('d',), 156, 12), ('b',)),
1090
            }
1091
        self.assertTotalBuildSize(100, [('a',)], positions)
1092
        self.assertTotalBuildSize(121, [('b',)], positions)
1093
        # c needs both a & b
1094
        self.assertTotalBuildSize(156, [('c',)], positions)
1095
        # we shouldn't count 'b' twice
1096
        self.assertTotalBuildSize(156, [('b',), ('c',)], positions)
1097
        self.assertTotalBuildSize(133, [('d',)], positions)
1098
        self.assertTotalBuildSize(168, [('c',), ('d',)], positions)
1099
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1100
    def test_get_position(self):
1101
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1102
            _KndxIndex.HEADER,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1103
            "a option 0 1 :",
1104
            "b option 1 2 :"
1105
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1106
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1107
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1108
        self.assertEqual((("a",), 0, 1), index.get_position(("a",)))
1109
        self.assertEqual((("b",), 1, 2), index.get_position(("b",)))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1110
1111
    def test_get_method(self):
1112
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1113
            _KndxIndex.HEADER,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1114
            "a fulltext,unknown 0 1 :",
1115
            "b unknown,line-delta 1 2 :",
1116
            "c bad 3 4 :"
1117
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1118
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1119
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
1120
        self.assertEqual("fulltext", index.get_method("a"))
1121
        self.assertEqual("line-delta", index.get_method("b"))
1122
        self.assertRaises(errors.KnitIndexUnknownMethod, index.get_method, "c")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1123
1124
    def test_get_options(self):
1125
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1126
            _KndxIndex.HEADER,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1127
            "a opt1 0 1 :",
1128
            "b opt2,opt3 1 2 :"
1129
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1130
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1131
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
1132
        self.assertEqual(["opt1"], index.get_options("a"))
1133
        self.assertEqual(["opt2", "opt3"], index.get_options("b"))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1134
3287.5.6 by Robert Collins
Remove _KnitIndex.get_parents.
1135
    def test_get_parent_map(self):
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1136
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1137
            _KndxIndex.HEADER,
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1138
            "a option 0 1 :",
1139
            "b option 1 2 0 .c :",
1140
            "c option 1 2 1 0 .e :"
1141
            ])
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1142
        index = self.get_knit_index(transport, "filename", "r")
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1143
3287.5.6 by Robert Collins
Remove _KnitIndex.get_parents.
1144
        self.assertEqual({
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1145
            ("a",):(),
1146
            ("b",):(("a",), ("c",)),
1147
            ("c",):(("b",), ("a",), ("e",)),
1148
            }, index.get_parent_map(index.keys()))
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1149
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1150
    def test_impossible_parent(self):
1151
        """Test we get KnitCorrupt if the parent couldn't possibly exist."""
1152
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1153
            _KndxIndex.HEADER,
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1154
            "a option 0 1 :",
1155
            "b option 0 1 4 :"  # We don't have a 4th record
1156
            ])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1157
        index = self.get_knit_index(transport, 'filename', 'r')
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
1158
        try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1159
            self.assertRaises(errors.KnitCorrupt, index.keys)
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
1160
        except TypeError, e:
1161
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1162
                           ' not exceptions.IndexError')
1163
                and sys.version_info[0:2] >= (2,5)):
1164
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1165
                                  ' raising new style exceptions with python'
1166
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1167
            else:
1168
                raise
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1169
1170
    def test_corrupted_parent(self):
1171
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1172
            _KndxIndex.HEADER,
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1173
            "a option 0 1 :",
1174
            "b option 0 1 :",
1175
            "c option 0 1 1v :", # Can't have a parent of '1v'
1176
            ])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1177
        index = self.get_knit_index(transport, 'filename', 'r')
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
1178
        try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1179
            self.assertRaises(errors.KnitCorrupt, index.keys)
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
1180
        except TypeError, e:
1181
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1182
                           ' not exceptions.ValueError')
1183
                and sys.version_info[0:2] >= (2,5)):
1184
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1185
                                  ' raising new style exceptions with python'
1186
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1187
            else:
1188
                raise
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1189
1190
    def test_corrupted_parent_in_list(self):
1191
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1192
            _KndxIndex.HEADER,
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1193
            "a option 0 1 :",
1194
            "b option 0 1 :",
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
1195
            "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.
1196
            ])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1197
        index = self.get_knit_index(transport, 'filename', 'r')
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
1198
        try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1199
            self.assertRaises(errors.KnitCorrupt, index.keys)
2484.1.17 by John Arbash Meinel
Workaround for Pyrex <0.9.5 and python >=2.5 incompatibilities.
1200
        except TypeError, e:
1201
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1202
                           ' not exceptions.ValueError')
1203
                and sys.version_info[0:2] >= (2,5)):
1204
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1205
                                  ' raising new style exceptions with python'
1206
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1207
            else:
1208
                raise
2484.1.13 by John Arbash Meinel
Add a test that KnitCorrupt is raised when parent strings are invalid.
1209
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1210
    def test_invalid_position(self):
1211
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1212
            _KndxIndex.HEADER,
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1213
            "a option 1v 1 :",
1214
            ])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1215
        index = self.get_knit_index(transport, 'filename', 'r')
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1216
        try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1217
            self.assertRaises(errors.KnitCorrupt, index.keys)
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1218
        except TypeError, e:
1219
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1220
                           ' not exceptions.ValueError')
1221
                and sys.version_info[0:2] >= (2,5)):
1222
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1223
                                  ' raising new style exceptions with python'
1224
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1225
            else:
1226
                raise
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1227
1228
    def test_invalid_size(self):
1229
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1230
            _KndxIndex.HEADER,
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1231
            "a option 1 1v :",
1232
            ])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1233
        index = self.get_knit_index(transport, 'filename', 'r')
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1234
        try:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1235
            self.assertRaises(errors.KnitCorrupt, index.keys)
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1236
        except TypeError, e:
1237
            if (str(e) == ('exceptions must be strings, classes, or instances,'
1238
                           ' not exceptions.ValueError')
1239
                and sys.version_info[0:2] >= (2,5)):
1240
                self.knownFailure('Pyrex <0.9.5 fails with TypeError when'
1241
                                  ' raising new style exceptions with python'
1242
                                  ' >=2.5')
2484.1.19 by John Arbash Meinel
Don't suppress the TypeError if it doesn't match our requirements.
1243
            else:
1244
                raise
2484.1.18 by John Arbash Meinel
Test that we properly verify the size and position strings.
1245
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
1246
    def test_scan_unvalidated_index_not_implemented(self):
1247
        transport = MockTransport()
1248
        index = self.get_knit_index(transport, 'filename', 'r')
1249
        self.assertRaises(
1250
            NotImplementedError, index.scan_unvalidated_index,
1251
            'dummy graph_index')
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
1252
        self.assertRaises(
1253
            NotImplementedError, index.get_missing_compression_parents)
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
1254
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1255
    def test_short_line(self):
1256
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1257
            _KndxIndex.HEADER,
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1258
            "a option 0 10  :",
1259
            "b option 10 10 0", # This line isn't terminated, ignored
1260
            ])
1261
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1262
        self.assertEqual(set([('a',)]), index.keys())
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1263
1264
    def test_skip_incomplete_record(self):
1265
        # A line with bogus data should just be skipped
1266
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1267
            _KndxIndex.HEADER,
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1268
            "a option 0 10  :",
1269
            "b option 10 10 0", # This line isn't terminated, ignored
1270
            "c option 20 10 0 :", # Properly terminated, and starts with '\n'
1271
            ])
1272
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1273
        self.assertEqual(set([('a',), ('c',)]), index.keys())
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1274
1275
    def test_trailing_characters(self):
1276
        # A line with bogus data should just be skipped
1277
        transport = MockTransport([
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1278
            _KndxIndex.HEADER,
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1279
            "a option 0 10  :",
1280
            "b option 10 10 0 :a", # This line has extra trailing characters
1281
            "c option 20 10 0 :", # Properly terminated, and starts with '\n'
1282
            ])
1283
        index = self.get_knit_index(transport, "filename", "r")
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1284
        self.assertEqual(set([('a',), ('c',)]), index.keys())
2484.1.24 by John Arbash Meinel
Add direct tests of how we handle incomplete/'broken' lines
1285
2158.3.1 by Dmitry Vasiliev
KnitIndex tests/fixes/optimizations
1286
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1287
class LowLevelKnitIndexTests_c(LowLevelKnitIndexTests):
1288
4913.2.20 by John Arbash Meinel
Change all of the compiled_foo to compiled_foo_feature
1289
    _test_needs_features = [compiled_knit_feature]
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1290
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1291
    def get_knit_index(self, transport, name, mode):
1292
        mapper = ConstantMapper(name)
4573.1.1 by Andrew Bennetts
Fix imports for _knit_load_data_pyx, which was recently renamed.
1293
        from bzrlib._knit_load_data_pyx import _load_data_c
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
1294
        self.overrideAttr(knit, '_load_data', _load_data_c)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1295
        allow_writes = lambda: mode == 'w'
4985.2.1 by Vincent Ladeuil
Deploy addAttrCleanup on the whole test suite.
1296
        return _KndxIndex(transport, mapper, lambda:None,
1297
                          allow_writes, lambda:True)
2484.1.1 by John Arbash Meinel
Add an initial function to read knit indexes in pyrex.
1298
1299
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
1300
class Test_KnitAnnotator(TestCaseWithMemoryTransport):
1301
1302
    def make_annotator(self):
1303
        factory = knit.make_pack_factory(True, True, 1)
1304
        vf = factory(self.get_transport())
1305
        return knit._KnitAnnotator(vf)
1306
1307
    def test__expand_fulltext(self):
1308
        ann = self.make_annotator()
1309
        rev_key = ('rev-id',)
4454.3.36 by John Arbash Meinel
Only cache the content objects that we will reuse.
1310
        ann._num_compression_children[rev_key] = 1
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
1311
        res = ann._expand_record(rev_key, (('parent-id',),), None,
1312
                           ['line1\n', 'line2\n'], ('fulltext', True))
1313
        # The content object and text lines should be cached appropriately
1314
        self.assertEqual(['line1\n', 'line2'], res)
1315
        content_obj = ann._content_objects[rev_key]
1316
        self.assertEqual(['line1\n', 'line2\n'], content_obj._lines)
1317
        self.assertEqual(res, content_obj.text())
1318
        self.assertEqual(res, ann._text_cache[rev_key])
1319
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
1320
    def test__expand_delta_comp_parent_not_available(self):
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
1321
        # Parent isn't available yet, so we return nothing, but queue up this
1322
        # node for later processing
1323
        ann = self.make_annotator()
1324
        rev_key = ('rev-id',)
1325
        parent_key = ('parent-id',)
1326
        record = ['0,1,1\n', 'new-line\n']
1327
        details = ('line-delta', False)
1328
        res = ann._expand_record(rev_key, (parent_key,), parent_key,
1329
                                 record, details)
1330
        self.assertEqual(None, res)
1331
        self.assertTrue(parent_key in ann._pending_deltas)
1332
        pending = ann._pending_deltas[parent_key]
1333
        self.assertEqual(1, len(pending))
1334
        self.assertEqual((rev_key, (parent_key,), record, details), pending[0])
1335
4454.3.33 by John Arbash Meinel
Change the _expand_record code to pop out old content objects.
1336
    def test__expand_record_tracks_num_children(self):
1337
        ann = self.make_annotator()
1338
        rev_key = ('rev-id',)
1339
        rev2_key = ('rev2-id',)
1340
        parent_key = ('parent-id',)
1341
        record = ['0,1,1\n', 'new-line\n']
1342
        details = ('line-delta', False)
1343
        ann._num_compression_children[parent_key] = 2
1344
        ann._expand_record(parent_key, (), None, ['line1\n', 'line2\n'],
1345
                           ('fulltext', False))
1346
        res = ann._expand_record(rev_key, (parent_key,), parent_key,
1347
                                 record, details)
1348
        self.assertEqual({parent_key: 1}, ann._num_compression_children)
1349
        # Expanding the second child should remove the content object, and the
1350
        # num_compression_children entry
1351
        res = ann._expand_record(rev2_key, (parent_key,), parent_key,
1352
                                 record, details)
1353
        self.assertFalse(parent_key in ann._content_objects)
1354
        self.assertEqual({}, ann._num_compression_children)
4454.3.36 by John Arbash Meinel
Only cache the content objects that we will reuse.
1355
        # We should not cache the content_objects for rev2 and rev, because
1356
        # they do not have compression children of their own.
1357
        self.assertEqual({}, ann._content_objects)
4454.3.33 by John Arbash Meinel
Change the _expand_record code to pop out old content objects.
1358
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
1359
    def test__expand_delta_records_blocks(self):
1360
        ann = self.make_annotator()
1361
        rev_key = ('rev-id',)
1362
        parent_key = ('parent-id',)
1363
        record = ['0,1,1\n', 'new-line\n']
1364
        details = ('line-delta', True)
1365
        ann._num_compression_children[parent_key] = 2
1366
        ann._expand_record(parent_key, (), None,
1367
                           ['line1\n', 'line2\n', 'line3\n'],
1368
                           ('fulltext', False))
1369
        ann._expand_record(rev_key, (parent_key,), parent_key, record, details)
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
1370
        self.assertEqual({(rev_key, parent_key): [(1, 1, 1), (3, 3, 0)]},
1371
                         ann._matching_blocks)
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
1372
        rev2_key = ('rev2-id',)
1373
        record = ['0,1,1\n', 'new-line\n']
1374
        details = ('line-delta', False)
1375
        ann._expand_record(rev2_key, (parent_key,), parent_key, record, details)
1376
        self.assertEqual([(1, 1, 2), (3, 3, 0)],
4454.3.38 by John Arbash Meinel
Start using left-matching-blocks during the actual annotation.
1377
                         ann._matching_blocks[(rev2_key, parent_key)])
1378
1379
    def test__get_parent_ann_uses_matching_blocks(self):
1380
        ann = self.make_annotator()
1381
        rev_key = ('rev-id',)
1382
        parent_key = ('parent-id',)
1383
        parent_ann = [(parent_key,)]*3
1384
        block_key = (rev_key, parent_key)
1385
        ann._annotations_cache[parent_key] = parent_ann
1386
        ann._matching_blocks[block_key] = [(0, 1, 1), (3, 3, 0)]
1387
        # We should not try to access any parent_lines content, because we know
1388
        # we already have the matching blocks
1389
        par_ann, blocks = ann._get_parent_annotations_and_matches(rev_key,
1390
                                        ['1\n', '2\n', '3\n'], parent_key)
1391
        self.assertEqual(parent_ann, par_ann)
1392
        self.assertEqual([(0, 1, 1), (3, 3, 0)], blocks)
1393
        self.assertEqual({}, ann._matching_blocks)
4454.3.37 by John Arbash Meinel
Add tests tha left-matching-blocks gets populated.
1394
4454.3.31 by John Arbash Meinel
Change the processing lines to now handle fallbacks properly.
1395
    def test__process_pending(self):
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
1396
        ann = self.make_annotator()
1397
        rev_key = ('rev-id',)
1398
        p1_key = ('p1-id',)
1399
        p2_key = ('p2-id',)
1400
        record = ['0,1,1\n', 'new-line\n']
1401
        details = ('line-delta', False)
1402
        p1_record = ['line1\n', 'line2\n']
4454.3.33 by John Arbash Meinel
Change the _expand_record code to pop out old content objects.
1403
        ann._num_compression_children[p1_key] = 1
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
1404
        res = ann._expand_record(rev_key, (p1_key,p2_key), p1_key,
1405
                                 record, details)
1406
        self.assertEqual(None, res)
1407
        # self.assertTrue(p1_key in ann._pending_deltas)
1408
        self.assertEqual({}, ann._pending_annotation)
1409
        # Now insert p1, and we should be able to expand the delta
1410
        res = ann._expand_record(p1_key, (), None, p1_record,
1411
                                 ('fulltext', False))
1412
        self.assertEqual(p1_record, res)
1413
        ann._annotations_cache[p1_key] = [(p1_key,)]*2
1414
        res = ann._process_pending(p1_key)
4454.3.31 by John Arbash Meinel
Change the processing lines to now handle fallbacks properly.
1415
        self.assertEqual([], res)
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
1416
        self.assertFalse(p1_key in ann._pending_deltas)
1417
        self.assertTrue(p2_key in ann._pending_annotation)
1418
        self.assertEqual({p2_key: [(rev_key, (p1_key, p2_key))]},
1419
                         ann._pending_annotation)
1420
        # Now fill in parent 2, and pending annotation should be satisfied
1421
        res = ann._expand_record(p2_key, (), None, [], ('fulltext', False))
4454.3.31 by John Arbash Meinel
Change the processing lines to now handle fallbacks properly.
1422
        ann._annotations_cache[p2_key] = []
1423
        res = ann._process_pending(p2_key)
1424
        self.assertEqual([rev_key], res)
1425
        self.assertEqual({}, ann._pending_annotation)
1426
        self.assertEqual({}, ann._pending_deltas)
4454.3.30 by John Arbash Meinel
add a bit more work to be able to process 'pending_annotations'.
1427
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
1428
    def test_record_delta_removes_basis(self):
1429
        ann = self.make_annotator()
1430
        ann._expand_record(('parent-id',), (), None,
1431
                           ['line1\n', 'line2\n'], ('fulltext', False))
1432
        ann._num_compression_children['parent-id'] = 2
1433
4454.3.64 by John Arbash Meinel
Ensure that _KnitAnnotator also supports add_special_text.
1434
    def test_annotate_special_text(self):
1435
        ann = self.make_annotator()
1436
        vf = ann._vf
1437
        rev1_key = ('rev-1',)
1438
        rev2_key = ('rev-2',)
1439
        rev3_key = ('rev-3',)
1440
        spec_key = ('special:',)
1441
        vf.add_lines(rev1_key, [], ['initial content\n'])
1442
        vf.add_lines(rev2_key, [rev1_key], ['initial content\n',
1443
                                            'common content\n',
1444
                                            'content in 2\n'])
1445
        vf.add_lines(rev3_key, [rev1_key], ['initial content\n',
1446
                                            'common content\n',
1447
                                            'content in 3\n'])
1448
        spec_text = ('initial content\n'
1449
                     'common content\n'
1450
                     'content in 2\n'
1451
                     'content in 3\n')
1452
        ann.add_special_text(spec_key, [rev2_key, rev3_key], spec_text)
1453
        anns, lines = ann.annotate(spec_key)
1454
        self.assertEqual([(rev1_key,),
1455
                          (rev2_key, rev3_key),
1456
                          (rev2_key,),
1457
                          (rev3_key,),
1458
                         ], anns)
1459
        self.assertEqualDiff(spec_text, ''.join(lines))
1460
4454.3.28 by John Arbash Meinel
Continue breaking things to build it up cleanly.
1461
1684.3.3 by Robert Collins
Add a special cased weaves to knit converter.
1462
class KnitTests(TestCaseWithTransport):
1463
    """Class containing knit test helper routines."""
1563.2.16 by Robert Collins
Change WeaveStore into VersionedFileStore and make its versoined file class parameterisable.
1464
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1465
    def make_test_knit(self, annotate=False, name='test'):
1466
        mapper = ConstantMapper(name)
1467
        return make_file_factory(annotate, mapper)(self.get_transport())
1863.1.1 by John Arbash Meinel
Allow Versioned files to do caching if explicitly asked, and implement for Knit
1468
1469
3787.1.1 by Robert Collins
Embed the failed text in sha1 knit errors.
1470
class TestBadShaError(KnitTests):
1471
    """Tests for handling of sha errors."""
1472
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1473
    def test_sha_exception_has_text(self):
3787.1.1 by Robert Collins
Embed the failed text in sha1 knit errors.
1474
        # having the failed text included in the error allows for recovery.
1475
        source = self.make_test_knit()
1476
        target = self.make_test_knit(name="target")
1477
        if not source._max_delta_chain:
1478
            raise TestNotApplicable(
1479
                "cannot get delta-caused sha failures without deltas.")
1480
        # create a basis
1481
        basis = ('basis',)
1482
        broken = ('broken',)
1483
        source.add_lines(basis, (), ['foo\n'])
1484
        source.add_lines(broken, (basis,), ['foo\n', 'bar\n'])
1485
        # Seed target with a bad basis text
1486
        target.add_lines(basis, (), ['gam\n'])
1487
        target.insert_record_stream(
1488
            source.get_record_stream([broken], 'unordered', False))
1489
        err = self.assertRaises(errors.KnitCorrupt,
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
1490
            target.get_record_stream([broken], 'unordered', True
1491
            ).next().get_bytes_as, 'chunked')
3787.1.1 by Robert Collins
Embed the failed text in sha1 knit errors.
1492
        self.assertEqual(['gam\n', 'bar\n'], err.content)
3787.1.2 by Robert Collins
Ensure SHA1KnitCorrupt formats ok.
1493
        # Test for formatting with live data
1494
        self.assertStartsWith(str(err), "Knit ")
3787.1.1 by Robert Collins
Embed the failed text in sha1 knit errors.
1495
1496
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
1497
class TestKnitIndex(KnitTests):
1498
1499
    def test_add_versions_dictionary_compresses(self):
1500
        """Adding versions to the index should update the lookup dict"""
1501
        knit = self.make_test_knit()
1502
        idx = knit._index
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1503
        idx.add_records([(('a-1',), ['fulltext'], (('a-1',), 0, 0), [])])
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
1504
        self.check_file_contents('test.kndx',
1505
            '# bzr knit index 8\n'
1506
            '\n'
1507
            'a-1 fulltext 0 0  :'
1508
            )
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1509
        idx.add_records([
1510
            (('a-2',), ['fulltext'], (('a-2',), 0, 0), [('a-1',)]),
1511
            (('a-3',), ['fulltext'], (('a-3',), 0, 0), [('a-2',)]),
1512
            ])
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
1513
        self.check_file_contents('test.kndx',
1514
            '# bzr knit index 8\n'
1515
            '\n'
1516
            'a-1 fulltext 0 0  :\n'
1517
            'a-2 fulltext 0 0 0 :\n'
1518
            'a-3 fulltext 0 0 1 :'
1519
            )
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1520
        self.assertEqual(set([('a-3',), ('a-1',), ('a-2',)]), idx.keys())
1521
        self.assertEqual({
1522
            ('a-1',): ((('a-1',), 0, 0), None, (), ('fulltext', False)),
1523
            ('a-2',): ((('a-2',), 0, 0), None, (('a-1',),), ('fulltext', False)),
1524
            ('a-3',): ((('a-3',), 0, 0), None, (('a-2',),), ('fulltext', False)),
1525
            }, idx.get_build_details(idx.keys()))
1526
        self.assertEqual({('a-1',):(),
1527
            ('a-2',):(('a-1',),),
1528
            ('a-3',):(('a-2',),),},
1529
            idx.get_parent_map(idx.keys()))
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
1530
1531
    def test_add_versions_fails_clean(self):
1532
        """If add_versions fails in the middle, it restores a pristine state.
1533
1534
        Any modifications that are made to the index are reset if all versions
1535
        cannot be added.
1536
        """
1537
        # This cheats a little bit by passing in a generator which will
1538
        # raise an exception before the processing finishes
1539
        # Other possibilities would be to have an version with the wrong number
1540
        # of entries, or to make the backing transport unable to write any
1541
        # files.
1542
1543
        knit = self.make_test_knit()
1544
        idx = knit._index
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1545
        idx.add_records([(('a-1',), ['fulltext'], (('a-1',), 0, 0), [])])
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
1546
1547
        class StopEarly(Exception):
1548
            pass
1549
1550
        def generate_failure():
1551
            """Add some entries and then raise an exception"""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1552
            yield (('a-2',), ['fulltext'], (None, 0, 0), ('a-1',))
1553
            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
1554
            raise StopEarly()
1555
1556
        # Assert the pre-condition
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1557
        def assertA1Only():
1558
            self.assertEqual(set([('a-1',)]), set(idx.keys()))
1559
            self.assertEqual(
1560
                {('a-1',): ((('a-1',), 0, 0), None, (), ('fulltext', False))},
1561
                idx.get_build_details([('a-1',)]))
1562
            self.assertEqual({('a-1',):()}, idx.get_parent_map(idx.keys()))
1563
1564
        assertA1Only()
1565
        self.assertRaises(StopEarly, idx.add_records, generate_failure())
2102.2.1 by John Arbash Meinel
Fix bug #64789 _KnitIndex.add_versions() should dict compress new revisions
1566
        # And it shouldn't be modified
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1567
        assertA1Only()
2171.1.1 by John Arbash Meinel
Knit index files should ignore empty indexes rather than consider them corrupt.
1568
1569
    def test_knit_index_ignores_empty_files(self):
1570
        # There was a race condition in older bzr, where a ^C at the right time
1571
        # could leave an empty .kndx file, which bzr would later claim was a
1572
        # corrupted file since the header was not present. In reality, the file
1573
        # just wasn't created, so it should be ignored.
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
1574
        t = transport.get_transport('.')
2171.1.1 by John Arbash Meinel
Knit index files should ignore empty indexes rather than consider them corrupt.
1575
        t.put_bytes('test.kndx', '')
1576
1577
        knit = self.make_test_knit()
1578
1579
    def test_knit_index_checks_header(self):
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
1580
        t = transport.get_transport('.')
2171.1.1 by John Arbash Meinel
Knit index files should ignore empty indexes rather than consider them corrupt.
1581
        t.put_bytes('test.kndx', '# not really a knit header\n\n')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1582
        k = self.make_test_knit()
1583
        self.assertRaises(KnitHeaderError, k.keys)
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.
1584
1585
1586
class TestGraphIndexKnit(KnitTests):
1587
    """Tests for knits using a GraphIndex rather than a KnitIndex."""
1588
1589
    def make_g_index(self, name, ref_lists=0, nodes=[]):
1590
        builder = GraphIndexBuilder(ref_lists)
1591
        for node, references, value in nodes:
1592
            builder.add_node(node, references, value)
1593
        stream = builder.finish()
1594
        trans = self.get_transport()
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
1595
        size = trans.put_file(name, stream)
1596
        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.
1597
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1598
    def two_graph_index(self, deltas=False, catch_adds=False):
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1599
        """Build a two-graph index.
1600
1601
        :param deltas: If true, use underlying indices with two node-ref
1602
            lists and 'parent' set to a delta-compressed against tail.
1603
        """
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.
1604
        # build a complex graph across several indices.
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1605
        if deltas:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1606
            # delta compression inn the index
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1607
            index1 = self.make_g_index('1', 2, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1608
                (('tip', ), 'N0 100', ([('parent', )], [], )),
1609
                (('tail', ), '', ([], []))])
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1610
            index2 = self.make_g_index('2', 2, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1611
                (('parent', ), ' 100 78', ([('tail', ), ('ghost', )], [('tail', )])),
1612
                (('separate', ), '', ([], []))])
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1613
        else:
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1614
            # just blob location and graph in the index.
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1615
            index1 = self.make_g_index('1', 1, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1616
                (('tip', ), 'N0 100', ([('parent', )], )),
1617
                (('tail', ), '', ([], ))])
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1618
            index2 = self.make_g_index('2', 1, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1619
                (('parent', ), ' 100 78', ([('tail', ), ('ghost', )], )),
1620
                (('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.
1621
        combined_index = CombinedGraphIndex([index1, index2])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1622
        if catch_adds:
1623
            self.combined_index = combined_index
1624
            self.caught_entries = []
1625
            add_callback = self.catch_add
1626
        else:
1627
            add_callback = None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1628
        return _KnitGraphIndex(combined_index, lambda:True, deltas=deltas,
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1629
            add_callback=add_callback)
2592.3.4 by Robert Collins
Implement get_ancestry/get_ancestry_with_ghosts for KnitGraphIndex.
1630
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1631
    def test_keys(self):
1632
        index = self.two_graph_index()
1633
        self.assertEqual(set([('tail',), ('tip',), ('parent',), ('separate',)]),
1634
            set(index.keys()))
2592.3.9 by Robert Collins
Implement KnitGraphIndex.has_version.
1635
2592.3.10 by Robert Collins
Implement KnitGraphIndex.get_position.
1636
    def test_get_position(self):
1637
        index = self.two_graph_index()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1638
        self.assertEqual((index._graph_index._indices[0], 0, 100), index.get_position(('tip',)))
1639
        self.assertEqual((index._graph_index._indices[1], 100, 78), index.get_position(('parent',)))
2592.3.10 by Robert Collins
Implement KnitGraphIndex.get_position.
1640
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1641
    def test_get_method_deltas(self):
1642
        index = self.two_graph_index(deltas=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1643
        self.assertEqual('fulltext', index.get_method(('tip',)))
1644
        self.assertEqual('line-delta', index.get_method(('parent',)))
2592.3.11 by Robert Collins
Implement KnitGraphIndex.get_method.
1645
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1646
    def test_get_method_no_deltas(self):
1647
        # check that the parent-history lookup is ignored with deltas=False.
1648
        index = self.two_graph_index(deltas=False)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1649
        self.assertEqual('fulltext', index.get_method(('tip',)))
1650
        self.assertEqual('fulltext', index.get_method(('parent',)))
2592.3.13 by Robert Collins
Implement KnitGraphIndex.get_method.
1651
2592.3.14 by Robert Collins
Implement KnitGraphIndex.get_options.
1652
    def test_get_options_deltas(self):
1653
        index = self.two_graph_index(deltas=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1654
        self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1655
        self.assertEqual(['line-delta'], index.get_options(('parent',)))
2592.3.14 by Robert Collins
Implement KnitGraphIndex.get_options.
1656
1657
    def test_get_options_no_deltas(self):
1658
        # check that the parent-history lookup is ignored with deltas=False.
1659
        index = self.two_graph_index(deltas=False)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1660
        self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1661
        self.assertEqual(['fulltext'], index.get_options(('parent',)))
1662
1663
    def test_get_parent_map(self):
1664
        index = self.two_graph_index()
1665
        self.assertEqual({('parent',):(('tail',), ('ghost',))},
1666
            index.get_parent_map([('parent',), ('ghost',)]))
2592.3.14 by Robert Collins
Implement KnitGraphIndex.get_options.
1667
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1668
    def catch_add(self, entries):
1669
        self.caught_entries.append(entries)
1670
1671
    def test_add_no_callback_errors(self):
1672
        index = self.two_graph_index()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1673
        self.assertRaises(errors.ReadOnlyError, index.add_records,
1674
            [(('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.
1675
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1676
    def test_add_version_smoke(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1677
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1678
        index.add_records([(('new',), 'fulltext,no-eol', (None, 50, 60),
1679
            [('separate',)])])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1680
        self.assertEqual([[(('new', ), 'N50 60', ((('separate',),),))]],
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1681
            self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1682
1683
    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.
1684
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1685
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1686
            [(('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.
1687
        self.assertEqual([], self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1688
1689
    def test_add_version_same_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1690
        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.
1691
        # options can be spelt two different ways
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1692
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
1693
        index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [('parent',)])])
1694
        # position/length are ignored (because each pack could have fulltext or
1695
        # delta, and be at a different position.
1696
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100),
1697
            [('parent',)])])
1698
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000),
1699
            [('parent',)])])
1700
        # but neither should have added data:
1701
        self.assertEqual([[], [], [], []], self.caught_entries)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1702
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1703
    def test_add_version_different_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1704
        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.
1705
        # change options
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1706
        self.assertRaises(errors.KnitCorrupt, index.add_records,
3946.2.2 by Jelmer Vernooij
Remove matching test, fix handling of parentless indexes.
1707
            [(('tip',), 'line-delta', (None, 0, 100), [('parent',)])])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1708
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1709
            [(('tip',), 'fulltext', (None, 0, 100), [('parent',)])])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1710
        # parents
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1711
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1712
            [(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1713
        self.assertEqual([], self.caught_entries)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1714
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1715
    def test_add_versions_nodeltas(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1716
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1717
        index.add_records([
1718
                (('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)]),
1719
                (('new2',), 'fulltext', (None, 0, 6), [('new',)]),
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1720
                ])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1721
        self.assertEqual([(('new', ), 'N50 60', ((('separate',),),)),
1722
            (('new2', ), ' 0 6', ((('new',),),))],
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1723
            sorted(self.caught_entries[0]))
1724
        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.
1725
1726
    def test_add_versions_deltas(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1727
        index = self.two_graph_index(deltas=True, catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1728
        index.add_records([
1729
                (('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)]),
1730
                (('new2',), 'line-delta', (None, 0, 6), [('new',)]),
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1731
                ])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1732
        self.assertEqual([(('new', ), 'N50 60', ((('separate',),), ())),
1733
            (('new2', ), ' 0 6', ((('new',),), (('new',),), ))],
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1734
            sorted(self.caught_entries[0]))
1735
        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.
1736
1737
    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.
1738
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1739
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1740
            [(('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.
1741
        self.assertEqual([], self.caught_entries)
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1742
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
1743
    def test_add_versions_random_id_accepted(self):
1744
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1745
        index.add_records([], random_id=True)
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
1746
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1747
    def test_add_versions_same_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1748
        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.
1749
        # options can be spelt two different ways
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1750
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100),
1751
            [('parent',)])])
1752
        index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100),
1753
            [('parent',)])])
1754
        # position/length are ignored (because each pack could have fulltext or
1755
        # delta, and be at a different position.
1756
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100),
1757
            [('parent',)])])
1758
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000),
1759
            [('parent',)])])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1760
        # but neither should have added data.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1761
        self.assertEqual([[], [], [], []], self.caught_entries)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1762
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1763
    def test_add_versions_different_dup(self):
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1764
        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.
1765
        # change options
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1766
        self.assertRaises(errors.KnitCorrupt, index.add_records,
3946.2.2 by Jelmer Vernooij
Remove matching test, fix handling of parentless indexes.
1767
            [(('tip',), 'line-delta', (None, 0, 100), [('parent',)])])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1768
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1769
            [(('tip',), 'fulltext', (None, 0, 100), [('parent',)])])
2592.3.17 by Robert Collins
Add add_version(s) to KnitGraphIndex, completing the required api for KnitVersionedFile.
1770
        # parents
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1771
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1772
            [(('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.
1773
        # change options in the second record
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1774
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1775
            [(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)]),
3946.2.2 by Jelmer Vernooij
Remove matching test, fix handling of parentless indexes.
1776
             (('tip',), 'line-delta', (None, 0, 100), [('parent',)])])
2592.3.19 by Robert Collins
Change KnitGraphIndex from returning data to performing a callback on insertions.
1777
        self.assertEqual([], self.caught_entries)
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1778
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1779
    def make_g_index_missing_compression_parent(self):
1780
        graph_index = self.make_g_index('missing_comp', 2,
1781
            [(('tip', ), ' 100 78',
1782
              ([('missing-parent', ), ('ghost', )], [('missing-parent', )]))])
1783
        return graph_index
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
1784
4257.4.14 by Andrew Bennetts
Add a unit test for _KnitGraphIndex.get_missing_parents, fix bug that it reveals.
1785
    def make_g_index_missing_parent(self):
1786
        graph_index = self.make_g_index('missing_parent', 2,
1787
            [(('parent', ), ' 100 78', ([], [])),
1788
             (('tip', ), ' 100 78',
1789
              ([('parent', ), ('missing-parent', )], [('parent', )])),
1790
              ])
1791
        return graph_index
1792
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1793
    def make_g_index_no_external_refs(self):
1794
        graph_index = self.make_g_index('no_external_refs', 2,
1795
            [(('rev', ), ' 100 78',
1796
              ([('parent', ), ('ghost', )], []))])
1797
        return graph_index
1798
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
1799
    def test_add_good_unvalidated_index(self):
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1800
        unvalidated = self.make_g_index_no_external_refs()
1801
        combined = CombinedGraphIndex([unvalidated])
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
1802
        index = _KnitGraphIndex(combined, lambda: True, deltas=True)
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
1803
        index.scan_unvalidated_index(unvalidated)
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
1804
        self.assertEqual(frozenset(), index.get_missing_compression_parents())
1805
4257.4.14 by Andrew Bennetts
Add a unit test for _KnitGraphIndex.get_missing_parents, fix bug that it reveals.
1806
    def test_add_missing_compression_parent_unvalidated_index(self):
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1807
        unvalidated = self.make_g_index_missing_compression_parent()
1808
        combined = CombinedGraphIndex([unvalidated])
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
1809
        index = _KnitGraphIndex(combined, lambda: True, deltas=True)
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
1810
        index.scan_unvalidated_index(unvalidated)
4011.5.6 by Andrew Bennetts
Make sure it's not possible to commit a pack write group when any versioned file has missing compression parents.
1811
        # This also checks that its only the compression parent that is
1812
        # examined, otherwise 'ghost' would also be reported as a missing
1813
        # parent.
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
1814
        self.assertEqual(
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1815
            frozenset([('missing-parent',)]),
1816
            index.get_missing_compression_parents())
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
1817
4257.4.14 by Andrew Bennetts
Add a unit test for _KnitGraphIndex.get_missing_parents, fix bug that it reveals.
1818
    def test_add_missing_noncompression_parent_unvalidated_index(self):
1819
        unvalidated = self.make_g_index_missing_parent()
1820
        combined = CombinedGraphIndex([unvalidated])
1821
        index = _KnitGraphIndex(combined, lambda: True, deltas=True,
1822
            track_external_parent_refs=True)
1823
        index.scan_unvalidated_index(unvalidated)
1824
        self.assertEqual(
1825
            frozenset([('missing-parent',)]), index.get_missing_parents())
1826
4257.4.15 by Andrew Bennetts
Add another test for _KnitGraphIndex.get_missing_parents().
1827
    def test_track_external_parent_refs(self):
1828
        g_index = self.make_g_index('empty', 2, [])
1829
        combined = CombinedGraphIndex([g_index])
1830
        index = _KnitGraphIndex(combined, lambda: True, deltas=True,
1831
            add_callback=self.catch_add, track_external_parent_refs=True)
1832
        self.caught_entries = []
1833
        index.add_records([
1834
            (('new-key',), 'fulltext,no-eol', (None, 50, 60),
1835
             [('parent-1',), ('parent-2',)])])
1836
        self.assertEqual(
1837
            frozenset([('parent-1',), ('parent-2',)]),
1838
            index.get_missing_parents())
1839
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
1840
    def test_add_unvalidated_index_with_present_external_references(self):
1841
        index = self.two_graph_index(deltas=True)
4011.5.10 by Andrew Bennetts
Replace XXX with better comment.
1842
        # Ugly hack to get at one of the underlying GraphIndex objects that
1843
        # two_graph_index built.
1844
        unvalidated = index._graph_index._indices[1]
1845
        # 'parent' is an external ref of _indices[1] (unvalidated), but is
1846
        # present in _indices[0].
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
1847
        index.scan_unvalidated_index(unvalidated)
4011.5.1 by Andrew Bennetts
Start to add _add_unvalidated_index/get_missing_compression_parents methods to _KnitGraphIndex.
1848
        self.assertEqual(frozenset(), index.get_missing_compression_parents())
1849
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1850
    def make_new_missing_parent_g_index(self, name):
1851
        missing_parent = name + '-missing-parent'
1852
        graph_index = self.make_g_index(name, 2,
1853
            [((name + 'tip', ), ' 100 78',
1854
              ([(missing_parent, ), ('ghost', )], [(missing_parent, )]))])
1855
        return graph_index
1856
1857
    def test_add_mulitiple_unvalidated_indices_with_missing_parents(self):
1858
        g_index_1 = self.make_new_missing_parent_g_index('one')
1859
        g_index_2 = self.make_new_missing_parent_g_index('two')
1860
        combined = CombinedGraphIndex([g_index_1, g_index_2])
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
1861
        index = _KnitGraphIndex(combined, lambda: True, deltas=True)
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
1862
        index.scan_unvalidated_index(g_index_1)
1863
        index.scan_unvalidated_index(g_index_2)
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1864
        self.assertEqual(
1865
            frozenset([('one-missing-parent',), ('two-missing-parent',)]),
1866
            index.get_missing_compression_parents())
1867
1868
    def test_add_mulitiple_unvalidated_indices_with_mutual_dependencies(self):
1869
        graph_index_a = self.make_g_index('one', 2,
1870
            [(('parent-one', ), ' 100 78', ([('non-compression-parent',)], [])),
1871
             (('child-of-two', ), ' 100 78',
1872
              ([('parent-two',)], [('parent-two',)]))])
1873
        graph_index_b = self.make_g_index('two', 2,
1874
            [(('parent-two', ), ' 100 78', ([('non-compression-parent',)], [])),
1875
             (('child-of-one', ), ' 100 78',
1876
              ([('parent-one',)], [('parent-one',)]))])
1877
        combined = CombinedGraphIndex([graph_index_a, graph_index_b])
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
1878
        index = _KnitGraphIndex(combined, lambda: True, deltas=True)
4011.5.7 by Andrew Bennetts
Remove leading underscore from _scan_unvalidate_index, explicitly NotImplementedError it for _KndxIndex.
1879
        index.scan_unvalidated_index(graph_index_a)
1880
        index.scan_unvalidated_index(graph_index_b)
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1881
        self.assertEqual(
1882
            frozenset([]), index.get_missing_compression_parents())
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
1883
4011.5.2 by Andrew Bennetts
Add more tests, improve existing tests, add GraphIndex._external_references()
1884
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1885
class TestNoParentsGraphIndexKnit(KnitTests):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1886
    """Tests for knits using _KnitGraphIndex with no parents."""
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1887
1888
    def make_g_index(self, name, ref_lists=0, nodes=[]):
1889
        builder = GraphIndexBuilder(ref_lists)
1890
        for node, references in nodes:
1891
            builder.add_node(node, references)
1892
        stream = builder.finish()
1893
        trans = self.get_transport()
2890.2.1 by Robert Collins
* ``bzrlib.index.GraphIndex`` now requires a size parameter to the
1894
        size = trans.put_file(name, stream)
1895
        return GraphIndex(trans, name, size)
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1896
4011.5.11 by Robert Collins
Polish the KnitVersionedFiles.scan_unvalidated_index api.
1897
    def test_add_good_unvalidated_index(self):
1898
        unvalidated = self.make_g_index('unvalidated')
1899
        combined = CombinedGraphIndex([unvalidated])
1900
        index = _KnitGraphIndex(combined, lambda: True, parents=False)
1901
        index.scan_unvalidated_index(unvalidated)
1902
        self.assertEqual(frozenset(),
1903
            index.get_missing_compression_parents())
1904
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1905
    def test_parents_deltas_incompatible(self):
1906
        index = CombinedGraphIndex([])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1907
        self.assertRaises(errors.KnitError, _KnitGraphIndex, lambda:True,
1908
            index, deltas=True, parents=False)
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1909
1910
    def two_graph_index(self, catch_adds=False):
1911
        """Build a two-graph index.
1912
1913
        :param deltas: If true, use underlying indices with two node-ref
1914
            lists and 'parent' set to a delta-compressed against tail.
1915
        """
1916
        # put several versions in the index.
1917
        index1 = self.make_g_index('1', 0, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1918
            (('tip', ), 'N0 100'),
1919
            (('tail', ), '')])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1920
        index2 = self.make_g_index('2', 0, [
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1921
            (('parent', ), ' 100 78'),
1922
            (('separate', ), '')])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1923
        combined_index = CombinedGraphIndex([index1, index2])
1924
        if catch_adds:
1925
            self.combined_index = combined_index
1926
            self.caught_entries = []
1927
            add_callback = self.catch_add
1928
        else:
1929
            add_callback = None
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1930
        return _KnitGraphIndex(combined_index, lambda:True, parents=False,
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1931
            add_callback=add_callback)
1932
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1933
    def test_keys(self):
1934
        index = self.two_graph_index()
1935
        self.assertEqual(set([('tail',), ('tip',), ('parent',), ('separate',)]),
1936
            set(index.keys()))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1937
1938
    def test_get_position(self):
1939
        index = self.two_graph_index()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1940
        self.assertEqual((index._graph_index._indices[0], 0, 100),
1941
            index.get_position(('tip',)))
1942
        self.assertEqual((index._graph_index._indices[1], 100, 78),
1943
            index.get_position(('parent',)))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1944
1945
    def test_get_method(self):
1946
        index = self.two_graph_index()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1947
        self.assertEqual('fulltext', index.get_method(('tip',)))
1948
        self.assertEqual(['fulltext'], index.get_options(('parent',)))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1949
1950
    def test_get_options(self):
1951
        index = self.two_graph_index()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1952
        self.assertEqual(['fulltext', 'no-eol'], index.get_options(('tip',)))
1953
        self.assertEqual(['fulltext'], index.get_options(('parent',)))
1954
1955
    def test_get_parent_map(self):
1956
        index = self.two_graph_index()
1957
        self.assertEqual({('parent',):None},
1958
            index.get_parent_map([('parent',), ('ghost',)]))
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1959
1960
    def catch_add(self, entries):
1961
        self.caught_entries.append(entries)
1962
1963
    def test_add_no_callback_errors(self):
1964
        index = self.two_graph_index()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1965
        self.assertRaises(errors.ReadOnlyError, index.add_records,
1966
            [(('new',), 'fulltext,no-eol', (None, 50, 60), [('separate',)])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1967
1968
    def test_add_version_smoke(self):
1969
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1970
        index.add_records([(('new',), 'fulltext,no-eol', (None, 50, 60), [])])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
1971
        self.assertEqual([[(('new', ), 'N50 60')]],
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1972
            self.caught_entries)
1973
1974
    def test_add_version_delta_not_delta_index(self):
1975
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1976
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1977
            [(('new',), 'no-eol,line-delta', (None, 0, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1978
        self.assertEqual([], self.caught_entries)
1979
1980
    def test_add_version_same_dup(self):
1981
        index = self.two_graph_index(catch_adds=True)
1982
        # options can be spelt two different ways
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1983
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
1984
        index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [])])
1985
        # position/length are ignored (because each pack could have fulltext or
1986
        # delta, and be at a different position.
1987
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100), [])])
1988
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1989
        # but neither should have added data.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1990
        self.assertEqual([[], [], [], []], self.caught_entries)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1991
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
1992
    def test_add_version_different_dup(self):
1993
        index = self.two_graph_index(catch_adds=True)
1994
        # change options
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1995
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1996
            [(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
1997
        self.assertRaises(errors.KnitCorrupt, index.add_records,
1998
            [(('tip',), 'line-delta,no-eol', (None, 0, 100), [])])
1999
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2000
            [(('tip',), 'fulltext', (None, 0, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2001
        # parents
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2002
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2003
            [(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2004
        self.assertEqual([], self.caught_entries)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2005
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2006
    def test_add_versions(self):
2007
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2008
        index.add_records([
2009
                (('new',), 'fulltext,no-eol', (None, 50, 60), []),
2010
                (('new2',), 'fulltext', (None, 0, 6), []),
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2011
                ])
2624.2.5 by Robert Collins
Change bzrlib.index.Index keys to be 1-tuples, not strings.
2012
        self.assertEqual([(('new', ), 'N50 60'), (('new2', ), ' 0 6')],
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2013
            sorted(self.caught_entries[0]))
2014
        self.assertEqual(1, len(self.caught_entries))
2015
2016
    def test_add_versions_delta_not_delta_index(self):
2017
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2018
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2019
            [(('new',), 'no-eol,line-delta', (None, 0, 100), [('parent',)])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2020
        self.assertEqual([], self.caught_entries)
2021
2022
    def test_add_versions_parents_not_parents_index(self):
2023
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2024
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2025
            [(('new',), 'no-eol,fulltext', (None, 0, 100), [('parent',)])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2026
        self.assertEqual([], self.caught_entries)
2027
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2028
    def test_add_versions_random_id_accepted(self):
2029
        index = self.two_graph_index(catch_adds=True)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2030
        index.add_records([], random_id=True)
2841.2.1 by Robert Collins
* Commit no longer checks for new text keys during insertion when the
2031
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2032
    def test_add_versions_same_dup(self):
2033
        index = self.two_graph_index(catch_adds=True)
2034
        # options can be spelt two different ways
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2035
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 100), [])])
2036
        index.add_records([(('tip',), 'no-eol,fulltext', (None, 0, 100), [])])
2037
        # position/length are ignored (because each pack could have fulltext or
2038
        # delta, and be at a different position.
2039
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 50, 100), [])])
2040
        index.add_records([(('tip',), 'fulltext,no-eol', (None, 0, 1000), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2041
        # but neither should have added data.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2042
        self.assertEqual([[], [], [], []], self.caught_entries)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2043
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2044
    def test_add_versions_different_dup(self):
2045
        index = self.two_graph_index(catch_adds=True)
2046
        # change options
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2047
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2048
            [(('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
2049
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2050
            [(('tip',), 'line-delta,no-eol', (None, 0, 100), [])])
2051
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2052
            [(('tip',), 'fulltext', (None, 0, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2053
        # parents
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2054
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2055
            [(('tip',), 'fulltext,no-eol', (None, 0, 100), [('parent',)])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2056
        # change options in the second record
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2057
        self.assertRaises(errors.KnitCorrupt, index.add_records,
2058
            [(('tip',), 'fulltext,no-eol', (None, 0, 100), []),
2059
             (('tip',), 'no-eol,line-delta', (None, 0, 100), [])])
2592.3.34 by Robert Collins
Rough unfactored support for parentless KnitGraphIndexs.
2060
        self.assertEqual([], self.caught_entries)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2061
2062
4039.3.6 by John Arbash Meinel
Turn _split_by_prefix into a classmethod, and add direct tests.
2063
class TestKnitVersionedFiles(KnitTests):
2064
4039.3.7 by John Arbash Meinel
Some direct tests for _group_keys_for_io
2065
    def assertGroupKeysForIo(self, exp_groups, keys, non_local_keys,
2066
                             positions, _min_buffer_size=None):
2067
        kvf = self.make_test_knit()
2068
        if _min_buffer_size is None:
2069
            _min_buffer_size = knit._STREAM_MIN_BUFFER_SIZE
2070
        self.assertEqual(exp_groups, kvf._group_keys_for_io(keys,
2071
                                        non_local_keys, positions,
2072
                                        _min_buffer_size=_min_buffer_size))
2073
4039.3.6 by John Arbash Meinel
Turn _split_by_prefix into a classmethod, and add direct tests.
2074
    def assertSplitByPrefix(self, expected_map, expected_prefix_order,
2075
                            keys):
2076
        split, prefix_order = KnitVersionedFiles._split_by_prefix(keys)
2077
        self.assertEqual(expected_map, split)
2078
        self.assertEqual(expected_prefix_order, prefix_order)
2079
4039.3.7 by John Arbash Meinel
Some direct tests for _group_keys_for_io
2080
    def test__group_keys_for_io(self):
2081
        ft_detail = ('fulltext', False)
2082
        ld_detail = ('line-delta', False)
2083
        f_a = ('f', 'a')
2084
        f_b = ('f', 'b')
2085
        f_c = ('f', 'c')
2086
        g_a = ('g', 'a')
2087
        g_b = ('g', 'b')
2088
        g_c = ('g', 'c')
2089
        positions = {
2090
            f_a: (ft_detail, (f_a, 0, 100), None),
2091
            f_b: (ld_detail, (f_b, 100, 21), f_a),
2092
            f_c: (ld_detail, (f_c, 180, 15), f_b),
2093
            g_a: (ft_detail, (g_a, 121, 35), None),
2094
            g_b: (ld_detail, (g_b, 156, 12), g_a),
2095
            g_c: (ld_detail, (g_c, 195, 13), g_a),
2096
            }
2097
        self.assertGroupKeysForIo([([f_a], set())],
2098
                                  [f_a], [], positions)
2099
        self.assertGroupKeysForIo([([f_a], set([f_a]))],
2100
                                  [f_a], [f_a], positions)
2101
        self.assertGroupKeysForIo([([f_a, f_b], set([]))],
2102
                                  [f_a, f_b], [], positions)
2103
        self.assertGroupKeysForIo([([f_a, f_b], set([f_b]))],
2104
                                  [f_a, f_b], [f_b], positions)
2105
        self.assertGroupKeysForIo([([f_a, f_b, g_a, g_b], set())],
2106
                                  [f_a, g_a, f_b, g_b], [], positions)
2107
        self.assertGroupKeysForIo([([f_a, f_b, g_a, g_b], set())],
2108
                                  [f_a, g_a, f_b, g_b], [], positions,
2109
                                  _min_buffer_size=150)
2110
        self.assertGroupKeysForIo([([f_a, f_b], set()), ([g_a, g_b], set())],
2111
                                  [f_a, g_a, f_b, g_b], [], positions,
2112
                                  _min_buffer_size=100)
2113
        self.assertGroupKeysForIo([([f_c], set()), ([g_b], set())],
2114
                                  [f_c, g_b], [], positions,
2115
                                  _min_buffer_size=125)
2116
        self.assertGroupKeysForIo([([g_b, f_c], set())],
2117
                                  [g_b, f_c], [], positions,
2118
                                  _min_buffer_size=125)
2119
4039.3.6 by John Arbash Meinel
Turn _split_by_prefix into a classmethod, and add direct tests.
2120
    def test__split_by_prefix(self):
2121
        self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2122
                                  'g': [('g', 'b'), ('g', 'a')],
2123
                                 }, ['f', 'g'],
2124
                                 [('f', 'a'), ('g', 'b'),
2125
                                  ('g', 'a'), ('f', 'b')])
2126
2127
        self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2128
                                  'g': [('g', 'b'), ('g', 'a')],
2129
                                 }, ['f', 'g'],
2130
                                 [('f', 'a'), ('f', 'b'),
2131
                                  ('g', 'b'), ('g', 'a')])
2132
2133
        self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2134
                                  'g': [('g', 'b'), ('g', 'a')],
2135
                                 }, ['f', 'g'],
2136
                                 [('f', 'a'), ('f', 'b'),
2137
                                  ('g', 'b'), ('g', 'a')])
2138
2139
        self.assertSplitByPrefix({'f': [('f', 'a'), ('f', 'b')],
2140
                                  'g': [('g', 'b'), ('g', 'a')],
2141
                                  '': [('a',), ('b',)]
2142
                                 }, ['f', 'g', ''],
2143
                                 [('f', 'a'), ('g', 'b'),
2144
                                  ('a',), ('b',),
2145
                                  ('g', 'a'), ('f', 'b')])
2146
2147
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2148
class TestStacking(KnitTests):
2149
2150
    def get_basis_and_test_knit(self):
2151
        basis = self.make_test_knit(name='basis')
3350.8.2 by Robert Collins
stacked get_parent_map.
2152
        basis = RecordingVersionedFilesDecorator(basis)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2153
        test = self.make_test_knit(name='test')
2154
        test.add_fallback_versioned_files(basis)
2155
        return basis, test
2156
2157
    def test_add_fallback_versioned_files(self):
2158
        basis = self.make_test_knit(name='basis')
2159
        test = self.make_test_knit(name='test')
2160
        # It must not error; other tests test that the fallback is referred to
2161
        # when accessing data.
2162
        test.add_fallback_versioned_files(basis)
2163
2164
    def test_add_lines(self):
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
2165
        # lines added to the test are not added to the basis
2166
        basis, test = self.get_basis_and_test_knit()
2167
        key = ('foo',)
2168
        key_basis = ('bar',)
2169
        key_cross_border = ('quux',)
2170
        key_delta = ('zaphod',)
2171
        test.add_lines(key, (), ['foo\n'])
2172
        self.assertEqual({}, basis.get_parent_map([key]))
2173
        # lines added to the test that reference across the stack do a
2174
        # fulltext.
2175
        basis.add_lines(key_basis, (), ['foo\n'])
2176
        basis.calls = []
2177
        test.add_lines(key_cross_border, (key_basis,), ['foo\n'])
2178
        self.assertEqual('fulltext', test._index.get_method(key_cross_border))
3830.3.10 by Martin Pool
Update more stacking effort tests
2179
        # we don't even need to look at the basis to see that this should be
2180
        # stored as a fulltext
2181
        self.assertEqual([], basis.calls)
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
2182
        # Subsequent adds do delta.
3350.8.14 by Robert Collins
Review feedback.
2183
        basis.calls = []
3350.8.9 by Robert Collins
define behaviour for add_lines with stacked storage.
2184
        test.add_lines(key_delta, (key_cross_border,), ['foo\n'])
2185
        self.assertEqual('line-delta', test._index.get_method(key_delta))
2186
        self.assertEqual([], basis.calls)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2187
2188
    def test_annotate(self):
3350.8.8 by Robert Collins
Stacking and knits don't play nice for annotation yet.
2189
        # annotations from the test knit are answered without asking the basis
2190
        basis, test = self.get_basis_and_test_knit()
2191
        key = ('foo',)
2192
        key_basis = ('bar',)
2193
        key_missing = ('missing',)
2194
        test.add_lines(key, (), ['foo\n'])
2195
        details = test.annotate(key)
2196
        self.assertEqual([(key, 'foo\n')], details)
2197
        self.assertEqual([], basis.calls)
2198
        # But texts that are not in the test knit are looked for in the basis
2199
        # directly.
2200
        basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
2201
        basis.calls = []
2202
        details = test.annotate(key_basis)
2203
        self.assertEqual([(key_basis, 'foo\n'), (key_basis, 'bar\n')], details)
3350.9.1 by Robert Collins
Redo annotate more simply, using just the public interfaces for VersionedFiles.
2204
        # Not optimised to date:
2205
        # self.assertEqual([("annotate", key_basis)], basis.calls)
2206
        self.assertEqual([('get_parent_map', set([key_basis])),
2207
            ('get_parent_map', set([key_basis])),
4537.3.5 by John Arbash Meinel
Fix 3 tests that assumed it would use 'unordered' in the fallback,
2208
            ('get_record_stream', [key_basis], 'topological', True)],
3350.9.1 by Robert Collins
Redo annotate more simply, using just the public interfaces for VersionedFiles.
2209
            basis.calls)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2210
2211
    def test_check(self):
3517.4.19 by Martin Pool
Update test for knit.check() to expect it to recurse into fallback vfs
2212
        # At the moment checking a stacked knit does implicitly check the
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2213
        # fallback files.
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2214
        basis, test = self.get_basis_and_test_knit()
2215
        test.check()
2216
2217
    def test_get_parent_map(self):
3350.8.2 by Robert Collins
stacked get_parent_map.
2218
        # parents in the test knit are answered without asking the basis
2219
        basis, test = self.get_basis_and_test_knit()
2220
        key = ('foo',)
2221
        key_basis = ('bar',)
2222
        key_missing = ('missing',)
2223
        test.add_lines(key, (), [])
2224
        parent_map = test.get_parent_map([key])
2225
        self.assertEqual({key: ()}, parent_map)
2226
        self.assertEqual([], basis.calls)
2227
        # But parents that are not in the test knit are looked for in the basis
2228
        basis.add_lines(key_basis, (), [])
2229
        basis.calls = []
2230
        parent_map = test.get_parent_map([key, key_basis, key_missing])
2231
        self.assertEqual({key: (),
2232
            key_basis: ()}, parent_map)
2233
        self.assertEqual([("get_parent_map", set([key_basis, key_missing]))],
2234
            basis.calls)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2235
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
2236
    def test_get_record_stream_unordered_fulltexts(self):
2237
        # records from the test knit are answered without asking the basis:
2238
        basis, test = self.get_basis_and_test_knit()
2239
        key = ('foo',)
2240
        key_basis = ('bar',)
2241
        key_missing = ('missing',)
2242
        test.add_lines(key, (), ['foo\n'])
2243
        records = list(test.get_record_stream([key], 'unordered', True))
2244
        self.assertEqual(1, len(records))
2245
        self.assertEqual([], basis.calls)
2246
        # Missing (from test knit) objects are retrieved from the basis:
2247
        basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
2248
        basis.calls = []
2249
        records = list(test.get_record_stream([key_basis, key_missing],
2250
            'unordered', True))
2251
        self.assertEqual(2, len(records))
2252
        calls = list(basis.calls)
2253
        for record in records:
2254
            self.assertSubset([record.key], (key_basis, key_missing))
2255
            if record.key == key_missing:
2256
                self.assertIsInstance(record, AbsentContentFactory)
2257
            else:
2258
                reference = list(basis.get_record_stream([key_basis],
2259
                    'unordered', True))[0]
2260
                self.assertEqual(reference.key, record.key)
2261
                self.assertEqual(reference.sha1, record.sha1)
2262
                self.assertEqual(reference.storage_kind, record.storage_kind)
2263
                self.assertEqual(reference.get_bytes_as(reference.storage_kind),
2264
                    record.get_bytes_as(record.storage_kind))
2265
                self.assertEqual(reference.get_bytes_as('fulltext'),
2266
                    record.get_bytes_as('fulltext'))
3350.8.14 by Robert Collins
Review feedback.
2267
        # It's not strictly minimal, but it seems reasonable for now for it to
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
2268
        # ask which fallbacks have which parents.
2269
        self.assertEqual([
2270
            ("get_parent_map", set([key_basis, key_missing])),
2271
            ("get_record_stream", [key_basis], 'unordered', True)],
2272
            calls)
2273
2274
    def test_get_record_stream_ordered_fulltexts(self):
2275
        # ordering is preserved down into the fallback store.
2276
        basis, test = self.get_basis_and_test_knit()
2277
        key = ('foo',)
2278
        key_basis = ('bar',)
2279
        key_basis_2 = ('quux',)
2280
        key_missing = ('missing',)
2281
        test.add_lines(key, (key_basis,), ['foo\n'])
2282
        # Missing (from test knit) objects are retrieved from the basis:
2283
        basis.add_lines(key_basis, (key_basis_2,), ['foo\n', 'bar\n'])
2284
        basis.add_lines(key_basis_2, (), ['quux\n'])
2285
        basis.calls = []
2286
        # ask for in non-topological order
2287
        records = list(test.get_record_stream(
2288
            [key, key_basis, key_missing, key_basis_2], 'topological', True))
2289
        self.assertEqual(4, len(records))
2290
        results = []
2291
        for record in records:
2292
            self.assertSubset([record.key],
2293
                (key_basis, key_missing, key_basis_2, key))
2294
            if record.key == key_missing:
2295
                self.assertIsInstance(record, AbsentContentFactory)
2296
            else:
2297
                results.append((record.key, record.sha1, record.storage_kind,
2298
                    record.get_bytes_as('fulltext')))
2299
        calls = list(basis.calls)
2300
        order = [record[0] for record in results]
2301
        self.assertEqual([key_basis_2, key_basis, key], order)
2302
        for result in results:
2303
            if result[0] == key:
2304
                source = test
2305
            else:
2306
                source = basis
2307
            record = source.get_record_stream([result[0]], 'unordered',
2308
                True).next()
2309
            self.assertEqual(record.key, result[0])
2310
            self.assertEqual(record.sha1, result[1])
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2311
            # We used to check that the storage kind matched, but actually it
2312
            # depends on whether it was sourced from the basis, or in a single
2313
            # group, because asking for full texts returns proxy objects to a
2314
            # _ContentMapGenerator object; so checking the kind is unneeded.
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
2315
            self.assertEqual(record.get_bytes_as('fulltext'), result[3])
3350.8.14 by Robert Collins
Review feedback.
2316
        # It's not strictly minimal, but it seems reasonable for now for it to
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
2317
        # ask which fallbacks have which parents.
2318
        self.assertEqual([
2319
            ("get_parent_map", set([key_basis, key_basis_2, key_missing])),
4537.3.5 by John Arbash Meinel
Fix 3 tests that assumed it would use 'unordered' in the fallback,
2320
            # topological is requested from the fallback, because that is what
2321
            # was requested at the top level.
2322
            ("get_record_stream", [key_basis_2, key_basis], 'topological', True)],
3350.8.7 by Robert Collins
get_record_stream for fulltexts working (but note extreme memory use!).
2323
            calls)
2324
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
2325
    def test_get_record_stream_unordered_deltas(self):
2326
        # records from the test knit are answered without asking the basis:
2327
        basis, test = self.get_basis_and_test_knit()
2328
        key = ('foo',)
2329
        key_basis = ('bar',)
2330
        key_missing = ('missing',)
2331
        test.add_lines(key, (), ['foo\n'])
2332
        records = list(test.get_record_stream([key], 'unordered', False))
2333
        self.assertEqual(1, len(records))
2334
        self.assertEqual([], basis.calls)
2335
        # Missing (from test knit) objects are retrieved from the basis:
2336
        basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
2337
        basis.calls = []
2338
        records = list(test.get_record_stream([key_basis, key_missing],
2339
            'unordered', False))
2340
        self.assertEqual(2, len(records))
2341
        calls = list(basis.calls)
2342
        for record in records:
2343
            self.assertSubset([record.key], (key_basis, key_missing))
2344
            if record.key == key_missing:
2345
                self.assertIsInstance(record, AbsentContentFactory)
2346
            else:
2347
                reference = list(basis.get_record_stream([key_basis],
2348
                    'unordered', False))[0]
2349
                self.assertEqual(reference.key, record.key)
2350
                self.assertEqual(reference.sha1, record.sha1)
2351
                self.assertEqual(reference.storage_kind, record.storage_kind)
2352
                self.assertEqual(reference.get_bytes_as(reference.storage_kind),
2353
                    record.get_bytes_as(record.storage_kind))
3350.8.14 by Robert Collins
Review feedback.
2354
        # It's not strictly minimal, but it seems reasonable for now for it to
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
2355
        # ask which fallbacks have which parents.
2356
        self.assertEqual([
2357
            ("get_parent_map", set([key_basis, key_missing])),
2358
            ("get_record_stream", [key_basis], 'unordered', False)],
2359
            calls)
2360
2361
    def test_get_record_stream_ordered_deltas(self):
2362
        # ordering is preserved down into the fallback store.
2363
        basis, test = self.get_basis_and_test_knit()
2364
        key = ('foo',)
2365
        key_basis = ('bar',)
2366
        key_basis_2 = ('quux',)
2367
        key_missing = ('missing',)
2368
        test.add_lines(key, (key_basis,), ['foo\n'])
2369
        # Missing (from test knit) objects are retrieved from the basis:
2370
        basis.add_lines(key_basis, (key_basis_2,), ['foo\n', 'bar\n'])
2371
        basis.add_lines(key_basis_2, (), ['quux\n'])
2372
        basis.calls = []
2373
        # ask for in non-topological order
2374
        records = list(test.get_record_stream(
2375
            [key, key_basis, key_missing, key_basis_2], 'topological', False))
2376
        self.assertEqual(4, len(records))
2377
        results = []
2378
        for record in records:
2379
            self.assertSubset([record.key],
2380
                (key_basis, key_missing, key_basis_2, key))
2381
            if record.key == key_missing:
2382
                self.assertIsInstance(record, AbsentContentFactory)
2383
            else:
2384
                results.append((record.key, record.sha1, record.storage_kind,
2385
                    record.get_bytes_as(record.storage_kind)))
2386
        calls = list(basis.calls)
2387
        order = [record[0] for record in results]
2388
        self.assertEqual([key_basis_2, key_basis, key], order)
2389
        for result in results:
2390
            if result[0] == key:
2391
                source = test
2392
            else:
2393
                source = basis
2394
            record = source.get_record_stream([result[0]], 'unordered',
2395
                False).next()
2396
            self.assertEqual(record.key, result[0])
2397
            self.assertEqual(record.sha1, result[1])
2398
            self.assertEqual(record.storage_kind, result[2])
2399
            self.assertEqual(record.get_bytes_as(record.storage_kind), result[3])
3350.8.14 by Robert Collins
Review feedback.
2400
        # It's not strictly minimal, but it seems reasonable for now for it to
3350.8.6 by Robert Collins
get_record_stream stacking for delta access.
2401
        # ask which fallbacks have which parents.
2402
        self.assertEqual([
2403
            ("get_parent_map", set([key_basis, key_basis_2, key_missing])),
2404
            ("get_record_stream", [key_basis_2, key_basis], 'topological', False)],
2405
            calls)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2406
2407
    def test_get_sha1s(self):
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
2408
        # sha1's in the test knit are answered without asking the basis
2409
        basis, test = self.get_basis_and_test_knit()
2410
        key = ('foo',)
2411
        key_basis = ('bar',)
2412
        key_missing = ('missing',)
2413
        test.add_lines(key, (), ['foo\n'])
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
2414
        key_sha1sum = osutils.sha('foo\n').hexdigest()
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
2415
        sha1s = test.get_sha1s([key])
2416
        self.assertEqual({key: key_sha1sum}, sha1s)
2417
        self.assertEqual([], basis.calls)
2418
        # But texts that are not in the test knit are looked for in the basis
2419
        # directly (rather than via text reconstruction) so that remote servers
2420
        # etc don't have to answer with full content.
2421
        basis.add_lines(key_basis, (), ['foo\n', 'bar\n'])
3734.2.4 by Vincent Ladeuil
Fix python2.6 deprecation warnings related to hashlib.
2422
        basis_sha1sum = osutils.sha('foo\nbar\n').hexdigest()
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
2423
        basis.calls = []
2424
        sha1s = test.get_sha1s([key, key_missing, key_basis])
2425
        self.assertEqual({key: key_sha1sum,
2426
            key_basis: basis_sha1sum}, sha1s)
2427
        self.assertEqual([("get_sha1s", set([key_basis, key_missing]))],
2428
            basis.calls)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2429
2430
    def test_insert_record_stream(self):
3350.8.10 by Robert Collins
Stacked insert_record_stream.
2431
        # records are inserted as normal; insert_record_stream builds on
3350.8.14 by Robert Collins
Review feedback.
2432
        # add_lines, so a smoke test should be all that's needed:
3350.8.10 by Robert Collins
Stacked insert_record_stream.
2433
        key = ('foo',)
2434
        key_basis = ('bar',)
2435
        key_delta = ('zaphod',)
2436
        basis, test = self.get_basis_and_test_knit()
2437
        source = self.make_test_knit(name='source')
2438
        basis.add_lines(key_basis, (), ['foo\n'])
2439
        basis.calls = []
2440
        source.add_lines(key_basis, (), ['foo\n'])
2441
        source.add_lines(key_delta, (key_basis,), ['bar\n'])
2442
        stream = source.get_record_stream([key_delta], 'unordered', False)
2443
        test.insert_record_stream(stream)
3830.3.9 by Martin Pool
Simplify kvf insert_record_stream; add has_key shorthand methods; update stacking effort tests
2444
        # XXX: this does somewhat too many calls in making sure of whether it
2445
        # has to recreate the full text.
2446
        self.assertEqual([("get_parent_map", set([key_basis])),
2447
             ('get_parent_map', set([key_basis])),
3830.3.10 by Martin Pool
Update more stacking effort tests
2448
             ('get_record_stream', [key_basis], 'unordered', True)],
3350.8.10 by Robert Collins
Stacked insert_record_stream.
2449
            basis.calls)
2450
        self.assertEqual({key_delta:(key_basis,)},
2451
            test.get_parent_map([key_delta]))
2452
        self.assertEqual('bar\n', test.get_record_stream([key_delta],
2453
            'unordered', True).next().get_bytes_as('fulltext'))
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2454
2455
    def test_iter_lines_added_or_present_in_keys(self):
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
2456
        # Lines from the basis are returned, and lines for a given key are only
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2457
        # returned once.
3350.8.5 by Robert Collins
Iter_lines_added_or_present_in_keys stacks.
2458
        key1 = ('foo1',)
2459
        key2 = ('foo2',)
2460
        # all sources are asked for keys:
2461
        basis, test = self.get_basis_and_test_knit()
2462
        basis.add_lines(key1, (), ["foo"])
2463
        basis.calls = []
2464
        lines = list(test.iter_lines_added_or_present_in_keys([key1]))
2465
        self.assertEqual([("foo\n", key1)], lines)
2466
        self.assertEqual([("iter_lines_added_or_present_in_keys", set([key1]))],
2467
            basis.calls)
2468
        # keys in both are not duplicated:
2469
        test.add_lines(key2, (), ["bar\n"])
2470
        basis.add_lines(key2, (), ["bar\n"])
2471
        basis.calls = []
2472
        lines = list(test.iter_lines_added_or_present_in_keys([key2]))
2473
        self.assertEqual([("bar\n", key2)], lines)
2474
        self.assertEqual([], basis.calls)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2475
2476
    def test_keys(self):
3350.8.4 by Robert Collins
Vf.keys() stacking support.
2477
        key1 = ('foo1',)
2478
        key2 = ('foo2',)
2479
        # all sources are asked for keys:
2480
        basis, test = self.get_basis_and_test_knit()
2481
        keys = test.keys()
2482
        self.assertEqual(set(), set(keys))
2483
        self.assertEqual([("keys",)], basis.calls)
2484
        # keys from a basis are returned:
2485
        basis.add_lines(key1, (), [])
2486
        basis.calls = []
2487
        keys = test.keys()
2488
        self.assertEqual(set([key1]), set(keys))
2489
        self.assertEqual([("keys",)], basis.calls)
2490
        # keys in both are not duplicated:
2491
        test.add_lines(key2, (), [])
2492
        basis.add_lines(key2, (), [])
2493
        basis.calls = []
2494
        keys = test.keys()
2495
        self.assertEqual(2, len(keys))
2496
        self.assertEqual(set([key1, key2]), set(keys))
2497
        self.assertEqual([("keys",)], basis.calls)
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2498
2499
    def test_add_mpdiffs(self):
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
2500
        # records are inserted as normal; add_mpdiff builds on
3350.8.14 by Robert Collins
Review feedback.
2501
        # add_lines, so a smoke test should be all that's needed:
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
2502
        key = ('foo',)
2503
        key_basis = ('bar',)
2504
        key_delta = ('zaphod',)
2505
        basis, test = self.get_basis_and_test_knit()
2506
        source = self.make_test_knit(name='source')
2507
        basis.add_lines(key_basis, (), ['foo\n'])
2508
        basis.calls = []
2509
        source.add_lines(key_basis, (), ['foo\n'])
2510
        source.add_lines(key_delta, (key_basis,), ['bar\n'])
2511
        diffs = source.make_mpdiffs([key_delta])
2512
        test.add_mpdiffs([(key_delta, (key_basis,),
2513
            source.get_sha1s([key_delta])[key_delta], diffs[0])])
2514
        self.assertEqual([("get_parent_map", set([key_basis])),
3830.3.10 by Martin Pool
Update more stacking effort tests
2515
            ('get_record_stream', [key_basis], 'unordered', True),],
3350.8.11 by Robert Collins
Stacked add_mpdiffs.
2516
            basis.calls)
2517
        self.assertEqual({key_delta:(key_basis,)},
2518
            test.get_parent_map([key_delta]))
2519
        self.assertEqual('bar\n', test.get_record_stream([key_delta],
2520
            'unordered', True).next().get_bytes_as('fulltext'))
3350.8.1 by Robert Collins
KnitVersionedFiles.add_fallback_versioned_files exists.
2521
2522
    def test_make_mpdiffs(self):
3350.8.12 by Robert Collins
Stacked make_mpdiffs.
2523
        # Generating an mpdiff across a stacking boundary should detect parent
2524
        # texts regions.
2525
        key = ('foo',)
2526
        key_left = ('bar',)
2527
        key_right = ('zaphod',)
2528
        basis, test = self.get_basis_and_test_knit()
2529
        basis.add_lines(key_left, (), ['bar\n'])
2530
        basis.add_lines(key_right, (), ['zaphod\n'])
2531
        basis.calls = []
2532
        test.add_lines(key, (key_left, key_right),
2533
            ['bar\n', 'foo\n', 'zaphod\n'])
2534
        diffs = test.make_mpdiffs([key])
2535
        self.assertEqual([
2536
            multiparent.MultiParent([multiparent.ParentText(0, 0, 0, 1),
2537
                multiparent.NewText(['foo\n']),
2538
                multiparent.ParentText(1, 0, 2, 1)])],
2539
            diffs)
3830.3.10 by Martin Pool
Update more stacking effort tests
2540
        self.assertEqual(3, len(basis.calls))
3350.8.12 by Robert Collins
Stacked make_mpdiffs.
2541
        self.assertEqual([
2542
            ("get_parent_map", set([key_left, key_right])),
2543
            ("get_parent_map", set([key_left, key_right])),
2544
            ],
3830.3.10 by Martin Pool
Update more stacking effort tests
2545
            basis.calls[:-1])
2546
        last_call = basis.calls[-1]
3350.8.14 by Robert Collins
Review feedback.
2547
        self.assertEqual('get_record_stream', last_call[0])
2548
        self.assertEqual(set([key_left, key_right]), set(last_call[1]))
4537.3.5 by John Arbash Meinel
Fix 3 tests that assumed it would use 'unordered' in the fallback,
2549
        self.assertEqual('topological', last_call[2])
3350.8.14 by Robert Collins
Review feedback.
2550
        self.assertEqual(True, last_call[3])
4005.3.6 by Robert Collins
Support delta_closure=True with NetworkRecordStream to transmit deltas over the wire when full text extraction is required on the far end.
2551
2552
2553
class TestNetworkBehaviour(KnitTests):
2554
    """Tests for getting data out of/into knits over the network."""
2555
2556
    def test_include_delta_closure_generates_a_knit_delta_closure(self):
2557
        vf = self.make_test_knit(name='test')
2558
        # put in three texts, giving ft, delta, delta
2559
        vf.add_lines(('base',), (), ['base\n', 'content\n'])
2560
        vf.add_lines(('d1',), (('base',),), ['d1\n'])
2561
        vf.add_lines(('d2',), (('d1',),), ['d2\n'])
2562
        # But heuristics could interfere, so check what happened:
2563
        self.assertEqual(['knit-ft-gz', 'knit-delta-gz', 'knit-delta-gz'],
2564
            [record.storage_kind for record in
2565
             vf.get_record_stream([('base',), ('d1',), ('d2',)],
2566
                'topological', False)])
2567
        # generate a stream of just the deltas include_delta_closure=True,
2568
        # serialise to the network, and check that we get a delta closure on the wire.
2569
        stream = vf.get_record_stream([('d1',), ('d2',)], 'topological', True)
2570
        netb = [record.get_bytes_as(record.storage_kind) for record in stream]
2571
        # The first bytes should be a memo from _ContentMapGenerator, and the
2572
        # second bytes should be empty (because its a API proxy not something
2573
        # for wire serialisation.
2574
        self.assertEqual('', netb[1])
2575
        bytes = netb[0]
2576
        kind, line_end = network_bytes_to_kind_and_offset(bytes)
2577
        self.assertEqual('knit-delta-closure', kind)
2578
2579
2580
class TestContentMapGenerator(KnitTests):
2581
    """Tests for ContentMapGenerator"""
2582
2583
    def test_get_record_stream_gives_records(self):
2584
        vf = self.make_test_knit(name='test')
2585
        # put in three texts, giving ft, delta, delta
2586
        vf.add_lines(('base',), (), ['base\n', 'content\n'])
2587
        vf.add_lines(('d1',), (('base',),), ['d1\n'])
2588
        vf.add_lines(('d2',), (('d1',),), ['d2\n'])
2589
        keys = [('d1',), ('d2',)]
2590
        generator = _VFContentMapGenerator(vf, keys,
2591
            global_map=vf.get_parent_map(keys))
2592
        for record in generator.get_record_stream():
2593
            if record.key == ('d1',):
2594
                self.assertEqual('d1\n', record.get_bytes_as('fulltext'))
2595
            else:
2596
                self.assertEqual('d2\n', record.get_bytes_as('fulltext'))
2597
2598
    def test_get_record_stream_kinds_are_raw(self):
2599
        vf = self.make_test_knit(name='test')
2600
        # put in three texts, giving ft, delta, delta
2601
        vf.add_lines(('base',), (), ['base\n', 'content\n'])
2602
        vf.add_lines(('d1',), (('base',),), ['d1\n'])
2603
        vf.add_lines(('d2',), (('d1',),), ['d2\n'])
2604
        keys = [('base',), ('d1',), ('d2',)]
2605
        generator = _VFContentMapGenerator(vf, keys,
2606
            global_map=vf.get_parent_map(keys))
2607
        kinds = {('base',): 'knit-delta-closure',
2608
            ('d1',): 'knit-delta-closure-ref',
2609
            ('d2',): 'knit-delta-closure-ref',
2610
            }
2611
        for record in generator.get_record_stream():
2612
            self.assertEqual(kinds[record.key], record.storage_kind)