/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2008-2011 Canonical Ltd
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
2
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
3
# This program is free software; you can redistribute it and/or modify
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
3735.31.2 by John Arbash Meinel
Cleanup trailing whitespace, get test_source to pass by removing asserts.
12
#
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
3735.36.3 by John Arbash Meinel
Add the new address for FSF to the new files.
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
0.17.1 by Robert Collins
Starting point. Interface tests hooked up and failing.
16
17
"""Tests for group compression."""
18
19
import zlib
20
3735.31.1 by John Arbash Meinel
Bring the groupcompress plugin into the brisbane-core branch.
21
from bzrlib import (
4343.3.20 by John Arbash Meinel
Copy the track_external_parent_refs tests over to GCVF.
22
    btree_index,
5755.2.4 by John Arbash Meinel
Expose the max_entries_per_source into GroupCompressVersionedFiles
23
    config,
3735.31.1 by John Arbash Meinel
Bring the groupcompress plugin into the brisbane-core branch.
24
    groupcompress,
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
25
    errors,
4343.3.20 by John Arbash Meinel
Copy the track_external_parent_refs tests over to GCVF.
26
    index as _mod_index,
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
27
    osutils,
3735.31.1 by John Arbash Meinel
Bring the groupcompress plugin into the brisbane-core branch.
28
    tests,
4465.2.3 by Aaron Bentley
Update to change redundant inserts into a warning.
29
    trace,
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
30
    versionedfile,
3735.31.1 by John Arbash Meinel
Bring the groupcompress plugin into the brisbane-core branch.
31
    )
0.23.58 by John Arbash Meinel
fix up the failing tests.
32
from bzrlib.osutils import sha_string
4913.2.24 by John Arbash Meinel
Track down a few more import typos.
33
from bzrlib.tests.test__groupcompress import compiled_groupcompress_feature
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
34
from bzrlib.tests.scenarios import load_tests_apply_scenarios
35
36
37
def group_compress_implementation_scenarios():
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
38
    scenarios = [
39
        ('python', {'compressor': groupcompress.PythonGroupCompressor}),
40
        ]
4913.2.24 by John Arbash Meinel
Track down a few more import typos.
41
    if compiled_groupcompress_feature.available():
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
42
        scenarios.append(('C',
43
            {'compressor': groupcompress.PyrexGroupCompressor}))
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
44
    return scenarios
45
46
47
load_tests = load_tests_apply_scenarios
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
48
49
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
50
class TestGroupCompressor(tests.TestCase):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
51
52
    def _chunks_to_repr_lines(self, chunks):
53
        return '\n'.join(map(repr, ''.join(chunks).split('\n')))
54
55
    def assertEqualDiffEncoded(self, expected, actual):
56
        """Compare the actual content to the expected content.
57
58
        :param expected: A group of chunks that we expect to see
59
        :param actual: The measured 'chunks'
60
61
        We will transform the chunks back into lines, and then run 'repr()'
62
        over them to handle non-ascii characters.
63
        """
64
        self.assertEqualDiff(self._chunks_to_repr_lines(expected),
65
                             self._chunks_to_repr_lines(actual))
66
67
68
class TestAllGroupCompressors(TestGroupCompressor):
0.17.2 by Robert Collins
Core proof of concept working.
69
    """Tests for GroupCompressor"""
70
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
71
    scenarios = group_compress_implementation_scenarios()
72
    compressor = None # Set by scenario
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
73
0.17.2 by Robert Collins
Core proof of concept working.
74
    def test_empty_delta(self):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
75
        compressor = self.compressor()
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
76
        self.assertEqual([], compressor.chunks)
0.17.2 by Robert Collins
Core proof of concept working.
77
78
    def test_one_nosha_delta(self):
79
        # diff against NUKK
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
80
        compressor = self.compressor()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
81
        sha1, start_point, end_point, _ = compressor.compress(('label',),
0.23.58 by John Arbash Meinel
fix up the failing tests.
82
            'strange\ncommon\n', None)
83
        self.assertEqual(sha_string('strange\ncommon\n'), sha1)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
84
        expected_lines = 'f' '\x0f' 'strange\ncommon\n'
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
85
        self.assertEqual(expected_lines, ''.join(compressor.chunks))
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
86
        self.assertEqual(0, start_point)
0.17.2 by Robert Collins
Core proof of concept working.
87
        self.assertEqual(sum(map(len, expected_lines)), end_point)
88
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
89
    def test_empty_content(self):
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
90
        compressor = self.compressor()
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
91
        # Adding empty bytes should return the 'null' record
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
92
        sha1, start_point, end_point, kind = compressor.compress(('empty',),
93
                                                                 '', None)
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
94
        self.assertEqual(0, start_point)
95
        self.assertEqual(0, end_point)
96
        self.assertEqual('fulltext', kind)
97
        self.assertEqual(groupcompress._null_sha1, sha1)
98
        self.assertEqual(0, compressor.endpoint)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
99
        self.assertEqual([], compressor.chunks)
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
100
        # Even after adding some content
101
        compressor.compress(('content',), 'some\nbytes\n', None)
102
        self.assertTrue(compressor.endpoint > 0)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
103
        sha1, start_point, end_point, kind = compressor.compress(('empty2',),
104
                                                                 '', None)
3735.2.162 by John Arbash Meinel
Change GroupCompressor.compress() to return the start_point.
105
        self.assertEqual(0, start_point)
106
        self.assertEqual(0, end_point)
107
        self.assertEqual('fulltext', kind)
108
        self.assertEqual(groupcompress._null_sha1, sha1)
109
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
110
    def test_extract_from_compressor(self):
111
        # Knit fetching will try to reconstruct texts locally which results in
112
        # reading something that is in the compressor stream already.
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
113
        compressor = self.compressor()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
114
        sha1_1, _, _, _ = compressor.compress(('label',),
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
115
            'strange\ncommon long line\nthat needs a 16 byte match\n', None)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
116
        expected_lines = list(compressor.chunks)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
117
        sha1_2, _, end_point, _ = compressor.compress(('newlabel',),
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
118
            'common long line\nthat needs a 16 byte match\ndifferent\n', None)
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
119
        # get the first out
0.25.8 by John Arbash Meinel
Fix up the tests. Mostly it was just changing things to
120
        self.assertEqual(('strange\ncommon long line\n'
121
                          'that needs a 16 byte match\n', sha1_1),
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
122
                         compressor.extract(('label',)))
0.17.11 by Robert Collins
Add extraction of just-compressed texts to support converting from knits.
123
        # and the second
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
124
        self.assertEqual(('common long line\nthat needs a 16 byte match\n'
125
                          'different\n', sha1_2),
126
                         compressor.extract(('newlabel',)))
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
127
4241.17.2 by John Arbash Meinel
PythonGroupCompressor needs to support pop_last() properly.
128
    def test_pop_last(self):
129
        compressor = self.compressor()
130
        _, _, _, _ = compressor.compress(('key1',),
131
            'some text\nfor the first entry\n', None)
132
        expected_lines = list(compressor.chunks)
133
        _, _, _, _ = compressor.compress(('key2',),
134
            'some text\nfor the second entry\n', None)
135
        compressor.pop_last()
136
        self.assertEqual(expected_lines, compressor.chunks)
137
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
138
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
139
class TestPyrexGroupCompressor(TestGroupCompressor):
140
4913.2.24 by John Arbash Meinel
Track down a few more import typos.
141
    _test_needs_features = [compiled_groupcompress_feature]
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
142
    compressor = groupcompress.PyrexGroupCompressor
143
144
    def test_stats(self):
145
        compressor = self.compressor()
3735.40.7 by John Arbash Meinel
Move even more functionality into EquivalenceTable.
146
        compressor.compress(('label',),
147
                            'strange\n'
148
                            'common very very long line\n'
149
                            'plus more text\n', None)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
150
        compressor.compress(('newlabel',),
3735.40.7 by John Arbash Meinel
Move even more functionality into EquivalenceTable.
151
                            'common very very long line\n'
152
                            'plus more text\n'
153
                            'different\n'
154
                            'moredifferent\n', None)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
