/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4634.170.1 by John Arbash Meinel
Fix bug #437003. Autopacking should not fail for an
1
# Copyright (C) 2006-2011 Canonical Ltd
1685.1.63 by Martin Pool
Small Transport fixups
2
#
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
1685.1.63 by Martin Pool
Small Transport fixups
7
#
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
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.
1685.1.63 by Martin Pool
Small Transport fixups
12
#
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
16
17
"""Tests for the Repository facility that are not interface tests.
18
3689.1.4 by John Arbash Meinel
Doc strings that reference repository_implementations
19
For interface tests see tests/per_repository/*.py.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
20
21
For concrete class tests see this file, and for storage formats tests
22
also see this file.
23
"""
24
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
25
from stat import S_ISDIR
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
26
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
27
import bzrlib
5651.3.1 by Jelmer Vernooij
Add RepositoryFormatRegistry.
28
from bzrlib.errors import (
29
    UnknownFormatError,
30
    UnsupportedFormatError,
31
    )
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
32
from bzrlib import (
5365.5.20 by John Arbash Meinel
Add some tests that check the leaf factory is correct.
33
    btree_index,
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
34
    graph,
5651.3.2 by Jelmer Vernooij
Fix deprecation warnings in test suite.
35
    symbol_versioning,
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
36
    tests,
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
37
    transport,
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
38
    )
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
39
from bzrlib.btree_index import BTreeBuilder, BTreeGraphIndex
5121.2.2 by Jelmer Vernooij
Remove more unused imports in the tests.
40
from bzrlib.index import GraphIndex
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
41
from bzrlib.repository import RepositoryFormat
2670.3.5 by Andrew Bennetts
Remove get_stream_as_bytes from KnitVersionedFile's API, make it a function in knitrepo.py instead.
42
from bzrlib.tests import (
43
    TestCase,
44
    TestCaseWithTransport,
45
    )
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
46
from bzrlib import (
2535.3.41 by Andrew Bennetts
Add tests for InterRemoteToOther.is_compatible.
47
    bzrdir,
48
    errors,
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
49
    inventory,
2929.3.5 by Vincent Ladeuil
New files, same warnings, same fixes.
50
    osutils,
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
51
    repository,
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
52
    revision as _mod_revision,
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
53
    upgrade,
4634.126.1 by John Arbash Meinel
(jam) Fix bug #507566, concurrent autopacking correctness.
54
    versionedfile,
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
55
    workingtree,
56
    )
3735.42.5 by John Arbash Meinel
Change the tests so we now just use a direct test that _get_source is
57
from bzrlib.repofmt import (
58
    groupcompress_repo,
59
    knitrepo,
60
    pack_repo,
61
    )
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
62
63
64
class TestDefaultFormat(TestCase):
65
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
66
    def test_get_set_default_format(self):
2204.5.3 by Aaron Bentley
zap old repository default handling
67
        old_default = bzrdir.format_registry.get('default')
68
        private_default = old_default().repository_format.__class__
5651.3.2 by Jelmer Vernooij
Fix deprecation warnings in test suite.
69
        old_format = repository.format_registry.get_default()
1910.2.33 by Aaron Bentley
Fix default format test
70
        self.assertTrue(isinstance(old_format, private_default))
2204.5.3 by Aaron Bentley
zap old repository default handling
71
        def make_sample_bzrdir():
72
            my_bzrdir = bzrdir.BzrDirMetaFormat1()
73
            my_bzrdir.repository_format = SampleRepositoryFormat()
74
            return my_bzrdir
75
        bzrdir.format_registry.remove('default')
76
        bzrdir.format_registry.register('sample', make_sample_bzrdir, '')
77
        bzrdir.format_registry.set_default('sample')
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
78
        # creating a repository should now create an instrumented dir.
79
        try:
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
80
            # the default branch format is used by the meta dir format
81
            # which is not the default bzrdir format at this point
1685.1.63 by Martin Pool
Small Transport fixups
82
            dir = bzrdir.BzrDirMetaFormat1().initialize('memory:///')
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
83
            result = dir.create_repository()
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
84
            self.assertEqual(result, 'A bzr repository dir')
2241.1.1 by Martin Pool
Change RepositoryFormat to use a Registry rather than ad-hoc dictionary
85
        finally:
2204.5.3 by Aaron Bentley
zap old repository default handling
86
            bzrdir.format_registry.remove('default')
2363.5.14 by Aaron Bentley
Prevent repository.get_set_default_format from corrupting inventory
87
            bzrdir.format_registry.remove('sample')
2204.5.3 by Aaron Bentley
zap old repository default handling
88
            bzrdir.format_registry.register('default', old_default, '')
5651.3.2 by Jelmer Vernooij
Fix deprecation warnings in test suite.
89
        self.assertIsInstance(repository.format_registry.get_default(),
2204.5.3 by Aaron Bentley
zap old repository default handling
90
                              old_format.__class__)
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
91
92
93
class SampleRepositoryFormat(repository.RepositoryFormat):
94
    """A sample format
95
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
96
    this format is initializable, unsupported to aid in testing the
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
97
    open and open(unsupported=True) routines.
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
98
    """
99
100
    def get_format_string(self):
101
        """See RepositoryFormat.get_format_string()."""
102
        return "Sample .bzr repository format."
103
1534.6.1 by Robert Collins
allow API creation of shared repositories
104
    def initialize(self, a_bzrdir, shared=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
105
        """Initialize a repository in a BzrDir"""
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
106
        t = a_bzrdir.get_repository_transport(self)
1955.3.13 by John Arbash Meinel
Run the full test suite, and fix up any deprecation warnings.
107
        t.put_bytes('format', self.get_format_string())
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
108
        return 'A bzr repository dir'
109
110
    def is_supported(self):
111
        return False
112
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
113
    def open(self, a_bzrdir, _found=False):
1534.4.40 by Robert Collins
Add RepositoryFormats and allow bzrdir.open or create _repository to be used.
114
        return "opened repository."
1534.4.41 by Robert Collins
Branch now uses BzrDir reasonably sanely.
115
116
5651.3.5 by Jelmer Vernooij
add tests for 'extra' repository formats.
117
class SampleExtraRepositoryFormat(repository.RepositoryFormat):
118
    """A sample format that can not be used in a metadir
119
120
    """
121
122
    def get_format_string(self):
123
        raise NotImplementedError
124
125
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
126
class TestRepositoryFormat(TestCaseWithTransport):
127
    """Tests for the Repository format detection used by the bzr meta dir facility.BzrBranchFormat facility."""
128
129
    def test_find_format(self):
130
        # is the right format object found for a repository?
131
        # create a branch with a few known format objects.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
132
        # this is not quite the same as
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
133
        self.build_tree(["foo/", "bar/"])
134
        def check_format(format, url):
135
            dir = format._matchingbzrdir.initialize(url)
136
            format.initialize(dir)
5609.9.1 by Martin
Blindly change all users of get_transport to address the function via the transport module
137
            t = transport.get_transport(url)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
138
            found_format = repository.RepositoryFormat.find_format(dir)
139
            self.failUnless(isinstance(found_format, format.__class__))
5582.10.54 by Jelmer Vernooij
Use default format rather than RepositoryFormat7.
140
        check_format(repository.format_registry.get_default(), "bar")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
141
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
142
    def test_find_format_no_repository(self):
143
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
144
        self.assertRaises(errors.NoRepositoryPresent,
145
                          repository.RepositoryFormat.find_format,
146
                          dir)
147
148
    def test_find_format_unknown_format(self):
149
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
150
        SampleRepositoryFormat().initialize(dir)
151
        self.assertRaises(UnknownFormatError,
152
                          repository.RepositoryFormat.find_format,
153
                          dir)
154
155
    def test_register_unregister_format(self):
5651.3.1 by Jelmer Vernooij
Add RepositoryFormatRegistry.
156
        # Test deprecated format registration functions
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
157
        format = SampleRepositoryFormat()
158
        # make a control dir
159
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
160
        # make a repo
161
        format.initialize(dir)
162
        # register a format for it.
5651.3.2 by Jelmer Vernooij
Fix deprecation warnings in test suite.
163
        self.applyDeprecated(symbol_versioning.deprecated_in((2, 4, 0)),
164
            repository.RepositoryFormat.register_format, format)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
165
        # which repository.Open will refuse (not supported)
5651.3.1 by Jelmer Vernooij
Add RepositoryFormatRegistry.
166
        self.assertRaises(UnsupportedFormatError, repository.Repository.open,
167
            self.get_url())
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
168
        # but open(unsupported) will work
169
        self.assertEqual(format.open(dir), "opened repository.")
170
        # unregister the format
5651.3.2 by Jelmer Vernooij
Fix deprecation warnings in test suite.
171
        self.applyDeprecated(symbol_versioning.deprecated_in((2, 4, 0)),
172
            repository.RepositoryFormat.unregister_format, format)
1534.4.47 by Robert Collins
Split out repository into .bzr/repository
173
174
5651.3.1 by Jelmer Vernooij
Add RepositoryFormatRegistry.
175
class TestRepositoryFormatRegistry(TestCase):
176
177
    def setUp(self):
178
        super(TestRepositoryFormatRegistry, self).setUp()
179
        self.registry = repository.RepositoryFormatRegistry()
180
181
    def test_register_unregister_format(self):
182
        format = SampleRepositoryFormat()
183
        self.registry.register(format)
184
        self.assertEquals(format, self.registry.get("Sample .bzr repository format."))
185
        self.registry.remove(format)
186
        self.assertRaises(KeyError, self.registry.get, "Sample .bzr repository format.")
187
5651.3.2 by Jelmer Vernooij
Fix deprecation warnings in test suite.
188
    def test_get_all(self):
5651.3.1 by Jelmer Vernooij
Add RepositoryFormatRegistry.
189
        format = SampleRepositoryFormat()
5651.3.7 by Jelmer Vernooij
Fix tests.
190
        self.assertEquals([], self.registry._get_all())
5651.3.1 by Jelmer Vernooij
Add RepositoryFormatRegistry.
191
        self.registry.register(format)
5651.3.7 by Jelmer Vernooij
Fix tests.
192
        self.assertEquals([format], self.registry._get_all())
5651.3.5 by Jelmer Vernooij
add tests for 'extra' repository formats.
193
194
    def test_register_extra(self):
195
        format = SampleExtraRepositoryFormat()
5651.3.7 by Jelmer Vernooij
Fix tests.
196
        self.assertEquals([], self.registry._get_all())
5651.3.5 by Jelmer Vernooij
add tests for 'extra' repository formats.
197
        self.registry.register_extra(format)
5651.3.7 by Jelmer Vernooij
Fix tests.
198
        self.assertEquals([format], self.registry._get_all())
5651.3.5 by Jelmer Vernooij
add tests for 'extra' repository formats.
199
200
    def test_register_extra_lazy(self):
5651.3.7 by Jelmer Vernooij
Fix tests.
201
        self.assertEquals([], self.registry._get_all())
5651.3.5 by Jelmer Vernooij
add tests for 'extra' repository formats.
202
        self.registry.register_extra_lazy("bzrlib.tests.test_repository",
203
            "SampleExtraRepositoryFormat")
5651.3.7 by Jelmer Vernooij
Fix tests.
204
        formats = self.registry._get_all()
5651.3.5 by Jelmer Vernooij
add tests for 'extra' repository formats.
205
        self.assertEquals(1, len(formats))
206
        self.assertIsInstance(formats[0], SampleExtraRepositoryFormat)
5651.3.1 by Jelmer Vernooij
Add RepositoryFormatRegistry.
207
208
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
209
class TestFormatKnit1(TestCaseWithTransport):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
210
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
211
    def test_attribute__fetch_order(self):
212
        """Knits need topological data insertion."""
213
        repo = self.make_repository('.',
214
                format=bzrdir.format_registry.get('knit')())
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
215
        self.assertEqual('topological', repo._format._fetch_order)
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
216
217
    def test_attribute__fetch_uses_deltas(self):
218
        """Knits reuse deltas."""
219
        repo = self.make_repository('.',
220
                format=bzrdir.format_registry.get('knit')())
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
221
        self.assertEqual(True, repo._format._fetch_uses_deltas)
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
222
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
223
    def test_disk_layout(self):
224
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
225
        repo = knitrepo.RepositoryFormatKnit1().initialize(control)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
226
        # in case of side effects of locking.
227
        repo.lock_write()
228
        repo.unlock()
229
        # we want:
230
        # format 'Bazaar-NG Knit Repository Format 1'
1553.5.62 by Martin Pool
Add tests that MetaDir repositories use LockDirs
231
        # lock: is a directory
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
232
        # inventory.weave == empty_weave
233
        # empty revision-store directory
234
        # empty weaves directory
235
        t = control.get_repository_transport(None)
236
        self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
237
                             t.get('format').read())
