/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
2
#
3
# Authors:
4
#   Johan Rydberg <jrydberg@gnu.org>
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
10
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
15
#
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
19
20
1704.2.15 by Martin Pool
Remove TODO about knit testing printed from test suite
21
# TODO: might be nice to create a versionedfile with some type of corruption
22
# considered typical and check that it can be detected/corrected.
23
5590.1.1 by John Arbash Meinel
Stop using tuned_gzip, it seems to give incorrect results on python 2.7
24
from gzip import GzipFile
6631.2.3 by Martin
Fix per_versionedfile test failures and rethink future_builtins
25
import itertools
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
26
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
27
from .. import (
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
28
    errors,
4593.5.35 by John Arbash Meinel
Start working on a per-vf implementation test of find_ancestry.
29
    graph as _mod_graph,
2309.4.7 by John Arbash Meinel
Update VersionedFile tests to ensure that they can take Unicode,
30
    osutils,
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
31
    progress,
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
32
    transport,
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
33
    ui,
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
34
    )
6670.4.1 by Jelmer Vernooij
Update imports.
35
from ..bzr import (
36
    groupcompress,
37
    knit as _mod_knit,
38
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
39
from ..errors import (
6670.4.1 by Jelmer Vernooij
Update imports.
40
    RevisionNotPresent,
41
    RevisionAlreadyPresent,
42
    )
43
from ..bzr.knit import (
3350.6.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
    cleanup_pack_knit,
45
    make_file_factory,
46
    make_pack_factory,
2770.1.1 by Aaron Bentley
Initial implmentation of plain knit annotation
47
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
48
from ..sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
49
    BytesIO,
6631.2.3 by Martin
Fix per_versionedfile test failures and rethink future_builtins
50
    zip,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
51
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
52
from . import (
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
53
    TestCase,
3350.6.2 by Robert Collins
Prepare parameterised test environment.
54
    TestCaseWithMemoryTransport,
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
55
    TestNotApplicable,
3350.6.2 by Robert Collins
Prepare parameterised test environment.
56
    TestSkipped,
57
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
58
from .http_utils import TestCaseWithWebserver
59
from ..transport.memory import MemoryTransport
6670.4.1 by Jelmer Vernooij
Update imports.
60
from ..bzr import versionedfile as versionedfile
61
from ..bzr.versionedfile import (
3350.6.2 by Robert Collins
Prepare parameterised test environment.
62
    ConstantMapper,
63
    HashEscapedPrefixMapper,
64
    PrefixMapper,
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
65
    VirtualVersionedFiles,
3350.6.2 by Robert Collins
Prepare parameterised test environment.
66
    make_versioned_files_factory,
67
    )
6731 by Jelmer Vernooij
Move weave errors to breezy.bzr.weave.
68
from ..bzr.weave import (
69
    WeaveFile,
70
    WeaveInvalidChecksum,
71
    )
6670.4.1 by Jelmer Vernooij
Update imports.
72
from ..bzr.weavefile import write_weave
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
73
from .scenarios import load_tests_apply_scenarios
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
74
75
76
load_tests = load_tests_apply_scenarios
3350.6.2 by Robert Collins
Prepare parameterised test environment.
77
78
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
79
def get_diamond_vf(f, trailing_eol=True, left_only=False):
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
80
    """Get a diamond graph to exercise deltas and merges.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
81
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
82
    :param trailing_eol: If True end the last line with \n.
83
    """
84
    parents = {
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
85
        b'origin': (),
86
        b'base': ((b'origin',),),
87
        b'left': ((b'base',),),
88
        b'right': ((b'base',),),
89
        b'merged': ((b'left',), (b'right',)),
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
90
        }
91
    # insert a diamond graph to exercise deltas and merges.
92
    if trailing_eol:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
93
        last_char = b'\n'
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
94
    else:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
95
        last_char = b''
96
    f.add_lines(b'origin', [], [b'origin' + last_char])
97
    f.add_lines(b'base', [b'origin'], [b'base' + last_char])
98
    f.add_lines(b'left', [b'base'], [b'base\n', b'left' + last_char])
3350.3.11 by Robert Collins
Test inserting a stream that overlaps the current content of a knit does not error.
99
    if not left_only:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
100
        f.add_lines(b'right', [b'base'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
101
                    [b'base\n', b'right' + last_char])
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
102
        f.add_lines(b'merged', [b'left', b'right'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
103
                    [b'base\n', b'left\n', b'right\n', b'merged' + last_char])
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
104
    return f, parents
105
106
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
107
def get_diamond_files(files, key_length, trailing_eol=True, left_only=False,
7143.15.2 by Jelmer Vernooij
Run autopep8.
108
                      nograph=False, nokeys=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.
109
    """Get a diamond graph to exercise deltas and merges.
110
111
    This creates a 5-node graph in files. If files supports 2-length keys two
112
    graphs are made to exercise the support for multiple ids.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
113
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
114
    :param trailing_eol: If True end the last line with \n.
115
    :param key_length: The length of keys in files. Currently supports length 1
116
        and 2 keys.
117
    :param left_only: If True do not add the right and merged nodes.
118
    :param nograph: If True, do not provide parents to the add_lines calls;
119
        this is useful for tests that need inserted data but have graphless
120
        stores.
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
121
    :param nokeys: If True, pass None is as the key for all insertions.
122
        Currently implies nograph.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
123
    :return: The results of the add_lines calls.
124
    """
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
125
    if nokeys:
126
        nograph = 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.
127
    if key_length == 1:
128
        prefixes = [()]
129
    else:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
130
        prefixes = [(b'FileA',), (b'FileB',)]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
131
    # insert a diamond graph to exercise deltas and merges.
132
    if trailing_eol:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
133
        last_char = b'\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.
134
    else:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
135
        last_char = b''
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
136
    result = []
7143.15.2 by Jelmer Vernooij
Run autopep8.
137
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
138
    def get_parents(suffix_list):
139
        if nograph:
140
            return ()
141
        else:
142
            result = [prefix + suffix for suffix in suffix_list]
143
            return result
7143.15.2 by Jelmer Vernooij
Run autopep8.
144
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
145
    def get_key(suffix):
146
        if nokeys:
147
            return (None, )
148
        else:
149
            return (suffix,)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
150
    # we loop over each key because that spreads the inserts across prefixes,
151
    # which is how commit operates.
152
    for prefix in prefixes:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
153
        result.append(files.add_lines(prefix + get_key(b'origin'), (),
7143.15.2 by Jelmer Vernooij
Run autopep8.
154
                                      [b'origin' + last_char]))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
155
    for prefix in prefixes:
156
        result.append(files.add_lines(prefix + get_key(b'base'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
157
                                      get_parents([(b'origin',)]), [b'base' + last_char]))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
158
    for prefix in prefixes:
159
        result.append(files.add_lines(prefix + get_key(b'left'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
160
                                      get_parents([(b'base',)]),
161
                                      [b'base\n', b'left' + last_char]))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
162
    if not left_only:
163
        for prefix in prefixes:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
164
            result.append(files.add_lines(prefix + get_key(b'right'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
165
                                          get_parents([(b'base',)]),
166
                                          [b'base\n', b'right' + last_char]))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
167
        for prefix in prefixes:
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
168
            result.append(files.add_lines(prefix + get_key(b'merged'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
169
                                          get_parents(
170
                                              [(b'left',), (b'right',)]),
171
                                          [b'base\n', b'left\n', b'right\n', b'merged' + last_char]))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
172
    return result
173
174
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
175
class VersionedFileTestMixIn(object):
176
    """A mixin test class for testing VersionedFiles.
177
178
    This is not an adaptor-style test at this point because
179
    theres no dynamic substitution of versioned file implementations,
180
    they are strictly controlled by their owning repositories.
181
    """
182
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
183
    def get_transaction(self):
184
        if not hasattr(self, '_transaction'):
185
            self._transaction = None
186
        return self._transaction
187
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
188
    def test_add(self):
189
        f = self.get_file()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
190
        f.add_lines(b'r0', [], [b'a\n', b'b\n'])
191
        f.add_lines(b'r1', [b'r0'], [b'b\n', b'c\n'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
192
1563.2.9 by Robert Collins
Update versionedfile api tests to ensure that data is available after every operation.
193
        def verify_file(f):
194
            versions = f.versions()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
195
            self.assertTrue(b'r0' in versions)
196
            self.assertTrue(b'r1' in versions)
197
            self.assertEqual(f.get_lines(b'r0'), [b'a\n', b'b\n'])
198
            self.assertEqual(f.get_text(b'r0'), b'a\nb\n')
199
            self.assertEqual(f.get_lines(b'r1'), [b'b\n', b'c\n'])
1563.2.18 by Robert Collins
get knit repositories really using knits for text storage.
200
            self.assertEqual(2, len(f))
201
            self.assertEqual(2, f.num_versions())
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
202
1563.2.9 by Robert Collins
Update versionedfile api tests to ensure that data is available after every operation.
203
            self.assertRaises(RevisionNotPresent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
204
                              f.add_lines, b'r2', [b'foo'], [])
1563.2.9 by Robert Collins
Update versionedfile api tests to ensure that data is available after every operation.
205
            self.assertRaises(RevisionAlreadyPresent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
206
                              f.add_lines, b'r1', [], [])
1563.2.9 by Robert Collins
Update versionedfile api tests to ensure that data is available after every operation.
207
        verify_file(f)
1666.1.6 by Robert Collins
Make knit the default format.
208
        # this checks that reopen with create=True does not break anything.
209
        f = self.reopen_file(create=True)
1563.2.9 by Robert Collins
Update versionedfile api tests to ensure that data is available after every operation.
210
        verify_file(f)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
211
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
212
    def test_adds_with_parent_texts(self):
213
        f = self.get_file()
214
        parent_texts = {}
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
215
        _, _, parent_texts[b'r0'] = f.add_lines(b'r0', [], [b'a\n', b'b\n'])
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
216
        try:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
217
            _, _, parent_texts[b'r1'] = f.add_lines_with_ghosts(b'r1',
7143.15.2 by Jelmer Vernooij
Run autopep8.
218
                                                                [b'r0', b'ghost'], [b'b\n', b'c\n'], parent_texts=parent_texts)
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
219
        except NotImplementedError:
220
            # if the format doesn't support ghosts, just add normally.
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
221
            _, _, parent_texts[b'r1'] = f.add_lines(b'r1',
7143.15.2 by Jelmer Vernooij
Run autopep8.
222
                                                    [b'r0'], [b'b\n', b'c\n'], parent_texts=parent_texts)
223
        f.add_lines(b'r2', [b'r1'], [b'c\n', b'd\n'],
224
                    parent_texts=parent_texts)
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
225
        self.assertNotEqual(None, parent_texts[b'r0'])
226
        self.assertNotEqual(None, parent_texts[b'r1'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
227
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
228
        def verify_file(f):
229
            versions = f.versions()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
230
            self.assertTrue(b'r0' in versions)
231
            self.assertTrue(b'r1' in versions)
232
            self.assertTrue(b'r2' in versions)
233
            self.assertEqual(f.get_lines(b'r0'), [b'a\n', b'b\n'])
234
            self.assertEqual(f.get_lines(b'r1'), [b'b\n', b'c\n'])
235
            self.assertEqual(f.get_lines(b'r2'), [b'c\n', b'd\n'])
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
236
            self.assertEqual(3, f.num_versions())
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
237
            origins = f.annotate(b'r1')
238
            self.assertEqual(origins[0][0], b'r0')
239
            self.assertEqual(origins[1][0], b'r1')
240
            origins = f.annotate(b'r2')
241
            self.assertEqual(origins[0][0], b'r1')
242
            self.assertEqual(origins[1][0], b'r2')
1596.2.32 by Robert Collins
Reduce re-extraction of texts during weave to knit joins by providing a memoisation facility.
243
244
        verify_file(f)
245
        f = self.reopen_file()
246
        verify_file(f)
247
2805.6.7 by Robert Collins
Review feedback.
248
    def test_add_unicode_content(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
249
        # unicode content is not permitted in versioned files.
2805.6.7 by Robert Collins
Review feedback.
250
        # versioned files version sequences of bytes only.
251
        vf = self.get_file()
252
        self.assertRaises(errors.BzrBadParameterUnicode,
7143.15.2 by Jelmer Vernooij
Run autopep8.
253
                          vf.add_lines, b'a', [], [b'a\n', u'b\n', b'c\n'])
2805.6.7 by Robert Collins
Review feedback.
254
        self.assertRaises(
255
            (errors.BzrBadParameterUnicode, NotImplementedError),
6973.14.4 by Jelmer Vernooij
Fix checking for options.
256
            vf.add_lines_with_ghosts, b'a', [], [b'a\n', u'b\n', b'c\n'])
2805.6.7 by Robert Collins
Review feedback.
257
2520.4.150 by Aaron Bentley
Test that non-Weave uses left_matching_blocks for add_lines
258
    def test_add_follows_left_matching_blocks(self):
259
        """If we change left_matching_blocks, delta changes
260
261
        Note: There are multiple correct deltas in this case, because
262
        we start with 1 "a" and we get 3.
263
        """
264
        vf = self.get_file()
265
        if isinstance(vf, WeaveFile):
266
            raise TestSkipped("WeaveFile ignores left_matching_blocks")
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
267
        vf.add_lines(b'1', [], [b'a\n'])
268
        vf.add_lines(b'2', [b'1'], [b'a\n', b'a\n', b'a\n'],
2520.4.150 by Aaron Bentley
Test that non-Weave uses left_matching_blocks for add_lines
269
                     left_matching_blocks=[(0, 0, 1), (1, 3, 0)])
6963.2.4 by Jelmer Vernooij
Add bees.
270
        self.assertEqual([b'a\n', b'a\n', b'a\n'], vf.get_lines(b'2'))
271
        vf.add_lines(b'3', [b'1'], [b'a\n', b'a\n', b'a\n'],
2520.4.150 by Aaron Bentley
Test that non-Weave uses left_matching_blocks for add_lines
272
                     left_matching_blocks=[(0, 2, 1), (1, 3, 0)])
6963.2.4 by Jelmer Vernooij
Add bees.
273
        self.assertEqual([b'a\n', b'a\n', b'a\n'], vf.get_lines(b'3'))
2520.4.150 by Aaron Bentley
Test that non-Weave uses left_matching_blocks for add_lines
274
2805.6.7 by Robert Collins
Review feedback.
275
    def test_inline_newline_throws(self):
276
        # \r characters are not permitted in lines being added
277
        vf = self.get_file()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
278
        self.assertRaises(errors.BzrBadParameterContainsNewline,
7143.15.2 by Jelmer Vernooij
Run autopep8.
279
                          vf.add_lines, b'a', [], [b'a\n\n'])
2805.6.7 by Robert Collins
Review feedback.
280
        self.assertRaises(
281
            (errors.BzrBadParameterContainsNewline, NotImplementedError),
6963.2.3 by Jelmer Vernooij
Fix some more tests.
282
            vf.add_lines_with_ghosts, b'a', [], [b'a\n\n'])
2805.6.7 by Robert Collins
Review feedback.
283
        # but inline CR's are allowed
6963.2.3 by Jelmer Vernooij
Fix some more tests.
284
        vf.add_lines(b'a', [], [b'a\r\n'])
2805.6.7 by Robert Collins
Review feedback.
285
        try:
6963.2.3 by Jelmer Vernooij
Fix some more tests.
286
            vf.add_lines_with_ghosts(b'b', [], [b'a\r\n'])
2805.6.7 by Robert Collins
Review feedback.
287
        except NotImplementedError:
288
            pass
289
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
290
    def test_add_reserved(self):
291
        vf = self.get_file()
292
        self.assertRaises(errors.ReservedId,
7143.15.2 by Jelmer Vernooij
Run autopep8.
293
                          vf.add_lines, b'a:', [], [b'a\n', b'b\n', b'c\n'])
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
294
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
295
    def test_add_lines_nostoresha(self):
296
        """When nostore_sha is supplied using old content raises."""
297
        vf = self.get_file()
6963.2.4 by Jelmer Vernooij
Add bees.
298
        empty_text = (b'a', [])
299
        sample_text_nl = (b'b', [b"foo\n", b"bar\n"])
300
        sample_text_no_nl = (b'c', [b"foo\n", b"bar"])
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
301
        shas = []
302
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
303
            sha, _, _ = vf.add_lines(version, [], lines)
304
            shas.append(sha)
305
        # we now have a copy of all the lines in the vf.
306
        for sha, (version, lines) in zip(
7143.15.2 by Jelmer Vernooij
Run autopep8.
307
                shas, (empty_text, sample_text_nl, sample_text_no_nl)):
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
308
            self.assertRaises(errors.ExistingContent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
309
                              vf.add_lines, version + b"2", [], lines,
310
                              nostore_sha=sha)
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
311
            # and no new version should have been added.
312
            self.assertRaises(errors.RevisionNotPresent, vf.get_lines,
7143.15.2 by Jelmer Vernooij
Run autopep8.
313
                              version + b"2")
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
314
2803.1.1 by Robert Collins
Fix typo in ghosts version of test_add_lines_nostoresha.
315
    def test_add_lines_with_ghosts_nostoresha(self):
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
316
        """When nostore_sha is supplied using old content raises."""
317
        vf = self.get_file()
6963.2.4 by Jelmer Vernooij
Add bees.
318
        empty_text = (b'a', [])
319
        sample_text_nl = (b'b', [b"foo\n", b"bar\n"])
320
        sample_text_no_nl = (b'c', [b"foo\n", b"bar"])
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
321
        shas = []
322
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
323
            sha, _, _ = vf.add_lines(version, [], lines)
324
            shas.append(sha)
325
        # we now have a copy of all the lines in the vf.
326
        # is the test applicable to this vf implementation?
327
        try:
6963.2.4 by Jelmer Vernooij
Add bees.
328
            vf.add_lines_with_ghosts(b'd', [], [])
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
329
        except NotImplementedError:
330
            raise TestSkipped("add_lines_with_ghosts is optional")
331
        for sha, (version, lines) in zip(
7143.15.2 by Jelmer Vernooij
Run autopep8.
332
                shas, (empty_text, sample_text_nl, sample_text_no_nl)):
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
333
            self.assertRaises(errors.ExistingContent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
334
                              vf.add_lines_with_ghosts, version + b"2", [], lines,
335
                              nostore_sha=sha)
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
336
            # and no new version should have been added.
337
            self.assertRaises(errors.RevisionNotPresent, vf.get_lines,
7143.15.2 by Jelmer Vernooij
Run autopep8.
338
                              version + b"2")
2794.1.1 by Robert Collins
Allow knits to be instructed not to add a text based on a sha, for commit.
339
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
340
    def test_add_lines_return_value(self):
341
        # add_lines should return the sha1 and the text size.
342
        vf = self.get_file()
6963.2.4 by Jelmer Vernooij
Add bees.
343
        empty_text = (b'a', [])
344
        sample_text_nl = (b'b', [b"foo\n", b"bar\n"])
345
        sample_text_no_nl = (b'c', [b"foo\n", b"bar"])
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
346
        # check results for the three cases:
347
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
348
            # the first two elements are the same for all versioned files:
349
            # - the digest and the size of the text. For some versioned files
350
            #   additional data is returned in additional tuple elements.
351
            result = vf.add_lines(version, [], lines)
352
            self.assertEqual(3, len(result))
353
            self.assertEqual((osutils.sha_strings(lines), sum(map(len, lines))),
7143.15.2 by Jelmer Vernooij
Run autopep8.
354
                             result[0:2])
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
355
        # parents should not affect the result:
356
        lines = sample_text_nl[1]
357
        self.assertEqual((osutils.sha_strings(lines), sum(map(len, lines))),
7143.15.2 by Jelmer Vernooij
Run autopep8.
358
                         vf.add_lines(b'd', [b'b', b'c'], lines)[0:2])
2776.1.1 by Robert Collins
* The ``add_lines`` methods on ``VersionedFile`` implementations has changed
359
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
360
    def test_get_reserved(self):
361
        vf = self.get_file()
6963.2.4 by Jelmer Vernooij
Add bees.
362
        self.assertRaises(errors.ReservedId, vf.get_texts, [b'b:'])
363
        self.assertRaises(errors.ReservedId, vf.get_lines, b'b:')
364
        self.assertRaises(errors.ReservedId, vf.get_text, b'b:')
2229.2.1 by Aaron Bentley
Reject reserved ids in versiondfile, tree, branch and repository
365
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
366
    def test_add_unchanged_last_line_noeol_snapshot(self):
367
        """Add a text with an unchanged last line with no eol should work."""
368
        # Test adding this in a number of chain lengths; because the interface
369
        # for VersionedFile does not allow forcing a specific chain length, we
370
        # just use a small base to get the first snapshot, then a much longer
371
        # first line for the next add (which will make the third add snapshot)
372
        # and so on. 20 has been chosen as an aribtrary figure - knits use 200
373
        # as a capped delta length, but ideally we would have some way of
374
        # tuning the test to the store (e.g. keep going until a snapshot
375
        # happens).
376
        for length in range(20):
377
            version_lines = {}
378
            vf = self.get_file('case-%d' % length)
6963.2.4 by Jelmer Vernooij
Add bees.
379
            prefix = b'step-%d'
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
380
            parents = []
381
            for step in range(length):
382
                version = prefix % step
6963.2.4 by Jelmer Vernooij
Add bees.
383
                lines = ([b'prelude \n'] * step) + [b'line']
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
384
                vf.add_lines(version, parents, lines)
385
                version_lines[version] = lines
386
                parents = [version]
6963.2.4 by Jelmer Vernooij
Add bees.
387
            vf.add_lines(b'no-eol', parents, [b'line'])
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
388
            vf.get_texts(version_lines.keys())
6963.2.4 by Jelmer Vernooij
Add bees.
389
            self.assertEqualDiff(b'line', vf.get_text(b'no-eol'))
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
390
391
    def test_get_texts_eol_variation(self):
392
        # similar to the failure in <http://bugs.launchpad.net/234748>
393
        vf = self.get_file()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
394
        sample_text_nl = [b"line\n"]
395
        sample_text_no_nl = [b"line"]
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
396
        versions = []
397
        version_lines = {}
398
        parents = []
399
        for i in range(4):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
400
            version = b'v%d' % i
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
401
            if i % 2:
402
                lines = sample_text_nl
403
            else:
404
                lines = sample_text_no_nl
405
            # left_matching blocks is an internal api; it operates on the
406
            # *internal* representation for a knit, which is with *all* lines
407
            # being normalised to end with \n - even the final line in a no_nl
408
            # file. Using it here ensures that a broken internal implementation
409
            # (which is what this test tests) will generate a correct line
410
            # delta (which is to say, an empty delta).
411
            vf.add_lines(version, parents, lines,
7143.15.2 by Jelmer Vernooij
Run autopep8.
412
                         left_matching_blocks=[(0, 0, 1)])
3468.2.4 by Martin Pool
Test and fix #234748 problems in trailing newline diffs
413
            parents = [version]
414
            versions.append(version)
415
            version_lines[version] = lines
416
        vf.check()
417
        vf.get_texts(versions)
418
        vf.get_texts(reversed(versions))
419
3460.2.1 by Robert Collins
* Inserting a bundle which changes the contents of a file with no trailing
420
    def test_add_lines_with_matching_blocks_noeol_last_line(self):
421
        """Add a text with an unchanged last line with no eol should work."""
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
422
        from breezy import multiparent
3460.2.1 by Robert Collins
* Inserting a bundle which changes the contents of a file with no trailing
423
        # Hand verified sha1 of the text we're adding.
424
        sha1 = '6a1d115ec7b60afb664dc14890b5af5ce3c827a4'
425
        # Create a mpdiff which adds a new line before the trailing line, and
426
        # reuse the last line unaltered (which can cause annotation reuse).
427
        # Test adding this in two situations:
428
        # On top of a new insertion
429
        vf = self.get_file('fulltext')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
430
        vf.add_lines(b'noeol', [], [b'line'])
431
        vf.add_lines(b'noeol2', [b'noeol'], [b'newline\n', b'line'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
432
                     left_matching_blocks=[(0, 1, 1)])
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
433
        self.assertEqualDiff(b'newline\nline', vf.get_text(b'noeol2'))
3460.2.1 by Robert Collins
* Inserting a bundle which changes the contents of a file with no trailing
434
        # On top of a delta
435
        vf = self.get_file('delta')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
436
        vf.add_lines(b'base', [], [b'line'])
437
        vf.add_lines(b'noeol', [b'base'], [b'prelude\n', b'line'])
438
        vf.add_lines(b'noeol2', [b'noeol'], [b'newline\n', b'line'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
439
                     left_matching_blocks=[(1, 1, 1)])
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
440
        self.assertEqualDiff(b'newline\nline', vf.get_text(b'noeol2'))
3460.2.1 by Robert Collins
* Inserting a bundle which changes the contents of a file with no trailing
441
2520.4.85 by Aaron Bentley
Get all test passing (which just proves there aren't enough tests!)
442
    def test_make_mpdiffs(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
443
        from breezy import multiparent
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
444
        vf = self.get_file('foo')
445
        sha1s = self._setup_for_deltas(vf)
446
        new_vf = self.get_file('bar')
447
        for version in multiparent.topo_iter(vf):
2520.4.85 by Aaron Bentley
Get all test passing (which just proves there aren't enough tests!)
448
            mpdiff = vf.make_mpdiffs([version])[0]
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
449
            new_vf.add_mpdiffs([(version, vf.get_parent_map([version])[version],
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
450
                                 vf.get_sha1s([version])[version], mpdiff)])
2520.4.3 by Aaron Bentley
Implement plain strategy for extracting and installing multiparent diffs
451
            self.assertEqualDiff(vf.get_text(version),
452
                                 new_vf.get_text(version))
453
3453.3.2 by John Arbash Meinel
Add a test case for the first loop, unable to find a way to trigger the second loop
454
    def test_make_mpdiffs_with_ghosts(self):
455
        vf = self.get_file('foo')
3453.3.4 by John Arbash Meinel
Skip the new test for old weave formats that don't support ghosts
456
        try:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
457
            vf.add_lines_with_ghosts(b'text', [b'ghost'], [b'line\n'])
3453.3.4 by John Arbash Meinel
Skip the new test for old weave formats that don't support ghosts
458
        except NotImplementedError:
459
            # old Weave formats do not allow ghosts
460
            return
7143.15.2 by Jelmer Vernooij
Run autopep8.
461
        self.assertRaises(errors.RevisionNotPresent,
462
                          vf.make_mpdiffs, [b'ghost'])
3453.3.2 by John Arbash Meinel
Add a test case for the first loop, unable to find a way to trigger the second loop
463
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
464
    def _setup_for_deltas(self, f):
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.
465
        self.assertFalse(f.has_version('base'))
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
466
        # add texts that should trip the knit maximum delta chain threshold
467
        # as well as doing parallel chains of data in knits.
468
        # this is done by two chains of 25 insertions
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
469
        f.add_lines(b'base', [], [b'line\n'])
470
        f.add_lines(b'noeol', [b'base'], [b'line'])
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
471
        # detailed eol tests:
472
        # shared last line with parent no-eol
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
473
        f.add_lines(b'noeolsecond', [b'noeol'], [b'line\n', b'line'])
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
474
        # differing last line with parent, both no-eol
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
475
        f.add_lines(b'noeolnotshared', [b'noeolsecond'], [b'line\n', b'phone'])
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
476
        # add eol following a noneol parent, change content
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
477
        f.add_lines(b'eol', [b'noeol'], [b'phone\n'])
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
478
        # add eol following a noneol parent, no change content
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
479
        f.add_lines(b'eolline', [b'noeol'], [b'line\n'])
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
480
        # noeol with no parents:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
481
        f.add_lines(b'noeolbase', [], [b'line'])
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
482
        # noeol preceeding its leftmost parent in the output:
483
        # this is done by making it a merge of two parents with no common
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
484
        # anestry: noeolbase and noeol with the
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
485
        # later-inserted parent the leftmost.
7143.15.2 by Jelmer Vernooij
Run autopep8.
486
        f.add_lines(b'eolbeforefirstparent', [
487
                    b'noeolbase', b'noeol'], [b'line'])
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
488
        # two identical eol texts
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
489
        f.add_lines(b'noeoldup', [b'noeol'], [b'line'])
490
        next_parent = b'base'
491
        text_name = b'chain1-'
492
        text = [b'line\n']
493
        sha1s = {0: b'da6d3141cb4a5e6f464bf6e0518042ddc7bfd079',
494
                 1: b'45e21ea146a81ea44a821737acdb4f9791c8abe7',
495
                 2: b'e1f11570edf3e2a070052366c582837a4fe4e9fa',
496
                 3: b'26b4b8626da827088c514b8f9bbe4ebf181edda1',
497
                 4: b'e28a5510be25ba84d31121cff00956f9970ae6f6',
498
                 5: b'd63ec0ce22e11dcf65a931b69255d3ac747a318d',
499
                 6: b'2c2888d288cb5e1d98009d822fedfe6019c6a4ea',
500
                 7: b'95c14da9cafbf828e3e74a6f016d87926ba234ab',
501
                 8: b'779e9a0b28f9f832528d4b21e17e168c67697272',
502
                 9: b'1f8ff4e5c6ff78ac106fcfe6b1e8cb8740ff9a8f',
503
                 10: b'131a2ae712cf51ed62f143e3fbac3d4206c25a05',
504
                 11: b'c5a9d6f520d2515e1ec401a8f8a67e6c3c89f199',
505
                 12: b'31a2286267f24d8bedaa43355f8ad7129509ea85',
506
                 13: b'dc2a7fe80e8ec5cae920973973a8ee28b2da5e0a',
507
                 14: b'2c4b1736566b8ca6051e668de68650686a3922f2',
508
                 15: b'5912e4ecd9b0c07be4d013e7e2bdcf9323276cde',
509
                 16: b'b0d2e18d3559a00580f6b49804c23fea500feab3',
510
                 17: b'8e1d43ad72f7562d7cb8f57ee584e20eb1a69fc7',
511
                 18: b'5cf64a3459ae28efa60239e44b20312d25b253f3',
512
                 19: b'1ebed371807ba5935958ad0884595126e8c4e823',
513
                 20: b'2aa62a8b06fb3b3b892a3292a068ade69d5ee0d3',
514
                 21: b'01edc447978004f6e4e962b417a4ae1955b6fe5d',
515
                 22: b'd8d8dc49c4bf0bab401e0298bb5ad827768618bb',
516
                 23: b'c21f62b1c482862983a8ffb2b0c64b3451876e3f',
517
                 24: b'c0593fe795e00dff6b3c0fe857a074364d5f04fc',
6986.1.1 by Jelmer Vernooij
Address review comments.
518
                 25: b'dd1a1cf2ba9cc225c3aff729953e6364bf1d1855',
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
519
                 }
520
        for depth in range(26):
6963.2.12 by Jelmer Vernooij
Fix some more tests.
521
            new_version = text_name + b'%d' % depth
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
522
            text = text + [b'line\n']
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
523
            f.add_lines(new_version, [next_parent], text)
524
            next_parent = new_version
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
525
        next_parent = b'base'
526
        text_name = b'chain2-'
527
        text = [b'line\n']
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
528
        for depth in range(26):
6963.2.12 by Jelmer Vernooij
Fix some more tests.
529
            new_version = text_name + b'%d' % depth
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
530
            text = text + [b'line\n']
1596.2.36 by Robert Collins
add a get_delta api to versioned_file.
531
            f.add_lines(new_version, [next_parent], text)
532
            next_parent = new_version
1596.2.38 by Robert Collins
rollback from using deltas to using fulltexts - deltas need more work to be ready.
533
        return sha1s
1596.2.37 by Robert Collins
Switch to delta based content copying in the generic versioned file copier.
534
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
535
    def test_ancestry(self):
536
        f = self.get_file()
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
537
        self.assertEqual([], f.get_ancestry([]))
6963.2.4 by Jelmer Vernooij
Add bees.
538
        f.add_lines(b'r0', [], [b'a\n', b'b\n'])
539
        f.add_lines(b'r1', [b'r0'], [b'b\n', b'c\n'])
540
        f.add_lines(b'r2', [b'r0'], [b'b\n', b'c\n'])
541
        f.add_lines(b'r3', [b'r2'], [b'b\n', b'c\n'])
542
        f.add_lines(b'rM', [b'r1', b'r2'], [b'b\n', b'c\n'])
1563.2.29 by Robert Collins
Remove all but fetch references to repository.revision_store.
543
        self.assertEqual([], f.get_ancestry([]))
6963.2.4 by Jelmer Vernooij
Add bees.
544
        versions = f.get_ancestry([b'rM'])
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
545
        # there are some possibilities:
546
        # r0 r1 r2 rM r3
547
        # r0 r1 r2 r3 rM
548
        # etc
549
        # so we check indexes
6963.2.4 by Jelmer Vernooij
Add bees.
550
        r0 = versions.index(b'r0')
551
        r1 = versions.index(b'r1')
552
        r2 = versions.index(b'r2')
553
        self.assertFalse(b'r3' in versions)
554
        rM = versions.index(b'rM')
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
555
        self.assertTrue(r0 < r1)
556
        self.assertTrue(r0 < r2)
557
        self.assertTrue(r1 < rM)
558
        self.assertTrue(r2 < rM)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
559
560
        self.assertRaises(RevisionNotPresent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
561
                          f.get_ancestry, [b'rM', b'rX'])
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
562
6963.2.4 by Jelmer Vernooij
Add bees.
563
        self.assertEqual(set(f.get_ancestry(b'rM')),
7143.15.2 by Jelmer Vernooij
Run autopep8.
564
                         set(f.get_ancestry(b'rM', topo_sorted=False)))
2530.1.1 by Aaron Bentley
Make topological sorting optional for get_ancestry
565
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
566
    def test_mutate_after_finish(self):
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
567
        self._transaction = 'before'
1594.2.21 by Robert Collins
Teach versioned files to prevent mutation after finishing.
568
        f = self.get_file()
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
569
        self._transaction = 'after'
6963.2.4 by Jelmer Vernooij
Add bees.
570
        self.assertRaises(errors.OutSideTransaction, f.add_lines, b'', [], [])
7143.15.2 by Jelmer Vernooij
Run autopep8.
571
        self.assertRaises(errors.OutSideTransaction,
572
                          f.add_lines_with_ghosts, b'', [], [])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
573
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
574
    def test_copy_to(self):
575
        f = self.get_file()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
576
        f.add_lines(b'0', [], [b'a\n'])
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
577
        t = MemoryTransport()
578
        f.copy_to('foo', t)
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
579
        for suffix in self.get_factory().get_suffixes():
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
580
            self.assertTrue(t.has('foo' + suffix))
581
582
    def test_get_suffixes(self):
583
        f = self.get_file()
584
        # and should be a list
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
585
        self.assertTrue(isinstance(self.get_factory().get_suffixes(), list))
1563.2.15 by Robert Collins
remove the weavestore assumptions about the number and nature of files it manages.
586
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
587
    def test_get_parent_map(self):
588
        f = self.get_file()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
589
        f.add_lines(b'r0', [], [b'a\n', b'b\n'])
590
        self.assertEqual(
7143.15.2 by Jelmer Vernooij
Run autopep8.
591
            {b'r0': ()}, f.get_parent_map([b'r0']))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
592
        f.add_lines(b'r1', [b'r0'], [b'a\n', b'b\n'])
593
        self.assertEqual(
7143.15.2 by Jelmer Vernooij
Run autopep8.
594
            {b'r1': (b'r0',)}, f.get_parent_map([b'r1']))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
595
        self.assertEqual(
7143.15.2 by Jelmer Vernooij
Run autopep8.
596
            {b'r0': (),
597
             b'r1': (b'r0',)},
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
598
            f.get_parent_map([b'r0', b'r1']))
599
        f.add_lines(b'r2', [], [b'a\n', b'b\n'])
600
        f.add_lines(b'r3', [], [b'a\n', b'b\n'])
601
        f.add_lines(b'm', [b'r0', b'r1', b'r2', b'r3'], [b'a\n', b'b\n'])
602
        self.assertEqual(
7143.15.2 by Jelmer Vernooij
Run autopep8.
603
            {b'm': (b'r0', b'r1', b'r2', b'r3')}, f.get_parent_map([b'm']))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
604
        self.assertEqual({}, f.get_parent_map(b'y'))
605
        self.assertEqual(
7143.15.2 by Jelmer Vernooij
Run autopep8.
606
            {b'r0': (),
607
             b'r1': (b'r0',)},
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
608
            f.get_parent_map([b'r0', b'y', b'r1']))
3287.5.1 by Robert Collins
Add VersionedFile.get_parent_map.
609
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
610
    def test_annotate(self):
611
        f = self.get_file()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
612
        f.add_lines(b'r0', [], [b'a\n', b'b\n'])
613
        f.add_lines(b'r1', [b'r0'], [b'c\n', b'b\n'])
614
        origins = f.annotate(b'r1')
615
        self.assertEqual(origins[0][0], b'r1')
616
        self.assertEqual(origins[1][0], b'r0')
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
617
618
        self.assertRaises(RevisionNotPresent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
619
                          f.annotate, b'foo')
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
620
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
621
    def test_detection(self):
622
        # Test weaves detect corruption.
623
        #
624
        # Weaves contain a checksum of their texts.
625
        # When a text is extracted, this checksum should be
626
        # verified.
627
628
        w = self.get_file_corrupted_text()
629
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
630
        self.assertEqual(b'hello\n', w.get_text(b'v1'))
631
        self.assertRaises(WeaveInvalidChecksum, w.get_text, b'v2')
632
        self.assertRaises(WeaveInvalidChecksum, w.get_lines, b'v2')
6731 by Jelmer Vernooij
Move weave errors to breezy.bzr.weave.
633
        self.assertRaises(WeaveInvalidChecksum, w.check)
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
634
635
        w = self.get_file_corrupted_checksum()
636
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
637
        self.assertEqual(b'hello\n', w.get_text(b'v1'))
638
        self.assertRaises(WeaveInvalidChecksum, w.get_text, b'v2')
639
        self.assertRaises(WeaveInvalidChecksum, w.get_lines, b'v2')
6731 by Jelmer Vernooij
Move weave errors to breezy.bzr.weave.
640
        self.assertRaises(WeaveInvalidChecksum, w.check)
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
641
642
    def get_file_corrupted_text(self):
643
        """Return a versioned file with corrupt text but valid metadata."""
644
        raise NotImplementedError(self.get_file_corrupted_text)
645
1563.2.9 by Robert Collins
Update versionedfile api tests to ensure that data is available after every operation.
646
    def reopen_file(self, name='foo'):
647
        """Open the versioned file from disk again."""
648
        raise NotImplementedError(self.reopen_file)
649
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
650
    def test_iter_lines_added_or_present_in_versions(self):
651
        # test that we get at least an equalset of the lines added by
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
652
        # versions in the weave
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
653
        # the ordering here is to make a tree so that dumb searches have
654
        # more changes to muck up.
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
655
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
656
        class InstrumentedProgress(progress.ProgressTask):
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
657
658
            def __init__(self):
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
659
                progress.ProgressTask.__init__(self)
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
660
                self.updates = []
661
662
            def update(self, msg=None, current=None, total=None):
663
                self.updates.append((msg, current, total))
664
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
665
        vf = self.get_file()
666
        # add a base to get included
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
667
        vf.add_lines(b'base', [], [b'base\n'])
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
668
        # add a ancestor to be included on one side
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
669
        vf.add_lines(b'lancestor', [], [b'lancestor\n'])
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
670
        # add a ancestor to be included on the other side
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
671
        vf.add_lines(b'rancestor', [b'base'], [b'rancestor\n'])
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
672
        # add a child of rancestor with no eofile-nl
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
673
        vf.add_lines(b'child', [b'rancestor'], [b'base\n', b'child\n'])
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
674
        # add a child of lancestor and base to join the two roots
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
675
        vf.add_lines(b'otherchild',
676
                     [b'lancestor', b'base'],
677
                     [b'base\n', b'lancestor\n', b'otherchild\n'])
7143.15.2 by Jelmer Vernooij
Run autopep8.
678
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
679
        def iter_with_versions(versions, expected):
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
680
            # now we need to see what lines are returned, and how often.
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
681
            lines = {}
2039.1.1 by Aaron Bentley
Clean up progress properly when interrupted during fetch (#54000)
682
            progress = InstrumentedProgress()
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
683
            # iterate over the lines
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
684
            for line in vf.iter_lines_added_or_present_in_versions(versions,
7143.15.2 by Jelmer Vernooij
Run autopep8.
685
                                                                   pb=progress):
2975.3.1 by Robert Collins
Change (without backwards compatibility) the
686
                lines.setdefault(line, 0)
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
687
                lines[line] += 1
7143.15.2 by Jelmer Vernooij
Run autopep8.
688
            if [] != progress.updates:
2039.1.2 by Aaron Bentley
Tweak test to avoid catching assert
689
                self.assertEqual(expected, progress.updates)
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
690
            return lines
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
691
        lines = iter_with_versions([b'child', b'otherchild'],
4103.3.4 by Martin Pool
Update test that depends on progress bar strings
692
                                   [('Walking content', 0, 2),
693
                                    ('Walking content', 1, 2),
694
                                    ('Walking content', 2, 2)])
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
695
        # we must see child and otherchild
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
696
        self.assertTrue(lines[(b'child\n', b'child')] > 0)
697
        self.assertTrue(lines[(b'otherchild\n', b'otherchild')] > 0)
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
698
        # we dont care if we got more than that.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
699
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
700
        # test all lines
4103.3.4 by Martin Pool
Update test that depends on progress bar strings
701
        lines = iter_with_versions(None, [('Walking content', 0, 5),
702
                                          ('Walking content', 1, 5),
703
                                          ('Walking content', 2, 5),
704
                                          ('Walking content', 3, 5),
705
                                          ('Walking content', 4, 5),
706
                                          ('Walking content', 5, 5)])
1594.2.6 by Robert Collins
Introduce a api specifically for looking at lines in some versions of the inventory, for fileid_involved.
707
        # all lines must be seen at least once
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
708
        self.assertTrue(lines[(b'base\n', b'base')] > 0)
709
        self.assertTrue(lines[(b'lancestor\n', b'lancestor')] > 0)
710
        self.assertTrue(lines[(b'rancestor\n', b'rancestor')] > 0)
711
        self.assertTrue(lines[(b'child\n', b'child')] > 0)
712
        self.assertTrue(lines[(b'otherchild\n', b'otherchild')] > 0)
1594.2.7 by Robert Collins
Add versionedfile.fix_parents api for correcting data post hoc.
713
1594.2.8 by Robert Collins
add ghost aware apis to knits.
714
    def test_add_lines_with_ghosts(self):
715
        # some versioned file formats allow lines to be added with parent
716
        # information that is > than that in the format. Formats that do
717
        # not support this need to raise NotImplementedError on the
718
        # add_lines_with_ghosts api.
719
        vf = self.get_file()
720
        # add a revision with ghost parents
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
721
        # The preferred form is utf8, but we should translate when needed
722
        parent_id_unicode = u'b\xbfse'
723
        parent_id_utf8 = parent_id_unicode.encode('utf8')
1594.2.8 by Robert Collins
add ghost aware apis to knits.
724
        try:
6963.2.4 by Jelmer Vernooij
Add bees.
725
            vf.add_lines_with_ghosts(b'notbxbfse', [parent_id_utf8], [])
1594.2.8 by Robert Collins
add ghost aware apis to knits.
726
        except NotImplementedError:
727
            # check the other ghost apis are also not implemented
7143.15.2 by Jelmer Vernooij
Run autopep8.
728
            self.assertRaises(NotImplementedError,
729
                              vf.get_ancestry_with_ghosts, [b'foo'])
730
            self.assertRaises(NotImplementedError,
731
                              vf.get_parents_with_ghosts, b'foo')
1594.2.8 by Robert Collins
add ghost aware apis to knits.
732
            return
2150.2.1 by Robert Collins
Correctly decode utf8 revision ids from knits when parsing, fixes a regression where a unicode revision id is stored correctly, but then indexed by the utf8 value on the next invocation of bzr, rather than the unicode value.
733
        vf = self.reopen_file()
1594.2.8 by Robert Collins
add ghost aware apis to knits.
734
        # test key graph related apis: getncestry, _graph, get_parents
735
        # has_version
736
        # - these are ghost unaware and must not be reflect ghosts
6963.2.4 by Jelmer Vernooij
Add bees.
737
        self.assertEqual([b'notbxbfse'], vf.get_ancestry(b'notbxbfse'))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
738
        self.assertFalse(vf.has_version(parent_id_utf8))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
739
        # we have _with_ghost apis to give us ghost information.
7143.15.2 by Jelmer Vernooij
Run autopep8.
740
        self.assertEqual([parent_id_utf8, b'notbxbfse'],
741
                         vf.get_ancestry_with_ghosts([b'notbxbfse']))
742
        self.assertEqual([parent_id_utf8],
743
                         vf.get_parents_with_ghosts(b'notbxbfse'))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
744
        # if we add something that is a ghost of another, it should correct the
745
        # results of the prior apis
2858.2.1 by Martin Pool
Remove most calls to safe_file_id and safe_revision_id.
746
        vf.add_lines(parent_id_utf8, [], [])
7143.15.2 by Jelmer Vernooij
Run autopep8.
747
        self.assertEqual([parent_id_utf8, b'notbxbfse'],
748
                         vf.get_ancestry([b'notbxbfse']))
749
        self.assertEqual({b'notbxbfse': (parent_id_utf8,)},
750
                         vf.get_parent_map([b'notbxbfse']))
2249.5.12 by John Arbash Meinel
Change the APIs for VersionedFile, Store, and some of Repository into utf-8
751
        self.assertTrue(vf.has_version(parent_id_utf8))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
752
        # we have _with_ghost apis to give us ghost information.
6963.2.4 by Jelmer Vernooij
Add bees.
753
        self.assertEqual([parent_id_utf8, b'notbxbfse'],
7143.15.2 by Jelmer Vernooij
Run autopep8.
754
                         vf.get_ancestry_with_ghosts([b'notbxbfse']))
755
        self.assertEqual([parent_id_utf8],
756
                         vf.get_parents_with_ghosts(b'notbxbfse'))
1594.2.8 by Robert Collins
add ghost aware apis to knits.
757
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
758
    def test_add_lines_with_ghosts_after_normal_revs(self):
759
        # some versioned file formats allow lines to be added with parent
760
        # information that is > than that in the format. Formats that do
761
        # not support this need to raise NotImplementedError on the
762
        # add_lines_with_ghosts api.
763
        vf = self.get_file()
764
        # probe for ghost support
765
        try:
6963.2.4 by Jelmer Vernooij
Add bees.
766
            vf.add_lines_with_ghosts(b'base', [], [b'line\n', b'line_b\n'])
1594.2.9 by Robert Collins
Teach Knit repositories how to handle ghosts without corrupting at all.
767
        except NotImplementedError:
768
            return
6963.2.4 by Jelmer Vernooij
Add bees.
769
        vf.add_lines_with_ghosts(b'references_ghost',
770
                                 [b'base', b'a_ghost'],
771
                                 [b'line\n', b'line_b\n', b'line_c\n'])
772
        origins = vf.annotate(b'references_ghost')
773
        self.assertEqual((b'base', b'line\n'), origins[0])
774
        self.assertEqual((b'base', b'line_b\n'), origins[1])
775
        self.assertEqual((b'references_ghost', b'line_c\n'), origins[2])
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
776
777
    def test_readonly_mode(self):
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
778
        t = self.get_transport()
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
779
        factory = self.get_factory()
6619.3.14 by Jelmer Vernooij
Convert some octal numbers to new notations.
780
        vf = factory('id', t, 0o777, create=True, access_mode='w')
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
781
        vf = factory('id', t, access_mode='r')
6963.2.4 by Jelmer Vernooij
Add bees.
782
        self.assertRaises(errors.ReadOnlyError, vf.add_lines, b'base', [], [])
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
783
        self.assertRaises(errors.ReadOnlyError,
784
                          vf.add_lines_with_ghosts,
6963.2.4 by Jelmer Vernooij
Add bees.
785
                          b'base',
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
786
                          [],
787
                          [])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
788
3316.2.9 by Robert Collins
* ``VersionedFile.get_sha1`` is deprecated, please use
789
    def test_get_sha1s(self):
1666.1.6 by Robert Collins
Make knit the default format.
790
        # check the sha1 data is available
791
        vf = self.get_file()
792
        # a simple file
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
793
        vf.add_lines(b'a', [], [b'a\n'])
1666.1.6 by Robert Collins
Make knit the default format.
794
        # the same file, different metadata
6973.14.4 by Jelmer Vernooij
Fix checking for options.
795
        vf.add_lines(b'b', [b'a'], [b'a\n'])
1666.1.6 by Robert Collins
Make knit the default format.
796
        # a file differing only in last newline.
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
797
        vf.add_lines(b'c', [], [b'a'])
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
798
        self.assertEqual({
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
799
            b'a': b'3f786850e387550fdab836ed7e6dc881de23001b',
800
            b'c': b'86f7e437faa5a7fce15d1ddcb9eaeaea377667b8',
801
            b'b': b'3f786850e387550fdab836ed7e6dc881de23001b',
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
802
            },
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
803
            vf.get_sha1s([b'a', b'c', b'b']))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
804
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
805
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
806
class TestWeave(TestCaseWithMemoryTransport, VersionedFileTestMixIn):
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
807
808
    def get_file(self, name='foo'):
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
809
        return WeaveFile(name, self.get_transport(),
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
810
                         create=True,
811
                         get_scope=self.get_transaction)
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
812
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
813
    def get_file_corrupted_text(self):
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
814
        w = WeaveFile('foo', self.get_transport(),
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
815
                      create=True,
816
                      get_scope=self.get_transaction)
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
817
        w.add_lines(b'v1', [], [b'hello\n'])
818
        w.add_lines(b'v2', [b'v1'], [b'hello\n', b'there\n'])
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
819
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
820
        # We are going to invasively corrupt the text
821
        # Make sure the internals of weave are the same
7143.15.2 by Jelmer Vernooij
Run autopep8.
822
        self.assertEqual([(b'{', 0), b'hello\n', (b'}', None), (b'{', 1), b'there\n', (b'}', None)
823
                          ], w._weave)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
824
7143.15.2 by Jelmer Vernooij
Run autopep8.
825
        self.assertEqual([b'f572d396fae9206628714fb2ce00f72e94f2258f', b'90f265c6e75f1c8f9ab76dcf85528352c5f215ef'
826
                          ], w._sha1s)
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
827
        w.check()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
828
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
829
        # Corrupted
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
830
        w._weave[4] = b'There\n'
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
831
        return w
832
833
    def get_file_corrupted_checksum(self):
834
        w = self.get_file_corrupted_text()
835
        # Corrected
6963.2.4 by Jelmer Vernooij
Add bees.
836
        w._weave[4] = b'there\n'
837
        self.assertEqual(b'hello\nthere\n', w.get_text(b'v2'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
838
7143.15.2 by Jelmer Vernooij
Run autopep8.
839
        # Invalid checksum, first digit changed
840
        w._sha1s[1] = b'f0f265c6e75f1c8f9ab76dcf85528352c5f215ef'
1563.2.6 by Robert Collins
Start check tests for knits (pending), and remove dead code.
841
        return w
842
1666.1.6 by Robert Collins
Make knit the default format.
843
    def reopen_file(self, name='foo', create=False):
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
844
        return WeaveFile(name, self.get_transport(),
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
845
                         create=create,
846
                         get_scope=self.get_transaction)
1563.2.9 by Robert Collins
Update versionedfile api tests to ensure that data is available after every operation.
847
1563.2.25 by Robert Collins
Merge in upstream.
848
    def test_no_implicit_create(self):
849
        self.assertRaises(errors.NoSuchFile,
850
                          WeaveFile,
851
                          'foo',
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
852
                          self.get_transport(),
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
853
                          get_scope=self.get_transaction)
1563.2.25 by Robert Collins
Merge in upstream.
854
1594.2.23 by Robert Collins
Test versioned file storage handling of clean/dirty status for accessed versioned files.
855
    def get_factory(self):
856
        return WeaveFile
857
1563.2.1 by Robert Collins
Merge in a variation of the versionedfile api from versioned-file.
858
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
859
class TestPlanMergeVersionedFile(TestCaseWithMemoryTransport):
860
861
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
862
        super(TestPlanMergeVersionedFile, self).setUp()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
863
        mapper = PrefixMapper()
864
        factory = make_file_factory(True, mapper)
865
        self.vf1 = factory(self.get_transport('root-1'))
866
        self.vf2 = factory(self.get_transport('root-2'))
867
        self.plan_merge_vf = versionedfile._PlanMergeVersionedFile('root')
868
        self.plan_merge_vf.fallback_versionedfiles.extend([self.vf1, self.vf2])
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
869
870
    def test_add_lines(self):
6963.2.4 by Jelmer Vernooij
Add bees.
871
        self.plan_merge_vf.add_lines((b'root', b'a:'), [], [])
872
        self.assertRaises(ValueError, self.plan_merge_vf.add_lines,
7143.15.2 by Jelmer Vernooij
Run autopep8.
873
                          (b'root', b'a'), [], [])
874
        self.assertRaises(ValueError, self.plan_merge_vf.add_lines,
875
                          (b'root', b'a:'), None, [])
876
        self.assertRaises(ValueError, self.plan_merge_vf.add_lines,
877
                          (b'root', b'a:'), [], None)
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
878
879
    def setup_abcde(self):
6963.2.4 by Jelmer Vernooij
Add bees.
880
        self.vf1.add_lines((b'root', b'A'), [], [b'a'])
881
        self.vf1.add_lines((b'root', b'B'), [(b'root', b'A')], [b'b'])
882
        self.vf2.add_lines((b'root', b'C'), [], [b'c'])
883
        self.vf2.add_lines((b'root', b'D'), [(b'root', b'C')], [b'd'])
884
        self.plan_merge_vf.add_lines((b'root', b'E:'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
885
                                     [(b'root', b'B'), (b'root', b'D')], [b'e'])
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
886
887
    def test_get_parents(self):
888
        self.setup_abcde()
6963.2.4 by Jelmer Vernooij
Add bees.
889
        self.assertEqual({(b'root', b'B'): ((b'root', b'A'),)},
7143.15.2 by Jelmer Vernooij
Run autopep8.
890
                         self.plan_merge_vf.get_parent_map([(b'root', b'B')]))
6963.2.4 by Jelmer Vernooij
Add bees.
891
        self.assertEqual({(b'root', b'D'): ((b'root', b'C'),)},
7143.15.2 by Jelmer Vernooij
Run autopep8.
892
                         self.plan_merge_vf.get_parent_map([(b'root', b'D')]))
6963.2.4 by Jelmer Vernooij
Add bees.
893
        self.assertEqual({(b'root', b'E:'): ((b'root', b'B'), (b'root', b'D'))},
7143.15.2 by Jelmer Vernooij
Run autopep8.
894
                         self.plan_merge_vf.get_parent_map([(b'root', b'E:')]))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
895
        self.assertEqual({},
7143.15.2 by Jelmer Vernooij
Run autopep8.
896
                         self.plan_merge_vf.get_parent_map([(b'root', b'F')]))
3287.5.2 by Robert Collins
Deprecate VersionedFile.get_parents, breaking pulling from a ghost containing knit or pack repository to weaves, which improves correctness and allows simplification of core code.
897
        self.assertEqual({
7143.15.2 by Jelmer Vernooij
Run autopep8.
898
            (b'root', b'B'): ((b'root', b'A'),),
899
            (b'root', b'D'): ((b'root', b'C'),),
900
            (b'root', b'E:'): ((b'root', b'B'), (b'root', b'D')),
901
            },
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
902
            self.plan_merge_vf.get_parent_map(
6963.2.4 by Jelmer Vernooij
Add bees.
903
                [(b'root', b'B'), (b'root', b'D'), (b'root', b'E:'), (b'root', b'F')]))
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
904
3350.6.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
    def test_get_record_stream(self):
3062.1.9 by Aaron Bentley
Move PlanMerge into merge and _PlanMergeVersionedFile into versionedfile
906
        self.setup_abcde()
7143.15.2 by Jelmer Vernooij
Run autopep8.
907
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
908
        def get_record(suffix):
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
909
            return next(self.plan_merge_vf.get_record_stream(
6963.2.4 by Jelmer Vernooij
Add bees.
910
                [(b'root', suffix)], 'unordered', True))
6963.2.13 by Jelmer Vernooij
Fix more tests.
911
        self.assertEqual(b'a', get_record(b'A').get_bytes_as('fulltext'))
912
        self.assertEqual(b'c', get_record(b'C').get_bytes_as('fulltext'))
913
        self.assertEqual(b'e', get_record(b'E:').get_bytes_as('fulltext'))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
914
        self.assertEqual('absent', get_record('F').storage_kind)
1666.1.1 by Robert Collins
Add trivial http-using test for versioned files.
915
916
917
class TestReadonlyHttpMixin(object):
918
3316.2.3 by Robert Collins
Remove manual notification of transaction finishing on versioned files.
919
    def get_transaction(self):
920
        return 1
921
1666.1.1 by Robert Collins
Add trivial http-using test for versioned files.
922
    def test_readonly_http_works(self):
923
        # we should be able to read from http with a versioned file.
924
        vf = self.get_file()
1666.1.6 by Robert Collins
Make knit the default format.
925
        # try an empty file access
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
926
        readonly_vf = self.get_factory()('foo',
7143.15.2 by Jelmer Vernooij
Run autopep8.
927
                                         transport.get_transport_from_url(self.get_readonly_url('.')))
1666.1.6 by Robert Collins
Make knit the default format.
928
        self.assertEqual([], readonly_vf.versions())
5229.1.13 by Vincent Ladeuil
Eager tests are bad, we really want two tests here.
929
930
    def test_readonly_http_works_with_feeling(self):
931
        # we should be able to read from http with a versioned file.
932
        vf = self.get_file()
1666.1.6 by Robert Collins
Make knit the default format.
933
        # now with feeling.
6963.2.4 by Jelmer Vernooij
Add bees.
934
        vf.add_lines(b'1', [], [b'a\n'])
935
        vf.add_lines(b'2', [b'1'], [b'b\n', b'a\n'])
6083.1.1 by Jelmer Vernooij
Use get_transport_from_{url,path} in more places.
936
        readonly_vf = self.get_factory()('foo',
7143.15.2 by Jelmer Vernooij
Run autopep8.
937
                                         transport.get_transport_from_url(self.get_readonly_url('.')))
6963.2.4 by Jelmer Vernooij
Add bees.
938
        self.assertEqual([b'1', b'2'], vf.versions())
939
        self.assertEqual([b'1', b'2'], readonly_vf.versions())
1666.1.1 by Robert Collins
Add trivial http-using test for versioned files.
940
        for version in readonly_vf.versions():
941
            readonly_vf.get_lines(version)
942
943
944
class TestWeaveHTTP(TestCaseWithWebserver, TestReadonlyHttpMixin):
945
946
    def get_file(self):
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
947
        return WeaveFile('foo', self.get_transport(),
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
948
                         create=True,
949
                         get_scope=self.get_transaction)
1666.1.1 by Robert Collins
Add trivial http-using test for versioned files.
950
951
    def get_factory(self):
952
        return WeaveFile
953
954
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
955
class MergeCasesMixin(object):
956
957
    def doMerge(self, base, a, b, mp):
958
        from textwrap import dedent
959
960
        def addcrlf(x):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
961
            return x + b'\n'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
962
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
963
        w = self.get_file()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
964
        w.add_lines(b'text0', [], list(map(addcrlf, base)))
965
        w.add_lines(b'text1', [b'text0'], list(map(addcrlf, a)))
966
        w.add_lines(b'text2', [b'text0'], list(map(addcrlf, b)))
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
967
968
        self.log_contents(w)
969
970
        self.log('merge plan:')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
971
        p = list(w.plan_merge(b'text1', b'text2'))
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
972
        for state, line in p:
973
            if line:
974
                self.log('%12s | %s' % (state, line[:-1]))
975
976
        self.log('merge:')
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
977
        mt = BytesIO()
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
978
        mt.writelines(w.weave_merge(p))
979
        mt.seek(0)
980
        self.log(mt.getvalue())
981
6631.3.1 by Martin
Run 2to3 map fixer and refactor after
982
        mp = list(map(addcrlf, mp))
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
983
        self.assertEqual(mt.readlines(), mp)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
984
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
985
    def testOneInsert(self):
986
        self.doMerge([],
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
987
                     [b'aa'],
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
988
                     [],
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
989
                     [b'aa'])
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
990
991
    def testSeparateInserts(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
992
        self.doMerge([b'aaa', b'bbb', b'ccc'],
993
                     [b'aaa', b'xxx', b'bbb', b'ccc'],
994
                     [b'aaa', b'bbb', b'yyy', b'ccc'],
995
                     [b'aaa', b'xxx', b'bbb', b'yyy', b'ccc'])
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
996
997
    def testSameInsert(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
998
        self.doMerge([b'aaa', b'bbb', b'ccc'],
999
                     [b'aaa', b'xxx', b'bbb', b'ccc'],
1000
                     [b'aaa', b'xxx', b'bbb', b'yyy', b'ccc'],
1001
                     [b'aaa', b'xxx', b'bbb', b'yyy', b'ccc'])
1002
    overlappedInsertExpected = [b'aaa', b'xxx', b'yyy', b'bbb']
7143.15.2 by Jelmer Vernooij
Run autopep8.
1003
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1004
    def testOverlappedInsert(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1005
        self.doMerge([b'aaa', b'bbb'],
1006
                     [b'aaa', b'xxx', b'yyy', b'bbb'],
1007
                     [b'aaa', b'xxx', b'bbb'], self.overlappedInsertExpected)
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1008
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1009
        # really it ought to reduce this to
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1010
        # [b'aaa', b'xxx', b'yyy', b'bbb']
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1011
1012
    def testClashReplace(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1013
        self.doMerge([b'aaa'],
1014
                     [b'xxx'],
1015
                     [b'yyy', b'zzz'],
1016
                     [b'<<<<<<< ', b'xxx', b'=======', b'yyy', b'zzz',
1017
                      b'>>>>>>> '])
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1018
1019
    def testNonClashInsert1(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1020
        self.doMerge([b'aaa'],
1021
                     [b'xxx', b'aaa'],
1022
                     [b'yyy', b'zzz'],
1023
                     [b'<<<<<<< ', b'xxx', b'aaa', b'=======', b'yyy', b'zzz',
1024
                      b'>>>>>>> '])
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1025
1026
    def testNonClashInsert2(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1027
        self.doMerge([b'aaa'],
1028
                     [b'aaa'],
1029
                     [b'yyy', b'zzz'],
1030
                     [b'yyy', b'zzz'])
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1031
1032
    def testDeleteAndModify(self):
1033
        """Clashing delete and modification.
1034
1035
        If one side modifies a region and the other deletes it then
1036
        there should be a conflict with one side blank.
1037
        """
1038
1039
        #######################################
1040
        # skippd, not working yet
1041
        return
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1042
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1043
        self.doMerge([b'aaa', b'bbb', b'ccc'],
1044
                     [b'aaa', b'ddd', b'ccc'],
1045
                     [b'aaa', b'ccc'],
1046
                     [b'<<<<<<<< ', b'aaa', b'=======', b'>>>>>>> ', b'ccc'])
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1047
1048
    def _test_merge_from_strings(self, base, a, b, expected):
1049
        w = self.get_file()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1050
        w.add_lines(b'text0', [], base.splitlines(True))
1051
        w.add_lines(b'text1', [b'text0'], a.splitlines(True))
1052
        w.add_lines(b'text2', [b'text0'], b.splitlines(True))
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1053
        self.log('merge plan:')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1054
        p = list(w.plan_merge(b'text1', b'text2'))
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1055
        for state, line in p:
1056
            if line:
1057
                self.log('%12s | %s' % (state, line[:-1]))
1058
        self.log('merge result:')
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
1059
        result_text = b''.join(w.weave_merge(p))
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1060
        self.log(result_text)
1061
        self.assertEqualDiff(result_text, expected)
1062
1063
    def test_weave_merge_conflicts(self):
1064
        # does weave merge properly handle plans that end with unchanged?
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1065
        result = b''.join(self.get_file().weave_merge([('new-a', b'hello\n')]))
1066
        self.assertEqual(result, b'hello\n')
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1067
1068
    def test_deletion_extended(self):
1069
        """One side deletes, the other deletes more.
1070
        """
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1071
        base = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1072
            line 1
1073
            line 2
1074
            line 3
1075
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1076
        a = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1077
            line 1
1078
            line 2
1079
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1080
        b = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1081
            line 1
1082
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1083
        result = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1084
            line 1
4312.1.3 by John Arbash Meinel
Different sides deleting different amounts is now a conflict.
1085
<<<<<<<\x20
1086
            line 2
1087
=======
1088
>>>>>>>\x20
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1089
            """
1090
        self._test_merge_from_strings(base, a, b, result)
1091
1092
    def test_deletion_overlap(self):
1093
        """Delete overlapping regions with no other conflict.
1094
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1095
        Arguably it'd be better to treat these as agreement, rather than
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1096
        conflict, but for now conflict is safer.
1097
        """
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1098
        base = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1099
            start context
1100
            int a() {}
1101
            int b() {}
1102
            int c() {}
1103
            end context
1104
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1105
        a = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1106
            start context
1107
            int a() {}
1108
            end context
1109
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1110
        b = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1111
            start context
1112
            int c() {}
1113
            end context
1114
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1115
        result = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1116
            start context
3943.8.2 by Marius Kruger
fix tests relying on trailing whitespace by replacing it with \x20.
1117
<<<<<<<\x20
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1118
            int a() {}
1119
=======
1120
            int c() {}
3943.8.2 by Marius Kruger
fix tests relying on trailing whitespace by replacing it with \x20.
1121
>>>>>>>\x20
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1122
            end context
1123
            """
1124
        self._test_merge_from_strings(base, a, b, result)
1125
1126
    def test_agreement_deletion(self):
1127
        """Agree to delete some lines, without conflicts."""
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1128
        base = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1129
            start context
1130
            base line 1
1131
            base line 2
1132
            end context
1133
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1134
        a = b"""\
1135
            start context
1136
            base line 1
1137
            end context
1138
            """
1139
        b = b"""\
1140
            start context
1141
            base line 1
1142
            end context
1143
            """
1144
        result = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1145
            start context
1146
            base line 1
1147
            end context
1148
            """
1149
        self._test_merge_from_strings(base, a, b, result)
1150
1151
    def test_sync_on_deletion(self):
1152
        """Specific case of merge where we can synchronize incorrectly.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1153
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1154
        A previous version of the weave merge concluded that the two versions
1155
        agreed on deleting line 2, and this could be a synchronization point.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1156
        Line 1 was then considered in isolation, and thought to be deleted on
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1157
        both sides.
1158
1159
        It's better to consider the whole thing as a disagreement region.
1160
        """
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1161
        base = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1162
            start context
1163
            base line 1
1164
            base line 2
1165
            end context
1166
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1167
        a = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1168
            start context
1169
            base line 1
1170
            a's replacement line 2
1171
            end context
1172
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1173
        b = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1174
            start context
1175
            b replaces
1176
            both lines
1177
            end context
1178
            """
6963.2.4 by Jelmer Vernooij
Add bees.
1179
        result = b"""\
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1180
            start context
3943.8.2 by Marius Kruger
fix tests relying on trailing whitespace by replacing it with \x20.
1181
<<<<<<<\x20
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1182
            base line 1
1183
            a's replacement line 2
1184
=======
1185
            b replaces
1186
            both lines
3943.8.2 by Marius Kruger
fix tests relying on trailing whitespace by replacing it with \x20.
1187
>>>>>>>\x20
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1188
            end context
1189
            """
1190
        self._test_merge_from_strings(base, a, b, result)
1191
1192
2535.3.1 by Andrew Bennetts
Add get_format_signature to VersionedFile
1193
class TestWeaveMerge(TestCaseWithMemoryTransport, MergeCasesMixin):
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1194
1195
    def get_file(self, name='foo'):
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
1196
        return WeaveFile(name, self.get_transport(),
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
1197
                         create=True)
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1198
1199
    def log_contents(self, w):
1200
        self.log('weave is:')
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1201
        tmpf = BytesIO()
1664.2.9 by Aaron Bentley
Ported weave merge test to versionedfile
1202
        write_weave(w, tmpf)
1203
        self.log(tmpf.getvalue())
1204
6963.2.4 by Jelmer Vernooij
Add bees.
1205
    overlappedInsertExpected = [b'aaa', b'<<<<<<< ', b'xxx', b'yyy', b'=======',
1206
                                b'xxx', b'>>>>>>> ', b'bbb']
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1207
1208
1209
class TestContentFactoryAdaption(TestCaseWithMemoryTransport):
1210
1211
    def test_select_adaptor(self):
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
1212
        """Test expected adapters exist."""
1213
        # One scenario for each lookup combination we expect to use.
1214
        # Each is source_kind, requested_kind, adapter class
1215
        scenarios = [
1216
            ('knit-delta-gz', 'fulltext', _mod_knit.DeltaPlainToFullText),
7459.3.4 by Jelmer Vernooij
Merge trunk.
1217
            ('knit-delta-gz', 'lines', _mod_knit.DeltaPlainToFullText),
1218
            ('knit-delta-gz', 'chunked', _mod_knit.DeltaPlainToFullText),
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
1219
            ('knit-ft-gz', 'fulltext', _mod_knit.FTPlainToFullText),
7459.3.4 by Jelmer Vernooij
Merge trunk.
1220
            ('knit-ft-gz', 'lines', _mod_knit.FTPlainToFullText),
1221
            ('knit-ft-gz', 'chunked', _mod_knit.FTPlainToFullText),
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
1222
            ('knit-annotated-delta-gz', 'knit-delta-gz',
1223
                _mod_knit.DeltaAnnotatedToUnannotated),
1224
            ('knit-annotated-delta-gz', 'fulltext',
1225
                _mod_knit.DeltaAnnotatedToFullText),
1226
            ('knit-annotated-ft-gz', 'knit-ft-gz',
1227
                _mod_knit.FTAnnotatedToUnannotated),
1228
            ('knit-annotated-ft-gz', 'fulltext',
1229
                _mod_knit.FTAnnotatedToFullText),
7459.3.4 by Jelmer Vernooij
Merge trunk.
1230
            ('knit-annotated-ft-gz', 'lines',
1231
                _mod_knit.FTAnnotatedToFullText),
1232
            ('knit-annotated-ft-gz', 'chunked',
1233
                _mod_knit.FTAnnotatedToFullText),
3350.3.7 by Robert Collins
Create a registry of versioned file record adapters.
1234
            ]
1235
        for source, requested, klass in scenarios:
1236
            adapter_factory = versionedfile.adapter_registry.get(
1237
                (source, requested))
1238
            adapter = adapter_factory(None)
1239
            self.assertIsInstance(adapter, klass)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1240
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
1241
    def get_knit(self, annotated=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.
1242
        mapper = ConstantMapper('knit')
1243
        transport = self.get_transport()
1244
        return make_file_factory(annotated, mapper)(transport)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1245
7459.3.6 by Jelmer Vernooij
Fix tests.
1246
    def helpGetBytes(self, f, ft_name, ft_adapter, delta_name, delta_adapter):
3350.3.22 by Robert Collins
Review feedback.
1247
        """Grab the interested adapted texts for tests."""
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1248
        # origin is a fulltext
6963.2.4 by Jelmer Vernooij
Add bees.
1249
        entries = f.get_record_stream([(b'origin',)], 'unordered', False)
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
1250
        base = next(entries)
7459.3.6 by Jelmer Vernooij
Fix tests.
1251
        ft_data = ft_adapter.get_bytes(base, ft_name)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1252
        # merged is both a delta and multiple parents.
6963.2.4 by Jelmer Vernooij
Add bees.
1253
        entries = f.get_record_stream([(b'merged',)], 'unordered', False)
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
1254
        merged = next(entries)
7459.3.6 by Jelmer Vernooij
Fix tests.
1255
        delta_data = delta_adapter.get_bytes(merged, delta_name)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1256
        return ft_data, delta_data
1257
1258
    def test_deannotation_noeol(self):
1259
        """Test converting annotated knits to unannotated knits."""
1260
        # we need a full text, and a delta
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1261
        f = self.get_knit()
1262
        get_diamond_files(f, 1, trailing_eol=False)
7459.3.6 by Jelmer Vernooij
Fix tests.
1263
        ft_data, delta_data = self.helpGetBytes(
1264
            f, 'knit-ft-gz', _mod_knit.FTAnnotatedToUnannotated(None),
1265
            'knit-delta-gz', _mod_knit.DeltaAnnotatedToUnannotated(None))
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1266
        self.assertEqual(
6963.2.4 by Jelmer Vernooij
Add bees.
1267
            b'version origin 1 b284f94827db1fa2970d9e2014f080413b547a7e\n'
1268
            b'origin\n'
1269
            b'end origin\n',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1270
            GzipFile(mode='rb', fileobj=BytesIO(ft_data)).read())
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1271
        self.assertEqual(
6963.2.4 by Jelmer Vernooij
Add bees.
1272
            b'version merged 4 32c2e79763b3f90e8ccde37f9710b6629c25a796\n'
1273
            b'1,2,3\nleft\nright\nmerged\nend merged\n',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1274
            GzipFile(mode='rb', fileobj=BytesIO(delta_data)).read())
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1275
1276
    def test_deannotation(self):
1277
        """Test converting annotated knits to unannotated knits."""
1278
        # we need a full text, and a delta
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1279
        f = self.get_knit()
1280
        get_diamond_files(f, 1)
7459.3.6 by Jelmer Vernooij
Fix tests.
1281
        ft_data, delta_data = self.helpGetBytes(
1282
            f, 'knit-ft-gz', _mod_knit.FTAnnotatedToUnannotated(None),
1283
            'knit-delta-gz', _mod_knit.DeltaAnnotatedToUnannotated(None))
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1284
        self.assertEqual(
6963.2.4 by Jelmer Vernooij
Add bees.
1285
            b'version origin 1 00e364d235126be43292ab09cb4686cf703ddc17\n'
1286
            b'origin\n'
1287
            b'end origin\n',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1288
            GzipFile(mode='rb', fileobj=BytesIO(ft_data)).read())
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1289
        self.assertEqual(
6963.2.4 by Jelmer Vernooij
Add bees.
1290
            b'version merged 3 ed8bce375198ea62444dc71952b22cfc2b09226d\n'
1291
            b'2,2,2\nright\nmerged\nend merged\n',
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
1292
            GzipFile(mode='rb', fileobj=BytesIO(delta_data)).read())
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1293
1294
    def test_annotated_to_fulltext_no_eol(self):
1295
        """Test adapting annotated knits to full texts (for -> weaves)."""
1296
        # we need a full text, and a delta
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1297
        f = self.get_knit()
1298
        get_diamond_files(f, 1, trailing_eol=False)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1299
        # Reconstructing a full text requires a backing versioned file, and it
1300
        # must have the base lines requested from it.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1301
        logged_vf = versionedfile.RecordingVersionedFilesDecorator(f)
7459.3.6 by Jelmer Vernooij
Fix tests.
1302
        ft_data, delta_data = self.helpGetBytes(
1303
            f, 'fulltext', _mod_knit.FTAnnotatedToFullText(None),
1304
            'fulltext', _mod_knit.DeltaAnnotatedToFullText(logged_vf))
6963.2.4 by Jelmer Vernooij
Add bees.
1305
        self.assertEqual(b'origin', ft_data)
1306
        self.assertEqual(b'base\nleft\nright\nmerged', delta_data)
1307
        self.assertEqual([('get_record_stream', [(b'left',)], 'unordered',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1308
                           True)], logged_vf.calls)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1309
1310
    def test_annotated_to_fulltext(self):
1311
        """Test adapting annotated knits to full texts (for -> weaves)."""
1312
        # we need a full text, and a delta
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1313
        f = self.get_knit()
1314
        get_diamond_files(f, 1)
3350.3.4 by Robert Collins
Finish adapters for annotated knits to unannotated knits and full texts.
1315
        # Reconstructing a full text requires a backing versioned file, and it
1316
        # must have the base lines requested from it.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1317
        logged_vf = versionedfile.RecordingVersionedFilesDecorator(f)
7459.3.6 by Jelmer Vernooij
Fix tests.
1318
        ft_data, delta_data = self.helpGetBytes(
1319
            f, 'fulltext', _mod_knit.FTAnnotatedToFullText(None),
1320
            'fulltext', _mod_knit.DeltaAnnotatedToFullText(logged_vf))
6963.2.4 by Jelmer Vernooij
Add bees.
1321
        self.assertEqual(b'origin\n', ft_data)
1322
        self.assertEqual(b'base\nleft\nright\nmerged\n', delta_data)
1323
        self.assertEqual([('get_record_stream', [(b'left',)], 'unordered',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1324
                           True)], logged_vf.calls)
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
1325
1326
    def test_unannotated_to_fulltext(self):
1327
        """Test adapting unannotated knits to full texts.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1328
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
1329
        This is used for -> weaves, and for -> annotated knits.
1330
        """
1331
        # we need a full text, and a delta
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1332
        f = self.get_knit(annotated=False)
1333
        get_diamond_files(f, 1)
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
1334
        # Reconstructing a full text requires a backing versioned file, and it
1335
        # must have the base lines requested from it.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1336
        logged_vf = versionedfile.RecordingVersionedFilesDecorator(f)
7459.3.6 by Jelmer Vernooij
Fix tests.
1337
        ft_data, delta_data = self.helpGetBytes(
1338
            f, 'fulltext', _mod_knit.FTPlainToFullText(None),
1339
            'fulltext', _mod_knit.DeltaPlainToFullText(logged_vf))
6963.2.4 by Jelmer Vernooij
Add bees.
1340
        self.assertEqual(b'origin\n', ft_data)
1341
        self.assertEqual(b'base\nleft\nright\nmerged\n', delta_data)
1342
        self.assertEqual([('get_record_stream', [(b'left',)], 'unordered',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1343
                           True)], logged_vf.calls)
3350.3.5 by Robert Collins
Create adapters from plain compressed knit content.
1344
3350.3.6 by Robert Collins
Test EOL behaviour of plain knit record adapters.
1345
    def test_unannotated_to_fulltext_no_eol(self):
1346
        """Test adapting unannotated knits to full texts.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1347
3350.3.6 by Robert Collins
Test EOL behaviour of plain knit record adapters.
1348
        This is used for -> weaves, and for -> annotated knits.
1349
        """
1350
        # we need a full text, and a delta
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1351
        f = self.get_knit(annotated=False)
1352
        get_diamond_files(f, 1, trailing_eol=False)
3350.3.6 by Robert Collins
Test EOL behaviour of plain knit record adapters.
1353
        # Reconstructing a full text requires a backing versioned file, and it
1354
        # must have the base lines requested from it.
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1355
        logged_vf = versionedfile.RecordingVersionedFilesDecorator(f)
7459.3.6 by Jelmer Vernooij
Fix tests.
1356
        ft_data, delta_data = self.helpGetBytes(
7459.3.7 by Jelmer Vernooij
Fix syntax.
1357
            f, 'fulltext', _mod_knit.FTPlainToFullText(None),
1358
            'fulltext', _mod_knit.DeltaPlainToFullText(logged_vf))
6963.2.4 by Jelmer Vernooij
Add bees.
1359
        self.assertEqual(b'origin', ft_data)
1360
        self.assertEqual(b'base\nleft\nright\nmerged', delta_data)
1361
        self.assertEqual([('get_record_stream', [(b'left',)], 'unordered',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1362
                           True)], logged_vf.calls)
3350.3.6 by Robert Collins
Test EOL behaviour of plain knit record adapters.
1363
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
1364
1365
class TestKeyMapper(TestCaseWithMemoryTransport):
1366
    """Tests for various key mapping logic."""
1367
1368
    def test_identity_mapper(self):
1369
        mapper = versionedfile.ConstantMapper("inventory")
6963.2.4 by Jelmer Vernooij
Add bees.
1370
        self.assertEqual("inventory", mapper.map((b'foo@ar',)))
1371
        self.assertEqual("inventory", mapper.map((b'quux',)))
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
1372
1373
    def test_prefix_mapper(self):
1374
        #format5: plain
1375
        mapper = versionedfile.PrefixMapper()
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
1376
        self.assertEqual("file-id", mapper.map((b"file-id", b"revision-id")))
1377
        self.assertEqual("new-id", mapper.map((b"new-id", b"revision-id")))
1378
        self.assertEqual((b'file-id',), mapper.unmap("file-id"))
1379
        self.assertEqual((b'new-id',), mapper.unmap("new-id"))
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
1380
1381
    def test_hash_prefix_mapper(self):
1382
        #format6: hash + plain
1383
        mapper = versionedfile.HashPrefixMapper()
7143.15.2 by Jelmer Vernooij
Run autopep8.
1384
        self.assertEqual(
1385
            "9b/file-id", mapper.map((b"file-id", b"revision-id")))
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
1386
        self.assertEqual("45/new-id", mapper.map((b"new-id", b"revision-id")))
6963.2.12 by Jelmer Vernooij
Fix some more tests.
1387
        self.assertEqual((b'file-id',), mapper.unmap("9b/file-id"))
1388
        self.assertEqual((b'new-id',), mapper.unmap("45/new-id"))
3350.6.1 by Robert Collins
* New ``versionedfile.KeyMapper`` interface to abstract out the access to
1389
1390
    def test_hash_escaped_mapper(self):
1391
        #knit1: hash + escaped
1392
        mapper = versionedfile.HashEscapedPrefixMapper()
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
1393
        self.assertEqual("88/%2520", mapper.map((b" ", b"revision-id")))
1394
        self.assertEqual("ed/fil%2545-%2549d", mapper.map((b"filE-Id",
7143.15.2 by Jelmer Vernooij
Run autopep8.
1395
                                                           b"revision-id")))
6963.2.13 by Jelmer Vernooij
Fix more tests.
1396
        self.assertEqual("88/ne%2557-%2549d", mapper.map((b"neW-Id",
7143.15.2 by Jelmer Vernooij
Run autopep8.
1397
                                                          b"revision-id")))
6963.2.12 by Jelmer Vernooij
Fix some more tests.
1398
        self.assertEqual((b'filE-Id',), mapper.unmap("ed/fil%2545-%2549d"))
1399
        self.assertEqual((b'neW-Id',), mapper.unmap("88/ne%2557-%2549d"))
3350.6.2 by Robert Collins
Prepare parameterised test environment.
1400
1401
1402
class TestVersionedFiles(TestCaseWithMemoryTransport):
1403
    """Tests for the multiple-file variant of VersionedFile."""
1404
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1405
    # We want to be sure of behaviour for:
1406
    # weaves prefix layout (weave texts)
1407
    # individually named weaves (weave inventories)
1408
    # annotated knits - prefix|hash|hash-escape layout, we test the third only
1409
    #                   as it is the most complex mapper.
1410
    # individually named knits
1411
    # individual no-graph knits in packs (signatures)
1412
    # individual graph knits in packs (inventories)
1413
    # individual graph nocompression knits in packs (revisions)
1414
    # plain text knits in packs (texts)
1415
    len_one_scenarios = [
1416
        ('weave-named', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1417
            'cleanup': None,
1418
            'factory': make_versioned_files_factory(WeaveFile,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1419
                                                    ConstantMapper('inventory')),
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1420
            'graph': True,
1421
            'key_length': 1,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1422
            'support_partial_insertion': False,
1423
            }),
1424
        ('named-knit', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1425
            'cleanup': None,
1426
            'factory': make_file_factory(False, ConstantMapper('revisions')),
1427
            'graph': True,
1428
            'key_length': 1,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1429
            'support_partial_insertion': False,
1430
            }),
1431
        ('named-nograph-nodelta-knit-pack', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1432
            'cleanup': cleanup_pack_knit,
1433
            'factory': make_pack_factory(False, False, 1),
1434
            'graph': False,
1435
            'key_length': 1,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1436
            'support_partial_insertion': False,
1437
            }),
1438
        ('named-graph-knit-pack', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1439
            'cleanup': cleanup_pack_knit,
1440
            'factory': make_pack_factory(True, True, 1),
1441
            'graph': True,
1442
            'key_length': 1,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1443
            'support_partial_insertion': True,
1444
            }),
1445
        ('named-graph-nodelta-knit-pack', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1446
            'cleanup': cleanup_pack_knit,
1447
            'factory': make_pack_factory(True, False, 1),
1448
            'graph': True,
1449
            'key_length': 1,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1450
            'support_partial_insertion': False,
1451
            }),
1452
        ('groupcompress-nograph', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1453
            'cleanup': groupcompress.cleanup_pack_group,
1454
            'factory': groupcompress.make_pack_factory(False, False, 1),
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1455
            'graph': False,
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1456
            'key_length': 1,
1457
            'support_partial_insertion': False,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1458
            }),
1459
        ]
1460
    len_two_scenarios = [
1461
        ('weave-prefix', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1462
            'cleanup': None,
1463
            'factory': make_versioned_files_factory(WeaveFile,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1464
                                                    PrefixMapper()),
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1465
            'graph': True,
1466
            'key_length': 2,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1467
            'support_partial_insertion': False,
1468
            }),
1469
        ('annotated-knit-escape', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1470
            'cleanup': None,
1471
            'factory': make_file_factory(True, HashEscapedPrefixMapper()),
1472
            'graph': True,
1473
            'key_length': 2,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1474
            'support_partial_insertion': False,
1475
            }),
1476
        ('plain-knit-pack', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1477
            'cleanup': cleanup_pack_knit,
1478
            'factory': make_pack_factory(True, True, 2),
1479
            'graph': True,
1480
            'key_length': 2,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1481
            'support_partial_insertion': True,
1482
            }),
1483
        ('groupcompress', {
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1484
            'cleanup': groupcompress.cleanup_pack_group,
1485
            'factory': groupcompress.make_pack_factory(True, False, 1),
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1486
            'graph': True,
6809.1.1 by Martin
Apply 2to3 ws_comma fixer
1487
            'key_length': 1,
1488
            'support_partial_insertion': False,
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
1489
            }),
1490
        ]
1491
1492
    scenarios = len_one_scenarios + len_two_scenarios
1493
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1494
    def get_versionedfiles(self, relpath='files'):
1495
        transport = self.get_transport(relpath)
1496
        if relpath != '.':
1497
            transport.mkdir('.')
1498
        files = self.factory(transport)
1499
        if self.cleanup is not None:
4985.2.1 by Vincent Ladeuil
Deploy addAttrCleanup on the whole test suite.
1500
            self.addCleanup(self.cleanup, files)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1501
        return files
1502
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1503
    def get_simple_key(self, suffix):
1504
        """Return a key for the object under test."""
1505
        if self.key_length == 1:
1506
            return (suffix,)
1507
        else:
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1508
            return (b'FileA',) + (suffix,)
4398.8.8 by John Arbash Meinel
Respond to Andrew's review comments.
1509
5816.8.2 by Andrew Bennetts
Add test for without_fallbacks.
1510
    def test_add_fallback_implies_without_fallbacks(self):
1511
        f = self.get_versionedfiles('files')
1512
        if getattr(f, 'add_fallback_versioned_files', None) is None:
1513
            raise TestNotApplicable("%s doesn't support fallbacks"
1514
                                    % (f.__class__.__name__,))
1515
        g = self.get_versionedfiles('fallback')
6963.2.4 by Jelmer Vernooij
Add bees.
1516
        key_a = self.get_simple_key(b'a')
1517
        g.add_lines(key_a, [], [b'\n'])
5816.8.2 by Andrew Bennetts
Add test for without_fallbacks.
1518
        f.add_fallback_versioned_files(g)
1519
        self.assertTrue(key_a in f.get_parent_map([key_a]))
7143.15.2 by Jelmer Vernooij
Run autopep8.
1520
        self.assertFalse(
1521
            key_a in f.without_fallbacks().get_parent_map([key_a]))
5816.8.2 by Andrew Bennetts
Add test for without_fallbacks.
1522
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1523
    def test_add_lines(self):
1524
        f = self.get_versionedfiles()
6963.2.4 by Jelmer Vernooij
Add bees.
1525
        key0 = self.get_simple_key(b'r0')
1526
        key1 = self.get_simple_key(b'r1')
1527
        key2 = self.get_simple_key(b'r2')
1528
        keyf = self.get_simple_key(b'foo')
1529
        f.add_lines(key0, [], [b'a\n', b'b\n'])
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1530
        if self.graph:
6963.2.4 by Jelmer Vernooij
Add bees.
1531
            f.add_lines(key1, [key0], [b'b\n', b'c\n'])
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1532
        else:
6963.2.4 by Jelmer Vernooij
Add bees.
1533
            f.add_lines(key1, [], [b'b\n', b'c\n'])
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1534
        keys = f.keys()
1535
        self.assertTrue(key0 in keys)
1536
        self.assertTrue(key1 in keys)
1537
        records = []
1538
        for record in f.get_record_stream([key0, key1], 'unordered', True):
1539
            records.append((record.key, record.get_bytes_as('fulltext')))
1540
        records.sort()
6963.2.4 by Jelmer Vernooij
Add bees.
1541
        self.assertEqual([(key0, b'a\nb\n'), (key1, b'b\nc\n')], records)
4398.8.1 by John Arbash Meinel
Add a VersionedFile.add_text() api.
1542
7331.4.8 by Jelmer Vernooij
Add unit test.
1543
    def test_add_chunks(self):
1544
        f = self.get_versionedfiles()
1545
        key0 = self.get_simple_key(b'r0')
1546
        key1 = self.get_simple_key(b'r1')
1547
        key2 = self.get_simple_key(b'r2')
1548
        keyf = self.get_simple_key(b'foo')
1549
        f.add_chunks(key0, [], [b'a', b'\nb\n'])
1550
        if self.graph:
1551
            f.add_chunks(key1, [key0], [b'b', b'\n', b'c\n'])
1552
        else:
1553
            f.add_chunks(key1, [], [b'b\n', b'c\n'])
1554
        keys = f.keys()
7331.4.9 by Jelmer Vernooij
Use assertIn.
1555
        self.assertIn(key0, keys)
1556
        self.assertIn(key1, keys)
7331.4.8 by Jelmer Vernooij
Add unit test.
1557
        records = []
1558
        for record in f.get_record_stream([key0, key1], 'unordered', True):
1559
            records.append((record.key, record.get_bytes_as('fulltext')))
1560
        records.sort()
1561
        self.assertEqual([(key0, b'a\nb\n'), (key1, b'b\nc\n')], records)
1562
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1563
    def test_annotate(self):
1564
        files = self.get_versionedfiles()
1565
        self.get_diamond_files(files)
1566
        if self.key_length == 1:
1567
            prefix = ()
1568
        else:
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1569
            prefix = (b'FileA',)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1570
        # introduced full text
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1571
        origins = files.annotate(prefix + (b'origin',))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1572
        self.assertEqual([
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1573
            (prefix + (b'origin',), b'origin\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.
1574
            origins)
1575
        # a delta
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1576
        origins = files.annotate(prefix + (b'base',))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1577
        self.assertEqual([
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1578
            (prefix + (b'base',), b'base\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.
1579
            origins)
1580
        # a merge
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1581
        origins = files.annotate(prefix + (b'merged',))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1582
        if self.graph:
1583
            self.assertEqual([
6963.2.3 by Jelmer Vernooij
Fix some more tests.
1584
                (prefix + (b'base',), b'base\n'),
1585
                (prefix + (b'left',), b'left\n'),
1586
                (prefix + (b'right',), b'right\n'),
1587
                (prefix + (b'merged',), b'merged\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.
1588
                ],
1589
                origins)
1590
        else:
1591
            # Without a graph everything is new.
1592
            self.assertEqual([
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1593
                (prefix + (b'merged',), b'base\n'),
1594
                (prefix + (b'merged',), b'left\n'),
1595
                (prefix + (b'merged',), b'right\n'),
1596
                (prefix + (b'merged',), b'merged\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.
1597
                ],
1598
                origins)
1599
        self.assertRaises(RevisionNotPresent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1600
                          files.annotate, prefix + ('missing-key',))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1601
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1602
    def test_check_no_parameters(self):
1603
        files = self.get_versionedfiles()
1604
1605
    def test_check_progressbar_parameter(self):
1606
        """A progress bar can be supplied because check can be a generator."""
1607
        pb = ui.ui_factory.nested_progress_bar()
1608
        self.addCleanup(pb.finished)
1609
        files = self.get_versionedfiles()
1610
        files.check(progress_bar=pb)
1611
1612
    def test_check_with_keys_becomes_generator(self):
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
1613
        files = self.get_versionedfiles()
1614
        self.get_diamond_files(files)
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1615
        keys = files.keys()
1616
        entries = files.check(keys=keys)
1617
        seen = set()
1618
        # Texts output should be fulltexts.
1619
        self.capture_stream(files, entries, seen.add,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1620
                            files.get_parent_map(keys), require_fulltext=True)
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1621
        # All texts should be output.
1622
        self.assertEqual(set(keys), seen)
4454.3.65 by John Arbash Meinel
Tests that VF implementations support .get_annotator()
1623
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
1624
    def test_clear_cache(self):
1625
        files = self.get_versionedfiles()
1626
        files.clear_cache()
1627
3350.6.2 by Robert Collins
Prepare parameterised test environment.
1628
    def test_construct(self):
1629
        """Each parameterised test can be constructed on a transport."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1630
        files = self.get_versionedfiles()
1631
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1632
    def get_diamond_files(self, files, trailing_eol=True, left_only=False,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1633
                          nokeys=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.
1634
        return get_diamond_files(files, self.key_length,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1635
                                 trailing_eol=trailing_eol, nograph=not self.graph,
1636
                                 left_only=left_only, nokeys=nokeys)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1637
4398.8.4 by John Arbash Meinel
Implement add_text for GroupCompressVersionedFiles
1638
    def _add_content_nostoresha(self, add_lines):
4119.1.1 by John Arbash Meinel
Move the 'add_lines_nostoresha' to being tested against all VF implementations.
1639
        """When nostore_sha is supplied using old content raises."""
1640
        vf = self.get_versionedfiles()
6963.2.4 by Jelmer Vernooij
Add bees.
1641
        empty_text = (b'a', [])
1642
        sample_text_nl = (b'b', [b"foo\n", b"bar\n"])
1643
        sample_text_no_nl = (b'c', [b"foo\n", b"bar"])
4119.1.1 by John Arbash Meinel
Move the 'add_lines_nostoresha' to being tested against all VF implementations.
1644
        shas = []
1645
        for version, lines in (empty_text, sample_text_nl, sample_text_no_nl):
4398.8.4 by John Arbash Meinel
Implement add_text for GroupCompressVersionedFiles
1646
            if add_lines:
1647
                sha, _, _ = vf.add_lines(self.get_simple_key(version), [],
1648
                                         lines)
1649
            else:
6839 by Jelmer Vernooij
Merge lp:~jelmer/brz/get-full.
1650
                sha, _, _ = vf.add_lines(self.get_simple_key(version), [],
1651
                                         lines)
4119.1.1 by John Arbash Meinel
Move the 'add_lines_nostoresha' to being tested against all VF implementations.
1652
            shas.append(sha)
1653
        # we now have a copy of all the lines in the vf.
1654
        for sha, (version, lines) in zip(
7143.15.2 by Jelmer Vernooij
Run autopep8.
1655
                shas, (empty_text, sample_text_nl, sample_text_no_nl)):
6963.2.4 by Jelmer Vernooij
Add bees.
1656
            new_key = self.get_simple_key(version + b"2")
4119.1.1 by John Arbash Meinel
Move the 'add_lines_nostoresha' to being tested against all VF implementations.
1657
            self.assertRaises(errors.ExistingContent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1658
                              vf.add_lines, new_key, [], lines,
1659
                              nostore_sha=sha)
4398.8.4 by John Arbash Meinel
Implement add_text for GroupCompressVersionedFiles
1660
            self.assertRaises(errors.ExistingContent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1661
                              vf.add_lines, new_key, [], lines,
1662
                              nostore_sha=sha)
4119.1.1 by John Arbash Meinel
Move the 'add_lines_nostoresha' to being tested against all VF implementations.
1663
            # and no new version should have been added.
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
1664
            record = next(vf.get_record_stream([new_key], 'unordered', True))
4119.1.1 by John Arbash Meinel
Move the 'add_lines_nostoresha' to being tested against all VF implementations.
1665
            self.assertEqual('absent', record.storage_kind)
1666
4398.8.4 by John Arbash Meinel
Implement add_text for GroupCompressVersionedFiles
1667
    def test_add_lines_nostoresha(self):
1668
        self._add_content_nostoresha(add_lines=True)
1669
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1670
    def test_add_lines_return(self):
1671
        files = self.get_versionedfiles()
1672
        # save code by using the stock data insertion helper.
1673
        adds = self.get_diamond_files(files)
1674
        results = []
1675
        # We can only validate the first 2 elements returned from add_lines.
1676
        for add in adds:
1677
            self.assertEqual(3, len(add))
1678
            results.append(add[:2])
1679
        if self.key_length == 1:
1680
            self.assertEqual([
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1681
                (b'00e364d235126be43292ab09cb4686cf703ddc17', 7),
1682
                (b'51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1683
                (b'a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1684
                (b'9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1685
                (b'ed8bce375198ea62444dc71952b22cfc2b09226d', 23)],
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1686
                results)
1687
        elif self.key_length == 2:
1688
            self.assertEqual([
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1689
                (b'00e364d235126be43292ab09cb4686cf703ddc17', 7),
1690
                (b'00e364d235126be43292ab09cb4686cf703ddc17', 7),
1691
                (b'51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1692
                (b'51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1693
                (b'a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1694
                (b'a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1695
                (b'9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1696
                (b'9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1697
                (b'ed8bce375198ea62444dc71952b22cfc2b09226d', 23),
1698
                (b'ed8bce375198ea62444dc71952b22cfc2b09226d', 23)],
3350.6.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
                results)
1700
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1701
    def test_add_lines_no_key_generates_chk_key(self):
1702
        files = self.get_versionedfiles()
1703
        # save code by using the stock data insertion helper.
1704
        adds = self.get_diamond_files(files, nokeys=True)
1705
        results = []
1706
        # We can only validate the first 2 elements returned from add_lines.
1707
        for add in adds:
1708
            self.assertEqual(3, len(add))
1709
            results.append(add[:2])
1710
        if self.key_length == 1:
1711
            self.assertEqual([
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1712
                (b'00e364d235126be43292ab09cb4686cf703ddc17', 7),
1713
                (b'51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1714
                (b'a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1715
                (b'9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1716
                (b'ed8bce375198ea62444dc71952b22cfc2b09226d', 23)],
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1717
                results)
1718
            # Check the added items got CHK keys.
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1719
            self.assertEqual({
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1720
                (b'sha1:00e364d235126be43292ab09cb4686cf703ddc17',),
1721
                (b'sha1:51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44',),
1722
                (b'sha1:9ef09dfa9d86780bdec9219a22560c6ece8e0ef1',),
1723
                (b'sha1:a8478686da38e370e32e42e8a0c220e33ee9132f',),
1724
                (b'sha1:ed8bce375198ea62444dc71952b22cfc2b09226d',),
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1725
                },
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1726
                files.keys())
1727
        elif self.key_length == 2:
1728
            self.assertEqual([
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1729
                (b'00e364d235126be43292ab09cb4686cf703ddc17', 7),
1730
                (b'00e364d235126be43292ab09cb4686cf703ddc17', 7),
1731
                (b'51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1732
                (b'51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44', 5),
1733
                (b'a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1734
                (b'a8478686da38e370e32e42e8a0c220e33ee9132f', 10),
1735
                (b'9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1736
                (b'9ef09dfa9d86780bdec9219a22560c6ece8e0ef1', 11),
1737
                (b'ed8bce375198ea62444dc71952b22cfc2b09226d', 23),
1738
                (b'ed8bce375198ea62444dc71952b22cfc2b09226d', 23)],
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1739
                results)
1740
            # Check the added items got CHK keys.
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1741
            self.assertEqual({
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1742
                (b'FileA', b'sha1:00e364d235126be43292ab09cb4686cf703ddc17'),
1743
                (b'FileA', b'sha1:51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44'),
1744
                (b'FileA', b'sha1:9ef09dfa9d86780bdec9219a22560c6ece8e0ef1'),
1745
                (b'FileA', b'sha1:a8478686da38e370e32e42e8a0c220e33ee9132f'),
1746
                (b'FileA', b'sha1:ed8bce375198ea62444dc71952b22cfc2b09226d'),
1747
                (b'FileB', b'sha1:00e364d235126be43292ab09cb4686cf703ddc17'),
1748
                (b'FileB', b'sha1:51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44'),
1749
                (b'FileB', b'sha1:9ef09dfa9d86780bdec9219a22560c6ece8e0ef1'),
1750
                (b'FileB', b'sha1:a8478686da38e370e32e42e8a0c220e33ee9132f'),
1751
                (b'FileB', b'sha1:ed8bce375198ea62444dc71952b22cfc2b09226d'),
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
1752
                },
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1753
                files.keys())
1754
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1755
    def test_empty_lines(self):
1756
        """Empty files can be stored."""
1757
        f = self.get_versionedfiles()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1758
        key_a = self.get_simple_key(b'a')
3350.6.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
        f.add_lines(key_a, [], [])
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1760
        self.assertEqual(b'',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1761
                         next(f.get_record_stream([key_a], 'unordered', True
1762
                                                  )).get_bytes_as('fulltext'))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1763
        key_b = self.get_simple_key(b'b')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1764
        f.add_lines(key_b, self.get_parents([key_a]), [])
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1765
        self.assertEqual(b'',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1766
                         next(f.get_record_stream([key_b], 'unordered', True
1767
                                                  )).get_bytes_as('fulltext'))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1768
1769
    def test_newline_only(self):
1770
        f = self.get_versionedfiles()
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1771
        key_a = self.get_simple_key(b'a')
1772
        f.add_lines(key_a, [], [b'\n'])
1773
        self.assertEqual(b'\n',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1774
                         next(f.get_record_stream([key_a], 'unordered', True
1775
                                                  )).get_bytes_as('fulltext'))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1776
        key_b = self.get_simple_key(b'b')
1777
        f.add_lines(key_b, self.get_parents([key_a]), [b'\n'])
1778
        self.assertEqual(b'\n',
7143.15.2 by Jelmer Vernooij
Run autopep8.
1779
                         next(f.get_record_stream([key_b], 'unordered', True
1780
                                                  )).get_bytes_as('fulltext'))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1781
4593.5.35 by John Arbash Meinel
Start working on a per-vf implementation test of find_ancestry.
1782
    def test_get_known_graph_ancestry(self):
1783
        f = self.get_versionedfiles()
4593.5.36 by John Arbash Meinel
a few more implementations of the interface.
1784
        if not self.graph:
1785
            raise TestNotApplicable('ancestry info only relevant with graph.')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1786
        key_a = self.get_simple_key(b'a')
1787
        key_b = self.get_simple_key(b'b')
1788
        key_c = self.get_simple_key(b'c')
4593.5.35 by John Arbash Meinel
Start working on a per-vf implementation test of find_ancestry.
1789
        # A
1790
        # |\
1791
        # | B
1792
        # |/
1793
        # C
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1794
        f.add_lines(key_a, [], [b'\n'])
1795
        f.add_lines(key_b, [key_a], [b'\n'])
1796
        f.add_lines(key_c, [key_a, key_b], [b'\n'])
4593.5.35 by John Arbash Meinel
Start working on a per-vf implementation test of find_ancestry.
1797
        kg = f.get_known_graph_ancestry([key_c])
1798
        self.assertIsInstance(kg, _mod_graph.KnownGraph)
1799
        self.assertEqual([key_a, key_b, key_c], list(kg.topo_sort()))
1800
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1801
    def test_known_graph_with_fallbacks(self):
1802
        f = self.get_versionedfiles('files')
1803
        if not self.graph:
1804
            raise TestNotApplicable('ancestry info only relevant with graph.')
1805
        if getattr(f, 'add_fallback_versioned_files', None) is None:
1806
            raise TestNotApplicable("%s doesn't support fallbacks"
1807
                                    % (f.__class__.__name__,))
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1808
        key_a = self.get_simple_key(b'a')
1809
        key_b = self.get_simple_key(b'b')
1810
        key_c = self.get_simple_key(b'c')
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1811
        # A     only in fallback
1812
        # |\
1813
        # | B
1814
        # |/
1815
        # C
1816
        g = self.get_versionedfiles('fallback')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1817
        g.add_lines(key_a, [], [b'\n'])
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1818
        f.add_fallback_versioned_files(g)
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1819
        f.add_lines(key_b, [key_a], [b'\n'])
1820
        f.add_lines(key_c, [key_a, key_b], [b'\n'])
4634.11.2 by John Arbash Meinel
Teach VF.get_known_graph_ancestry to go to fallbacks (bug #419241)
1821
        kg = f.get_known_graph_ancestry([key_c])
1822
        self.assertEqual([key_a, key_b, key_c], list(kg.topo_sort()))
1823
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1824
    def test_get_record_stream_empty(self):
1825
        """An empty stream can be requested without error."""
1826
        f = self.get_versionedfiles()
1827
        entries = f.get_record_stream([], 'unordered', False)
1828
        self.assertEqual([], list(entries))
1829
1830
    def assertValidStorageKind(self, storage_kind):
1831
        """Assert that storage_kind is a valid storage_kind."""
1832
        self.assertSubset([storage_kind],
7143.15.2 by Jelmer Vernooij
Run autopep8.
1833
                          ['mpdiff', 'knit-annotated-ft', 'knit-annotated-delta',
1834
                           'knit-ft', 'knit-delta', 'chunked', 'fulltext',
1835
                           'knit-annotated-ft-gz', 'knit-annotated-delta-gz', 'knit-ft-gz',
1836
                           'knit-delta-gz',
1837
                           'knit-delta-closure', 'knit-delta-closure-ref',
1838
                           'groupcompress-block', 'groupcompress-block-ref'])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1839
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1840
    def capture_stream(self, f, entries, on_seen, parents,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1841
                       require_fulltext=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.
1842
        """Capture a stream for testing."""
1843
        for factory in entries:
1844
            on_seen(factory.key)
1845
            self.assertValidStorageKind(factory.storage_kind)
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1846
            if factory.sha1 is not None:
1847
                self.assertEqual(f.get_sha1s([factory.key])[factory.key],
7143.15.2 by Jelmer Vernooij
Run autopep8.
1848
                                 factory.sha1)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1849
            self.assertEqual(parents[factory.key], factory.parents)
1850
            self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
7143.15.2 by Jelmer Vernooij
Run autopep8.
1851
                                  bytes)
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
1852
            if require_fulltext:
1853
                factory.get_bytes_as('fulltext')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1854
1855
    def test_get_record_stream_interface(self):
1856
        """each item in a stream has to provide a regular interface."""
1857
        files = self.get_versionedfiles()
1858
        self.get_diamond_files(files)
1859
        keys, _ = self.get_keys_and_sort_order()
1860
        parent_map = files.get_parent_map(keys)
1861
        entries = files.get_record_stream(keys, 'unordered', False)
1862
        seen = set()
1863
        self.capture_stream(files, entries, seen.add, parent_map)
1864
        self.assertEqual(set(keys), seen)
1865
1866
    def get_keys_and_sort_order(self):
1867
        """Get diamond test keys list, and their sort ordering."""
1868
        if self.key_length == 1:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1869
            keys = [(b'merged',), (b'left',), (b'right',), (b'base',)]
7143.15.2 by Jelmer Vernooij
Run autopep8.
1870
            sort_order = {(b'merged',): 2, (b'left',): 1,
1871
                          (b'right',): 1, (b'base',): 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.
1872
        else:
1873
            keys = [
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1874
                (b'FileA', b'merged'), (b'FileA', b'left'), (b'FileA', b'right'),
1875
                (b'FileA', b'base'),
1876
                (b'FileB', b'merged'), (b'FileB', b'left'), (b'FileB', b'right'),
1877
                (b'FileB', b'base'),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1878
                ]
1879
            sort_order = {
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
1880
                (b'FileA', b'merged'): 2, (b'FileA', b'left'): 1, (b'FileA', b'right'): 1,
1881
                (b'FileA', b'base'): 0,
1882
                (b'FileB', b'merged'): 2, (b'FileB', b'left'): 1, (b'FileB', b'right'): 1,
1883
                (b'FileB', b'base'): 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.
1884
                }
1885
        return keys, sort_order
1886
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1887
    def get_keys_and_groupcompress_sort_order(self):
1888
        """Get diamond test keys list, and their groupcompress sort ordering."""
1889
        if self.key_length == 1:
6963.2.4 by Jelmer Vernooij
Add bees.
1890
            keys = [(b'merged',), (b'left',), (b'right',), (b'base',)]
7143.15.2 by Jelmer Vernooij
Run autopep8.
1891
            sort_order = {(b'merged',): 0, (b'left',): 1,
1892
                          (b'right',): 1, (b'base',): 2}
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1893
        else:
1894
            keys = [
6963.2.4 by Jelmer Vernooij
Add bees.
1895
                (b'FileA', b'merged'), (b'FileA', b'left'), (b'FileA', b'right'),
1896
                (b'FileA', b'base'),
1897
                (b'FileB', b'merged'), (b'FileB', b'left'), (b'FileB', b'right'),
1898
                (b'FileB', b'base'),
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1899
                ]
1900
            sort_order = {
6963.2.4 by Jelmer Vernooij
Add bees.
1901
                (b'FileA', b'merged'): 0, (b'FileA', b'left'): 1, (b'FileA', b'right'): 1,
1902
                (b'FileA', b'base'): 2,
1903
                (b'FileB', b'merged'): 3, (b'FileB', b'left'): 4, (b'FileB', b'right'): 4,
1904
                (b'FileB', b'base'): 5,
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1905
                }
1906
        return keys, sort_order
1907
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1908
    def test_get_record_stream_interface_ordered(self):
1909
        """each item in a stream has to provide a regular interface."""
1910
        files = self.get_versionedfiles()
1911
        self.get_diamond_files(files)
1912
        keys, sort_order = self.get_keys_and_sort_order()
1913
        parent_map = files.get_parent_map(keys)
1914
        entries = files.get_record_stream(keys, 'topological', False)
1915
        seen = []
1916
        self.capture_stream(files, entries, seen.append, parent_map)
1917
        self.assertStreamOrder(sort_order, seen, keys)
1918
1919
    def test_get_record_stream_interface_ordered_with_delta_closure(self):
1920
        """each item must be accessible as a fulltext."""
1921
        files = self.get_versionedfiles()
1922
        self.get_diamond_files(files)
1923
        keys, sort_order = self.get_keys_and_sort_order()
1924
        parent_map = files.get_parent_map(keys)
1925
        entries = files.get_record_stream(keys, 'topological', True)
1926
        seen = []
1927
        for factory in entries:
1928
            seen.append(factory.key)
1929
            self.assertValidStorageKind(factory.storage_kind)
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
1930
            self.assertSubset([factory.sha1],
7143.15.2 by Jelmer Vernooij
Run autopep8.
1931
                              [None, files.get_sha1s([factory.key])[factory.key]])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1932
            self.assertEqual(parent_map[factory.key], factory.parents)
1933
            # self.assertEqual(files.get_text(factory.key),
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1934
            ft_bytes = factory.get_bytes_as('fulltext')
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
1935
            self.assertIsInstance(ft_bytes, bytes)
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1936
            chunked_bytes = factory.get_bytes_as('chunked')
6963.2.4 by Jelmer Vernooij
Add bees.
1937
            self.assertEqualDiff(ft_bytes, b''.join(chunked_bytes))
3890.2.1 by John Arbash Meinel
Start working on a ChunkedContentFactory.
1938
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1939
        self.assertStreamOrder(sort_order, seen, keys)
1940
4111.1.1 by Robert Collins
Add a groupcompress sort order.
1941
    def test_get_record_stream_interface_groupcompress(self):
1942
        """each item in a stream has to provide a regular interface."""
1943
        files = self.get_versionedfiles()
1944
        self.get_diamond_files(files)
1945
        keys, sort_order = self.get_keys_and_groupcompress_sort_order()
1946
        parent_map = files.get_parent_map(keys)
1947
        entries = files.get_record_stream(keys, 'groupcompress', False)
1948
        seen = []
1949
        self.capture_stream(files, entries, seen.append, parent_map)
1950
        self.assertStreamOrder(sort_order, seen, keys)
1951
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1952
    def assertStreamOrder(self, sort_order, seen, keys):
1953
        self.assertEqual(len(set(seen)), len(keys))
1954
        if self.key_length == 1:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1955
            lows = {(): 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.
1956
        else:
7143.15.2 by Jelmer Vernooij
Run autopep8.
1957
            lows = {(b'FileA',): 0, (b'FileB',): 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.
1958
        if not self.graph:
1959
            self.assertEqual(set(keys), set(seen))
1960
        else:
1961
            for key in seen:
1962
                sort_pos = sort_order[key]
1963
                self.assertTrue(sort_pos >= lows[key[:-1]],
7143.15.2 by Jelmer Vernooij
Run autopep8.
1964
                                "Out of order in sorted stream: %r, %r" % (key, seen))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1965
                lows[key[:-1]] = sort_pos
1966
1967
    def test_get_record_stream_unknown_storage_kind_raises(self):
1968
        """Asking for a storage kind that the stream cannot supply raises."""
1969
        files = self.get_versionedfiles()
1970
        self.get_diamond_files(files)
1971
        if self.key_length == 1:
6963.2.4 by Jelmer Vernooij
Add bees.
1972
            keys = [(b'merged',), (b'left',), (b'right',), (b'base',)]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1973
        else:
1974
            keys = [
6963.2.4 by Jelmer Vernooij
Add bees.
1975
                (b'FileA', b'merged'), (b'FileA', b'left'), (b'FileA', b'right'),
1976
                (b'FileA', b'base'),
1977
                (b'FileB', b'merged'), (b'FileB', b'left'), (b'FileB', b'right'),
1978
                (b'FileB', b'base'),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1979
                ]
1980
        parent_map = files.get_parent_map(keys)
1981
        entries = files.get_record_stream(keys, 'unordered', False)
1982
        # We track the contents because we should be able to try, fail a
1983
        # particular kind and then ask for one that works and continue.
1984
        seen = set()
1985
        for factory in entries:
1986
            seen.add(factory.key)
1987
            self.assertValidStorageKind(factory.storage_kind)
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
1988
            if factory.sha1 is not None:
1989
                self.assertEqual(files.get_sha1s([factory.key])[factory.key],
1990
                                 factory.sha1)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1991
            self.assertEqual(parent_map[factory.key], factory.parents)
1992
            # currently no stream emits mpdiff
1993
            self.assertRaises(errors.UnavailableRepresentation,
7143.15.2 by Jelmer Vernooij
Run autopep8.
1994
                              factory.get_bytes_as, 'mpdiff')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1995
            self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
7143.15.2 by Jelmer Vernooij
Run autopep8.
1996
                                  bytes)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
1997
        self.assertEqual(set(keys), seen)
1998
1999
    def test_get_record_stream_missing_records_are_absent(self):
2000
        files = self.get_versionedfiles()
2001
        self.get_diamond_files(files)
2002
        if self.key_length == 1:
7143.15.2 by Jelmer Vernooij
Run autopep8.
2003
            keys = [(b'merged',), (b'left',), (b'right',),
2004
                    (b'absent',), (b'base',)]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2005
        else:
2006
            keys = [
6963.2.4 by Jelmer Vernooij
Add bees.
2007
                (b'FileA', b'merged'), (b'FileA', b'left'), (b'FileA', b'right'),
2008
                (b'FileA', b'absent'), (b'FileA', b'base'),
2009
                (b'FileB', b'merged'), (b'FileB', b'left'), (b'FileB', b'right'),
2010
                (b'FileB', b'absent'), (b'FileB', b'base'),
2011
                (b'absent', b'absent'),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2012
                ]
2013
        parent_map = files.get_parent_map(keys)
2014
        entries = files.get_record_stream(keys, 'unordered', False)
2015
        self.assertAbsentRecord(files, keys, parent_map, entries)
2016
        entries = files.get_record_stream(keys, 'topological', False)
2017
        self.assertAbsentRecord(files, keys, parent_map, entries)
2018
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2019
    def assertRecordHasContent(self, record, bytes):
2020
        """Assert that record has the bytes bytes."""
2021
        self.assertEqual(bytes, record.get_bytes_as('fulltext'))
6963.2.4 by Jelmer Vernooij
Add bees.
2022
        self.assertEqual(bytes, b''.join(record.get_bytes_as('chunked')))
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2023
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
2024
    def test_get_record_stream_native_formats_are_wire_ready_one_ft(self):
2025
        files = self.get_versionedfiles()
6963.2.3 by Jelmer Vernooij
Fix some more tests.
2026
        key = self.get_simple_key(b'foo')
2027
        files.add_lines(key, (), [b'my text\n', b'content'])
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
2028
        stream = files.get_record_stream([key], 'unordered', False)
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
2029
        record = next(stream)
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
2030
        if record.storage_kind in ('chunked', 'fulltext'):
2031
            # chunked and fulltext representations are for direct use not wire
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2032
            # serialisation: check they are able to be used directly. To send
2033
            # such records over the wire translation will be needed.
6963.2.3 by Jelmer Vernooij
Fix some more tests.
2034
            self.assertRecordHasContent(record, b"my text\ncontent")
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
2035
        else:
2036
            bytes = [record.get_bytes_as(record.storage_kind)]
2037
            network_stream = versionedfile.NetworkRecordStream(bytes).read()
2038
            source_record = record
2039
            records = []
2040
            for record in network_stream:
2041
                records.append(record)
2042
                self.assertEqual(source_record.storage_kind,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2043
                                 record.storage_kind)
4005.3.2 by Robert Collins
First passing NetworkRecordStream test - a fulltext from any record type which isn't a chunked or fulltext can be serialised and deserialised successfully.
2044
                self.assertEqual(source_record.parents, record.parents)
2045
                self.assertEqual(
2046
                    source_record.get_bytes_as(source_record.storage_kind),
2047
                    record.get_bytes_as(record.storage_kind))
2048
            self.assertEqual(1, len(records))
2049
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2050
    def assertStreamMetaEqual(self, records, expected, stream):
2051
        """Assert that streams expected and stream have the same records.
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
2052
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2053
        :param records: A list to collect the seen records.
2054
        :return: A generator of the records in stream.
2055
        """
6631.2.3 by Martin
Fix per_versionedfile test failures and rethink future_builtins
2056
        # We make assertions during copying to catch things early for easier
2057
        # debugging. This must use the iterating zip() from the future.
6631.2.2 by Martin
Run 2to3 itertools fixer and refactor
2058
        for record, ref_record in zip(stream, expected):
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2059
            records.append(record)
2060
            self.assertEqual(ref_record.key, record.key)
2061
            self.assertEqual(ref_record.storage_kind, record.storage_kind)
2062
            self.assertEqual(ref_record.parents, record.parents)
2063
            yield record
2064
2065
    def stream_to_bytes_or_skip_counter(self, skipped_records, full_texts,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2066
                                        stream):
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2067
        """Convert a stream to a bytes iterator.
2068
2069
        :param skipped_records: A list with one element to increment when a
2070
            record is skipped.
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
2071
        :param full_texts: A dict from key->fulltext representation, for
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2072
            checking chunked or fulltext stored records.
2073
        :param stream: A record_stream.
2074
        :return: An iterator over the bytes of each record.
2075
        """
2076
        for record in stream:
2077
            if record.storage_kind in ('chunked', 'fulltext'):
2078
                skipped_records[0] += 1
2079
                # check the content is correct for direct use.
2080
                self.assertRecordHasContent(record, full_texts[record.key])
2081
            else:
2082
                yield record.get_bytes_as(record.storage_kind)
2083
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2084
    def test_get_record_stream_native_formats_are_wire_ready_ft_delta(self):
2085
        files = self.get_versionedfiles()
2086
        target_files = self.get_versionedfiles('target')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2087
        key = self.get_simple_key(b'ft')
2088
        key_delta = self.get_simple_key(b'delta')
2089
        files.add_lines(key, (), [b'my text\n', b'content'])
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2090
        if self.graph:
2091
            delta_parents = (key,)
2092
        else:
2093
            delta_parents = ()
7143.15.2 by Jelmer Vernooij
Run autopep8.
2094
        files.add_lines(key_delta, delta_parents, [
2095
                        b'different\n', b'content\n'])
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2096
        local = files.get_record_stream([key, key_delta], 'unordered', False)
2097
        ref = files.get_record_stream([key, key_delta], 'unordered', False)
2098
        skipped_records = [0]
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2099
        full_texts = {
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2100
            key: b"my text\ncontent",
2101
            key_delta: b"different\ncontent\n",
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2102
            }
2103
        byte_stream = self.stream_to_bytes_or_skip_counter(
2104
            skipped_records, full_texts, local)
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2105
        network_stream = versionedfile.NetworkRecordStream(byte_stream).read()
2106
        records = []
2107
        # insert the stream from the network into a versioned files object so we can
2108
        # check the content was carried across correctly without doing delta
2109
        # inspection.
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2110
        target_files.insert_record_stream(
2111
            self.assertStreamMetaEqual(records, ref, network_stream))
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2112
        # No duplicates on the wire thank you!
2113
        self.assertEqual(2, len(records) + skipped_records[0])
2114
        if len(records):
4005.3.4 by Robert Collins
Test copying just a delta over the wire.
2115
            # if any content was copied it all must have all been.
2116
            self.assertIdenticalVersionedFile(files, target_files)
2117
2118
    def test_get_record_stream_native_formats_are_wire_ready_delta(self):
2119
        # copy a delta over the wire
2120
        files = self.get_versionedfiles()
2121
        target_files = self.get_versionedfiles('target')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2122
        key = self.get_simple_key(b'ft')
2123
        key_delta = self.get_simple_key(b'delta')
2124
        files.add_lines(key, (), [b'my text\n', b'content'])
4005.3.4 by Robert Collins
Test copying just a delta over the wire.
2125
        if self.graph:
2126
            delta_parents = (key,)
2127
        else:
2128
            delta_parents = ()
7143.15.2 by Jelmer Vernooij
Run autopep8.
2129
        files.add_lines(key_delta, delta_parents, [
2130
                        b'different\n', b'content\n'])
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2131
        # Copy the basis text across so we can reconstruct the delta during
2132
        # insertion into target.
4005.3.4 by Robert Collins
Test copying just a delta over the wire.
2133
        target_files.insert_record_stream(files.get_record_stream([key],
7143.15.2 by Jelmer Vernooij
Run autopep8.
2134
                                                                  'unordered', False))
4005.3.4 by Robert Collins
Test copying just a delta over the wire.
2135
        local = files.get_record_stream([key_delta], 'unordered', False)
2136
        ref = files.get_record_stream([key_delta], 'unordered', False)
2137
        skipped_records = [0]
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2138
        full_texts = {
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2139
            key_delta: b"different\ncontent\n",
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2140
            }
2141
        byte_stream = self.stream_to_bytes_or_skip_counter(
2142
            skipped_records, full_texts, local)
4005.3.4 by Robert Collins
Test copying just a delta over the wire.
2143
        network_stream = versionedfile.NetworkRecordStream(byte_stream).read()
2144
        records = []
2145
        # insert the stream from the network into a versioned files object so we can
2146
        # check the content was carried across correctly without doing delta
2147
        # inspection during check_stream.
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2148
        target_files.insert_record_stream(
2149
            self.assertStreamMetaEqual(records, ref, network_stream))
4005.3.4 by Robert Collins
Test copying just a delta over the wire.
2150
        # No duplicates on the wire thank you!
2151
        self.assertEqual(1, len(records) + skipped_records[0])
2152
        if len(records):
2153
            # if any content was copied it all must have all been
4005.3.3 by Robert Collins
Test NetworkRecordStream with delta'd texts.
2154
            self.assertIdenticalVersionedFile(files, target_files)
2155
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2156
    def test_get_record_stream_wire_ready_delta_closure_included(self):
2157
        # copy a delta over the wire with the ability to get its full text.
2158
        files = self.get_versionedfiles()
6963.2.12 by Jelmer Vernooij
Fix some more tests.
2159
        key = self.get_simple_key(b'ft')
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2160
        key_delta = self.get_simple_key(b'delta')
2161
        files.add_lines(key, (), [b'my text\n', b'content'])
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2162
        if self.graph:
2163
            delta_parents = (key,)
2164
        else:
2165
            delta_parents = ()
7143.15.2 by Jelmer Vernooij
Run autopep8.
2166
        files.add_lines(key_delta, delta_parents, [
2167
                        b'different\n', b'content\n'])
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2168
        local = files.get_record_stream([key_delta], 'unordered', True)
2169
        ref = files.get_record_stream([key_delta], 'unordered', True)
2170
        skipped_records = [0]
2171
        full_texts = {
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2172
            key_delta: b"different\ncontent\n",
4005.3.5 by Robert Collins
Interface level test for using delta_closure=True over the network.
2173
            }
2174
        byte_stream = self.stream_to_bytes_or_skip_counter(
2175
            skipped_records, full_texts, local)
2176
        network_stream = versionedfile.NetworkRecordStream(byte_stream).read()
2177
        records = []
2178
        # insert the stream from the network into a versioned files object so we can
2179
        # check the content was carried across correctly without doing delta
2180
        # inspection during check_stream.
2181
        for record in self.assertStreamMetaEqual(records, ref, network_stream):
2182
            # we have to be able to get the full text out:
2183
            self.assertRecordHasContent(record, full_texts[record.key])
2184
        # No duplicates on the wire thank you!
2185
        self.assertEqual(1, len(records) + skipped_records[0])
2186
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2187
    def assertAbsentRecord(self, files, keys, parents, entries):
2188
        """Helper for test_get_record_stream_missing_records_are_absent."""
2189
        seen = set()
2190
        for factory in entries:
2191
            seen.add(factory.key)
6963.2.4 by Jelmer Vernooij
Add bees.
2192
            if factory.key[-1] == b'absent':
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
2193
                self.assertEqual('absent', factory.storage_kind)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2194
                self.assertEqual(None, factory.sha1)
2195
                self.assertEqual(None, factory.parents)
2196
            else:
2197
                self.assertValidStorageKind(factory.storage_kind)
4241.4.1 by Ian Clatworthy
add sha generation support to versionedfiles
2198
                if factory.sha1 is not None:
2199
                    sha1 = files.get_sha1s([factory.key])[factory.key]
2200
                    self.assertEqual(sha1, factory.sha1)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2201
                self.assertEqual(parents[factory.key], factory.parents)
2202
                self.assertIsInstance(factory.get_bytes_as(factory.storage_kind),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2203
                                      bytes)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2204
        self.assertEqual(set(keys), seen)
2205
2206
    def test_filter_absent_records(self):
2207
        """Requested missing records can be filter trivially."""
2208
        files = self.get_versionedfiles()
2209
        self.get_diamond_files(files)
2210
        keys, _ = self.get_keys_and_sort_order()
2211
        parent_map = files.get_parent_map(keys)
2212
        # Add an absent record in the middle of the present keys. (We don't ask
2213
        # for just absent keys to ensure that content before and after the
2214
        # absent keys is still delivered).
2215
        present_keys = list(keys)
2216
        if self.key_length == 1:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2217
            keys.insert(2, (b'extra',))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2218
        else:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2219
            keys.insert(2, (b'extra', b'extra'))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2220
        entries = files.get_record_stream(keys, 'unordered', False)
2221
        seen = set()
2222
        self.capture_stream(files, versionedfile.filter_absent(entries), seen.add,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2223
                            parent_map)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2224
        self.assertEqual(set(present_keys), seen)
2225
2226
    def get_mapper(self):
2227
        """Get a mapper suitable for the key length of the test interface."""
2228
        if self.key_length == 1:
2229
            return ConstantMapper('source')
2230
        else:
2231
            return HashEscapedPrefixMapper()
2232
2233
    def get_parents(self, parents):
2234
        """Get parents, taking self.graph into consideration."""
2235
        if self.graph:
2236
            return parents
2237
        else:
2238
            return None
2239
4332.3.32 by Robert Collins
Merge bzr.dev.
2240
    def test_get_annotator(self):
2241
        files = self.get_versionedfiles()
2242
        self.get_diamond_files(files)
6963.2.4 by Jelmer Vernooij
Add bees.
2243
        origin_key = self.get_simple_key(b'origin')
2244
        base_key = self.get_simple_key(b'base')
2245
        left_key = self.get_simple_key(b'left')
2246
        right_key = self.get_simple_key(b'right')
2247
        merged_key = self.get_simple_key(b'merged')
4332.3.32 by Robert Collins
Merge bzr.dev.
2248
        # annotator = files.get_annotator()
2249
        # introduced full text
2250
        origins, lines = files.get_annotator().annotate(origin_key)
2251
        self.assertEqual([(origin_key,)], origins)
6963.2.4 by Jelmer Vernooij
Add bees.
2252
        self.assertEqual([b'origin\n'], lines)
4332.3.32 by Robert Collins
Merge bzr.dev.
2253
        # a delta
2254
        origins, lines = files.get_annotator().annotate(base_key)
2255
        self.assertEqual([(base_key,)], origins)
2256
        # a merge
2257
        origins, lines = files.get_annotator().annotate(merged_key)
2258
        if self.graph:
2259
            self.assertEqual([
2260
                (base_key,),
2261
                (left_key,),
2262
                (right_key,),
2263
                (merged_key,),
2264
                ], origins)
2265
        else:
2266
            # Without a graph everything is new.
2267
            self.assertEqual([
2268
                (merged_key,),
2269
                (merged_key,),
2270
                (merged_key,),
2271
                (merged_key,),
2272
                ], origins)
2273
        self.assertRaises(RevisionNotPresent,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2274
                          files.get_annotator().annotate, self.get_simple_key(b'missing-key'))
4332.3.32 by Robert Collins
Merge bzr.dev.
2275
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2276
    def test_get_parent_map(self):
2277
        files = self.get_versionedfiles()
2278
        if self.key_length == 1:
2279
            parent_details = [
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2280
                ((b'r0',), self.get_parents(())),
2281
                ((b'r1',), self.get_parents(((b'r0',),))),
2282
                ((b'r2',), self.get_parents(())),
2283
                ((b'r3',), self.get_parents(())),
2284
                ((b'm',), self.get_parents(((b'r0',), (b'r1',), (b'r2',), (b'r3',)))),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2285
                ]
2286
        else:
2287
            parent_details = [
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2288
                ((b'FileA', b'r0'), self.get_parents(())),
2289
                ((b'FileA', b'r1'), self.get_parents(((b'FileA', b'r0'),))),
2290
                ((b'FileA', b'r2'), self.get_parents(())),
2291
                ((b'FileA', b'r3'), self.get_parents(())),
2292
                ((b'FileA', b'm'), self.get_parents(((b'FileA', b'r0'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2293
                                                     (b'FileA', b'r1'), (b'FileA', b'r2'), (b'FileA', b'r3')))),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2294
                ]
2295
        for key, parents in parent_details:
2296
            files.add_lines(key, parents, [])
2297
            # immediately after adding it should be queryable.
7143.15.2 by Jelmer Vernooij
Run autopep8.
2298
            self.assertEqual({key: parents}, files.get_parent_map([key]))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2299
        # We can ask for an empty set
2300
        self.assertEqual({}, files.get_parent_map([]))
2301
        # We can ask for many keys
2302
        all_parents = dict(parent_details)
2303
        self.assertEqual(all_parents, files.get_parent_map(all_parents.keys()))
2304
        # Absent keys are just not included in the result.
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
2305
        keys = list(all_parents.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.
2306
        if self.key_length == 1:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2307
            keys.insert(1, (b'missing',))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2308
        else:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2309
            keys.insert(1, (b'missing', b'missing'))
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2310
        # Absent keys are just ignored
2311
        self.assertEqual(all_parents, files.get_parent_map(keys))
2312
2313
    def test_get_sha1s(self):
2314
        files = self.get_versionedfiles()
2315
        self.get_diamond_files(files)
2316
        if self.key_length == 1:
7143.15.2 by Jelmer Vernooij
Run autopep8.
2317
            keys = [(b'base',), (b'origin',), (b'left',),
2318
                    (b'merged',), (b'right',)]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2319
        else:
2320
            # ask for shas from different prefixes.
2321
            keys = [
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2322
                (b'FileA', b'base'), (b'FileB', b'origin'), (b'FileA', b'left'),
2323
                (b'FileA', b'merged'), (b'FileB', b'right'),
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2324
                ]
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
2325
        self.assertEqual({
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2326
            keys[0]: b'51c64a6f4fc375daf0d24aafbabe4d91b6f4bb44',
2327
            keys[1]: b'00e364d235126be43292ab09cb4686cf703ddc17',
2328
            keys[2]: b'a8478686da38e370e32e42e8a0c220e33ee9132f',
2329
            keys[3]: b'ed8bce375198ea62444dc71952b22cfc2b09226d',
2330
            keys[4]: b'9ef09dfa9d86780bdec9219a22560c6ece8e0ef1',
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
2331
            },
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2332
            files.get_sha1s(keys))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2333
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2334
    def test_insert_record_stream_empty(self):
2335
        """Inserting an empty record stream should work."""
2336
        files = self.get_versionedfiles()
2337
        files.insert_record_stream([])
2338
2339
    def assertIdenticalVersionedFile(self, expected, actual):
2340
        """Assert that left and right have the same contents."""
2341
        self.assertEqual(set(actual.keys()), set(expected.keys()))
2342
        actual_parents = actual.get_parent_map(actual.keys())
2343
        if self.graph:
7143.15.2 by Jelmer Vernooij
Run autopep8.
2344
            self.assertEqual(
2345
                actual_parents, expected.get_parent_map(expected.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.
2346
        else:
2347
            for key, parents in actual_parents.items():
2348
                self.assertEqual(None, parents)
2349
        for key in actual.keys():
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2350
            actual_text = next(actual.get_record_stream(
2351
                [key], 'unordered', True)).get_bytes_as('fulltext')
2352
            expected_text = next(expected.get_record_stream(
2353
                [key], 'unordered', True)).get_bytes_as('fulltext')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2354
            self.assertEqual(actual_text, expected_text)
2355
2356
    def test_insert_record_stream_fulltexts(self):
2357
        """Any file should accept a stream of fulltexts."""
2358
        files = self.get_versionedfiles()
2359
        mapper = self.get_mapper()
2360
        source_transport = self.get_transport('source')
2361
        source_transport.mkdir('.')
2362
        # weaves always output fulltexts.
2363
        source = make_versioned_files_factory(WeaveFile, mapper)(
2364
            source_transport)
2365
        self.get_diamond_files(source, trailing_eol=False)
2366
        stream = source.get_record_stream(source.keys(), 'topological',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2367
                                          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.
2368
        files.insert_record_stream(stream)
2369
        self.assertIdenticalVersionedFile(source, files)
2370
2371
    def test_insert_record_stream_fulltexts_noeol(self):
2372
        """Any file should accept a stream of fulltexts."""
2373
        files = self.get_versionedfiles()
2374
        mapper = self.get_mapper()
2375
        source_transport = self.get_transport('source')
2376
        source_transport.mkdir('.')
2377
        # weaves always output fulltexts.
2378
        source = make_versioned_files_factory(WeaveFile, mapper)(
2379
            source_transport)
2380
        self.get_diamond_files(source, trailing_eol=False)
2381
        stream = source.get_record_stream(source.keys(), 'topological',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2382
                                          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.
2383
        files.insert_record_stream(stream)
2384
        self.assertIdenticalVersionedFile(source, files)
2385
2386
    def test_insert_record_stream_annotated_knits(self):
2387
        """Any file should accept a stream from plain knits."""
2388
        files = self.get_versionedfiles()
2389
        mapper = self.get_mapper()
2390
        source_transport = self.get_transport('source')
2391
        source_transport.mkdir('.')
2392
        source = make_file_factory(True, mapper)(source_transport)
2393
        self.get_diamond_files(source)
2394
        stream = source.get_record_stream(source.keys(), 'topological',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2395
                                          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.
2396
        files.insert_record_stream(stream)
2397
        self.assertIdenticalVersionedFile(source, files)
2398
2399
    def test_insert_record_stream_annotated_knits_noeol(self):
2400
        """Any file should accept a stream from plain knits."""
2401
        files = self.get_versionedfiles()
2402
        mapper = self.get_mapper()
2403
        source_transport = self.get_transport('source')
2404
        source_transport.mkdir('.')
2405
        source = make_file_factory(True, mapper)(source_transport)
2406
        self.get_diamond_files(source, trailing_eol=False)
2407
        stream = source.get_record_stream(source.keys(), 'topological',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2408
                                          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.
2409
        files.insert_record_stream(stream)
2410
        self.assertIdenticalVersionedFile(source, files)
2411
2412
    def test_insert_record_stream_plain_knits(self):
2413
        """Any file should accept a stream from plain knits."""
2414
        files = self.get_versionedfiles()
2415
        mapper = self.get_mapper()
2416
        source_transport = self.get_transport('source')
2417
        source_transport.mkdir('.')
2418
        source = make_file_factory(False, mapper)(source_transport)
2419
        self.get_diamond_files(source)
2420
        stream = source.get_record_stream(source.keys(), 'topological',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2421
                                          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.
2422
        files.insert_record_stream(stream)
2423
        self.assertIdenticalVersionedFile(source, files)
2424
2425
    def test_insert_record_stream_plain_knits_noeol(self):
2426
        """Any file should accept a stream from plain knits."""
2427
        files = self.get_versionedfiles()
2428
        mapper = self.get_mapper()
2429
        source_transport = self.get_transport('source')
2430
        source_transport.mkdir('.')
2431
        source = make_file_factory(False, mapper)(source_transport)
2432
        self.get_diamond_files(source, trailing_eol=False)
2433
        stream = source.get_record_stream(source.keys(), 'topological',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2434
                                          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.
2435
        files.insert_record_stream(stream)
2436
        self.assertIdenticalVersionedFile(source, files)
2437
2438
    def test_insert_record_stream_existing_keys(self):
2439
        """Inserting keys already in a file should not error."""
2440
        files = self.get_versionedfiles()
2441
        source = self.get_versionedfiles('source')
2442
        self.get_diamond_files(source)
2443
        # insert some keys into f.
2444
        self.get_diamond_files(files, left_only=True)
2445
        stream = source.get_record_stream(source.keys(), 'topological',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2446
                                          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.
2447
        files.insert_record_stream(stream)
2448
        self.assertIdenticalVersionedFile(source, files)
2449
2450
    def test_insert_record_stream_missing_keys(self):
2451
        """Inserting a stream with absent keys should raise an error."""
2452
        files = self.get_versionedfiles()
2453
        source = self.get_versionedfiles('source')
6963.2.11 by Jelmer Vernooij
Fix some more tests.
2454
        stream = source.get_record_stream([(b'missing',) * self.key_length],
7143.15.2 by Jelmer Vernooij
Run autopep8.
2455
                                          'topological', 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.
2456
        self.assertRaises(errors.RevisionNotPresent, files.insert_record_stream,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2457
                          stream)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2458
2459
    def test_insert_record_stream_out_of_order(self):
2460
        """An out of order stream can either error or work."""
2461
        files = self.get_versionedfiles()
2462
        source = self.get_versionedfiles('source')
2463
        self.get_diamond_files(source)
2464
        if self.key_length == 1:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2465
            origin_keys = [(b'origin',)]
2466
            end_keys = [(b'merged',), (b'left',)]
2467
            start_keys = [(b'right',), (b'base',)]
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2468
        else:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2469
            origin_keys = [(b'FileA', b'origin'), (b'FileB', b'origin')]
2470
            end_keys = [(b'FileA', b'merged',), (b'FileA', b'left',),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2471
                        (b'FileB', b'merged',), (b'FileB', b'left',)]
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2472
            start_keys = [(b'FileA', b'right',), (b'FileA', b'base',),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2473
                          (b'FileB', b'right',), (b'FileB', b'base',)]
2474
        origin_entries = source.get_record_stream(
2475
            origin_keys, 'unordered', 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.
2476
        end_entries = source.get_record_stream(end_keys, 'topological', False)
7143.15.2 by Jelmer Vernooij
Run autopep8.
2477
        start_entries = source.get_record_stream(
2478
            start_keys, 'topological', False)
6631.2.3 by Martin
Fix per_versionedfile test failures and rethink future_builtins
2479
        entries = itertools.chain(origin_entries, end_entries, start_entries)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2480
        try:
2481
            files.insert_record_stream(entries)
2482
        except RevisionNotPresent:
2483
            # Must not have corrupted the file.
2484
            files.check()
2485
        else:
2486
            self.assertIdenticalVersionedFile(source, files)
2487
4634.84.2 by Andrew Bennetts
Add test.
2488
    def test_insert_record_stream_long_parent_chain_out_of_order(self):
2489
        """An out of order stream can either error or work."""
2490
        if not self.graph:
2491
            raise TestNotApplicable('ancestry info only relevant with graph.')
2492
        # Create a reasonably long chain of records based on each other, where
2493
        # most will be deltas.
2494
        source = self.get_versionedfiles('source')
2495
        parents = ()
2496
        keys = []
6963.2.4 by Jelmer Vernooij
Add bees.
2497
        content = [(b'same same %d\n' % n) for n in range(500)]
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
2498
        letters = b'abcdefghijklmnopqrstuvwxyz'
2499
        for i in range(len(letters)):
7143.15.2 by Jelmer Vernooij
Run autopep8.
2500
            letter = letters[i:i + 1]
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
2501
            key = (b'key-' + letter,)
4634.84.2 by Andrew Bennetts
Add test.
2502
            if self.key_length == 2:
6963.2.4 by Jelmer Vernooij
Add bees.
2503
                key = (b'prefix',) + key
2504
            content.append(b'content for ' + letter + b'\n')
4634.84.2 by Andrew Bennetts
Add test.
2505
            source.add_lines(key, parents, content)
2506
            keys.append(key)
2507
            parents = (key,)
2508
        # Create a stream of these records, excluding the first record that the
2509
        # rest ultimately depend upon, and insert it into a new vf.
2510
        streams = []
2511
        for key in reversed(keys):
2512
            streams.append(source.get_record_stream([key], 'unordered', False))
6631.2.3 by Martin
Fix per_versionedfile test failures and rethink future_builtins
2513
        deltas = itertools.chain.from_iterable(streams[:-1])
4634.84.2 by Andrew Bennetts
Add test.
2514
        files = self.get_versionedfiles()
2515
        try:
2516
            files.insert_record_stream(deltas)
2517
        except RevisionNotPresent:
2518
            # Must not have corrupted the file.
2519
            files.check()
2520
        else:
2521
            # Must only report either just the first key as a missing parent,
2522
            # no key as missing (for nodelta scenarios).
2523
            missing = set(files.get_missing_compression_parent_keys())
2524
            missing.discard(keys[0])
2525
            self.assertEqual(set(), missing)
2526
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2527
    def get_knit_delta_source(self):
2528
        """Get a source that can produce a stream with knit delta records,
2529
        regardless of this test's scenario.
2530
        """
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2531
        mapper = self.get_mapper()
2532
        source_transport = self.get_transport('source')
2533
        source_transport.mkdir('.')
2534
        source = make_file_factory(False, mapper)(source_transport)
4009.3.1 by Andrew Bennetts
Fix test_insert_record_stream_delta_missing_basis_no_corruption to test what it claims to, and fix KnitVersionedFiles.get_record_stream to match the expected exception.
2535
        get_diamond_files(source, self.key_length, trailing_eol=True,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2536
                          nograph=False, left_only=False)
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2537
        return source
2538
2539
    def test_insert_record_stream_delta_missing_basis_no_corruption(self):
2540
        """Insertion where a needed basis is not included notifies the caller
2541
        of the missing basis.  In the meantime a record missing its basis is
2542
        not added.
2543
        """
2544
        source = self.get_knit_delta_source()
6963.2.4 by Jelmer Vernooij
Add bees.
2545
        keys = [self.get_simple_key(b'origin'), self.get_simple_key(b'merged')]
4009.3.7 by Andrew Bennetts
Most tests passing.
2546
        entries = source.get_record_stream(keys, 'unordered', 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.
2547
        files = self.get_versionedfiles()
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2548
        if self.support_partial_insertion:
4009.3.12 by Robert Collins
Polish on inserting record streams with missing compression parents.
2549
            self.assertEqual([],
7143.15.2 by Jelmer Vernooij
Run autopep8.
2550
                             list(files.get_missing_compression_parent_keys()))
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2551
            files.insert_record_stream(entries)
2552
            missing_bases = files.get_missing_compression_parent_keys()
6963.2.4 by Jelmer Vernooij
Add bees.
2553
            self.assertEqual({self.get_simple_key(b'left')},
7143.15.2 by Jelmer Vernooij
Run autopep8.
2554
                             set(missing_bases))
4009.3.7 by Andrew Bennetts
Most tests passing.
2555
            self.assertEqual(set(keys), set(files.get_parent_map(keys)))
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2556
        else:
2557
            self.assertRaises(
2558
                errors.RevisionNotPresent, files.insert_record_stream, entries)
4009.3.7 by Andrew Bennetts
Most tests passing.
2559
            files.check()
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2560
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2561
    def test_insert_record_stream_delta_missing_basis_can_be_added_later(self):
2562
        """Insertion where a needed basis is not included notifies the caller
2563
        of the missing basis.  That basis can be added in a second
2564
        insert_record_stream call that does not need to repeat records present
4009.3.3 by Andrew Bennetts
Add docstrings.
2565
        in the previous stream.  The record(s) that required that basis are
2566
        fully inserted once their basis is no longer missing.
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2567
        """
2568
        if not self.support_partial_insertion:
2569
            raise TestNotApplicable(
2570
                'versioned file scenario does not support partial insertion')
2571
        source = self.get_knit_delta_source()
6963.2.4 by Jelmer Vernooij
Add bees.
2572
        entries = source.get_record_stream([self.get_simple_key(b'origin'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2573
                                            self.get_simple_key(b'merged')], 'unordered', False)
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2574
        files = self.get_versionedfiles()
2575
        files.insert_record_stream(entries)
2576
        missing_bases = files.get_missing_compression_parent_keys()
6963.2.4 by Jelmer Vernooij
Add bees.
2577
        self.assertEqual({self.get_simple_key(b'left')},
7143.15.2 by Jelmer Vernooij
Run autopep8.
2578
                         set(missing_bases))
4009.3.7 by Andrew Bennetts
Most tests passing.
2579
        # 'merged' is inserted (although a commit of a write group involving
2580
        # this versionedfiles would fail).
6963.2.4 by Jelmer Vernooij
Add bees.
2581
        merged_key = self.get_simple_key(b'merged')
4009.3.7 by Andrew Bennetts
Most tests passing.
2582
        self.assertEqual(
6973.14.4 by Jelmer Vernooij
Fix checking for options.
2583
            [merged_key], list(files.get_parent_map([merged_key]).keys()))
4009.3.7 by Andrew Bennetts
Most tests passing.
2584
        # Add the full delta closure of the missing records
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2585
        missing_entries = source.get_record_stream(
4009.3.7 by Andrew Bennetts
Most tests passing.
2586
            missing_bases, 'unordered', True)
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2587
        files.insert_record_stream(missing_entries)
4009.3.7 by Andrew Bennetts
Most tests passing.
2588
        # Now 'merged' is fully inserted (and a commit would succeed).
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2589
        self.assertEqual([], list(files.get_missing_compression_parent_keys()))
2590
        self.assertEqual(
6973.14.4 by Jelmer Vernooij
Fix checking for options.
2591
            [merged_key], list(files.get_parent_map([merged_key]).keys()))
4009.3.7 by Andrew Bennetts
Most tests passing.
2592
        files.check()
4009.3.2 by Andrew Bennetts
Add test_insert_record_stream_delta_missing_basis_can_be_added_later.
2593
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2594
    def test_iter_lines_added_or_present_in_keys(self):
2595
        # test that we get at least an equalset of the lines added by
2596
        # versions in the store.
2597
        # the ordering here is to make a tree so that dumb searches have
2598
        # more changes to muck up.
2599
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
2600
        class InstrumentedProgress(progress.ProgressTask):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2601
2602
            def __init__(self):
4961.2.9 by Martin Pool
Rip out most remaining uses of DummyProgressBar
2603
                progress.ProgressTask.__init__(self)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2604
                self.updates = []
2605
2606
            def update(self, msg=None, current=None, total=None):
2607
                self.updates.append((msg, current, total))
2608
2609
        files = self.get_versionedfiles()
2610
        # add a base to get included
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2611
        files.add_lines(self.get_simple_key(b'base'), (), [b'base\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.
2612
        # add a ancestor to be included on one side
7143.15.2 by Jelmer Vernooij
Run autopep8.
2613
        files.add_lines(self.get_simple_key(
2614
            b'lancestor'), (), [b'lancestor\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.
2615
        # add a ancestor to be included on the other side
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2616
        files.add_lines(self.get_simple_key(b'rancestor'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2617
                        self.get_parents([self.get_simple_key(b'base')]), [b'rancestor\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.
2618
        # add a child of rancestor with no eofile-nl
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2619
        files.add_lines(self.get_simple_key(b'child'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2620
                        self.get_parents([self.get_simple_key(b'rancestor')]),
2621
                        [b'base\n', b'child\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.
2622
        # add a child of lancestor and base to join the two roots
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2623
        files.add_lines(self.get_simple_key(b'otherchild'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2624
                        self.get_parents([self.get_simple_key(b'lancestor'),
2625
                                          self.get_simple_key(b'base')]),
2626
                        [b'base\n', b'lancestor\n', b'otherchild\n'])
2627
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2628
        def iter_with_keys(keys, expected):
2629
            # now we need to see what lines are returned, and how often.
2630
            lines = {}
2631
            progress = InstrumentedProgress()
2632
            # iterate over the lines
2633
            for line in files.iter_lines_added_or_present_in_keys(keys,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2634
                                                                  pb=progress):
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2635
                lines.setdefault(line, 0)
2636
                lines[line] += 1
7143.15.2 by Jelmer Vernooij
Run autopep8.
2637
            if [] != progress.updates:
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2638
                self.assertEqual(expected, progress.updates)
2639
            return lines
2640
        lines = iter_with_keys(
7143.15.2 by Jelmer Vernooij
Run autopep8.
2641
            [self.get_simple_key(b'child'),
2642
             self.get_simple_key(b'otherchild')],
4103.3.4 by Martin Pool
Update test that depends on progress bar strings
2643
            [('Walking content', 0, 2),
2644
             ('Walking content', 1, 2),
2645
             ('Walking content', 2, 2)])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2646
        # we must see child and otherchild
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2647
        self.assertTrue(lines[(b'child\n', self.get_simple_key(b'child'))] > 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.
2648
        self.assertTrue(
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2649
            lines[(b'otherchild\n', self.get_simple_key(b'otherchild'))] > 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.
2650
        # we dont care if we got more than that.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2651
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2652
        # test all lines
2653
        lines = iter_with_keys(files.keys(),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2654
                               [('Walking content', 0, 5),
2655
                                ('Walking content', 1, 5),
2656
                                ('Walking content', 2, 5),
2657
                                ('Walking content', 3, 5),
2658
                                ('Walking content', 4, 5),
2659
                                ('Walking content', 5, 5)])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2660
        # all lines must be seen at least once
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2661
        self.assertTrue(lines[(b'base\n', self.get_simple_key(b'base'))] > 0)
2662
        self.assertTrue(
2663
            lines[(b'lancestor\n', self.get_simple_key(b'lancestor'))] > 0)
2664
        self.assertTrue(
2665
            lines[(b'rancestor\n', self.get_simple_key(b'rancestor'))] > 0)
2666
        self.assertTrue(lines[(b'child\n', self.get_simple_key(b'child'))] > 0)
2667
        self.assertTrue(
2668
            lines[(b'otherchild\n', self.get_simple_key(b'otherchild'))] > 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.
2669
2670
    def test_make_mpdiffs(self):
6622.1.34 by Jelmer Vernooij
Rename brzlib => breezy.
2671
        from breezy import multiparent
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2672
        files = self.get_versionedfiles('source')
2673
        # add texts that should trip the knit maximum delta chain threshold
2674
        # as well as doing parallel chains of data in knits.
2675
        # this is done by two chains of 25 insertions
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2676
        files.add_lines(self.get_simple_key(b'base'), [], [b'line\n'])
2677
        files.add_lines(self.get_simple_key(b'noeol'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2678
                        self.get_parents([self.get_simple_key(b'base')]), [b'line'])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2679
        # detailed eol tests:
2680
        # shared last line with parent no-eol
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2681
        files.add_lines(self.get_simple_key(b'noeolsecond'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2682
                        self.get_parents([self.get_simple_key(b'noeol')]),
2683
                        [b'line\n', b'line'])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2684
        # differing last line with parent, both no-eol
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2685
        files.add_lines(self.get_simple_key(b'noeolnotshared'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2686
                        self.get_parents(
2687
                            [self.get_simple_key(b'noeolsecond')]),
2688
                        [b'line\n', b'phone'])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2689
        # add eol following a noneol parent, change content
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2690
        files.add_lines(self.get_simple_key(b'eol'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2691
                        self.get_parents([self.get_simple_key(b'noeol')]), [b'phone\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.
2692
        # add eol following a noneol parent, no change content
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2693
        files.add_lines(self.get_simple_key(b'eolline'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2694
                        self.get_parents([self.get_simple_key(b'noeol')]), [b'line\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.
2695
        # noeol with no parents:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2696
        files.add_lines(self.get_simple_key(b'noeolbase'), [], [b'line'])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2697
        # noeol preceeding its leftmost parent in the output:
2698
        # this is done by making it a merge of two parents with no common
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2699
        # anestry: noeolbase and noeol with the
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2700
        # later-inserted parent the leftmost.
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2701
        files.add_lines(self.get_simple_key(b'eolbeforefirstparent'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2702
                        self.get_parents([self.get_simple_key(b'noeolbase'),
2703
                                          self.get_simple_key(b'noeol')]),
2704
                        [b'line'])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2705
        # two identical eol texts
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2706
        files.add_lines(self.get_simple_key(b'noeoldup'),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2707
                        self.get_parents([self.get_simple_key(b'noeol')]), [b'line'])
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2708
        next_parent = self.get_simple_key(b'base')
2709
        text_name = b'chain1-'
2710
        text = [b'line\n']
2711
        sha1s = {0: b'da6d3141cb4a5e6f464bf6e0518042ddc7bfd079',
2712
                 1: b'45e21ea146a81ea44a821737acdb4f9791c8abe7',
2713
                 2: b'e1f11570edf3e2a070052366c582837a4fe4e9fa',
2714
                 3: b'26b4b8626da827088c514b8f9bbe4ebf181edda1',
2715
                 4: b'e28a5510be25ba84d31121cff00956f9970ae6f6',
2716
                 5: b'd63ec0ce22e11dcf65a931b69255d3ac747a318d',
2717
                 6: b'2c2888d288cb5e1d98009d822fedfe6019c6a4ea',
2718
                 7: b'95c14da9cafbf828e3e74a6f016d87926ba234ab',
2719
                 8: b'779e9a0b28f9f832528d4b21e17e168c67697272',
2720
                 9: b'1f8ff4e5c6ff78ac106fcfe6b1e8cb8740ff9a8f',
2721
                 10: b'131a2ae712cf51ed62f143e3fbac3d4206c25a05',
2722
                 11: b'c5a9d6f520d2515e1ec401a8f8a67e6c3c89f199',
2723
                 12: b'31a2286267f24d8bedaa43355f8ad7129509ea85',
2724
                 13: b'dc2a7fe80e8ec5cae920973973a8ee28b2da5e0a',
2725
                 14: b'2c4b1736566b8ca6051e668de68650686a3922f2',
2726
                 15: b'5912e4ecd9b0c07be4d013e7e2bdcf9323276cde',
2727
                 16: b'b0d2e18d3559a00580f6b49804c23fea500feab3',
2728
                 17: b'8e1d43ad72f7562d7cb8f57ee584e20eb1a69fc7',
2729
                 18: b'5cf64a3459ae28efa60239e44b20312d25b253f3',
2730
                 19: b'1ebed371807ba5935958ad0884595126e8c4e823',
2731
                 20: b'2aa62a8b06fb3b3b892a3292a068ade69d5ee0d3',
2732
                 21: b'01edc447978004f6e4e962b417a4ae1955b6fe5d',
2733
                 22: b'd8d8dc49c4bf0bab401e0298bb5ad827768618bb',
2734
                 23: b'c21f62b1c482862983a8ffb2b0c64b3451876e3f',
2735
                 24: b'c0593fe795e00dff6b3c0fe857a074364d5f04fc',
2736
                 25: b'dd1a1cf2ba9cc225c3aff729953e6364bf1d1855',
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2737
                 }
2738
        for depth in range(26):
6963.2.6 by Jelmer Vernooij
Fix some more tests.
2739
            new_version = self.get_simple_key(text_name + b'%d' % depth)
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2740
            text = text + [b'line\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.
2741
            files.add_lines(new_version, self.get_parents([next_parent]), text)
2742
            next_parent = new_version
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2743
        next_parent = self.get_simple_key(b'base')
2744
        text_name = b'chain2-'
2745
        text = [b'line\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.
2746
        for depth in range(26):
6963.2.10 by Jelmer Vernooij
Fix a bunch of tests.
2747
            new_version = self.get_simple_key(text_name + b'%d' % depth)
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2748
            text = text + [b'line\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.
2749
            files.add_lines(new_version, self.get_parents([next_parent]), text)
2750
            next_parent = new_version
2751
        target = self.get_versionedfiles('target')
2752
        for key in multiparent.topo_iter_keys(files, files.keys()):
2753
            mpdiff = files.make_mpdiffs([key])[0]
2754
            parents = files.get_parent_map([key])[key] or []
2755
            target.add_mpdiffs(
3350.8.3 by Robert Collins
VF.get_sha1s needed changing to be stackable.
2756
                [(key, parents, files.get_sha1s([key])[key], mpdiff)])
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2757
            self.assertEqualDiff(
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2758
                next(files.get_record_stream([key], 'unordered',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2759
                                             True)).get_bytes_as('fulltext'),
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2760
                next(target.get_record_stream([key], 'unordered',
7143.15.2 by Jelmer Vernooij
Run autopep8.
2761
                                              True)).get_bytes_as('fulltext')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2762
                )
2763
2764
    def test_keys(self):
2765
        # While use is discouraged, versions() is still needed by aspects of
2766
        # bzr.
2767
        files = self.get_versionedfiles()
2768
        self.assertEqual(set(), set(files.keys()))
2769
        if self.key_length == 1:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2770
            key = (b'foo',)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2771
        else:
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2772
            key = (b'foo', b'bar',)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
2773
        files.add_lines(key, (), [])
6619.3.12 by Jelmer Vernooij
Use 2to3 set_literal fixer.
2774
        self.assertEqual({key}, set(files.keys()))
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2775
2776
2777
class VirtualVersionedFilesTests(TestCase):
2778
    """Basic tests for the VirtualVersionedFiles implementations."""
2779
2780
    def _get_parent_map(self, keys):
2781
        ret = {}
2782
        for k in keys:
2783
            if k in self._parent_map:
2784
                ret[k] = self._parent_map[k]
2785
        return ret
2786
2787
    def setUp(self):
6552.1.4 by Vincent Ladeuil
Remaining tests matching setup(self) that can be rewritten with super().
2788
        super(VirtualVersionedFilesTests, self).setUp()
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2789
        self._lines = {}
2790
        self._parent_map = {}
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2791
        self.texts = VirtualVersionedFiles(self._get_parent_map,
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2792
                                           self._lines.get)
2793
2794
    def test_add_lines(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2795
        self.assertRaises(NotImplementedError,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2796
                          self.texts.add_lines, b"foo", [], [])
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2797
2798
    def test_add_mpdiffs(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2799
        self.assertRaises(NotImplementedError,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2800
                          self.texts.add_mpdiffs, [])
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2801
4332.3.26 by Robert Collins
Allow passing keys to check to VersionedFile.check().
2802
    def test_check_noerrors(self):
2803
        self.texts.check()
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2804
2805
    def test_insert_record_stream(self):
2806
        self.assertRaises(NotImplementedError, self.texts.insert_record_stream,
2807
                          [])
2808
3518.1.2 by Jelmer Vernooij
Fix some stylistic issues pointed out by Ian.
2809
    def test_get_sha1s_nonexistent(self):
6963.2.4 by Jelmer Vernooij
Add bees.
2810
        self.assertEqual({}, self.texts.get_sha1s([(b"NONEXISTENT",)]))
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2811
2812
    def test_get_sha1s(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2813
        self._lines[b"key"] = [b"dataline1", b"dataline2"]
2814
        self.assertEqual({(b"key",): osutils.sha_strings(self._lines[b"key"])},
7143.15.2 by Jelmer Vernooij
Run autopep8.
2815
                         self.texts.get_sha1s([(b"key",)]))
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2816
2817
    def test_get_parent_map(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2818
        self._parent_map = {b"G": (b"A", b"B")}
2819
        self.assertEqual({(b"G",): ((b"A",), (b"B",))},
7143.15.2 by Jelmer Vernooij
Run autopep8.
2820
                         self.texts.get_parent_map([(b"G",), (b"L",)]))
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2821
2822
    def test_get_record_stream(self):
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2823
        self._lines[b"A"] = [b"FOO", b"BAR"]
2824
        it = self.texts.get_record_stream([(b"A",)], "unordered", True)
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
2825
        record = next(it)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2826
        self.assertEqual("chunked", record.storage_kind)
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2827
        self.assertEqual(b"FOOBAR", record.get_bytes_as("fulltext"))
2828
        self.assertEqual([b"FOO", b"BAR"], record.get_bytes_as("chunked"))
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2829
2830
    def test_get_record_stream_absent(self):
6963.2.4 by Jelmer Vernooij
Add bees.
2831
        it = self.texts.get_record_stream([(b"A",)], "unordered", True)
6634.2.1 by Martin
Apply 2to3 next fixer and make compatible
2832
        record = next(it)
6614.1.3 by Vincent Ladeuil
Fix assertEquals being deprecated by using assertEqual.
2833
        self.assertEqual("absent", record.storage_kind)
3518.1.1 by Jelmer Vernooij
Add VirtualVersionedFiles class.
2834
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
2835
    def test_iter_lines_added_or_present_in_keys(self):
6963.2.4 by Jelmer Vernooij
Add bees.
2836
        self._lines[b"A"] = [b"FOO", b"BAR"]
2837
        self._lines[b"B"] = [b"HEY"]
2838
        self._lines[b"C"] = [b"Alberta"]
2839
        it = self.texts.iter_lines_added_or_present_in_keys([(b"A",), (b"B",)])
2840
        self.assertEqual(sorted([(b"FOO", b"A"), (b"BAR", b"A"), (b"HEY", b"B")]),
7143.15.2 by Jelmer Vernooij
Run autopep8.
2841
                         sorted(list(it)))
3949.4.1 by Jelmer Vernooij
Implement VirtualVersionedFiles.iter_lines_added_or_present_in_keys.
2842
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2843
2844
class TestOrderingVersionedFilesDecorator(TestCaseWithMemoryTransport):
2845
2846
    def get_ordering_vf(self, key_priority):
2847
        builder = self.make_branch_builder('test')
2848
        builder.start_series()
6816.2.1 by Jelmer Vernooij
Migrate some build_snapshot code over to having revision_id as keyword argument.
2849
        builder.build_snapshot(None, [
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2850
            ('add', ('', b'TREE_ROOT', 'directory', None))],
2851
            revision_id=b'A')
2852
        builder.build_snapshot([b'A'], [], revision_id=b'B')
2853
        builder.build_snapshot([b'B'], [], revision_id=b'C')
2854
        builder.build_snapshot([b'C'], [], revision_id=b'D')
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2855
        builder.finish_series()
2856
        b = builder.get_branch()
2857
        b.lock_read()
2858
        self.addCleanup(b.unlock)
2859
        vf = b.repository.inventories
2860
        return versionedfile.OrderingVersionedFilesDecorator(vf, key_priority)
2861
2862
    def test_get_empty(self):
2863
        vf = self.get_ordering_vf({})
2864
        self.assertEqual([], vf.calls)
2865
2866
    def test_get_record_stream_topological(self):
7143.15.2 by Jelmer Vernooij
Run autopep8.
2867
        vf = self.get_ordering_vf(
2868
            {(b'A',): 3, (b'B',): 2, (b'C',): 4, (b'D',): 1})
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2869
        request_keys = [(b'B',), (b'C',), (b'D',), (b'A',)]
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2870
        keys = [r.key for r in vf.get_record_stream(request_keys,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2871
                                                    'topological', False)]
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2872
        # We should have gotten the keys in topological order
6963.2.1 by Jelmer Vernooij
Fix more python3 tests.
2873
        self.assertEqual([(b'A',), (b'B',), (b'C',), (b'D',)], keys)
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2874
        # And recorded that the request was made
2875
        self.assertEqual([('get_record_stream', request_keys, 'topological',
2876
                           False)], vf.calls)
2877
2878
    def test_get_record_stream_ordered(self):
7143.15.2 by Jelmer Vernooij
Run autopep8.
2879
        vf = self.get_ordering_vf(
2880
            {(b'A',): 3, (b'B',): 2, (b'C',): 4, (b'D',): 1})
6963.2.4 by Jelmer Vernooij
Add bees.
2881
        request_keys = [(b'B',), (b'C',), (b'D',), (b'A',)]
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2882
        keys = [r.key for r in vf.get_record_stream(request_keys,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2883
                                                    'unordered', False)]
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2884
        # They should be returned based on their priority
6963.2.4 by Jelmer Vernooij
Add bees.
2885
        self.assertEqual([(b'D',), (b'B',), (b'A',), (b'C',)], keys)
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2886
        # And the request recorded
2887
        self.assertEqual([('get_record_stream', request_keys, 'unordered',
2888
                           False)], vf.calls)
2889
2890
    def test_get_record_stream_implicit_order(self):
6963.2.4 by Jelmer Vernooij
Add bees.
2891
        vf = self.get_ordering_vf({(b'B',): 2, (b'D',): 1})
2892
        request_keys = [(b'B',), (b'C',), (b'D',), (b'A',)]
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2893
        keys = [r.key for r in vf.get_record_stream(request_keys,
7143.15.2 by Jelmer Vernooij
Run autopep8.
2894
                                                    'unordered', False)]
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2895
        # A and C are not in the map, so they get sorted to the front. A comes
2896
        # before C alphabetically, so it comes back first
6963.2.4 by Jelmer Vernooij
Add bees.
2897
        self.assertEqual([(b'A',), (b'C',), (b'D',), (b'B',)], keys)
3871.4.1 by John Arbash Meinel
Add a VFDecorator that can yield records in a specified order
2898
        # And the request recorded
2899
        self.assertEqual([('get_record_stream', request_keys, 'unordered',
2900
                           False)], vf.calls)