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