1553.5.57 by Martin Pool
[merge] sync from bzr.dev
238
        # XXX: no locks left when unlocked at the moment
239
        # self.assertEqualDiff('', t.get('lock').read())
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
240
        self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
241
        self.check_knits(t)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
242
        # Check per-file knits.
243
        branch = control.create_branch()
244
        tree = control.create_workingtree()
245
        tree.add(['foo'], ['Nasty-IdC:'], ['file'])
246
        tree.put_file_bytes_non_atomic('Nasty-IdC:', '')
247
        tree.commit('1st post', rev_id='foo')
248
        self.assertHasKnit(t, 'knits/e8/%254easty-%2549d%2543%253a',
249
            '\nfoo fulltext 0 81  :')
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
250
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
251
    def assertHasKnit(self, t, knit_name, extra_content=''):
1654.1.3 by Robert Collins
Refactor repository knit tests slightly to remove duplication - add a assertHasKnit method.
252
        """Assert that knit_name exists on t."""
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
253
        self.assertEqualDiff('# bzr knit index 8\n' + extra_content,
1654.1.3 by Robert Collins
Refactor repository knit tests slightly to remove duplication - add a assertHasKnit method.
254
                             t.get(knit_name + '.kndx').read())
255
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
256
    def check_knits(self, t):
257
        """check knit content for a repository."""
1654.1.3 by Robert Collins
Refactor repository knit tests slightly to remove duplication - add a assertHasKnit method.
258
        self.assertHasKnit(t, 'inventory')
259
        self.assertHasKnit(t, 'revisions')
260
        self.assertHasKnit(t, 'signatures')
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
261
262
    def test_shared_disk_layout(self):
263
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
264
        repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
265
        # we want:
266
        # format 'Bazaar-NG Knit Repository Format 1'
1553.5.62 by Martin Pool
Add tests that MetaDir repositories use LockDirs
267
        # lock: is a directory
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
268
        # inventory.weave == empty_weave
269
        # empty revision-store directory
270
        # empty weaves directory
271
        # a 'shared-storage' marker file.
272
        t = control.get_repository_transport(None)
273
        self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
274
                             t.get('format').read())
1553.5.57 by Martin Pool
[merge] sync from bzr.dev
275
        # XXX: no locks left when unlocked at the moment
276
        # self.assertEqualDiff('', t.get('lock').read())
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
277
        self.assertEqualDiff('', t.get('shared-storage').read())
278
        self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
279
        self.check_knits(t)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
280
281
    def test_shared_no_tree_disk_layout(self):
282
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
283
        repo = knitrepo.RepositoryFormatKnit1().initialize(control, shared=True)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
284
        repo.set_make_working_trees(False)
285
        # we want:
286
        # format 'Bazaar-NG Knit Repository Format 1'
287
        # lock ''
288
        # inventory.weave == empty_weave
289
        # empty revision-store directory
290
        # empty weaves directory
291
        # a 'shared-storage' marker file.
292
        t = control.get_repository_transport(None)
293
        self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
294
                             t.get('format').read())
1553.5.57 by Martin Pool
[merge] sync from bzr.dev
295
        # XXX: no locks left when unlocked at the moment
296
        # self.assertEqualDiff('', t.get('lock').read())
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
297
        self.assertEqualDiff('', t.get('shared-storage').read())
298
        self.assertEqualDiff('', t.get('no-working-trees').read())
299
        repo.set_make_working_trees(True)
300
        self.assertFalse(t.has('no-working-trees'))
301
        self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
1563.2.35 by Robert Collins
cleanup deprecation warnings and finish conversion so the inventory is knit based too.
302
        self.check_knits(t)
1556.1.3 by Robert Collins
Rearrangment of Repository logic to be less type code driven, and bugfix InterRepository.missing_revision_ids
303
2917.2.1 by John Arbash Meinel
Fix bug #152360. The xml5 serializer should be using
304
    def test_deserialise_sets_root_revision(self):
305
        """We must have a inventory.root.revision
306
307
        Old versions of the XML5 serializer did not set the revision_id for
308
        the whole inventory. So we grab the one from the expected text. Which
309
        is valid when the api is not being abused.
310
        """
311
        repo = self.make_repository('.',
312
                format=bzrdir.format_registry.get('knit')())
313
        inv_xml = '<inventory format="5">\n</inventory>\n'
4988.3.3 by Jelmer Vernooij
rename Repository.deserialise_inventory to Repository._deserialise_inventory.
314
        inv = repo._deserialise_inventory('test-rev-id', inv_xml)
2917.2.1 by John Arbash Meinel
Fix bug #152360. The xml5 serializer should be using
315
        self.assertEqual('test-rev-id', inv.root.revision)
316
317
    def test_deserialise_uses_global_revision_id(self):
318
        """If it is set, then we re-use the global revision id"""
319
        repo = self.make_repository('.',
320
                format=bzrdir.format_registry.get('knit')())
321
        inv_xml = ('<inventory format="5" revision_id="other-rev-id">\n'
322
                   '</inventory>\n')
323
        # Arguably, the deserialise_inventory should detect a mismatch, and
324
        # raise an error, rather than silently using one revision_id over the
325
        # other.
4988.3.3 by Jelmer Vernooij
rename Repository.deserialise_inventory to Repository._deserialise_inventory.
326
        self.assertRaises(AssertionError, repo._deserialise_inventory,
3169.2.2 by Robert Collins
Add a test to Repository.deserialise_inventory that the resulting ivnentory is the one asked for, and update relevant tests. Also tweak the model 1 to 2 regenerate inventories logic to use the revision trees parent marker which is more accurate in some cases.
327
            'test-rev-id', inv_xml)
4988.3.3 by Jelmer Vernooij
rename Repository.deserialise_inventory to Repository._deserialise_inventory.
328
        inv = repo._deserialise_inventory('other-rev-id', inv_xml)
2917.2.1 by John Arbash Meinel
Fix bug #152360. The xml5 serializer should be using
329
        self.assertEqual('other-rev-id', inv.root.revision)
330
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
331
    def test_supports_external_lookups(self):
332
        repo = self.make_repository('.',
333
                format=bzrdir.format_registry.get('knit')())
334
        self.assertFalse(repo._format.supports_external_lookups)
335
2535.3.53 by Andrew Bennetts
Remove get_stream_as_bytes from KnitVersionedFile's API, make it a function in knitrepo.py instead.
336
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
337
class DummyRepository(object):
338
    """A dummy repository for testing."""
339
3452.2.11 by Andrew Bennetts
Merge thread.
340
    _format = None
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
341
    _serializer = None
342
343
    def supports_rich_root(self):
4606.4.1 by Robert Collins
Prepare test_repository's inter_repository tests for 2a.
344
        if self._format is not None:
345
            return self._format.rich_root_data
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
346
        return False
347
3709.5.10 by Andrew Bennetts
Fix test failure caused by missing attributes on DummyRepository.
348
    def get_graph(self):
349
        raise NotImplementedError
350
351
    def get_parent_map(self, revision_ids):
352
        raise NotImplementedError
353
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
354
355
class InterDummy(repository.InterRepository):
356
    """An inter-repository optimised code path for DummyRepository.
357
358
    This is for use during testing where we use DummyRepository as repositories
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
359
    so that none of the default regsitered inter-repository classes will
2818.4.2 by Robert Collins
Review feedback.
360
    MATCH.
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
361
    """
362
363
    @staticmethod
364
    def is_compatible(repo_source, repo_target):
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
365
        """InterDummy is compatible with DummyRepository."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
366
        return (isinstance(repo_source, DummyRepository) and
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
367
            isinstance(repo_target, DummyRepository))
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
368
369
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
370
class TestInterRepository(TestCaseWithTransport):
371
372
    def test_get_default_inter_repository(self):
373
        # test that the InterRepository.get(repo_a, repo_b) probes
374
        # for a inter_repo class where is_compatible(repo_a, repo_b) returns
375
        # true and returns a default inter_repo otherwise.
376
        # This also tests that the default registered optimised interrepository
377
        # classes do not barf inappropriately when a surprising repository type
378
        # is handed to them.
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
379
        dummy_a = DummyRepository()
380
        dummy_b = DummyRepository()
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
381
        self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
382
383
    def assertGetsDefaultInterRepository(self, repo_a, repo_b):
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
384
        """Asserts that InterRepository.get(repo_a, repo_b) -> the default.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
385
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
386
        The effective default is now InterSameDataRepository because there is
387
        no actual sane default in the presence of incompatible data models.