155
        compressor.compress(('label3',),
3735.40.7 by John Arbash Meinel
Move even more functionality into EquivalenceTable.
156
                            'new\n'
157
                            'common very very long line\n'
158
                            'plus more text\n'
159
                            'different\n'
160
                            'moredifferent\n', None)
161
        self.assertAlmostEqual(1.9, compressor.ratio(), 1)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
162
163
    def test_two_nosha_delta(self):
164
        compressor = self.compressor()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
165
        sha1_1, _, _, _ = compressor.compress(('label',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
166
            'strange\ncommon long line\nthat needs a 16 byte match\n', None)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
167
        expected_lines = list(compressor.chunks)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
168
        sha1_2, start_point, end_point, _ = compressor.compress(('newlabel',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
169
            'common long line\nthat needs a 16 byte match\ndifferent\n', None)
170
        self.assertEqual(sha_string('common long line\n'
171
                                    'that needs a 16 byte match\n'
172
                                    'different\n'), sha1_2)
173
        expected_lines.extend([
174
            # 'delta', delta length
3735.40.10 by John Arbash Meinel
Merge in the new delta format code.
175
            'd\x0f',
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
176
            # source and target length
3735.40.10 by John Arbash Meinel
Merge in the new delta format code.
177
            '\x36',
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
178
            # copy the line common
179
            '\x91\x0a\x2c', #copy, offset 0x0a, len 0x2c
180
            # add the line different, and the trailing newline
181
            '\x0adifferent\n', # insert 10 bytes
182
            ])
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
183
        self.assertEqualDiffEncoded(expected_lines, compressor.chunks)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
184
        self.assertEqual(sum(map(len, expected_lines)), end_point)
185
186
    def test_three_nosha_delta(self):
187
        # The first interesting test: make a change that should use lines from
188
        # both parents.
189
        compressor = self.compressor()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
190
        sha1_1, _, _, _ = compressor.compress(('label',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
191
            'strange\ncommon very very long line\nwith some extra text\n', None)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
192
        sha1_2, _, _, _ = compressor.compress(('newlabel',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
193
            'different\nmoredifferent\nand then some more\n', None)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
194
        expected_lines = list(compressor.chunks)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
195
        sha1_3, start_point, end_point, _ = compressor.compress(('label3',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
196
            'new\ncommon very very long line\nwith some extra text\n'
197
            'different\nmoredifferent\nand then some more\n',
198
            None)
199
        self.assertEqual(
200
            sha_string('new\ncommon very very long line\nwith some extra text\n'
201
                       'different\nmoredifferent\nand then some more\n'),
202
            sha1_3)
203
        expected_lines.extend([
204
            # 'delta', delta length
3735.40.10 by John Arbash Meinel
Merge in the new delta format code.
205
            'd\x0b',
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
206
            # source and target length
3735.40.10 by John Arbash Meinel
Merge in the new delta format code.
207
            '\x5f'
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
208
            # insert new
209
            '\x03new',
210
            # Copy of first parent 'common' range
211
            '\x91\x09\x31' # copy, offset 0x09, 0x31 bytes
212
            # Copy of second parent 'different' range
213
            '\x91\x3c\x2b' # copy, offset 0x3c, 0x2b bytes
214
            ])
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
215
        self.assertEqualDiffEncoded(expected_lines, compressor.chunks)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
216
        self.assertEqual(sum(map(len, expected_lines)), end_point)
217
218
219
class TestPythonGroupCompressor(TestGroupCompressor):
220
221
    compressor = groupcompress.PythonGroupCompressor
222
223
    def test_stats(self):
224
        compressor = self.compressor()
3735.40.7 by John Arbash Meinel
Move even more functionality into EquivalenceTable.
225
        compressor.compress(('label',),
226
                            'strange\n'
227
                            'common very very long line\n'
228
                            'plus more text\n', None)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
229
        compressor.compress(('newlabel',),
3735.40.7 by John Arbash Meinel
Move even more functionality into EquivalenceTable.
230
                            'common very very long line\n'
231
                            'plus more text\n'
232
                            'different\n'
233
                            'moredifferent\n', None)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
234
        compressor.compress(('label3',),
3735.40.7 by John Arbash Meinel
Move even more functionality into EquivalenceTable.
235
                            'new\n'
236
                            'common very very long line\n'
237
                            'plus more text\n'
238
                            'different\n'
239
                            'moredifferent\n', None)
240
        self.assertAlmostEqual(1.9, compressor.ratio(), 1)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
241
242
    def test_two_nosha_delta(self):
243
        compressor = self.compressor()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
244
        sha1_1, _, _, _ = compressor.compress(('label',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
245
            'strange\ncommon long line\nthat needs a 16 byte match\n', None)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
246
        expected_lines = list(compressor.chunks)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
247
        sha1_2, start_point, end_point, _ = compressor.compress(('newlabel',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
248
            'common long line\nthat needs a 16 byte match\ndifferent\n', None)
249
        self.assertEqual(sha_string('common long line\n'
250
                                    'that needs a 16 byte match\n'
251
                                    'different\n'), sha1_2)
252
        expected_lines.extend([
253
            # 'delta', delta length
3735.40.10 by John Arbash Meinel
Merge in the new delta format code.
254
            'd\x0f',
255
            # target length
256
            '\x36',
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
257
            # copy the line common
258
            '\x91\x0a\x2c', #copy, offset 0x0a, len 0x2c
259
            # add the line different, and the trailing newline
260
            '\x0adifferent\n', # insert 10 bytes
261
            ])
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
262
        self.assertEqualDiffEncoded(expected_lines, compressor.chunks)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
263
        self.assertEqual(sum(map(len, expected_lines)), end_point)
264
265
    def test_three_nosha_delta(self):
266
        # The first interesting test: make a change that should use lines from
267
        # both parents.
268
        compressor = self.compressor()
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
269
        sha1_1, _, _, _ = compressor.compress(('label',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
270
            'strange\ncommon very very long line\nwith some extra text\n', None)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
271
        sha1_2, _, _, _ = compressor.compress(('newlabel',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
272
            'different\nmoredifferent\nand then some more\n', None)
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
273
        expected_lines = list(compressor.chunks)
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
274
        sha1_3, start_point, end_point, _ = compressor.compress(('label3',),
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
275
            'new\ncommon very very long line\nwith some extra text\n'
276
            'different\nmoredifferent\nand then some more\n',
277
            None)
278
        self.assertEqual(
279
            sha_string('new\ncommon very very long line\nwith some extra text\n'
280
                       'different\nmoredifferent\nand then some more\n'),
281
            sha1_3)
282
        expected_lines.extend([
283
            # 'delta', delta length
3735.40.10 by John Arbash Meinel
Merge in the new delta format code.
284
            'd\x0c',
285
            # target length
286
            '\x5f'
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
287
            # insert new
288
            '\x04new\n',
289
            # Copy of first parent 'common' range
290
            '\x91\x0a\x30' # copy, offset 0x0a, 0x30 bytes
291
            # Copy of second parent 'different' range
292
            '\x91\x3c\x2b' # copy, offset 0x3c, 0x2b bytes
293
            ])
3735.40.17 by John Arbash Meinel
Change the attribute from 'lines' to 'chunks' to make it more
294
        self.assertEqualDiffEncoded(expected_lines, compressor.chunks)
3735.40.4 by John Arbash Meinel
Factor out tests that rely on the exact bytecode.
295
        self.assertEqual(sum(map(len, expected_lines)), end_point)
296
297
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
298
class TestGroupCompressBlock(tests.TestCase):
299
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
300
    def make_block(self, key_to_text):
301
        """Create a GroupCompressBlock, filling it with the given texts."""
302
        compressor = groupcompress.GroupCompressor()
303
        start = 0
304
        for key in sorted(key_to_text):
305
            compressor.compress(key, key_to_text[key], None)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
306
        locs = dict((key, (start, end)) for key, (start, _, end, _)
307
                    in compressor.labels_deltas.iteritems())
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
308
        block = compressor.flush()
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
309
        raw_bytes = block.to_bytes()
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
310
        # Go through from_bytes(to_bytes()) so that we start with a compressed
311
        # content object
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
312
        return locs, groupcompress.GroupCompressBlock.from_bytes(raw_bytes)
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
313
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
314
    def test_from_empty_bytes(self):
3735.31.1 by John Arbash Meinel
Bring the groupcompress plugin into the brisbane-core branch.
315
        self.assertRaises(ValueError,
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
316
                          groupcompress.GroupCompressBlock.from_bytes, '')
317
0.25.4 by John Arbash Meinel
We at least have the rudimentary ability to encode and decode values.
318
    def test_from_minimal_bytes(self):
3735.32.4 by John Arbash Meinel
Change the byte representation of a groupcompress block.
319
        block = groupcompress.GroupCompressBlock.from_bytes(
3735.38.4 by John Arbash Meinel
Another disk format change.
320
            'gcb1z\n0\n0\n')
0.25.4 by John Arbash Meinel
We at least have the rudimentary ability to encode and decode values.
321
        self.assertIsInstance(block, groupcompress.GroupCompressBlock)
3735.32.6 by John Arbash Meinel
A bit of reworking changes things so content is expanded at extract() time.
322
        self.assertIs(None, block._content)
323
        self.assertEqual('', block._z_content)
324
        block._ensure_content()
3735.32.5 by John Arbash Meinel
Change the parsing code to start out just holding the compressed bytes.
325
        self.assertEqual('', block._content)
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
326
        self.assertEqual('', block._z_content)
3735.32.6 by John Arbash Meinel
A bit of reworking changes things so content is expanded at extract() time.
327
        block._ensure_content() # Ensure content is safe to call 2x
0.25.4 by John Arbash Meinel
We at least have the rudimentary ability to encode and decode values.
328
4241.6.6 by Robert Collins, John Arbash Meinel, Ian Clathworthy, Vincent Ladeuil
Groupcompress from brisbane-core.
329
    def test_from_invalid(self):
330
        self.assertRaises(ValueError,
331
                          groupcompress.GroupCompressBlock.from_bytes,
332
                          'this is not a valid header')
333
3735.38.4 by John Arbash Meinel
Another disk format change.
334
    def test_from_bytes(self):
3735.32.4 by John Arbash Meinel
Change the byte representation of a groupcompress block.
335
        content = ('a tiny bit of content\n')
336
        z_content = zlib.compress(content)
337
        z_bytes = (
338
            'gcb1z\n' # group compress block v1 plain
339
            '%d\n' # Length of compressed content
340
            '%d\n' # Length of uncompressed content
341
            '%s'   # Compressed content
3735.38.4 by John Arbash Meinel
Another disk format change.
342
            ) % (len(z_content), len(content), z_content)
0.25.6 by John Arbash Meinel
(tests broken) implement the basic ability to have a separate header
343
        block = groupcompress.GroupCompressBlock.from_bytes(
3735.32.4 by John Arbash Meinel
Change the byte representation of a groupcompress block.
344
            z_bytes)
3735.32.6 by John Arbash Meinel
A bit of reworking changes things so content is expanded at extract() time.
345
        self.assertEqual(z_content, block._z_content)
346
        self.assertIs(None, block._content)
3735.38.4 by John Arbash Meinel
Another disk format change.
347
        self.assertEqual(len(z_content), block._z_content_length)
348
        self.assertEqual(len(content), block._content_length)
3735.32.10 by John Arbash Meinel
test that we support reading from the gc blocks that didn't have their lengths.
349
        block._ensure_content()
3735.32.27 by John Arbash Meinel
Have _LazyGroupContentManager pre-extract everything it holds.
350
        self.assertEqual(z_content, block._z_content)
3735.32.10 by John Arbash Meinel
test that we support reading from the gc blocks that didn't have their lengths.
351
        self.assertEqual(content, block._content)
352
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
353
    def test_to_chunks(self):
354
        content_chunks = ['this is some content\n',
355
                          'this content will be compressed\n']
356
        content_len = sum(map(len, content_chunks))
357
        content = ''.join(content_chunks)
358
        gcb = groupcompress.GroupCompressBlock()
359
        gcb.set_chunked_content(content_chunks, content_len)
360
        total_len, block_chunks = gcb.to_chunks()
361
        block_bytes = ''.join(block_chunks)
362
        self.assertEqual(gcb._z_content_length, len(gcb._z_content))
363
        self.assertEqual(total_len, len(block_bytes))
364
        self.assertEqual(gcb._content_length, content_len)
365
        expected_header =('gcb1z\n' # group compress block v1 zlib
366
                          '%d\n' # Length of compressed content
367
                          '%d\n' # Length of uncompressed content
368
                         ) % (gcb._z_content_length, gcb._content_length)
369
        # The first chunk should be the header chunk. It is small, fixed size,
370
        # and there is no compelling reason to split it up
371
        self.assertEqual(expected_header, block_chunks[0])
372
        self.assertStartsWith(block_bytes, expected_header)
373
        remaining_bytes = block_bytes[len(expected_header):]
374
        raw_bytes = zlib.decompress(remaining_bytes)
375
        self.assertEqual(content, raw_bytes)
376
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
377
    def test_to_bytes(self):
3735.38.4 by John Arbash Meinel
Another disk format change.
378
        content = ('this is some content\n'
379
                   'this content will be compressed\n')
0.25.2 by John Arbash Meinel
First cut at meta-info as text form.
380
        gcb = groupcompress.GroupCompressBlock()
3735.38.4 by John Arbash Meinel
Another disk format change.
381
        gcb.set_content(content)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
382
        bytes = gcb.to_bytes()
3735.38.4 by John Arbash Meinel
Another disk format change.
383
        self.assertEqual(gcb._z_content_length, len(gcb._z_content))
384
        self.assertEqual(gcb._content_length, len(content))
3735.32.4 by John Arbash Meinel
Change the byte representation of a groupcompress block.
385
        expected_header =('gcb1z\n' # group compress block v1 zlib
3735.38.4 by John Arbash Meinel
Another disk format change.
386
                          '%d\n' # Length of compressed content
387
                          '%d\n' # Length of uncompressed content
388
                         ) % (gcb._z_content_length, gcb._content_length)
3735.32.4 by John Arbash Meinel
Change the byte representation of a groupcompress block.
389
        self.assertStartsWith(bytes, expected_header)
390
        remaining_bytes = bytes[len(expected_header):]
0.25.5 by John Arbash Meinel
Now using a zlib compressed format.
391
        raw_bytes = zlib.decompress(remaining_bytes)
3735.38.4 by John Arbash Meinel
Another disk format change.
392
        self.assertEqual(content, raw_bytes)
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
393
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
394
        # we should get the same results if using the chunked version
395
        gcb = groupcompress.GroupCompressBlock()
396
        gcb.set_chunked_content(['this is some content\n'
4469.1.2 by John Arbash Meinel
The only caller already knows the content length, so make the api such that
397
                                 'this content will be compressed\n'],
398
                                 len(content))
4469.1.1 by John Arbash Meinel
Add a set_content_chunked member to GroupCompressBlock.
399
        old_bytes = bytes
400
        bytes = gcb.to_bytes()
401
        self.assertEqual(old_bytes, bytes)
402
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
403
    def test_partial_decomp(self):
404
        content_chunks = []
405
        # We need a sufficient amount of data so that zlib.decompress has
406
        # partial decompression to work with. Most auto-generated data
407
        # compresses a bit too well, we want a combination, so we combine a sha
408
        # hash with compressible data.
409
        for i in xrange(2048):
410
            next_content = '%d\nThis is a bit of duplicate text\n' % (i,)
411
            content_chunks.append(next_content)
412
            next_sha1 = osutils.sha_string(next_content)
413
            content_chunks.append(next_sha1 + '\n')
414
        content = ''.join(content_chunks)
415
        self.assertEqual(158634, len(content))
416
        z_content = zlib.compress(content)
417
        self.assertEqual(57182, len(z_content))
418
        block = groupcompress.GroupCompressBlock()
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
419
        block._z_content_chunks = (z_content,)
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
420
        block._z_content_length = len(z_content)
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
421
        block._compressor_name = 'zlib'
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
422
        block._content_length = 158634
423
        self.assertIs(None, block._content)
424
        block._ensure_content(100)
425
        self.assertIsNot(None, block._content)
426
        # We have decompressed at least 100 bytes
427
        self.assertTrue(len(block._content) >= 100)
428
        # We have not decompressed the whole content
429
        self.assertTrue(len(block._content) < 158634)
430
        self.assertEqualDiff(content[:len(block._content)], block._content)
431
        # ensuring content that we already have shouldn't cause any more data
432
        # to be extracted
433
        cur_len = len(block._content)
434
        block._ensure_content(cur_len - 10)
435
        self.assertEqual(cur_len, len(block._content))
436
        # Now we want a bit more content
437
        cur_len += 10
438
        block._ensure_content(cur_len)
439
        self.assertTrue(len(block._content) >= cur_len)
440
        self.assertTrue(len(block._content) < 158634)
441
        self.assertEqualDiff(content[:len(block._content)], block._content)
442
        # And now lets finish
443
        block._ensure_content(158634)
444
        self.assertEqualDiff(content, block._content)
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
445
        # And the decompressor is finalized
3735.32.7 by John Arbash Meinel
Implement partial decompression support.
446
        self.assertIs(None, block._z_content_decompressor)
447
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
448
    def test__ensure_all_content(self):
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
449
        content_chunks = []
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
450
        # We need a sufficient amount of data so that zlib.decompress has
451
        # partial decompression to work with. Most auto-generated data
452
        # compresses a bit too well, we want a combination, so we combine a sha
453
        # hash with compressible data.
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
454
        for i in xrange(2048):
455
            next_content = '%d\nThis is a bit of duplicate text\n' % (i,)
456
            content_chunks.append(next_content)
457
            next_sha1 = osutils.sha_string(next_content)
458
            content_chunks.append(next_sha1 + '\n')
459
        content = ''.join(content_chunks)
460
        self.assertEqual(158634, len(content))
461
        z_content = zlib.compress(content)
462
        self.assertEqual(57182, len(z_content))
463
        block = groupcompress.GroupCompressBlock()
5439.2.1 by John Arbash Meinel
Change GroupCompressBlock to work in self._z_compress_chunks
464
        block._z_content_chunks = (z_content,)
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
465
        block._z_content_length = len(z_content)
466
        block._compressor_name = 'zlib'
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
467
        block._content_length = 158634
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
468
        self.assertIs(None, block._content)
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
469
        # The first _ensure_content got all of the required data
470
        block._ensure_content(158634)
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
471
        self.assertEqualDiff(content, block._content)
4744.2.3 by John Arbash Meinel
change the GroupcompressBlock code a bit.
472
        # And we should have released the _z_content_decompressor since it was
473
        # fully consumed
3735.32.11 by John Arbash Meinel
Add tests for the ability to do partial decompression without knowing the final length.
474
        self.assertIs(None, block._z_content_decompressor)
475
4300.1.1 by John Arbash Meinel
Add the ability to convert a gc block into 'human readable' form.
476
    def test__dump(self):
477
        dup_content = 'some duplicate content\nwhich is sufficiently long\n'
478
        key_to_text = {('1',): dup_content + '1 unique\n',
479
                       ('2',): dup_content + '2 extra special\n'}
480
        locs, block = self.make_block(key_to_text)
481
        self.assertEqual([('f', len(key_to_text[('1',)])),
482
                          ('d', 21, len(key_to_text[('2',)]),
483
                           [('c', 2, len(dup_content)),
484
                            ('i', len('2 extra special\n'), '')
485
                           ]),
486
                         ], block._dump())
487
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
488
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
489
class TestCaseWithGroupCompressVersionedFiles(
490
        tests.TestCaseWithMemoryTransport):
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
491
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
492
    def make_test_vf(self, create_graph, keylength=1, do_cleanup=True,
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
493
                     dir='.', inconsistency_fatal=True):
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
494
        t = self.get_transport(dir)
495
        t.ensure_base()
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
496
        vf = groupcompress.make_pack_factory(graph=create_graph,
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
497
            delta=False, keylength=keylength,
498
            inconsistency_fatal=inconsistency_fatal)(t)
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
499
        if do_cleanup:
500
            self.addCleanup(groupcompress.cleanup_pack_group, vf)
501
        return vf
502
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
503
504
class TestGroupCompressVersionedFiles(TestCaseWithGroupCompressVersionedFiles):
505
4343.3.20 by John Arbash Meinel
Copy the track_external_parent_refs tests over to GCVF.
506
    def make_g_index(self, name, ref_lists=0, nodes=[]):
507
        builder = btree_index.BTreeBuilder(ref_lists)
508
        for node, references, value in nodes:
509
            builder.add_node(node, references, value)
510
        stream = builder.finish()
511
        trans = self.get_transport()
512
        size = trans.put_file(name, stream)
513
        return btree_index.BTreeGraphIndex(trans, name, size)
514
515
    def make_g_index_missing_parent(self):
516
        graph_index = self.make_g_index('missing_parent', 1,
517
            [(('parent', ), '2 78 2 10', ([],)),
518
             (('tip', ), '2 78 2 10',
519
              ([('parent', ), ('missing-parent', )],)),
520
              ])
521
        return graph_index
522
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
523
    def test_get_record_stream_as_requested(self):
524
        # Consider promoting 'as-requested' to general availability, and
525
        # make this a VF interface test
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
526
        vf = self.make_test_vf(False, dir='source')
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
527
        vf.add_lines(('a',), (), ['lines\n'])
528
        vf.add_lines(('b',), (), ['lines\n'])
529
        vf.add_lines(('c',), (), ['lines\n'])
530
        vf.add_lines(('d',), (), ['lines\n'])
531
        vf.writer.end()
532
        keys = [record.key for record in vf.get_record_stream(
533
                    [('a',), ('b',), ('c',), ('d',)],
534
                    'as-requested', False)]
535
        self.assertEqual([('a',), ('b',), ('c',), ('d',)], keys)
536
        keys = [record.key for record in vf.get_record_stream(
537
                    [('b',), ('a',), ('d',), ('c',)],
538
                    'as-requested', False)]
539
        self.assertEqual([('b',), ('a',), ('d',), ('c',)], keys)
540
541
        # It should work even after being repacked into another VF
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
542
        vf2 = self.make_test_vf(False, dir='target')
3735.32.3 by John Arbash Meinel
Start doing some direct GCVF tests.
543
        vf2.insert_record_stream(vf.get_record_stream(
544
                    [('b',), ('a',), ('d',), ('c',)], 'as-requested', False))
545
        vf2.writer.end()
546
547
        keys = [record.key for record in vf2.get_record_stream(
548
                    [('a',), ('b',), ('c',), ('d',)],
549
                    'as-requested', False)]
550
        self.assertEqual([('a',), ('b',), ('c',), ('d',)], keys)
551
        keys = [record.key for record in vf2.get_record_stream(
552
                    [('b',), ('a',), ('d',), ('c',)],
553
                    'as-requested', False)]
554
        self.assertEqual([('b',), ('a',), ('d',), ('c',)], keys)
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
555
4665.3.9 by John Arbash Meinel
Start doing some work to make sure that we call _check_rebuild_block
556
    def test_insert_record_stream_reuses_blocks(self):
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
557
        vf = self.make_test_vf(True, dir='source')
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
558
        def grouped_stream(revision_ids, first_parents=()):
559
            parents = first_parents
560
            for revision_id in revision_ids:
561
                key = (revision_id,)
562
                record = versionedfile.FulltextContentFactory(
563
                    key, parents, None,
564
                    'some content that is\n'
565
                    'identical except for\n'
566
                    'revision_id:%s\n' % (revision_id,))
567
                yield record
568
                parents = (key,)
569
        # One group, a-d
570
        vf.insert_record_stream(grouped_stream(['a', 'b', 'c', 'd']))
571
        # Second group, e-h
572
        vf.insert_record_stream(grouped_stream(['e', 'f', 'g', 'h'],
573
                                               first_parents=(('d',),)))
574
        block_bytes = {}
575
        stream = vf.get_record_stream([(r,) for r in 'abcdefgh'],
576
                                      'unordered', False)
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
577
        num_records = 0
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
578
        for record in stream:
579
            if record.key in [('a',), ('e',)]:
580
                self.assertEqual('groupcompress-block', record.storage_kind)
581
            else:
582
                self.assertEqual('groupcompress-block-ref',
583
                                 record.storage_kind)
584
            block_bytes[record.key] = record._manager._block._z_content
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
585
            num_records += 1
586
        self.assertEqual(8, num_records)
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
587
        for r in 'abcd':
588
            key = (r,)
589
            self.assertIs(block_bytes[key], block_bytes[('a',)])
590
            self.assertNotEqual(block_bytes[key], block_bytes[('e',)])
591
        for r in 'efgh':
592
            key = (r,)
593
            self.assertIs(block_bytes[key], block_bytes[('e',)])
594
            self.assertNotEqual(block_bytes[key], block_bytes[('a',)])
595
        # Now copy the blocks into another vf, and ensure that the blocks are
596
        # preserved without creating new entries
597
        vf2 = self.make_test_vf(True, dir='target')
598
        # ordering in 'groupcompress' order, should actually swap the groups in
599
        # the target vf, but the groups themselves should not be disturbed.
4665.3.9 by John Arbash Meinel
Start doing some work to make sure that we call _check_rebuild_block
600
        def small_size_stream():
601
            for record in vf.get_record_stream([(r,) for r in 'abcdefgh'],
602
                                               'groupcompress', False):
603
                record._manager._full_enough_block_size = \
604
                    record._manager._block._content_length
605
                yield record
606
                        
607
        vf2.insert_record_stream(small_size_stream())
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
608
        stream = vf2.get_record_stream([(r,) for r in 'abcdefgh'],
609
                                       'groupcompress', False)
610
        vf2.writer.end()
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
611
        num_records = 0
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
612
        for record in stream:
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
613
            num_records += 1
3735.32.20 by John Arbash Meinel
groupcompress now copies the blocks exactly as they were given.
614
            self.assertEqual(block_bytes[record.key],
615
                             record._manager._block._z_content)
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
616
        self.assertEqual(8, num_records)
617
4665.3.9 by John Arbash Meinel
Start doing some work to make sure that we call _check_rebuild_block
618
    def test_insert_record_stream_packs_on_the_fly(self):
619
        vf = self.make_test_vf(True, dir='source')
620
        def grouped_stream(revision_ids, first_parents=()):
621
            parents = first_parents
622
            for revision_id in revision_ids:
623
                key = (revision_id,)
624
                record = versionedfile.FulltextContentFactory(
625
                    key, parents, None,
626
                    'some content that is\n'
627
                    'identical except for\n'
628
                    'revision_id:%s\n' % (revision_id,))
629
                yield record
630
                parents = (key,)
631
        # One group, a-d
632
        vf.insert_record_stream(grouped_stream(['a', 'b', 'c', 'd']))
633
        # Second group, e-h
634
        vf.insert_record_stream(grouped_stream(['e', 'f', 'g', 'h'],
635
                                               first_parents=(('d',),)))
636
        # Now copy the blocks into another vf, and see that the
637
        # insert_record_stream rebuilt a new block on-the-fly because of
638
        # under-utilization
639
        vf2 = self.make_test_vf(True, dir='target')
640
        vf2.insert_record_stream(vf.get_record_stream(
641
            [(r,) for r in 'abcdefgh'], 'groupcompress', False))
642
        stream = vf2.get_record_stream([(r,) for r in 'abcdefgh'],
643
                                       'groupcompress', False)
644
        vf2.writer.end()
645
        num_records = 0
646
        # All of the records should be recombined into a single block
647
        block = None
648
        for record in stream:
649
            num_records += 1
650
            if block is None:
651
                block = record._manager._block
652
            else:
653
                self.assertIs(block, record._manager._block)
654
        self.assertEqual(8, num_records)
655
3735.32.21 by John Arbash Meinel
We now have a 'reuse_blocks=False' flag for autopack et al.
656
    def test__insert_record_stream_no_reuse_block(self):
657
        vf = self.make_test_vf(True, dir='source')
658
        def grouped_stream(revision_ids, first_parents=()):
659
            parents = first_parents
660
            for revision_id in revision_ids:
661
                key = (revision_id,)
662
                record = versionedfile.FulltextContentFactory(
663
                    key, parents, None,
664
                    'some content that is\n'
665
                    'identical except for\n'
666
                    'revision_id:%s\n' % (revision_id,))
667
                yield record
668
                parents = (key,)
669
        # One group, a-d
670
        vf.insert_record_stream(grouped_stream(['a', 'b', 'c', 'd']))
671
        # Second group, e-h
672
        vf.insert_record_stream(grouped_stream(['e', 'f', 'g', 'h'],
673
                                               first_parents=(('d',),)))
674
        vf.writer.end()
675
        self.assertEqual(8, len(list(vf.get_record_stream(
676
                                        [(r,) for r in 'abcdefgh'],
677
                                        'unordered', False))))
678
        # Now copy the blocks into another vf, and ensure that the blocks are
679
        # preserved without creating new entries
680
        vf2 = self.make_test_vf(True, dir='target')
681
        # ordering in 'groupcompress' order, should actually swap the groups in
682
        # the target vf, but the groups themselves should not be disturbed.
683
        list(vf2._insert_record_stream(vf.get_record_stream(
684
            [(r,) for r in 'abcdefgh'], 'groupcompress', False),
685
            reuse_blocks=False))
686
        vf2.writer.end()
687
        # After inserting with reuse_blocks=False, we should have everything in
688
        # a single new block.
689
        stream = vf2.get_record_stream([(r,) for r in 'abcdefgh'],
690
                                       'groupcompress', False)
691
        block = None
692
        for record in stream:
693
            if block is None:
694
                block = record._manager._block
695
            else:
696
                self.assertIs(block, record._manager._block)
697
4343.3.20 by John Arbash Meinel
Copy the track_external_parent_refs tests over to GCVF.
698
    def test_add_missing_noncompression_parent_unvalidated_index(self):
699
        unvalidated = self.make_g_index_missing_parent()
700
        combined = _mod_index.CombinedGraphIndex([unvalidated])
701
        index = groupcompress._GCGraphIndex(combined,
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
702
            is_locked=lambda: True, parents=True,
703
            track_external_parent_refs=True)
4343.3.20 by John Arbash Meinel
Copy the track_external_parent_refs tests over to GCVF.
704
        index.scan_unvalidated_index(unvalidated)
705
        self.assertEqual(
706
            frozenset([('missing-parent',)]), index.get_missing_parents())
707
708
    def test_track_external_parent_refs(self):
709
        g_index = self.make_g_index('empty', 1, [])
710
        mod_index = btree_index.BTreeBuilder(1, 1)
711
        combined = _mod_index.CombinedGraphIndex([g_index, mod_index])
712
        index = groupcompress._GCGraphIndex(combined,
713
            is_locked=lambda: True, parents=True,
4343.3.21 by John Arbash Meinel
Implement get_missing_parents in terms of _KeyRefs.
714
            add_callback=mod_index.add_nodes,
715
            track_external_parent_refs=True)
4343.3.20 by John Arbash Meinel
Copy the track_external_parent_refs tests over to GCVF.
716
        index.add_records([
717
            (('new-key',), '2 10 2 10', [(('parent-1',), ('parent-2',))])])
718
        self.assertEqual(
719
            frozenset([('parent-1',), ('parent-2',)]),
720
            index.get_missing_parents())
721
4465.2.3 by Aaron Bentley
Update to change redundant inserts into a warning.
722
    def make_source_with_b(self, a_parent, path):
723
        source = self.make_test_vf(True, dir=path)
724
        source.add_lines(('a',), (), ['lines\n'])
725
        if a_parent:
726
            b_parents = (('a',),)
727
        else:
728
            b_parents = ()
729
        source.add_lines(('b',), b_parents, ['lines\n'])
730
        return source
731
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
732
    def do_inconsistent_inserts(self, inconsistency_fatal):
733
        target = self.make_test_vf(True, dir='target',
734
                                   inconsistency_fatal=inconsistency_fatal)
735
        for x in range(2):
736
            source = self.make_source_with_b(x==1, 'source%s' % x)
737
            target.insert_record_stream(source.get_record_stream(
738
                [('b',)], 'unordered', False))
739
4465.2.3 by Aaron Bentley
Update to change redundant inserts into a warning.
740
    def test_inconsistent_redundant_inserts_warn(self):
4465.2.2 by Aaron Bentley
Add test that duplicates are skipped.
741
        """Should not insert a record that is already present."""
4465.2.3 by Aaron Bentley
Update to change redundant inserts into a warning.
742
        warnings = []
743
        def warning(template, args):
744
            warnings.append(template % args)
745
        _trace_warning = trace.warning
746
        trace.warning = warning
747
        try:
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
748
            self.do_inconsistent_inserts(inconsistency_fatal=False)
4465.2.3 by Aaron Bentley
Update to change redundant inserts into a warning.
749
        finally:
750
            trace.warning = _trace_warning
751
        self.assertEqual(["inconsistent details in skipped record: ('b',)"
752
                          " ('42 32 0 8', ((),)) ('74 32 0 8', ((('a',),),))"],
753
                         warnings)
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
754
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
755
    def test_inconsistent_redundant_inserts_raises(self):
756
        e = self.assertRaises(errors.KnitCorrupt, self.do_inconsistent_inserts,
757
                              inconsistency_fatal=True)
758
        self.assertContainsRe(str(e), "Knit.* corrupt: inconsistent details"
759
                              " in add_records:"
760
                              " \('b',\) \('42 32 0 8', \(\(\),\)\) \('74 32"
761
                              " 0 8', \(\(\('a',\),\),\)\)")
762
4744.2.5 by John Arbash Meinel
Change to a generic 'VersionedFiles.clear_cache()' api.
763
    def test_clear_cache(self):
764
        vf = self.make_source_with_b(True, 'source')
765
        vf.writer.end()
766
        for record in vf.get_record_stream([('a',), ('b',)], 'unordered',
767
                                           True):
768
            pass
769
        self.assertTrue(len(vf._group_cache) > 0)
770
        vf.clear_cache()
771
        self.assertEqual(0, len(vf._group_cache))
772
773
5755.2.4 by John Arbash Meinel
Expose the max_entries_per_source into GroupCompressVersionedFiles
774
class TestGroupCompressConfig(tests.TestCaseWithTransport):
775
776
    def make_test_vf(self):
777
        t = self.get_transport('.')
778
        t.ensure_base()
779
        factory = groupcompress.make_pack_factory(graph=True,
780
            delta=False, keylength=1, inconsistency_fatal=True)
781
        vf = factory(t)
782
        self.addCleanup(groupcompress.cleanup_pack_group, vf)
783
        return vf
784
785
    def test_max_entries_per_source_default(self):
786
        vf = self.make_test_vf()
787
        gc = vf._make_group_compressor()
788
        self.assertEqual(vf._DEFAULT_MAX_ENTRIES_PER_SOURCE,
789
                         vf._max_entries_per_source)
790
        if isinstance(gc, groupcompress.PyrexGroupCompressor):
791
            self.assertEqual(vf._DEFAULT_MAX_ENTRIES_PER_SOURCE,
792
                             gc._delta_index._max_entries_per_source)
793
794
    def test_max_entries_per_source_in_config(self):
795
        c = config.GlobalConfig()
796
        c.set_user_option('bzr.groupcompress.max_entries_per_source', '10000')
797
        vf = self.make_test_vf()
798
        gc = vf._make_group_compressor()
799
        self.assertEqual(10000, vf._max_entries_per_source)
800
        if isinstance(gc, groupcompress.PyrexGroupCompressor):
801
            self.assertEqual(10000, gc._delta_index._max_entries_per_source)
802
803
    def test_max_entries_per_source_bad_config(self):
804
        c = config.GlobalConfig()
805
        c.set_user_option('bzr.groupcompress.max_entries_per_source', 'boogah')
806
        vf = self.make_test_vf()
807
        # TODO: This is triggering a warning, we might want to trap and make
808
        #       sure it is readable.
809
        gc = vf._make_group_compressor()
810
        self.assertEqual(vf._DEFAULT_MAX_ENTRIES_PER_SOURCE,
811
                         vf._max_entries_per_source)
812
        if isinstance(gc, groupcompress.PyrexGroupCompressor):
813
            self.assertEqual(vf._DEFAULT_MAX_ENTRIES_PER_SOURCE,
814
                             gc._delta_index._max_entries_per_source)
815
816
4465.2.4 by Aaron Bentley
Switch between warn and raise depending on inconsistent_fatal.
817
4634.3.20 by Andrew Bennetts
Some basic whitebox unit tests for _BatchingBlockFetcher.
818
class StubGCVF(object):
4634.3.21 by Andrew Bennetts
Direct tests now have complete line coverage of _BatchingBlockFetcher (except for the assertion).
819
    def __init__(self, canned_get_blocks=None):
4634.3.20 by Andrew Bennetts
Some basic whitebox unit tests for _BatchingBlockFetcher.
820
        self._group_cache = {}
4634.3.21 by Andrew Bennetts
Direct tests now have complete line coverage of _BatchingBlockFetcher (except for the assertion).
821
        self._canned_get_blocks = canned_get_blocks or []
822
    def _get_blocks(self, read_memos):
823
        return iter(self._canned_get_blocks)
4634.3.20 by Andrew Bennetts
Some basic whitebox unit tests for _BatchingBlockFetcher.
824
    
825
826
class Test_BatchingBlockFetcher(TestCaseWithGroupCompressVersionedFiles):
827
    """Simple whitebox unit tests for _BatchingBlockFetcher."""
828
    
829
    def test_add_key_new_read_memo(self):
830
        """Adding a key with an uncached read_memo new to this batch adds that
831
        read_memo to the list of memos to fetch.
832
        """
833
        # locations are: index_memo, ignored, parents, ignored
834
        # where index_memo is: (idx, offset, len, factory_start, factory_end)
835
        # and (idx, offset, size) is known as the 'read_memo', identifying the
836
        # raw bytes needed.
837
        read_memo = ('fake index', 100, 50)
838
        locations = {
839
            ('key',): (read_memo + (None, None), None, None, None)}
840
        batcher = groupcompress._BatchingBlockFetcher(StubGCVF(), locations)
841
        total_size = batcher.add_key(('key',))
842
        self.assertEqual(50, total_size)
843
        self.assertEqual([('key',)], batcher.keys)
844
        self.assertEqual([read_memo], batcher.memos_to_get)
845
846
    def test_add_key_duplicate_read_memo(self):
847
        """read_memos that occur multiple times in a batch will only be fetched
848
        once.
849
        """
850
        read_memo = ('fake index', 100, 50)
851
        # Two keys, both sharing the same read memo (but different overall
852
        # index_memos).
853
        locations = {
854
            ('key1',): (read_memo + (0, 1), None, None, None),
855
            ('key2',): (read_memo + (1, 2), None, None, None)}
856
        batcher = groupcompress._BatchingBlockFetcher(StubGCVF(), locations)
857
        total_size = batcher.add_key(('key1',))
858
        total_size = batcher.add_key(('key2',))
859
        self.assertEqual(50, total_size)
860
        self.assertEqual([('key1',), ('key2',)], batcher.keys)
861
        self.assertEqual([read_memo], batcher.memos_to_get)
862
863
    def test_add_key_cached_read_memo(self):
864
        """Adding a key with a cached read_memo will not cause that read_memo
865
        to be added to the list to fetch.
866
        """
867
        read_memo = ('fake index', 100, 50)
868
        gcvf = StubGCVF()
869
        gcvf._group_cache[read_memo] = 'fake block'
870
        locations = {
871
            ('key',): (read_memo + (None, None), None, None, None)}
872
        batcher = groupcompress._BatchingBlockFetcher(gcvf, locations)
873
        total_size = batcher.add_key(('key',))
874
        self.assertEqual(0, total_size)
875
        self.assertEqual([('key',)], batcher.keys)
876
        self.assertEqual([], batcher.memos_to_get)
877
4634.3.21 by Andrew Bennetts
Direct tests now have complete line coverage of _BatchingBlockFetcher (except for the assertion).
878
    def test_yield_factories_empty(self):
879
        """An empty batch yields no factories."""
880
        batcher = groupcompress._BatchingBlockFetcher(StubGCVF(), {})
881
        self.assertEqual([], list(batcher.yield_factories()))
882
883
    def test_yield_factories_calls_get_blocks(self):
4634.3.22 by Andrew Bennetts
Fix docstring.
884
        """Uncached memos are retrieved via get_blocks."""
4634.3.21 by Andrew Bennetts
Direct tests now have complete line coverage of _BatchingBlockFetcher (except for the assertion).
885
        read_memo1 = ('fake index', 100, 50)
886
        read_memo2 = ('fake index', 150, 40)
887
        gcvf = StubGCVF(
888
            canned_get_blocks=[
889
                (read_memo1, groupcompress.GroupCompressBlock()),
890
                (read_memo2, groupcompress.GroupCompressBlock())])
891
        locations = {
892
            ('key1',): (read_memo1 + (None, None), None, None, None),
893
            ('key2',): (read_memo2 + (None, None), None, None, None)}
894
        batcher = groupcompress._BatchingBlockFetcher(gcvf, locations)
895
        batcher.add_key(('key1',))
896
        batcher.add_key(('key2',))
897
        factories = list(batcher.yield_factories(full_flush=True))
898
        self.assertLength(2, factories)
899
        keys = [f.key for f in factories]
900
        kinds = [f.storage_kind for f in factories]
901
        self.assertEqual([('key1',), ('key2',)], keys)
902
        self.assertEqual(['groupcompress-block', 'groupcompress-block'], kinds)
903
904
    def test_yield_factories_flushing(self):
905
        """yield_factories holds back on yielding results from the final block
906
        unless passed full_flush=True.
907
        """
908
        fake_block = groupcompress.GroupCompressBlock()
909
        read_memo = ('fake index', 100, 50)
910
        gcvf = StubGCVF()
911
        gcvf._group_cache[read_memo] = fake_block
912
        locations = {
913
            ('key',): (read_memo + (None, None), None, None, None)}
914
        batcher = groupcompress._BatchingBlockFetcher(gcvf, locations)
915
        batcher.add_key(('key',))
916
        self.assertEqual([], list(batcher.yield_factories()))
917
        factories = list(batcher.yield_factories(full_flush=True))
918
        self.assertLength(1, factories)
919
        self.assertEqual(('key',), factories[0].key)
920
        self.assertEqual('groupcompress-block', factories[0].storage_kind)
921
4634.3.20 by Andrew Bennetts
Some basic whitebox unit tests for _BatchingBlockFetcher.
922
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
923
class TestLazyGroupCompress(tests.TestCaseWithTransport):
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
924
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
925
    _texts = {
926
        ('key1',): "this is a text\n"
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
927
                   "with a reasonable amount of compressible bytes\n"
928
                   "which can be shared between various other texts\n",
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
929
        ('key2',): "another text\n"
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
930
                   "with a reasonable amount of compressible bytes\n"
931
                   "which can be shared between various other texts\n",
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
932
        ('key3',): "yet another text which won't be extracted\n"
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
933
                   "with a reasonable amount of compressible bytes\n"
934
                   "which can be shared between various other texts\n",
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
935
        ('key4',): "this will be extracted\n"
3735.38.2 by John Arbash Meinel
Make the text for key4 slightly longer, rather than include key3.
936
                   "but references most of its bytes from\n"
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
937
                   "yet another text which won't be extracted\n"
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
938
                   "with a reasonable amount of compressible bytes\n"
939
                   "which can be shared between various other texts\n",
3735.32.14 by John Arbash Meinel
Move the tests over to testing the LazyGroupContentManager object.
940
    }
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
941
    def make_block(self, key_to_text):
942
        """Create a GroupCompressBlock, filling it with the given texts."""
943
        compressor = groupcompress.GroupCompressor()
944
        start = 0
945
        for key in sorted(key_to_text):
946
            compressor.compress(key, key_to_text[key], None)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
947
        locs = dict((key, (start, end)) for key, (start, _, end, _)
948
                    in compressor.labels_deltas.iteritems())
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
949
        block = compressor.flush()
950
        raw_bytes = block.to_bytes()
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
951
        return locs, groupcompress.GroupCompressBlock.from_bytes(raw_bytes)
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
952
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
953
    def add_key_to_manager(self, key, locations, block, manager):
954
        start, end = locations[key]
955
        manager.add_factory(key, (), start, end)
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
956
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
957
    def make_block_and_full_manager(self, texts):
958
        locations, block = self.make_block(texts)
959
        manager = groupcompress._LazyGroupContentManager(block)
960
        for key in sorted(texts):
961
            self.add_key_to_manager(key, locations, block, manager)
962
        return block, manager
963
3735.32.8 by John Arbash Meinel
Some tests for the LazyGroupCompressFactory
964
    def test_get_fulltexts(self):
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
965
        locations, block = self.make_block(self._texts)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
966
        manager = groupcompress._LazyGroupContentManager(block)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
967
        self.add_key_to_manager(('key1',), locations, block, manager)
968
        self.add_key_to_manager(('key2',), locations, block, manager)
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
969
        result_order = []
970
        for record in manager.get_record_stream():
971
            result_order.append(record.key)
972
            text = self._texts[record.key]
973
            self.assertEqual(text, record.get_bytes_as('fulltext'))
974
        self.assertEqual([('key1',), ('key2',)], result_order)
975
976
        # If we build the manager in the opposite order, we should get them
977
        # back in the opposite order
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
978
        manager = groupcompress._LazyGroupContentManager(block)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
979
        self.add_key_to_manager(('key2',), locations, block, manager)
980
        self.add_key_to_manager(('key1',), locations, block, manager)
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
981
        result_order = []
982
        for record in manager.get_record_stream():
983
            result_order.append(record.key)
984
            text = self._texts[record.key]
985
            self.assertEqual(text, record.get_bytes_as('fulltext'))
986
        self.assertEqual([('key2',), ('key1',)], result_order)
987
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
988
    def test__wire_bytes_no_keys(self):
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
989
        locations, block = self.make_block(self._texts)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
990
        manager = groupcompress._LazyGroupContentManager(block)
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
991
        wire_bytes = manager._wire_bytes()
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
992
        block_length = len(block.to_bytes())
3735.32.24 by John Arbash Meinel
_wire_bytes() now strips groups as necessary, as does _insert_record_stream
993
        # We should have triggered a strip, since we aren't using any content
994
        stripped_block = manager._block.to_bytes()
995
        self.assertTrue(block_length > len(stripped_block))
996
        empty_z_header = zlib.compress('')
997
        self.assertEqual('groupcompress-block\n'
998
                         '8\n' # len(compress(''))
999
                         '0\n' # len('')
1000
                         '%d\n'# compressed block len
1001
                         '%s'  # zheader
1002
                         '%s'  # block
1003
                         % (len(stripped_block), empty_z_header,
1004
                            stripped_block),
1005
                         wire_bytes)
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
1006
3735.32.15 by John Arbash Meinel
Change the GroupCompressBlock code to allow not recording 'end'.
1007
    def test__wire_bytes(self):
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1008
        locations, block = self.make_block(self._texts)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1009
        manager = groupcompress._LazyGroupContentManager(block)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1010
        self.add_key_to_manager(('key1',), locations, block, manager)
1011
        self.add_key_to_manager(('key4',), locations, block, manager)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1012
        block_bytes = block.to_bytes()
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
1013
        wire_bytes = manager._wire_bytes()
1014
        (storage_kind, z_header_len, header_len,
1015
         block_len, rest) = wire_bytes.split('\n', 4)
1016
        z_header_len = int(z_header_len)
1017
        header_len = int(header_len)
1018
        block_len = int(block_len)
1019
        self.assertEqual('groupcompress-block', storage_kind)
4665.3.8 by John Arbash Meinel
Of course, when you change the content, it can effect the stored wire bytes slightly.
1020
        self.assertEqual(34, z_header_len)
1021
        self.assertEqual(26, header_len)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1022
        self.assertEqual(len(block_bytes), block_len)
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
1023
        z_header = rest[:z_header_len]
1024
        header = zlib.decompress(z_header)
1025
        self.assertEqual(header_len, len(header))
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1026
        entry1 = locations[('key1',)]
1027
        entry4 = locations[('key4',)]
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
1028
        self.assertEqualDiff('key1\n'
1029
                             '\n'  # no parents
1030
                             '%d\n' # start offset
3735.38.2 by John Arbash Meinel
Make the text for key4 slightly longer, rather than include key3.
1031
                             '%d\n' # end offset
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
1032
                             'key4\n'
1033
                             '\n'
1034
                             '%d\n'
1035
                             '%d\n'
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1036
                             % (entry1[0], entry1[1],
1037
                                entry4[0], entry4[1]),
3735.32.16 by John Arbash Meinel
We now have a general header for the GC block.
1038
                            header)
1039
        z_block = rest[z_header_len:]
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1040
        self.assertEqual(block_bytes, z_block)
1041
1042
    def test_from_bytes(self):
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1043
        locations, block = self.make_block(self._texts)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1044
        manager = groupcompress._LazyGroupContentManager(block)
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1045
        self.add_key_to_manager(('key1',), locations, block, manager)
1046
        self.add_key_to_manager(('key4',), locations, block, manager)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1047
        wire_bytes = manager._wire_bytes()
1048
        self.assertStartsWith(wire_bytes, 'groupcompress-block\n')
3735.32.18 by John Arbash Meinel
We now support generating a network stream.
1049
        manager = groupcompress._LazyGroupContentManager.from_bytes(wire_bytes)
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1050
        self.assertIsInstance(manager, groupcompress._LazyGroupContentManager)
3735.38.2 by John Arbash Meinel
Make the text for key4 slightly longer, rather than include key3.
1051
        self.assertEqual(2, len(manager._factories))
3735.32.17 by John Arbash Meinel
We now round-trip the wire_bytes.
1052
        self.assertEqual(block._z_content, manager._block._z_content)
1053
        result_order = []
1054
        for record in manager.get_record_stream():
1055
            result_order.append(record.key)
1056
            text = self._texts[record.key]
1057
            self.assertEqual(text, record.get_bytes_as('fulltext'))
3735.38.2 by John Arbash Meinel
Make the text for key4 slightly longer, rather than include key3.
1058
        self.assertEqual([('key1',), ('key4',)], result_order)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
1059
1060
    def test__check_rebuild_no_changes(self):
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
1061
        block, manager = self.make_block_and_full_manager(self._texts)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
1062
        manager._check_rebuild_block()
1063
        self.assertIs(block, manager._block)
1064
1065
    def test__check_rebuild_only_one(self):
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1066
        locations, block = self.make_block(self._texts)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
1067
        manager = groupcompress._LazyGroupContentManager(block)
1068
        # Request just the first key, which should trigger a 'strip' action
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1069
        self.add_key_to_manager(('key1',), locations, block, manager)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
1070
        manager._check_rebuild_block()
1071
        self.assertIsNot(block, manager._block)
1072
        self.assertTrue(block._content_length > manager._block._content_length)
1073
        # We should be able to still get the content out of this block, though
1074
        # it should only have 1 entry
1075
        for record in manager.get_record_stream():
1076
            self.assertEqual(('key1',), record.key)
1077
            self.assertEqual(self._texts[record.key],
1078
                             record.get_bytes_as('fulltext'))
1079
1080
    def test__check_rebuild_middle(self):
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1081
        locations, block = self.make_block(self._texts)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
1082
        manager = groupcompress._LazyGroupContentManager(block)
1083
        # Request a small key in the middle should trigger a 'rebuild'
3735.40.18 by John Arbash Meinel
Get rid of the entries dict in GroupCompressBlock.
1084
        self.add_key_to_manager(('key4',), locations, block, manager)
3735.32.23 by John Arbash Meinel
Add a _LazyGroupContentManager._check_rebuild_block
1085
        manager._check_rebuild_block()
1086
        self.assertIsNot(block, manager._block)
1087
        self.assertTrue(block._content_length > manager._block._content_length)
1088
        for record in manager.get_record_stream():
1089
            self.assertEqual(('key4',), record.key)
1090
            self.assertEqual(self._texts[record.key],
1091
                             record.get_bytes_as('fulltext'))
4665.3.7 by John Arbash Meinel
We needed a bit more data to actually get groups doing delta-compression.
1092
1093
    def test_check_is_well_utilized_all_keys(self):
1094
        block, manager = self.make_block_and_full_manager(self._texts)
1095
        self.assertFalse(manager.check_is_well_utilized())
1096
        # Though we can fake it by changing the recommended minimum size
1097
        manager._full_enough_block_size = block._content_length
1098
        self.assertTrue(manager.check_is_well_utilized())
1099
        # Setting it just above causes it to fail
1100
        manager._full_enough_block_size = block._content_length + 1
1101
        self.assertFalse(manager.check_is_well_utilized())
1102
        # Setting the mixed-block size doesn't do anything, because the content
1103
        # is considered to not be 'mixed'
1104
        manager._full_enough_mixed_block_size = block._content_length
1105
        self.assertFalse(manager.check_is_well_utilized())
1106
1107
    def test_check_is_well_utilized_mixed_keys(self):
1108
        texts = {}
1109
        f1k1 = ('f1', 'k1')
1110
        f1k2 = ('f1', 'k2')
1111
        f2k1 = ('f2', 'k1')
1112
        f2k2 = ('f2', 'k2')
1113
        texts[f1k1] = self._texts[('key1',)]
1114
        texts[f1k2] = self._texts[('key2',)]
1115
        texts[f2k1] = self._texts[('key3',)]
1116
        texts[f2k2] = self._texts[('key4',)]
1117
        block, manager = self.make_block_and_full_manager(texts)
1118
        self.assertFalse(manager.check_is_well_utilized())
1119
        manager._full_enough_block_size = block._content_length
1120
        self.assertTrue(manager.check_is_well_utilized())
1121
        manager._full_enough_block_size = block._content_length + 1
1122
        self.assertFalse(manager.check_is_well_utilized())
1123
        manager._full_enough_mixed_block_size = block._content_length
1124
        self.assertTrue(manager.check_is_well_utilized())
1125
1126
    def test_check_is_well_utilized_partial_use(self):
1127
        locations, block = self.make_block(self._texts)
1128
        manager = groupcompress._LazyGroupContentManager(block)
1129
        manager._full_enough_block_size = block._content_length
1130
        self.add_key_to_manager(('key1',), locations, block, manager)
1131
        self.add_key_to_manager(('key2',), locations, block, manager)
1132
        # Just using the content from key1 and 2 is not enough to be considered
1133
        # 'complete'
1134
        self.assertFalse(manager.check_is_well_utilized())
1135
        # However if we add key3, then we have enough, as we only require 75%
1136
        # consumption
1137
        self.add_key_to_manager(('key4',), locations, block, manager)
1138
        self.assertTrue(manager.check_is_well_utilized())
5365.4.1 by John Arbash Meinel
Find a case where we are wasting a bit of memory.
1139
1140
1141
class Test_GCBuildDetails(tests.TestCase):
1142
1143
    def test_acts_like_tuple(self):
1144
        # _GCBuildDetails inlines some of the data that used to be spread out
1145
        # across a bunch of tuples
1146
        bd = groupcompress._GCBuildDetails((('parent1',), ('parent2',)),
1147
            ('INDEX', 10, 20, 0, 5))
1148
        self.assertEqual(4, len(bd))
1149
        self.assertEqual(('INDEX', 10, 20, 0, 5), bd[0])
1150
        self.assertEqual(None, bd[1]) # Compression Parent is always None
1151
        self.assertEqual((('parent1',), ('parent2',)), bd[2])
1152
        self.assertEqual(('group', None), bd[3]) # Record details
1153
1154
    def test__repr__(self):
1155
        bd = groupcompress._GCBuildDetails((('parent1',), ('parent2',)),
1156
            ('INDEX', 10, 20, 0, 5))
1157
        self.assertEqual("_GCBuildDetails(('INDEX', 10, 20, 0, 5),"
1158
                         " (('parent1',), ('parent2',)))",
1159
                         repr(bd))
1160