~bzr-pqm/bzr/bzr.dev

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