388
        """
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
389
        inter_repo = repository.InterRepository.get(repo_a, repo_b)
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
390
        self.assertEqual(repository.InterSameDataRepository,
1534.1.27 by Robert Collins
Start InterRepository with InterRepository.get.
391
                         inter_repo.__class__)
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
392
        self.assertEqual(repo_a, inter_repo.source)
393
        self.assertEqual(repo_b, inter_repo.target)
394
395
    def test_register_inter_repository_class(self):
396
        # test that a optimised code path provider - a
397
        # InterRepository subclass can be registered and unregistered
398
        # and that it is correctly selected when given a repository
399
        # pair that it returns true on for the is_compatible static method
400
        # check
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
401
        dummy_a = DummyRepository()
4606.4.1 by Robert Collins
Prepare test_repository's inter_repository tests for 2a.
402
        dummy_a._format = RepositoryFormat()
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
403
        dummy_b = DummyRepository()
4606.4.1 by Robert Collins
Prepare test_repository's inter_repository tests for 2a.
404
        dummy_b._format = RepositoryFormat()
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
405
        repo = self.make_repository('.')
406
        # hack dummies to look like repo somewhat.
407
        dummy_a._serializer = repo._serializer
4606.4.1 by Robert Collins
Prepare test_repository's inter_repository tests for 2a.
408
        dummy_a._format.supports_tree_reference = repo._format.supports_tree_reference
409
        dummy_a._format.rich_root_data = repo._format.rich_root_data
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
410
        dummy_b._serializer = repo._serializer
4606.4.1 by Robert Collins
Prepare test_repository's inter_repository tests for 2a.
411
        dummy_b._format.supports_tree_reference = repo._format.supports_tree_reference
412
        dummy_b._format.rich_root_data = repo._format.rich_root_data
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
413
        repository.InterRepository.register_optimiser(InterDummy)
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
414
        try:
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
415
            # we should get the default for something InterDummy returns False
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
416
            # to
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
417
            self.assertFalse(InterDummy.is_compatible(dummy_a, repo))
418
            self.assertGetsDefaultInterRepository(dummy_a, repo)
419
            # and we should get an InterDummy for a pair it 'likes'
420
            self.assertTrue(InterDummy.is_compatible(dummy_a, dummy_b))
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
421
            inter_repo = repository.InterRepository.get(dummy_a, dummy_b)
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
422
            self.assertEqual(InterDummy, inter_repo.__class__)
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
423
            self.assertEqual(dummy_a, inter_repo.source)
424
            self.assertEqual(dummy_b, inter_repo.target)
425
        finally:
2305.2.3 by Andrew Bennetts
Bring across test_repository improvements from the hpss branch to fix the last test failures.
426
            repository.InterRepository.unregister_optimiser(InterDummy)
1534.1.28 by Robert Collins
Allow for optimised InterRepository selection.
427
        # now we should get the default InterRepository object again.
428
        self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
1534.1.33 by Robert Collins
Move copy_content_into into InterRepository and InterWeaveRepo, and disable the default codepath test as we have optimised paths for all current combinations.
429
2241.1.17 by Martin Pool
Restore old InterWeave tests
430
5671.4.2 by Jelmer Vernooij
Use stub formats to test CopyConverter.
431
class TestRepositoryFormat1(knitrepo.RepositoryFormatKnit1):
432
433
    def get_format_string(self):
434
        return "Test Format 1"
435
436
437
class TestRepositoryFormat2(knitrepo.RepositoryFormatKnit1):
438
439
    def get_format_string(self):
440
        return "Test Format 2"
441
442
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
443
class TestRepositoryConverter(TestCaseWithTransport):
444
445
    def test_convert_empty(self):
5671.4.2 by Jelmer Vernooij
Use stub formats to test CopyConverter.
446
        source_format = TestRepositoryFormat1()
447
        target_format = TestRepositoryFormat2()
448
        repository.format_registry.register(source_format)
449
        self.addCleanup(repository.format_registry.remove,
450
            source_format)
451
        repository.format_registry.register(target_format)
452
        self.addCleanup(repository.format_registry.remove,
453
            target_format)
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
454
        t = self.get_transport()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
455
        t.mkdir('repository')
456
        repo_dir = bzrdir.BzrDirMetaFormat1().initialize('repository')
5671.4.2 by Jelmer Vernooij
Use stub formats to test CopyConverter.
457
        repo = TestRepositoryFormat1().initialize(repo_dir)
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
458
        converter = repository.CopyConverter(target_format)
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
459
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
460
        try:
461
            converter.convert(repo, pb)
462
        finally:
463
            pb.finished()
1556.1.4 by Robert Collins
Add a new format for what will become knit, and the surrounding logic to upgrade repositories within metadirs, and tests for the same.
464
        repo = repo_dir.open_repository()
465
        self.assertTrue(isinstance(target_format, repo._format.__class__))
1843.2.5 by Aaron Bentley
Add test of _unescape_xml
466
467
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
468
class TestRepositoryFormatKnit3(TestCaseWithTransport):
1910.2.13 by Aaron Bentley
Start work on converter
469
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
470
    def test_attribute__fetch_order(self):
471
        """Knits need topological data insertion."""
472
        format = bzrdir.BzrDirMetaFormat1()
473
        format.repository_format = knitrepo.RepositoryFormatKnit3()
474
        repo = self.make_repository('.', format=format)
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
475
        self.assertEqual('topological', repo._format._fetch_order)
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
476
477
    def test_attribute__fetch_uses_deltas(self):
478
        """Knits reuse deltas."""
479
        format = bzrdir.BzrDirMetaFormat1()
480
        format.repository_format = knitrepo.RepositoryFormatKnit3()
481
        repo = self.make_repository('.', format=format)
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
482
        self.assertEqual(True, repo._format._fetch_uses_deltas)
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
483
1910.2.13 by Aaron Bentley
Start work on converter
484
    def test_convert(self):
485
        """Ensure the upgrade adds weaves for roots"""
1910.2.35 by Aaron Bentley
Better fix for convesion test
486
        format = bzrdir.BzrDirMetaFormat1()
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
487
        format.repository_format = knitrepo.RepositoryFormatKnit1()
1910.2.35 by Aaron Bentley
Better fix for convesion test
488
        tree = self.make_branch_and_tree('.', format)
1910.2.13 by Aaron Bentley
Start work on converter
489
        tree.commit("Dull commit", rev_id="dull")
490
        revision_tree = tree.branch.repository.revision_tree('dull')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
491
        revision_tree.lock_read()
492
        try:
493
            self.assertRaises(errors.NoSuchFile, revision_tree.get_file_lines,
494
                revision_tree.inventory.root.file_id)
495
        finally:
496
            revision_tree.unlock()
1910.2.13 by Aaron Bentley
Start work on converter
497
        format = bzrdir.BzrDirMetaFormat1()
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
498
        format.repository_format = knitrepo.RepositoryFormatKnit3()
1910.2.13 by Aaron Bentley
Start work on converter
499
        upgrade.Convert('.', format)
1910.2.27 by Aaron Bentley
Fixed conversion test
500
        tree = workingtree.WorkingTree.open('.')
1910.2.13 by Aaron Bentley
Start work on converter
501
        revision_tree = tree.branch.repository.revision_tree('dull')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
502
        revision_tree.lock_read()
503
        try:
504
            revision_tree.get_file_lines(revision_tree.inventory.root.file_id)
505
        finally:
506
            revision_tree.unlock()
1910.2.27 by Aaron Bentley
Fixed conversion test
507
        tree.commit("Another dull commit", rev_id='dull2')
508
        revision_tree = tree.branch.repository.revision_tree('dull2')
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
509
        revision_tree.lock_read()
510
        self.addCleanup(revision_tree.unlock)
1910.2.27 by Aaron Bentley
Fixed conversion test
511
        self.assertEqual('dull', revision_tree.inventory.root.revision)
2220.2.2 by Martin Pool
Add tag command and basic implementation
512
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
513
    def test_supports_external_lookups(self):
514
        format = bzrdir.BzrDirMetaFormat1()
515
        format.repository_format = knitrepo.RepositoryFormatKnit3()
516
        repo = self.make_repository('.', format=format)
517
        self.assertFalse(repo._format.supports_external_lookups)
518
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
519
4667.1.1 by John Arbash Meinel
Drop the Test2a test times from 5+s down to 1.4s
520
class Test2a(tests.TestCaseWithMemoryTransport):
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
521
5365.5.20 by John Arbash Meinel
Add some tests that check the leaf factory is correct.
522
    def test_chk_bytes_uses_custom_btree_parser(self):
523
        mt = self.make_branch_and_memory_tree('test', format='2a')
524
        mt.lock_write()
525
        self.addCleanup(mt.unlock)
526
        mt.add([''], ['root-id'])
527
        mt.commit('first')
528
        index = mt.branch.repository.chk_bytes._index._graph_index._indices[0]
529
        self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
530
        # It should also work if we re-open the repo
531
        repo = mt.branch.repository.bzrdir.open_repository()
532
        repo.lock_read()
533
        self.addCleanup(repo.unlock)
534
        index = repo.chk_bytes._index._graph_index._indices[0]
535
        self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
536
4634.20.1 by Robert Collins
Fix bug 402652 by recompressing all texts that are streamed - slightly slower at fetch, substantially faster and more compact at read.
537
    def test_fetch_combines_groups(self):
538
        builder = self.make_branch_builder('source', format='2a')
539
        builder.start_series()
540
        builder.build_snapshot('1', None, [
541
            ('add', ('', 'root-id', 'directory', '')),
542
            ('add', ('file', 'file-id', 'file', 'content\n'))])
543
        builder.build_snapshot('2', ['1'], [
544
            ('modify', ('file-id', 'content-2\n'))])
545
        builder.finish_series()
546
        source = builder.get_branch()
547
        target = self.make_repository('target', format='2a')
548
        target.fetch(source.repository)
549
        target.lock_read()
4665.3.2 by John Arbash Meinel
An alternative implementation that passes both tests.
550
        self.addCleanup(target.unlock)
4634.20.1 by Robert Collins
Fix bug 402652 by recompressing all texts that are streamed - slightly slower at fetch, substantially faster and more compact at read.
551
        details = target.texts._index.get_build_details(
552
            [('file-id', '1',), ('file-id', '2',)])
553
        file_1_details = details[('file-id', '1')]
554
        file_2_details = details[('file-id', '2')]
555
        # The index, and what to read off disk, should be the same for both
556
        # versions of the file.
557
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
558
4634.23.1 by Robert Collins
Cherrypick from bzr.dev: Fix bug 402652: recompress badly packed groups during fetch. (John Arbash Meinel, Robert Collins)
559
    def test_fetch_combines_groups(self):
560
        builder = self.make_branch_builder('source', format='2a')
561
        builder.start_series()
562
        builder.build_snapshot('1', None, [
563
            ('add', ('', 'root-id', 'directory', '')),
564
            ('add', ('file', 'file-id', 'file', 'content\n'))])
565
        builder.build_snapshot('2', ['1'], [
566
            ('modify', ('file-id', 'content-2\n'))])
567
        builder.finish_series()
568
        source = builder.get_branch()
569
        target = self.make_repository('target', format='2a')
570
        target.fetch(source.repository)
571
        target.lock_read()
572
        self.addCleanup(target.unlock)
573
        details = target.texts._index.get_build_details(
574
            [('file-id', '1',), ('file-id', '2',)])
575
        file_1_details = details[('file-id', '1')]
576
        file_2_details = details[('file-id', '2')]
577
        # The index, and what to read off disk, should be the same for both
578
        # versions of the file.
579
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
580
581
    def test_fetch_combines_groups(self):
582
        builder = self.make_branch_builder('source', format='2a')
583
        builder.start_series()
584
        builder.build_snapshot('1', None, [
585
            ('add', ('', 'root-id', 'directory', '')),
586
            ('add', ('file', 'file-id', 'file', 'content\n'))])
587
        builder.build_snapshot('2', ['1'], [
588
            ('modify', ('file-id', 'content-2\n'))])
589
        builder.finish_series()
590
        source = builder.get_branch()
591
        target = self.make_repository('target', format='2a')
592
        target.fetch(source.repository)
593
        target.lock_read()
594
        self.addCleanup(target.unlock)
595
        details = target.texts._index.get_build_details(
596
            [('file-id', '1',), ('file-id', '2',)])
597
        file_1_details = details[('file-id', '1')]
598
        file_2_details = details[('file-id', '2')]
599
        # The index, and what to read off disk, should be the same for both
600
        # versions of the file.
601
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
602
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
603
    def test_format_pack_compresses_True(self):
604
        repo = self.make_repository('repo', format='2a')
605
        self.assertTrue(repo._format.pack_compresses)
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
606
607
    def test_inventories_use_chk_map_with_parent_base_dict(self):
4667.1.1 by John Arbash Meinel
Drop the Test2a test times from 5+s down to 1.4s
608
        tree = self.make_branch_and_memory_tree('repo', format="2a")
609
        tree.lock_write()
610
        tree.add([''], ['TREE_ROOT'])
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
611
        revid = tree.commit("foo")
4667.1.1 by John Arbash Meinel
Drop the Test2a test times from 5+s down to 1.4s
612
        tree.unlock()
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
613
        tree.lock_read()
614
        self.addCleanup(tree.unlock)
615
        inv = tree.branch.repository.get_inventory(revid)
3735.2.41 by Robert Collins
Make the parent_id_basename index be updated during CHKInventory.apply_delta.
616
        self.assertNotEqual(None, inv.parent_id_basename_to_file_id)
617
        inv.parent_id_basename_to_file_id._ensure_root()
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
618
        inv.id_to_entry._ensure_root()
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
619
        self.assertEqual(65536, inv.id_to_entry._root_node.maximum_size)
620
        self.assertEqual(65536,
3735.2.41 by Robert Collins
Make the parent_id_basename index be updated during CHKInventory.apply_delta.
621
            inv.parent_id_basename_to_file_id._root_node.maximum_size)
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
622
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
623
    def test_autopack_unchanged_chk_nodes(self):
624
        # at 20 unchanged commits, chk pages are packed that are split into
625
        # two groups such that the new pack being made doesn't have all its
626
        # pages in the source packs (though they are in the repository).
4667.1.1 by John Arbash Meinel
Drop the Test2a test times from 5+s down to 1.4s
627
        # Use a memory backed repository, we don't need to hit disk for this
628
        tree = self.make_branch_and_memory_tree('tree', format='2a')
629
        tree.lock_write()
630
        self.addCleanup(tree.unlock)
631
        tree.add([''], ['TREE_ROOT'])
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
632
        for pos in range(20):
633
            tree.commit(str(pos))
634
635
    def test_pack_with_hint(self):
4667.1.1 by John Arbash Meinel
Drop the Test2a test times from 5+s down to 1.4s
636
        tree = self.make_branch_and_memory_tree('tree', format='2a')
637
        tree.lock_write()
638
        self.addCleanup(tree.unlock)
639
        tree.add([''], ['TREE_ROOT'])
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
640
        # 1 commit to leave untouched
641
        tree.commit('1')
642
        to_keep = tree.branch.repository._pack_collection.names()
643
        # 2 to combine
644
        tree.commit('2')
645
        tree.commit('3')
646
        all = tree.branch.repository._pack_collection.names()
647
        combine = list(set(all) - set(to_keep))
648
        self.assertLength(3, all)
649
        self.assertLength(2, combine)
650
        tree.branch.repository.pack(hint=combine)
651
        final = tree.branch.repository._pack_collection.names()
652
        self.assertLength(2, final)
653
        self.assertFalse(combine[0] in final)
654
        self.assertFalse(combine[1] in final)
655
        self.assertSubset(to_keep, final)
656
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
657
    def test_stream_source_to_gc(self):
4462.2.1 by Robert Collins
Add new attribute to RepositoryFormat pack_compresses, hinting when pack can be useful.
658
        source = self.make_repository('source', format='2a')
659
        target = self.make_repository('target', format='2a')
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
660
        stream = source._get_source(target._format)
661
        self.assertIsInstance(stream, groupcompress_repo.GroupCHKStreamSource)
662
663
    def test_stream_source_to_non_gc(self):
4462.2.1 by Robert Collins
Add new attribute to RepositoryFormat pack_compresses, hinting when pack can be useful.
664
        source = self.make_repository('source', format='2a')
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
665
        target = self.make_repository('target', format='rich-root-pack')
666
        stream = source._get_source(target._format)
667
        # We don't want the child GroupCHKStreamSource
668
        self.assertIs(type(stream), repository.StreamSource)
669
4360.4.9 by John Arbash Meinel
Merge bzr.dev, bringing in the gc stacking fixes.
670
    def test_get_stream_for_missing_keys_includes_all_chk_refs(self):
671
        source_builder = self.make_branch_builder('source',
4462.2.1 by Robert Collins
Add new attribute to RepositoryFormat pack_compresses, hinting when pack can be useful.
672
                            format='2a')
4360.4.9 by John Arbash Meinel
Merge bzr.dev, bringing in the gc stacking fixes.
673
        # We have to build a fairly large tree, so that we are sure the chk
674
        # pages will have split into multiple pages.
675
        entries = [('add', ('', 'a-root-id', 'directory', None))]
676
        for i in 'abcdefghijklmnopqrstuvwxyz123456789':
677
            for j in 'abcdefghijklmnopqrstuvwxyz123456789':
678
                fname = i + j
679
                fid = fname + '-id'
680
                content = 'content for %s\n' % (fname,)
681
                entries.append(('add', (fname, fid, 'file', content)))
682
        source_builder.start_series()
683
        source_builder.build_snapshot('rev-1', None, entries)
684
        # Now change a few of them, so we get a few new pages for the second
685
        # revision
686
        source_builder.build_snapshot('rev-2', ['rev-1'], [
687
            ('modify', ('aa-id', 'new content for aa-id\n')),
688
            ('modify', ('cc-id', 'new content for cc-id\n')),
689
            ('modify', ('zz-id', 'new content for zz-id\n')),
690
            ])
691
        source_builder.finish_series()
692
        source_branch = source_builder.get_branch()
693
        source_branch.lock_read()
694
        self.addCleanup(source_branch.unlock)
4462.2.1 by Robert Collins
Add new attribute to RepositoryFormat pack_compresses, hinting when pack can be useful.
695
        target = self.make_repository('target', format='2a')
4360.4.9 by John Arbash Meinel
Merge bzr.dev, bringing in the gc stacking fixes.
696
        source = source_branch.repository._get_source(target._format)
697
        self.assertIsInstance(source, groupcompress_repo.GroupCHKStreamSource)
698
699
        # On a regular pass, getting the inventories and chk pages for rev-2
700
        # would only get the newly created chk pages
701
        search = graph.SearchResult(set(['rev-2']), set(['rev-1']), 1,
702
                                    set(['rev-2']))
703
        simple_chk_records = []
704
        for vf_name, substream in source.get_stream(search):
705
            if vf_name == 'chk_bytes':
706
                for record in substream:
707
                    simple_chk_records.append(record.key)
708
            else:
709
                for _ in substream:
710
                    continue
711
        # 3 pages, the root (InternalNode), + 2 pages which actually changed
712
        self.assertEqual([('sha1:91481f539e802c76542ea5e4c83ad416bf219f73',),
713
                          ('sha1:4ff91971043668583985aec83f4f0ab10a907d3f',),
714
                          ('sha1:81e7324507c5ca132eedaf2d8414ee4bb2226187',),
715
                          ('sha1:b101b7da280596c71a4540e9a1eeba8045985ee0',)],
716
                         simple_chk_records)
717
        # Now, when we do a similar call using 'get_stream_for_missing_keys'
718
        # we should get a much larger set of pages.
719
        missing = [('inventories', 'rev-2')]
720
        full_chk_records = []
721
        for vf_name, substream in source.get_stream_for_missing_keys(missing):
722
            if vf_name == 'inventories':
723
                for record in substream:
724
                    self.assertEqual(('rev-2',), record.key)
725
            elif vf_name == 'chk_bytes':
726
                for record in substream:
727
                    full_chk_records.append(record.key)
728
            else:
729
                self.fail('Should not be getting a stream of %s' % (vf_name,))
730
        # We have 257 records now. This is because we have 1 root page, and 256
731
        # leaf pages in a complete listing.
732
        self.assertEqual(257, len(full_chk_records))
733
        self.assertSubset(simple_chk_records, full_chk_records)
734
4465.2.7 by Aaron Bentley
Move test_inconsistency_fatal to test_repository
735
    def test_inconsistency_fatal(self):
736
        repo = self.make_repository('repo', format='2a')
737
        self.assertTrue(repo.revisions._index._inconsistency_fatal)
738
        self.assertFalse(repo.texts._index._inconsistency_fatal)
739
        self.assertFalse(repo.inventories._index._inconsistency_fatal)
740
        self.assertFalse(repo.signatures._index._inconsistency_fatal)
741
        self.assertFalse(repo.chk_bytes._index._inconsistency_fatal)
742
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
743
744
class TestKnitPackStreamSource(tests.TestCaseWithMemoryTransport):
745
746
    def test_source_to_exact_pack_092(self):
747
        source = self.make_repository('source', format='pack-0.92')
748
        target = self.make_repository('target', format='pack-0.92')
749
        stream_source = source._get_source(target._format)
750
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
751
752
    def test_source_to_exact_pack_rich_root_pack(self):
753
        source = self.make_repository('source', format='rich-root-pack')
754
        target = self.make_repository('target', format='rich-root-pack')
755
        stream_source = source._get_source(target._format)
756
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
757
758
    def test_source_to_exact_pack_19(self):
759
        source = self.make_repository('source', format='1.9')
760
        target = self.make_repository('target', format='1.9')
761
        stream_source = source._get_source(target._format)
762
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
763
764
    def test_source_to_exact_pack_19_rich_root(self):
765
        source = self.make_repository('source', format='1.9-rich-root')
766
        target = self.make_repository('target', format='1.9-rich-root')
767
        stream_source = source._get_source(target._format)
768
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
769
770
    def test_source_to_remote_exact_pack_19(self):
771
        trans = self.make_smart_server('target')
772
        trans.ensure_base()
773
        source = self.make_repository('source', format='1.9')
774
        target = self.make_repository('target', format='1.9')
775
        target = repository.Repository.open(trans.base)
776
        stream_source = source._get_source(target._format)
777
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
778
779
    def test_stream_source_to_non_exact(self):
780
        source = self.make_repository('source', format='pack-0.92')
781
        target = self.make_repository('target', format='1.9')
782
        stream = source._get_source(target._format)
783
        self.assertIs(type(stream), repository.StreamSource)
784
785
    def test_stream_source_to_non_exact_rich_root(self):
786
        source = self.make_repository('source', format='1.9')
787
        target = self.make_repository('target', format='1.9-rich-root')
788
        stream = source._get_source(target._format)
789
        self.assertIs(type(stream), repository.StreamSource)
790
791
    def test_source_to_remote_non_exact_pack_19(self):
792
        trans = self.make_smart_server('target')
793
        trans.ensure_base()
794
        source = self.make_repository('source', format='1.9')
795
        target = self.make_repository('target', format='1.6')
796
        target = repository.Repository.open(trans.base)
797
        stream_source = source._get_source(target._format)
798
        self.assertIs(type(stream_source), repository.StreamSource)
799
800
    def test_stream_source_to_knit(self):
801
        source = self.make_repository('source', format='pack-0.92')
802
        target = self.make_repository('target', format='dirstate')
803
        stream = source._get_source(target._format)
804
        self.assertIs(type(stream), repository.StreamSource)
805
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
806
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
807
class TestDevelopment6FindParentIdsOfRevisions(TestCaseWithTransport):
808
    """Tests for _find_parent_ids_of_revisions."""
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
809
810
    def setUp(self):
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
811
        super(TestDevelopment6FindParentIdsOfRevisions, self).setUp()
5546.1.1 by Andrew Bennetts
Remove RepositoryFormatCHK1 and RepositoryFormatCHK2.
812
        self.builder = self.make_branch_builder('source')
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
813
        self.builder.start_series()
814
        self.builder.build_snapshot('initial', None,
815
            [('add', ('', 'tree-root', 'directory', None))])
816
        self.repo = self.builder.get_branch().repository
817
        self.addCleanup(self.builder.finish_series)
3735.2.99 by John Arbash Meinel
Merge bzr.dev 4034. Whitespace cleanup
818
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
819
    def assertParentIds(self, expected_result, rev_set):
820
        self.assertEqual(sorted(expected_result),
821
            sorted(self.repo._find_parent_ids_of_revisions(rev_set)))
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
822
823
    def test_simple(self):
824
        self.builder.build_snapshot('revid1', None, [])
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
825
        self.builder.build_snapshot('revid2', ['revid1'], [])
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
826
        rev_set = ['revid2']
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
827
        self.assertParentIds(['revid1'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
828
829
    def test_not_first_parent(self):
830
        self.builder.build_snapshot('revid1', None, [])
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
831
        self.builder.build_snapshot('revid2', ['revid1'], [])
832
        self.builder.build_snapshot('revid3', ['revid2'], [])
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
833
        rev_set = ['revid3', 'revid2']
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
834
        self.assertParentIds(['revid1'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
835
836
    def test_not_null(self):
837
        rev_set = ['initial']
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
838
        self.assertParentIds([], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
839
840
    def test_not_null_set(self):
841
        self.builder.build_snapshot('revid1', None, [])
842
        rev_set = [_mod_revision.NULL_REVISION]
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
843
        self.assertParentIds([], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
844
845
    def test_ghost(self):
846
        self.builder.build_snapshot('revid1', None, [])
847
        rev_set = ['ghost', 'revid1']
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
848
        self.assertParentIds(['initial'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
849
850
    def test_ghost_parent(self):
851
        self.builder.build_snapshot('revid1', None, [])
852
        self.builder.build_snapshot('revid2', ['revid1', 'ghost'], [])
853
        rev_set = ['revid2', 'revid1']
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
854
        self.assertParentIds(['ghost', 'initial'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
855
856
    def test_righthand_parent(self):
857
        self.builder.build_snapshot('revid1', None, [])
858
        self.builder.build_snapshot('revid2a', ['revid1'], [])
859
        self.builder.build_snapshot('revid2b', ['revid1'], [])
860
        self.builder.build_snapshot('revid3', ['revid2a', 'revid2b'], [])
861
        rev_set = ['revid3', 'revid2a']
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
862
        self.assertParentIds(['revid1', 'revid2b'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
863
864
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
865
class TestWithBrokenRepo(TestCaseWithTransport):
2592.3.214 by Robert Collins
Merge bzr.dev.
866
    """These tests seem to be more appropriate as interface tests?"""
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
867
868
    def make_broken_repository(self):
869
        # XXX: This function is borrowed from Aaron's "Reconcile can fix bad
870
        # parent references" branch which is due to land in bzr.dev soon.  Once
871
        # it does, this duplication should be removed.
872
        repo = self.make_repository('broken-repo')
873
        cleanups = []
874
        try:
875
            repo.lock_write()
876
            cleanups.append(repo.unlock)
877
            repo.start_write_group()
878
            cleanups.append(repo.commit_write_group)
879
            # make rev1a: A well-formed revision, containing 'file1'
880
            inv = inventory.Inventory(revision_id='rev1a')
881
            inv.root.revision = 'rev1a'
882
            self.add_file(repo, inv, 'file1', 'rev1a', [])
4634.35.21 by Andrew Bennetts
Fix test_insert_from_broken_repo in test_repository.
883
            repo.texts.add_lines((inv.root.file_id, 'rev1a'), [], [])
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
884
            repo.add_inventory('rev1a', inv, [])
885
            revision = _mod_revision.Revision('rev1a',
886
                committer='jrandom@example.com', timestamp=0,
887
                inventory_sha1='', timezone=0, message='foo', parent_ids=[])
888
            repo.add_revision('rev1a',revision, inv)
889
890
            # make rev1b, which has no Revision, but has an Inventory, and
891
            # file1
892
            inv = inventory.Inventory(revision_id='rev1b')
893
            inv.root.revision = 'rev1b'
894
            self.add_file(repo, inv, 'file1', 'rev1b', [])
895
            repo.add_inventory('rev1b', inv, [])
896
897
            # make rev2, with file1 and file2
898
            # file2 is sane
899
            # file1 has 'rev1b' as an ancestor, even though this is not
900
            # mentioned by 'rev1a', making it an unreferenced ancestor
901
            inv = inventory.Inventory()
902
            self.add_file(repo, inv, 'file1', 'rev2', ['rev1a', 'rev1b'])
903
            self.add_file(repo, inv, 'file2', 'rev2', [])
904
            self.add_revision(repo, 'rev2', inv, ['rev1a'])
905
906
            # make ghost revision rev1c
907
            inv = inventory.Inventory()
908
            self.add_file(repo, inv, 'file2', 'rev1c', [])
909
910
            # make rev3 with file2
911
            # file2 refers to 'rev1c', which is a ghost in this repository, so
912
            # file2 cannot have rev1c as its ancestor.
913
            inv = inventory.Inventory()
914
            self.add_file(repo, inv, 'file2', 'rev3', ['rev1c'])
915
            self.add_revision(repo, 'rev3', inv, ['rev1c'])
916
            return repo
917
        finally:
918
            for cleanup in reversed(cleanups):
919
                cleanup()
920
921
    def add_revision(self, repo, revision_id, inv, parent_ids):
922
        inv.revision_id = revision_id
923
        inv.root.revision = revision_id
4634.35.21 by Andrew Bennetts
Fix test_insert_from_broken_repo in test_repository.
924
        repo.texts.add_lines((inv.root.file_id, revision_id), [], [])
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
925
        repo.add_inventory(revision_id, inv, parent_ids)
926
        revision = _mod_revision.Revision(revision_id,
927
            committer='jrandom@example.com', timestamp=0, inventory_sha1='',
928
            timezone=0, message='foo', parent_ids=parent_ids)
929
        repo.add_revision(revision_id,revision, inv)
930
931
    def add_file(self, repo, inv, filename, revision, parents):
932
        file_id = filename + '-id'
933
        entry = inventory.InventoryFile(file_id, filename, 'TREE_ROOT')
934
        entry.revision = revision
2535.4.10 by Andrew Bennetts
Fix one failing test, disable another.
935
        entry.text_size = 0
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
936
        inv.add(entry)
3350.6.4 by Robert Collins
First cut at pluralised VersionedFiles. Some rather massive API incompatabilities, primarily because of the difficulty of coherence among competing stores.
937
        text_key = (file_id, revision)
938
        parent_keys = [(file_id, parent) for parent in parents]
939
        repo.texts.add_lines(text_key, parent_keys, ['line\n'])
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
940
941
    def test_insert_from_broken_repo(self):
942
        """Inserting a data stream from a broken repository won't silently
