/brz/remove-bazaar

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