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