943
        corrupt the target repository.
944
        """
945
        broken_repo = self.make_broken_repository()
946
        empty_repo = self.make_repository('empty-repo')
4606.1.1 by Robert Collins
Change test_insert_from_broken_repo from a known failure to a working test.
947
        try:
948
            empty_repo.fetch(broken_repo)
949
        except (errors.RevisionNotPresent, errors.BzrCheckError):
950
            # Test successful: compression parent not being copied leads to
951
            # error.
952
            return
953
        empty_repo.lock_read()
954
        self.addCleanup(empty_repo.unlock)
955
        text = empty_repo.texts.get_record_stream(
956
            [('file2-id', 'rev3')], 'topological', True).next()
957
        self.assertEqual('line\n', text.get_bytes_as('fulltext'))
2592.3.214 by Robert Collins
Merge bzr.dev.
958
959
2592.3.84 by Robert Collins
Start of autopacking logic.
960
class TestRepositoryPackCollection(TestCaseWithTransport):
961
962
    def get_format(self):
3010.3.3 by Martin Pool
Merge trunk
963
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
2592.3.84 by Robert Collins
Start of autopacking logic.
964
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
965
    def get_packs(self):
966
        format = self.get_format()
967
        repo = self.make_repository('.', format=format)
968
        return repo._pack_collection
969
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
970
    def make_packs_and_alt_repo(self, write_lock=False):
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
971
        """Create a pack repo with 3 packs, and access it via a second repo."""
4617.4.1 by Robert Collins
Fix a pack specific test which didn't lock its format down.
972
        tree = self.make_branch_and_tree('.', format=self.get_format())
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
973
        tree.lock_write()
974
        self.addCleanup(tree.unlock)
975
        rev1 = tree.commit('one')
976
        rev2 = tree.commit('two')
977
        rev3 = tree.commit('three')
978
        r = repository.Repository.open('.')
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
979
        if write_lock:
980
            r.lock_write()
981
        else:
982
            r.lock_read()
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
983
        self.addCleanup(r.unlock)
984
        packs = r._pack_collection
985
        packs.ensure_loaded()
986
        return tree, r, packs, [rev1, rev2, rev3]
987
4634.127.1 by John Arbash Meinel
Partial fix for bug #507557.
988
    def test__clear_obsolete_packs(self):
989
        packs = self.get_packs()
990
        obsolete_pack_trans = packs.transport.clone('obsolete_packs')
991
        obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
992
        obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
993
        obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
994
        obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
995
        obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
996
        res = packs._clear_obsolete_packs()
997
        self.assertEqual(['a-pack', 'another-pack'], sorted(res))
998
        self.assertEqual([], obsolete_pack_trans.list_dir('.'))
999
1000
    def test__clear_obsolete_packs_preserve(self):
1001
        packs = self.get_packs()
1002
        obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1003
        obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1004
        obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1005
        obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1006
        obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1007
        obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1008
        res = packs._clear_obsolete_packs(preserve=set(['a-pack']))
1009
        self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1010
        self.assertEqual(['a-pack.iix', 'a-pack.pack', 'a-pack.rix'],
1011
                         sorted(obsolete_pack_trans.list_dir('.')))
1012
2592.3.84 by Robert Collins
Start of autopacking logic.
1013
    def test__max_pack_count(self):
2592.3.219 by Robert Collins
Review feedback.
1014
        """The maximum pack count is a function of the number of revisions."""
2592.3.84 by Robert Collins
Start of autopacking logic.
1015
        # no revisions - one pack, so that we can have a revision free repo
1016
        # without it blowing up
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1017
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1018
        self.assertEqual(1, packs._max_pack_count(0))
1019
        # after that the sum of the digits, - check the first 1-9
1020
        self.assertEqual(1, packs._max_pack_count(1))
1021
        self.assertEqual(2, packs._max_pack_count(2))
1022
        self.assertEqual(3, packs._max_pack_count(3))
1023
        self.assertEqual(4, packs._max_pack_count(4))
1024
        self.assertEqual(5, packs._max_pack_count(5))
1025
        self.assertEqual(6, packs._max_pack_count(6))
1026
        self.assertEqual(7, packs._max_pack_count(7))
1027
        self.assertEqual(8, packs._max_pack_count(8))
1028
        self.assertEqual(9, packs._max_pack_count(9))
1029
        # check the boundary cases with two digits for the next decade
1030
        self.assertEqual(1, packs._max_pack_count(10))
1031
        self.assertEqual(2, packs._max_pack_count(11))
1032
        self.assertEqual(10, packs._max_pack_count(19))
1033
        self.assertEqual(2, packs._max_pack_count(20))
1034
        self.assertEqual(3, packs._max_pack_count(21))
1035
        # check some arbitrary big numbers
1036
        self.assertEqual(25, packs._max_pack_count(112894))
1037
4928.1.1 by Martin Pool
Give RepositoryPackCollection a repr
1038
    def test_repr(self):
1039
        packs = self.get_packs()
1040
        self.assertContainsRe(repr(packs),
1041
            'RepositoryPackCollection(.*Repository(.*))')
1042
4634.127.2 by John Arbash Meinel
Change the _obsolete_packs code to handle files that are already gone.
1043
    def test__obsolete_packs(self):
1044
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1045
        names = packs.names()
1046
        pack = packs.get_pack_by_name(names[0])
1047
        # Schedule this one for removal
1048
        packs._remove_pack_from_memory(pack)
1049
        # Simulate a concurrent update by renaming the .pack file and one of
1050
        # the indices
1051
        packs.transport.rename('packs/%s.pack' % (names[0],),
1052
                               'obsolete_packs/%s.pack' % (names[0],))
1053
        packs.transport.rename('indices/%s.iix' % (names[0],),
1054
                               'obsolete_packs/%s.iix' % (names[0],))
1055
        # Now trigger the obsoletion, and ensure that all the remaining files
1056
        # are still renamed
1057
        packs._obsolete_packs([pack])
1058
        self.assertEqual([n + '.pack' for n in names[1:]],
1059
                         sorted(packs._pack_transport.list_dir('.')))
1060
        # names[0] should not be present in the index anymore
1061
        self.assertEqual(names[1:],
1062
            sorted(set([osutils.splitext(n)[0] for n in
1063
                        packs._index_transport.list_dir('.')])))
1064
2592.3.84 by Robert Collins
Start of autopacking logic.
1065
    def test_pack_distribution_zero(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1066
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1067
        self.assertEqual([0], packs.pack_distribution(0))
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
1068
1069
    def test_ensure_loaded_unlocked(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1070
        packs = self.get_packs()
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
1071
        self.assertRaises(errors.ObjectNotLocked,
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1072
                          packs.ensure_loaded)
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
1073
2592.3.84 by Robert Collins
Start of autopacking logic.
1074
    def test_pack_distribution_one_to_nine(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1075
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1076
        self.assertEqual([1],
1077
            packs.pack_distribution(1))
1078
        self.assertEqual([1, 1],
1079
            packs.pack_distribution(2))
1080
        self.assertEqual([1, 1, 1],
1081
            packs.pack_distribution(3))
1082
        self.assertEqual([1, 1, 1, 1],
1083
            packs.pack_distribution(4))
1084
        self.assertEqual([1, 1, 1, 1, 1],
1085
            packs.pack_distribution(5))
1086
        self.assertEqual([1, 1, 1, 1, 1, 1],
1087
            packs.pack_distribution(6))
1088
        self.assertEqual([1, 1, 1, 1, 1, 1, 1],
1089
            packs.pack_distribution(7))
1090
        self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1],
1091
            packs.pack_distribution(8))
1092
        self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1, 1],
1093
            packs.pack_distribution(9))
1094
1095
    def test_pack_distribution_stable_at_boundaries(self):
1096
        """When there are multi-rev packs the counts are stable."""
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1097
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1098
        # in 10s:
1099
        self.assertEqual([10], packs.pack_distribution(10))
1100
        self.assertEqual([10, 1], packs.pack_distribution(11))
1101
        self.assertEqual([10, 10], packs.pack_distribution(20))
1102
        self.assertEqual([10, 10, 1], packs.pack_distribution(21))
1103
        # 100s
1104
        self.assertEqual([100], packs.pack_distribution(100))
1105
        self.assertEqual([100, 1], packs.pack_distribution(101))
1106
        self.assertEqual([100, 10, 1], packs.pack_distribution(111))
1107
        self.assertEqual([100, 100], packs.pack_distribution(200))
1108
        self.assertEqual([100, 100, 1], packs.pack_distribution(201))
1109
        self.assertEqual([100, 100, 10, 1], packs.pack_distribution(211))
1110
2592.3.85 by Robert Collins
Finish autopack corner cases.
1111
    def test_plan_pack_operations_2009_revisions_skip_all_packs(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1112
        packs = self.get_packs()
2592.3.85 by Robert Collins
Finish autopack corner cases.
1113
        existing_packs = [(2000, "big"), (9, "medium")]
1114
        # rev count - 2009 -> 2x1000 + 9x1
1115
        pack_operations = packs.plan_autopack_combinations(
1116
            existing_packs, [1000, 1000, 1, 1, 1, 1, 1, 1, 1, 1, 1])
1117
        self.assertEqual([], pack_operations)
1118
1119
    def test_plan_pack_operations_2010_revisions_skip_all_packs(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1120
        packs = self.get_packs()
2592.3.85 by Robert Collins
Finish autopack corner cases.
1121
        existing_packs = [(2000, "big"), (9, "medium"), (1, "single")]
1122
        # rev count - 2010 -> 2x1000 + 1x10
1123
        pack_operations = packs.plan_autopack_combinations(
1124
            existing_packs, [1000, 1000, 10])
1125
        self.assertEqual([], pack_operations)
1126
1127
    def test_plan_pack_operations_2010_combines_smallest_two(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1128
        packs = self.get_packs()
2592.3.85 by Robert Collins
Finish autopack corner cases.
1129
        existing_packs = [(1999, "big"), (9, "medium"), (1, "single2"),
1130
            (1, "single1")]
1131
        # rev count - 2010 -> 2x1000 + 1x10 (3)
1132
        pack_operations = packs.plan_autopack_combinations(
1133
            existing_packs, [1000, 1000, 10])
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1134
        self.assertEqual([[2, ["single2", "single1"]]], pack_operations)
2592.3.85 by Robert Collins
Finish autopack corner cases.
1135
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1136
    def test_plan_pack_operations_creates_a_single_op(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1137
        packs = self.get_packs()
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1138
        existing_packs = [(50, 'a'), (40, 'b'), (30, 'c'), (10, 'd'),
1139
                          (10, 'e'), (6, 'f'), (4, 'g')]
1140
        # rev count 150 -> 1x100 and 5x10
1141
        # The two size 10 packs do not need to be touched. The 50, 40, 30 would
1142
        # be combined into a single 120 size pack, and the 6 & 4 would
1143
        # becombined into a size 10 pack. However, if we have to rewrite them,
1144
        # we save a pack file with no increased I/O by putting them into the
1145
        # same file.
1146
        distribution = packs.pack_distribution(150)
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1147
        pack_operations = packs.plan_autopack_combinations(existing_packs,
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1148
                                                           distribution)
1149
        self.assertEqual([[130, ['a', 'b', 'c', 'f', 'g']]], pack_operations)
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1150
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1151
    def test_all_packs_none(self):
1152
        format = self.get_format()
1153
        tree = self.make_branch_and_tree('.', format=format)
1154
        tree.lock_read()
1155
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1156
        packs = tree.branch.repository._pack_collection
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1157
        packs.ensure_loaded()
1158
        self.assertEqual([], packs.all_packs())
1159
1160
    def test_all_packs_one(self):
1161
        format = self.get_format()
1162
        tree = self.make_branch_and_tree('.', format=format)
1163
        tree.commit('start')
1164
        tree.lock_read()
1165
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1166
        packs = tree.branch.repository._pack_collection
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1167
        packs.ensure_loaded()
2592.3.176 by Robert Collins
Various pack refactorings.
1168
        self.assertEqual([
1169
            packs.get_pack_by_name(packs.names()[0])],
1170
            packs.all_packs())
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1171
1172
    def test_all_packs_two(self):
1173
        format = self.get_format()
1174
        tree = self.make_branch_and_tree('.', format=format)
1175
        tree.commit('start')
1176
        tree.commit('continue')
1177
        tree.lock_read()
1178
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1179
        packs = tree.branch.repository._pack_collection
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1180
        packs.ensure_loaded()
1181
        self.assertEqual([
2592.3.176 by Robert Collins
Various pack refactorings.
1182
            packs.get_pack_by_name(packs.names()[0]),
1183
            packs.get_pack_by_name(packs.names()[1]),
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1184
            ], packs.all_packs())
1185
2592.3.176 by Robert Collins
Various pack refactorings.
1186
    def test_get_pack_by_name(self):
1187
        format = self.get_format()
1188
        tree = self.make_branch_and_tree('.', format=format)
1189
        tree.commit('start')
1190
        tree.lock_read()
1191
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1192
        packs = tree.branch.repository._pack_collection
4145.1.6 by Robert Collins
More test fallout, but all caught now.
1193
        packs.reset()
2592.3.176 by Robert Collins
Various pack refactorings.
1194
        packs.ensure_loaded()
1195
        name = packs.names()[0]
1196
        pack_1 = packs.get_pack_by_name(name)
1197
        # the pack should be correctly initialised
3517.4.5 by Martin Pool
Correct use of packs._names in test_get_pack_by_name
1198
        sizes = packs._names[name]
3221.12.4 by Robert Collins
Implement basic repository supporting external references.
1199
        rev_index = GraphIndex(packs._index_transport, name + '.rix', sizes[0])
1200
        inv_index = GraphIndex(packs._index_transport, name + '.iix', sizes[1])
1201
        txt_index = GraphIndex(packs._index_transport, name + '.tix', sizes[2])
1202
        sig_index = GraphIndex(packs._index_transport, name + '.six', sizes[3])
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
1203
        self.assertEqual(pack_repo.ExistingPack(packs._pack_transport,
2592.3.219 by Robert Collins
Review feedback.
1204
            name, rev_index, inv_index, txt_index, sig_index), pack_1)
2592.3.176 by Robert Collins
Various pack refactorings.
1205
        # and the same instance should be returned on successive calls.
1206
        self.assertTrue(pack_1 is packs.get_pack_by_name(name))
1207
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1208
    def test_reload_pack_names_new_entry(self):
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1209
        tree, r, packs, revs = self.make_packs_and_alt_repo()
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1210
        names = packs.names()
1211
        # Add a new pack file into the repository
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1212
        rev4 = tree.commit('four')
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1213
        new_names = tree.branch.repository._pack_collection.names()
1214
        new_name = set(new_names).difference(names)
1215
        self.assertEqual(1, len(new_name))
1216
        new_name = new_name.pop()
1217
        # The old collection hasn't noticed yet
1218
        self.assertEqual(names, packs.names())
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1219
        self.assertTrue(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1220
        self.assertEqual(new_names, packs.names())
1221
        # And the repository can access the new revision
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1222
        self.assertEqual({rev4:(revs[-1],)}, r.get_parent_map([rev4]))
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1223
        self.assertFalse(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1224
1225
    def test_reload_pack_names_added_and_removed(self):
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1226
        tree, r, packs, revs = self.make_packs_and_alt_repo()
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1227
        names = packs.names()
1228
        # Now repack the whole thing
1229
        tree.branch.repository.pack()
1230
        new_names = tree.branch.repository._pack_collection.names()
1231
        # The other collection hasn't noticed yet
1232
        self.assertEqual(names, packs.names())
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1233
        self.assertTrue(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1234
        self.assertEqual(new_names, packs.names())
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1235
        self.assertEqual({revs[-1]:(revs[-2],)}, r.get_parent_map([revs[-1]]))
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1236
        self.assertFalse(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1237
4634.126.1 by John Arbash Meinel
(jam) Fix bug #507566, concurrent autopacking correctness.
1238
    def test_reload_pack_names_preserves_pending(self):
1239
        # TODO: Update this to also test for pending-deleted names
1240
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1241
        # We will add one pack (via start_write_group + insert_record_stream),
1242
        # and remove another pack (via _remove_pack_from_memory)
1243
        orig_names = packs.names()
1244
        orig_at_load = packs._packs_at_load
1245
        to_remove_name = iter(orig_names).next()
1246
        r.start_write_group()
1247
        self.addCleanup(r.abort_write_group)
1248
        r.texts.insert_record_stream([versionedfile.FulltextContentFactory(
1249
            ('text', 'rev'), (), None, 'content\n')])
1250
        new_pack = packs._new_pack
1251
        self.assertTrue(new_pack.data_inserted())
1252
        new_pack.finish()
1253
        packs.allocate(new_pack)
1254
        packs._new_pack = None
1255
        removed_pack = packs.get_pack_by_name(to_remove_name)
1256
        packs._remove_pack_from_memory(removed_pack)
1257
        names = packs.names()
4634.127.3 by John Arbash Meinel
Add code so we don't try to obsolete files someone else has 'claimed'.
1258
        all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
4634.126.1 by John Arbash Meinel
(jam) Fix bug #507566, concurrent autopacking correctness.
1259
        new_names = set([x[0][0] for x in new_nodes])
1260
        self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1261
        self.assertEqual(set(names) - set(orig_names), new_names)
1262
        self.assertEqual(set([new_pack.name]), new_names)
1263
        self.assertEqual([to_remove_name],
1264
                         sorted([x[0][0] for x in deleted_nodes]))
1265
        packs.reload_pack_names()
1266
        reloaded_names = packs.names()
1267
        self.assertEqual(orig_at_load, packs._packs_at_load)
1268
        self.assertEqual(names, reloaded_names)
4634.127.3 by John Arbash Meinel
Add code so we don't try to obsolete files someone else has 'claimed'.
1269
        all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
4634.126.1 by John Arbash Meinel
(jam) Fix bug #507566, concurrent autopacking correctness.
1270
        new_names = set([x[0][0] for x in new_nodes])
1271
        self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1272
        self.assertEqual(set(names) - set(orig_names), new_names)
1273
        self.assertEqual(set([new_pack.name]), new_names)
1274
        self.assertEqual([to_remove_name],
1275
                         sorted([x[0][0] for x in deleted_nodes]))
1276
4634.127.5 by John Arbash Meinel
Possible fix for making sure packs triggering autopacking get cleaned up.
1277
    def test_autopack_obsoletes_new_pack(self):
1278
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1279
        packs._max_pack_count = lambda x: 1
1280
        packs.pack_distribution = lambda x: [10]
1281
        r.start_write_group()
1282
        r.revisions.insert_record_stream([versionedfile.FulltextContentFactory(
1283
            ('bogus-rev',), (), None, 'bogus-content\n')])
1284
        # This should trigger an autopack, which will combine everything into a
1285
        # single pack file.
1286
        new_names = r.commit_write_group()
1287
        names = packs.names()
1288
        self.assertEqual(1, len(names))
1289
        self.assertEqual([names[0] + '.pack'],
1290
                         packs._pack_transport.list_dir('.'))
1291
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1292
    def test_autopack_reloads_and_stops(self):
1293
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1294
        # After we have determined what needs to be autopacked, trigger a
1295
        # full-pack via the other repo which will cause us to re-evaluate and
1296
        # decide we don't need to do anything
1297
        orig_execute = packs._execute_pack_operations
1298
        def _munged_execute_pack_ops(*args, **kwargs):
1299
            tree.branch.repository.pack()
1300
            return orig_execute(*args, **kwargs)
1301
        packs._execute_pack_operations = _munged_execute_pack_ops
1302
        packs._max_pack_count = lambda x: 1
1303
        packs.pack_distribution = lambda x: [10]
1304
        self.assertFalse(packs.autopack())
1305
        self.assertEqual(1, len(packs.names()))
1306
        self.assertEqual(tree.branch.repository._pack_collection.names(),
1307
                         packs.names())
1308
4634.127.1 by John Arbash Meinel
Partial fix for bug #507557.
1309
    def test__save_pack_names(self):
1310
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1311
        names = packs.names()
1312
        pack = packs.get_pack_by_name(names[0])
1313
        packs._remove_pack_from_memory(pack)
1314
        packs._save_pack_names(obsolete_packs=[pack])
1315
        cur_packs = packs._pack_transport.list_dir('.')
1316
        self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1317
        # obsolete_packs will also have stuff like .rix and .iix present.
1318
        obsolete_packs = packs.transport.list_dir('obsolete_packs')
1319
        obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
1320
        self.assertEqual([pack.name], sorted(obsolete_names))
1321
1322
    def test__save_pack_names_already_obsoleted(self):
1323
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1324
        names = packs.names()
1325
        pack = packs.get_pack_by_name(names[0])
1326
        packs._remove_pack_from_memory(pack)
1327
        # We are going to simulate a concurrent autopack by manually obsoleting
1328
        # the pack directly.
1329
        packs._obsolete_packs([pack])
1330
        packs._save_pack_names(clear_obsolete_packs=True,
1331
                               obsolete_packs=[pack])
1332
        cur_packs = packs._pack_transport.list_dir('.')
1333
        self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1334
        # Note that while we set clear_obsolete_packs=True, it should not
1335
        # delete a pack file that we have also scheduled for obsoletion.
1336
        obsolete_packs = packs.transport.list_dir('obsolete_packs')
1337
        obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
1338
        self.assertEqual([pack.name], sorted(obsolete_names))
1339
4634.127.3 by John Arbash Meinel
Add code so we don't try to obsolete files someone else has 'claimed'.
1340
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1341
1342
class TestPack(TestCaseWithTransport):
1343
    """Tests for the Pack object."""
1344
1345
    def assertCurrentlyEqual(self, left, right):
1346
        self.assertTrue(left == right)
1347
        self.assertTrue(right == left)
1348
        self.assertFalse(left != right)
1349
        self.assertFalse(right != left)
1350
1351
    def assertCurrentlyNotEqual(self, left, right):
1352
        self.assertFalse(left == right)
1353
        self.assertFalse(right == left)
1354
        self.assertTrue(left != right)
1355
        self.assertTrue(right != left)
1356
1357
    def test___eq____ne__(self):
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
1358
        left = pack_repo.ExistingPack('', '', '', '', '', '')
1359
        right = pack_repo.ExistingPack('', '', '', '', '', '')
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1360
        self.assertCurrentlyEqual(left, right)
1361
        # change all attributes and ensure equality changes as we do.
1362
        left.revision_index = 'a'
1363
        self.assertCurrentlyNotEqual(left, right)
1364
        right.revision_index = 'a'
1365
        self.assertCurrentlyEqual(left, right)
1366
        left.inventory_index = 'a'
1367
        self.assertCurrentlyNotEqual(left, right)
1368
        right.inventory_index = 'a'
1369
        self.assertCurrentlyEqual(left, right)
1370
        left.text_index = 'a'
1371
        self.assertCurrentlyNotEqual(left, right)
1372
        right.text_index = 'a'
1373
        self.assertCurrentlyEqual(left, right)
1374
        left.signature_index = 'a'
1375
        self.assertCurrentlyNotEqual(left, right)
1376
        right.signature_index = 'a'
1377
        self.assertCurrentlyEqual(left, right)
1378
        left.name = 'a'
1379
        self.assertCurrentlyNotEqual(left, right)
1380
        right.name = 'a'
1381
        self.assertCurrentlyEqual(left, right)
1382
        left.transport = 'a'
1383
        self.assertCurrentlyNotEqual(left, right)
1384
        right.transport = 'a'
1385
        self.assertCurrentlyEqual(left, right)
2592.3.179 by Robert Collins
Generate the revision_index_map for packing during the core operation, from the pack objects.
1386
1387
    def test_file_name(self):
2592.3.191 by Robert Collins
Give Pack responsibility for index naming, and two concrete classes - NewPack for new packs and ExistingPack for packs we read from disk.
1388
        pack = pack_repo.ExistingPack('', 'a_name', '', '', '', '')
2592.3.179 by Robert Collins
Generate the revision_index_map for packing during the core operation, from the pack objects.
1389
        self.assertEqual('a_name.pack', pack.file_name())
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
1390
1391
1392
class TestNewPack(TestCaseWithTransport):
1393
    """Tests for pack_repo.NewPack."""
1394
2592.3.193 by Robert Collins
Move hash tracking of new packs into NewPack.
1395
    def test_new_instance_attributes(self):
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
1396
        upload_transport = self.get_transport('upload')
1397
        pack_transport = self.get_transport('pack')
1398
        index_transport = self.get_transport('index')
1399
        upload_transport.mkdir('.')
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1400
        collection = pack_repo.RepositoryPackCollection(
1401
            repo=None,
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
1402
            transport=self.get_transport('.'),
1403
            index_transport=index_transport,
1404
            upload_transport=upload_transport,
1405
            pack_transport=pack_transport,
1406
            index_builder_class=BTreeBuilder,
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1407
            index_class=BTreeGraphIndex,
1408
            use_chk_index=False)
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
1409
        pack = pack_repo.NewPack(collection)
4857.2.1 by John Arbash Meinel
2 test_repository tests weren't adding cleanups when opening files.
1410
        self.addCleanup(pack.abort) # Make sure the write stream gets closed
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1411
        self.assertIsInstance(pack.revision_index, BTreeBuilder)
1412
        self.assertIsInstance(pack.inventory_index, BTreeBuilder)
2929.3.5 by Vincent Ladeuil
New files, same warnings, same fixes.
1413
        self.assertIsInstance(pack._hash, type(osutils.md5()))
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
1414
        self.assertTrue(pack.upload_transport is upload_transport)
1415
        self.assertTrue(pack.index_transport is index_transport)
1416
        self.assertTrue(pack.pack_transport is pack_transport)
1417
        self.assertEqual(None, pack.index_sizes)
1418
        self.assertEqual(20, len(pack.random_name))
1419
        self.assertIsInstance(pack.random_name, str)
1420
        self.assertIsInstance(pack.start_time, float)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1421
1422
1423
class TestPacker(TestCaseWithTransport):
1424
    """Tests for the packs repository Packer class."""
2951.1.10 by Robert Collins
Peer review feedback with Ian.
1425
3824.2.4 by John Arbash Meinel
Add a test that ensures the pack ordering changes as part of calling .pack()
1426
    def test_pack_optimizes_pack_order(self):
4617.8.1 by Robert Collins
Lock down another test assuming the default was a PackRepository.
1427
        builder = self.make_branch_builder('.', format="1.9")
3824.2.4 by John Arbash Meinel
Add a test that ensures the pack ordering changes as part of calling .pack()
1428
        builder.start_series()
1429
        builder.build_snapshot('A', None, [
1430
            ('add', ('', 'root-id', 'directory', None)),
1431
            ('add', ('f', 'f-id', 'file', 'content\n'))])
1432
        builder.build_snapshot('B', ['A'],
1433
            [('modify', ('f-id', 'new-content\n'))])
1434
        builder.build_snapshot('C', ['B'],
1435
            [('modify', ('f-id', 'third-content\n'))])
1436
        builder.build_snapshot('D', ['C'],
1437
            [('modify', ('f-id', 'fourth-content\n'))])
1438
        b = builder.get_branch()
1439
        b.lock_read()
1440
        builder.finish_series()
1441
        self.addCleanup(b.unlock)
1442
        # At this point, we should have 4 pack files available
1443
        # Because of how they were built, they correspond to
1444
        # ['D', 'C', 'B', 'A']
1445
        packs = b.repository._pack_collection.packs
1446
        packer = pack_repo.Packer(b.repository._pack_collection,
1447
                                  packs, 'testing',
1448
                                  revision_ids=['B', 'C'])
1449
        # Now, when we are copying the B & C revisions, their pack files should
1450
        # be moved to the front of the stack
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
1451
        # The new ordering moves B & C to the front of the .packs attribute,
1452
        # and leaves the others in the original order.
3824.2.4 by John Arbash Meinel
Add a test that ensures the pack ordering changes as part of calling .pack()
1453
        new_packs = [packs[1], packs[2], packs[0], packs[3]]
1454
        new_pack = packer.pack()
1455
        self.assertEqual(new_packs, packer.packs)
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
1456
1457
3777.5.4 by John Arbash Meinel
OptimisingPacker now sets the optimize flags for the indexes being built.
1458
class TestOptimisingPacker(TestCaseWithTransport):
1459
    """Tests for the OptimisingPacker class."""
1460
1461
    def get_pack_collection(self):
1462
        repo = self.make_repository('.')
1463
        return repo._pack_collection
1464
1465
    def test_open_pack_will_optimise(self):
1466
        packer = pack_repo.OptimisingPacker(self.get_pack_collection(),
1467
                                            [], '.test')
1468
        new_pack = packer.open_pack()
4857.2.1 by John Arbash Meinel
2 test_repository tests weren't adding cleanups when opening files.
1469
        self.addCleanup(new_pack.abort) # ensure cleanup
3777.5.4 by John Arbash Meinel
OptimisingPacker now sets the optimize flags for the indexes being built.
1470
        self.assertIsInstance(new_pack, pack_repo.NewPack)
1471
        self.assertTrue(new_pack.revision_index._optimize_for_size)
1472
        self.assertTrue(new_pack.inventory_index._optimize_for_size)
1473
        self.assertTrue(new_pack.text_index._optimize_for_size)
1474
        self.assertTrue(new_pack.signature_index._optimize_for_size)
4462.2.6 by Robert Collins
Cause StreamSink to partially pack repositories after cross format fetches when beneficial.
1475
1476
4634.170.1 by John Arbash Meinel
Fix bug #437003. Autopacking should not fail for an
1477
class TestGCCHKPacker(TestCaseWithTransport):
1478
1479
    def make_abc_branch(self):
1480
        builder = self.make_branch_builder('source')
1481
        builder.start_series()
1482
        builder.build_snapshot('A', None, [
1483
            ('add', ('', 'root-id', 'directory', None)),
1484
            ('add', ('file', 'file-id', 'file', 'content\n')),
1485
            ])
1486
        builder.build_snapshot('B', ['A'], [
1487
            ('add', ('dir', 'dir-id', 'directory', None))])
1488
        builder.build_snapshot('C', ['B'], [
1489
            ('modify', ('file-id', 'new content\n'))])
1490
        builder.finish_series()
1491
        return builder.get_branch()
1492
1493
    def make_branch_with_disjoint_inventory_and_revision(self):
1494
        """a repo with separate packs for a revisions Revision and Inventory.
