/brz/remove-bazaar

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