1495
1496
        There will be one pack file that holds the Revision content, and one
1497
        for the Inventory content.
1498
1499
        :return: (repository,
1500
                  pack_name_with_rev_A_Revision,
1501
                  pack_name_with_rev_A_Inventory,
1502
                  pack_name_with_rev_C_content)
1503
        """
1504
        b_source = self.make_abc_branch()
1505
        b_base = b_source.bzrdir.sprout('base', revision_id='A').open_branch()
1506
        b_stacked = b_base.bzrdir.sprout('stacked', stacked=True).open_branch()
1507
        b_stacked.lock_write()
1508
        self.addCleanup(b_stacked.unlock)
1509
        b_stacked.fetch(b_source, 'B')
1510
        # Now re-open the stacked repo directly (no fallbacks) so that we can
1511
        # fill in the A rev.
1512
        repo_not_stacked = b_stacked.bzrdir.open_repository()
1513
        repo_not_stacked.lock_write()
1514
        self.addCleanup(repo_not_stacked.unlock)
1515
        # Now we should have a pack file with A's inventory, but not its
1516
        # Revision
1517
        self.assertEqual([('A',), ('B',)],
1518
                         sorted(repo_not_stacked.inventories.keys()))
1519
        self.assertEqual([('B',)],
1520
                         sorted(repo_not_stacked.revisions.keys()))
1521
        stacked_pack_names = repo_not_stacked._pack_collection.names()
1522
        # We have a couple names here, figure out which has A's inventory
1523
        for name in stacked_pack_names:
1524
            pack = repo_not_stacked._pack_collection.get_pack_by_name(name)
1525
            keys = [n[1] for n in pack.inventory_index.iter_all_entries()]
1526
            if ('A',) in keys:
1527
                inv_a_pack_name = name
1528
                break
1529
        else:
1530
            self.fail('Could not find pack containing A\'s inventory')
1531
        repo_not_stacked.fetch(b_source.repository, 'A')
1532
        self.assertEqual([('A',), ('B',)],
1533
                         sorted(repo_not_stacked.revisions.keys()))
1534
        new_pack_names = set(repo_not_stacked._pack_collection.names())
1535
        rev_a_pack_names = new_pack_names.difference(stacked_pack_names)
1536
        self.assertEqual(1, len(rev_a_pack_names))
1537
        rev_a_pack_name = list(rev_a_pack_names)[0]
1538
        # Now fetch 'C', so we have a couple pack files to join
1539
        repo_not_stacked.fetch(b_source.repository, 'C')
1540
        rev_c_pack_names = set(repo_not_stacked._pack_collection.names())
1541
        rev_c_pack_names = rev_c_pack_names.difference(new_pack_names)
1542
        self.assertEqual(1, len(rev_c_pack_names))
1543
        rev_c_pack_name = list(rev_c_pack_names)[0]
1544
        return (repo_not_stacked, rev_a_pack_name, inv_a_pack_name,
1545
                rev_c_pack_name)
1546
1547
    def test_pack_with_distant_inventories(self):
1548
        # See https://bugs.launchpad.net/bzr/+bug/437003
1549
        # When repacking, it is possible to have an inventory in a different
1550
        # pack file than the associated revision. An autopack can then come
1551
        # along, and miss that inventory, and complain.
1552
        (repo, rev_a_pack_name, inv_a_pack_name, rev_c_pack_name
1553
         ) = self.make_branch_with_disjoint_inventory_and_revision()
1554
        a_pack = repo._pack_collection.get_pack_by_name(rev_a_pack_name)
1555
        c_pack = repo._pack_collection.get_pack_by_name(rev_c_pack_name)
1556
        packer = groupcompress_repo.GCCHKPacker(repo._pack_collection,
1557
                    [a_pack, c_pack], '.test-pack')
1558
        # This would raise ValueError in bug #437003, but should not raise an
1559
        # error once fixed.
1560
        packer.pack()
1561
1562
    def test_pack_with_missing_inventory(self):
1563
        # Similar to test_pack_with_missing_inventory, but this time, we force
1564
        # the A inventory to actually be gone from the repository.
1565
        (repo, rev_a_pack_name, inv_a_pack_name, rev_c_pack_name
1566
         ) = self.make_branch_with_disjoint_inventory_and_revision()
1567
        inv_a_pack = repo._pack_collection.get_pack_by_name(inv_a_pack_name)
1568
        repo._pack_collection._remove_pack_from_memory(inv_a_pack)
1569
        packer = groupcompress_repo.GCCHKPacker(repo._pack_collection,
1570
            repo._pack_collection.all_packs(), '.test-pack')
1571
        e = self.assertRaises(ValueError, packer.pack)
1572
        packer.new_pack.abort()
4634.170.2 by John Arbash Meinel
Loosen the match a bit. Newer versions have StaticTuple.
1573
        self.assertContainsRe(str(e),
1574
            r"We are missing inventories for revisions: .*'A'")
4634.170.1 by John Arbash Meinel
Fix bug #437003. Autopacking should not fail for an
1575
1576
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
1577
class TestCrossFormatPacks(TestCaseWithTransport):
1578
1579
    def log_pack(self, hint=None):
1580
        self.calls.append(('pack', hint))
1581
        self.orig_pack(hint=hint)
1582
        if self.expect_hint:
1583
            self.assertTrue(hint)
1584
1585
    def run_stream(self, src_fmt, target_fmt, expect_pack_called):
1586
        self.expect_hint = expect_pack_called
1587
        self.calls = []
1588
        source_tree = self.make_branch_and_tree('src', format=src_fmt)
1589
        source_tree.lock_write()
1590
        self.addCleanup(source_tree.unlock)
1591
        tip = source_tree.commit('foo')
1592
        target = self.make_repository('target', format=target_fmt)
1593
        target.lock_write()
1594
        self.addCleanup(target.unlock)
1595
        source = source_tree.branch.repository._get_source(target._format)
1596
        self.orig_pack = target.pack
1597
        target.pack = self.log_pack
1598
        search = target.search_missing_revision_ids(
5539.2.11 by Andrew Bennetts
Fix deprecation warning from test suite.
1599
            source_tree.branch.repository, revision_ids=[tip])
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
1600
        stream = source.get_stream(search)
1601
        from_format = source_tree.branch.repository._format
1602
        sink = target._get_sink()
1603
        sink.insert_stream(stream, from_format, [])
1604
        if expect_pack_called:
1605
            self.assertLength(1, self.calls)
1606
        else:
1607
            self.assertLength(0, self.calls)
1608
1609
    def run_fetch(self, src_fmt, target_fmt, expect_pack_called):
1610
        self.expect_hint = expect_pack_called
1611
        self.calls = []
1612
        source_tree = self.make_branch_and_tree('src', format=src_fmt)
1613
        source_tree.lock_write()
1614
        self.addCleanup(source_tree.unlock)
1615
        tip = source_tree.commit('foo')
1616
        target = self.make_repository('target', format=target_fmt)
1617
        target.lock_write()
1618
        self.addCleanup(target.unlock)
1619
        source = source_tree.branch.repository
1620
        self.orig_pack = target.pack
1621
        target.pack = self.log_pack
1622
        target.fetch(source)
1623
        if expect_pack_called:
1624
            self.assertLength(1, self.calls)
1625
        else:
1626
            self.assertLength(0, self.calls)
1627
1628
    def test_sink_format_hint_no(self):
1629
        # When the target format says packing makes no difference, pack is not
1630
        # called.
1631
        self.run_stream('1.9', 'rich-root-pack', False)
1632
1633
    def test_sink_format_hint_yes(self):
1634
        # When the target format says packing makes a difference, pack is
1635
        # called.
1636
        self.run_stream('1.9', '2a', True)
1637
1638
    def test_sink_format_same_no(self):
1639
        # When the formats are the same, pack is not called.
1640
        self.run_stream('2a', '2a', False)
1641
1642
    def test_IDS_format_hint_no(self):
1643
        # When the target format says packing makes no difference, pack is not
1644
        # called.
1645
        self.run_fetch('1.9', 'rich-root-pack', False)
1646
1647
    def test_IDS_format_hint_yes(self):
1648
        # When the target format says packing makes a difference, pack is
1649
        # called.
1650
        self.run_fetch('1.9', '2a', True)
1651
1652
    def test_IDS_format_same_no(self):
1653
        # When the formats are the same, pack is not called.
1654
        self.run_fetch('2a', '2a', False)