/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__))
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
143
        check_format(weaverepo.RepositoryFormat7(), "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
653
class TestRepositoryConverter(TestCaseWithTransport):
654
655
    def test_convert_empty(self):
5609.9.4 by Vincent Ladeuil
Use self.get_transport instead of transport.get_transport where possible.
656
        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.
657
        t.mkdir('repository')
658
        repo_dir = bzrdir.BzrDirMetaFormat1().initialize('repository')
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
659
        repo = weaverepo.RepositoryFormat7().initialize(repo_dir)
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
660
        target_format = knitrepo.RepositoryFormatKnit1()
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.
661
        converter = repository.CopyConverter(target_format)
1594.1.3 by Robert Collins
Fixup pb usage to use nested_progress_bar.
662
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
663
        try:
664
            converter.convert(repo, pb)
665
        finally:
666
            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.
667
        repo = repo_dir.open_repository()
668
        self.assertTrue(isinstance(target_format, repo._format.__class__))
1843.2.5 by Aaron Bentley
Add test of _unescape_xml
669
670
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
671
class TestRepositoryFormatKnit3(TestCaseWithTransport):
1910.2.13 by Aaron Bentley
Start work on converter
672
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
673
    def test_attribute__fetch_order(self):
674
        """Knits need topological data insertion."""
675
        format = bzrdir.BzrDirMetaFormat1()
676
        format.repository_format = knitrepo.RepositoryFormatKnit3()
677
        repo = self.make_repository('.', format=format)
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
678
        self.assertEqual('topological', repo._format._fetch_order)
3565.3.1 by Robert Collins
* The generic fetch code now uses two attributes on Repository objects
679
680
    def test_attribute__fetch_uses_deltas(self):
681
        """Knits reuse deltas."""
682
        format = bzrdir.BzrDirMetaFormat1()
683
        format.repository_format = knitrepo.RepositoryFormatKnit3()
684
        repo = self.make_repository('.', format=format)
4053.1.4 by Robert Collins
Move the fetch control attributes from Repository to RepositoryFormat.
685
        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
686
1910.2.13 by Aaron Bentley
Start work on converter
687
    def test_convert(self):
688
        """Ensure the upgrade adds weaves for roots"""
1910.2.35 by Aaron Bentley
Better fix for convesion test
689
        format = bzrdir.BzrDirMetaFormat1()
2241.1.6 by Martin Pool
Move Knit repositories into the submodule bzrlib.repofmt.knitrepo and
690
        format.repository_format = knitrepo.RepositoryFormatKnit1()
1910.2.35 by Aaron Bentley
Better fix for convesion test
691
        tree = self.make_branch_and_tree('.', format)
1910.2.13 by Aaron Bentley
Start work on converter
692
        tree.commit("Dull commit", rev_id="dull")
693
        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.
694
        revision_tree.lock_read()
695
        try:
696
            self.assertRaises(errors.NoSuchFile, revision_tree.get_file_lines,
697
                revision_tree.inventory.root.file_id)
698
        finally:
699
            revision_tree.unlock()
1910.2.13 by Aaron Bentley
Start work on converter
700
        format = bzrdir.BzrDirMetaFormat1()
2255.2.211 by Robert Collins
Remove knit2 repository format- it has never been supported.
701
        format.repository_format = knitrepo.RepositoryFormatKnit3()
1910.2.13 by Aaron Bentley
Start work on converter
702
        upgrade.Convert('.', format)
1910.2.27 by Aaron Bentley
Fixed conversion test
703
        tree = workingtree.WorkingTree.open('.')
1910.2.13 by Aaron Bentley
Start work on converter
704
        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.
705
        revision_tree.lock_read()
706
        try:
707
            revision_tree.get_file_lines(revision_tree.inventory.root.file_id)
708
        finally:
709
            revision_tree.unlock()
1910.2.27 by Aaron Bentley
Fixed conversion test
710
        tree.commit("Another dull commit", rev_id='dull2')
711
        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.
712
        revision_tree.lock_read()
713
        self.addCleanup(revision_tree.unlock)
1910.2.27 by Aaron Bentley
Fixed conversion test
714
        self.assertEqual('dull', revision_tree.inventory.root.revision)
2220.2.2 by Martin Pool
Add tag command and basic implementation
715
3221.3.1 by Robert Collins
* Repository formats have a new supported-feature attribute
716
    def test_supports_external_lookups(self):
717
        format = bzrdir.BzrDirMetaFormat1()
718
        format.repository_format = knitrepo.RepositoryFormatKnit3()
719
        repo = self.make_repository('.', format=format)
720
        self.assertFalse(repo._format.supports_external_lookups)
721
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
722
4667.1.1 by John Arbash Meinel
Drop the Test2a test times from 5+s down to 1.4s
723
class Test2a(tests.TestCaseWithMemoryTransport):
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
724
5365.5.20 by John Arbash Meinel
Add some tests that check the leaf factory is correct.
725
    def test_chk_bytes_uses_custom_btree_parser(self):
726
        mt = self.make_branch_and_memory_tree('test', format='2a')
727
        mt.lock_write()
728
        self.addCleanup(mt.unlock)
729
        mt.add([''], ['root-id'])
730
        mt.commit('first')
731
        index = mt.branch.repository.chk_bytes._index._graph_index._indices[0]
732
        self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
733
        # It should also work if we re-open the repo
734
        repo = mt.branch.repository.bzrdir.open_repository()
735
        repo.lock_read()
736
        self.addCleanup(repo.unlock)
737
        index = repo.chk_bytes._index._graph_index._indices[0]
738
        self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
739
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.
740
    def test_fetch_combines_groups(self):
741
        builder = self.make_branch_builder('source', format='2a')
742
        builder.start_series()
743
        builder.build_snapshot('1', None, [
744
            ('add', ('', 'root-id', 'directory', '')),
745
            ('add', ('file', 'file-id', 'file', 'content\n'))])
746
        builder.build_snapshot('2', ['1'], [
747
            ('modify', ('file-id', 'content-2\n'))])
748
        builder.finish_series()
749
        source = builder.get_branch()
750
        target = self.make_repository('target', format='2a')
751
        target.fetch(source.repository)
752
        target.lock_read()
4665.3.2 by John Arbash Meinel
An alternative implementation that passes both tests.
753
        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.
754
        details = target.texts._index.get_build_details(
755
            [('file-id', '1',), ('file-id', '2',)])
756
        file_1_details = details[('file-id', '1')]
757
        file_2_details = details[('file-id', '2')]
758
        # The index, and what to read off disk, should be the same for both
759
        # versions of the file.
760
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
761
4634.23.1 by Robert Collins
Cherrypick from bzr.dev: Fix bug 402652: recompress badly packed groups during fetch. (John Arbash Meinel, Robert Collins)
762
    def test_fetch_combines_groups(self):
763
        builder = self.make_branch_builder('source', format='2a')
764
        builder.start_series()
765
        builder.build_snapshot('1', None, [
766
            ('add', ('', 'root-id', 'directory', '')),
767
            ('add', ('file', 'file-id', 'file', 'content\n'))])
768
        builder.build_snapshot('2', ['1'], [
769
            ('modify', ('file-id', 'content-2\n'))])
770
        builder.finish_series()
771
        source = builder.get_branch()
772
        target = self.make_repository('target', format='2a')
773
        target.fetch(source.repository)
774
        target.lock_read()
775
        self.addCleanup(target.unlock)
776
        details = target.texts._index.get_build_details(
777
            [('file-id', '1',), ('file-id', '2',)])
778
        file_1_details = details[('file-id', '1')]
779
        file_2_details = details[('file-id', '2')]
780
        # The index, and what to read off disk, should be the same for both
781
        # versions of the file.
782
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
783
784
    def test_fetch_combines_groups(self):
785
        builder = self.make_branch_builder('source', format='2a')
786
        builder.start_series()
787
        builder.build_snapshot('1', None, [
788
            ('add', ('', 'root-id', 'directory', '')),
789
            ('add', ('file', 'file-id', 'file', 'content\n'))])
790
        builder.build_snapshot('2', ['1'], [
791
            ('modify', ('file-id', 'content-2\n'))])
792
        builder.finish_series()
793
        source = builder.get_branch()
794
        target = self.make_repository('target', format='2a')
795
        target.fetch(source.repository)
796
        target.lock_read()
797
        self.addCleanup(target.unlock)
798
        details = target.texts._index.get_build_details(
799
            [('file-id', '1',), ('file-id', '2',)])
800
        file_1_details = details[('file-id', '1')]
801
        file_2_details = details[('file-id', '2')]
802
        # The index, and what to read off disk, should be the same for both
803
        # versions of the file.
804
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
805
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
806
    def test_format_pack_compresses_True(self):
807
        repo = self.make_repository('repo', format='2a')
808
        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.
809
810
    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
811
        tree = self.make_branch_and_memory_tree('repo', format="2a")
812
        tree.lock_write()
813
        tree.add([''], ['TREE_ROOT'])
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
814
        revid = tree.commit("foo")
4667.1.1 by John Arbash Meinel
Drop the Test2a test times from 5+s down to 1.4s
815
        tree.unlock()
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
816
        tree.lock_read()
817
        self.addCleanup(tree.unlock)
818
        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.
819
        self.assertNotEqual(None, inv.parent_id_basename_to_file_id)
820
        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.
821
        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)
822
        self.assertEqual(65536, inv.id_to_entry._root_node.maximum_size)
823
        self.assertEqual(65536,
3735.2.41 by Robert Collins
Make the parent_id_basename index be updated during CHKInventory.apply_delta.
824
            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.
825
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
826
    def test_autopack_unchanged_chk_nodes(self):
827
        # at 20 unchanged commits, chk pages are packed that are split into
828
        # two groups such that the new pack being made doesn't have all its
829
        # 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
830
        # Use a memory backed repository, we don't need to hit disk for this
831
        tree = self.make_branch_and_memory_tree('tree', format='2a')
832
        tree.lock_write()
833
        self.addCleanup(tree.unlock)
834
        tree.add([''], ['TREE_ROOT'])
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
835
        for pos in range(20):
836
            tree.commit(str(pos))
837
838
    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
839
        tree = self.make_branch_and_memory_tree('tree', format='2a')
840
        tree.lock_write()
841
        self.addCleanup(tree.unlock)
842
        tree.add([''], ['TREE_ROOT'])
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
843
        # 1 commit to leave untouched
844
        tree.commit('1')
845
        to_keep = tree.branch.repository._pack_collection.names()
846
        # 2 to combine
847
        tree.commit('2')
848
        tree.commit('3')
849
        all = tree.branch.repository._pack_collection.names()
850
        combine = list(set(all) - set(to_keep))
851
        self.assertLength(3, all)
852
        self.assertLength(2, combine)
853
        tree.branch.repository.pack(hint=combine)
854
        final = tree.branch.repository._pack_collection.names()
855
        self.assertLength(2, final)
856
        self.assertFalse(combine[0] in final)
857
        self.assertFalse(combine[1] in final)
858
        self.assertSubset(to_keep, final)
859
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
860
    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.
861
        source = self.make_repository('source', format='2a')
862
        target = self.make_repository('target', format='2a')
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
863
        stream = source._get_source(target._format)
864
        self.assertIsInstance(stream, groupcompress_repo.GroupCHKStreamSource)
865
866
    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.
867
        source = self.make_repository('source', format='2a')
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
868
        target = self.make_repository('target', format='rich-root-pack')
869
        stream = source._get_source(target._format)
870
        # We don't want the child GroupCHKStreamSource
871
        self.assertIs(type(stream), repository.StreamSource)
872
4360.4.9 by John Arbash Meinel
Merge bzr.dev, bringing in the gc stacking fixes.
873
    def test_get_stream_for_missing_keys_includes_all_chk_refs(self):
874
        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.
875
                            format='2a')
4360.4.9 by John Arbash Meinel
Merge bzr.dev, bringing in the gc stacking fixes.
876
        # We have to build a fairly large tree, so that we are sure the chk
877
        # pages will have split into multiple pages.
878
        entries = [('add', ('', 'a-root-id', 'directory', None))]
879
        for i in 'abcdefghijklmnopqrstuvwxyz123456789':
880
            for j in 'abcdefghijklmnopqrstuvwxyz123456789':
881
                fname = i + j
882
                fid = fname + '-id'
883
                content = 'content for %s\n' % (fname,)
884
                entries.append(('add', (fname, fid, 'file', content)))
885
        source_builder.start_series()
886
        source_builder.build_snapshot('rev-1', None, entries)
887
        # Now change a few of them, so we get a few new pages for the second
888
        # revision
889
        source_builder.build_snapshot('rev-2', ['rev-1'], [
890
            ('modify', ('aa-id', 'new content for aa-id\n')),
891
            ('modify', ('cc-id', 'new content for cc-id\n')),
892
            ('modify', ('zz-id', 'new content for zz-id\n')),
893
            ])
894
        source_builder.finish_series()
895
        source_branch = source_builder.get_branch()
896
        source_branch.lock_read()
897
        self.addCleanup(source_branch.unlock)
4462.2.1 by Robert Collins
Add new attribute to RepositoryFormat pack_compresses, hinting when pack can be useful.
898
        target = self.make_repository('target', format='2a')
4360.4.9 by John Arbash Meinel
Merge bzr.dev, bringing in the gc stacking fixes.
899
        source = source_branch.repository._get_source(target._format)
900
        self.assertIsInstance(source, groupcompress_repo.GroupCHKStreamSource)
901
902
        # On a regular pass, getting the inventories and chk pages for rev-2
903
        # would only get the newly created chk pages
904
        search = graph.SearchResult(set(['rev-2']), set(['rev-1']), 1,
905
                                    set(['rev-2']))
906
        simple_chk_records = []
907
        for vf_name, substream in source.get_stream(search):
908
            if vf_name == 'chk_bytes':
909
                for record in substream:
910
                    simple_chk_records.append(record.key)
911
            else:
912
                for _ in substream:
913
                    continue
914
        # 3 pages, the root (InternalNode), + 2 pages which actually changed
915
        self.assertEqual([('sha1:91481f539e802c76542ea5e4c83ad416bf219f73',),
916
                          ('sha1:4ff91971043668583985aec83f4f0ab10a907d3f',),
917
                          ('sha1:81e7324507c5ca132eedaf2d8414ee4bb2226187',),
918
                          ('sha1:b101b7da280596c71a4540e9a1eeba8045985ee0',)],
919
                         simple_chk_records)
920
        # Now, when we do a similar call using 'get_stream_for_missing_keys'
921
        # we should get a much larger set of pages.
922
        missing = [('inventories', 'rev-2')]
923
        full_chk_records = []
924
        for vf_name, substream in source.get_stream_for_missing_keys(missing):
925
            if vf_name == 'inventories':
926
                for record in substream:
927
                    self.assertEqual(('rev-2',), record.key)
928
            elif vf_name == 'chk_bytes':
929
                for record in substream:
930
                    full_chk_records.append(record.key)
931
            else:
932
                self.fail('Should not be getting a stream of %s' % (vf_name,))
933
        # We have 257 records now. This is because we have 1 root page, and 256
934
        # leaf pages in a complete listing.
935
        self.assertEqual(257, len(full_chk_records))
936
        self.assertSubset(simple_chk_records, full_chk_records)
937
4465.2.7 by Aaron Bentley
Move test_inconsistency_fatal to test_repository
938
    def test_inconsistency_fatal(self):
939
        repo = self.make_repository('repo', format='2a')
940
        self.assertTrue(repo.revisions._index._inconsistency_fatal)
941
        self.assertFalse(repo.texts._index._inconsistency_fatal)
942
        self.assertFalse(repo.inventories._index._inconsistency_fatal)
943
        self.assertFalse(repo.signatures._index._inconsistency_fatal)
944
        self.assertFalse(repo.chk_bytes._index._inconsistency_fatal)
945
4360.4.3 by John Arbash Meinel
Introduce a KnitPackStreamSource which is used when
946
947
class TestKnitPackStreamSource(tests.TestCaseWithMemoryTransport):
948
949
    def test_source_to_exact_pack_092(self):
950
        source = self.make_repository('source', format='pack-0.92')
951
        target = self.make_repository('target', format='pack-0.92')
952
        stream_source = source._get_source(target._format)
953
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
954
955
    def test_source_to_exact_pack_rich_root_pack(self):
956
        source = self.make_repository('source', format='rich-root-pack')
957
        target = self.make_repository('target', format='rich-root-pack')
958
        stream_source = source._get_source(target._format)
959
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
960
961
    def test_source_to_exact_pack_19(self):
962
        source = self.make_repository('source', format='1.9')
963
        target = self.make_repository('target', format='1.9')
964
        stream_source = source._get_source(target._format)
965
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
966
967
    def test_source_to_exact_pack_19_rich_root(self):
968
        source = self.make_repository('source', format='1.9-rich-root')
969
        target = self.make_repository('target', format='1.9-rich-root')
970
        stream_source = source._get_source(target._format)
971
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
972
973
    def test_source_to_remote_exact_pack_19(self):
974
        trans = self.make_smart_server('target')
975
        trans.ensure_base()
976
        source = self.make_repository('source', format='1.9')
977
        target = self.make_repository('target', format='1.9')
978
        target = repository.Repository.open(trans.base)
979
        stream_source = source._get_source(target._format)
980
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
981
982
    def test_stream_source_to_non_exact(self):
983
        source = self.make_repository('source', format='pack-0.92')
984
        target = self.make_repository('target', format='1.9')
985
        stream = source._get_source(target._format)
986
        self.assertIs(type(stream), repository.StreamSource)
987
988
    def test_stream_source_to_non_exact_rich_root(self):
989
        source = self.make_repository('source', format='1.9')
990
        target = self.make_repository('target', format='1.9-rich-root')
991
        stream = source._get_source(target._format)
992
        self.assertIs(type(stream), repository.StreamSource)
993
994
    def test_source_to_remote_non_exact_pack_19(self):
995
        trans = self.make_smart_server('target')
996
        trans.ensure_base()
997
        source = self.make_repository('source', format='1.9')
998
        target = self.make_repository('target', format='1.6')
999
        target = repository.Repository.open(trans.base)
1000
        stream_source = source._get_source(target._format)
1001
        self.assertIs(type(stream_source), repository.StreamSource)
1002
1003
    def test_stream_source_to_knit(self):
1004
        source = self.make_repository('source', format='pack-0.92')
1005
        target = self.make_repository('target', format='dirstate')
1006
        stream = source._get_source(target._format)
1007
        self.assertIs(type(stream), repository.StreamSource)
1008
3735.2.40 by Robert Collins
Add development4 which has a parent_id to basename index on CHKInventory objects.
1009
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
1010
class TestDevelopment6FindParentIdsOfRevisions(TestCaseWithTransport):
1011
    """Tests for _find_parent_ids_of_revisions."""
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1012
1013
    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.
1014
        super(TestDevelopment6FindParentIdsOfRevisions, self).setUp()
5546.1.1 by Andrew Bennetts
Remove RepositoryFormatCHK1 and RepositoryFormatCHK2.
1015
        self.builder = self.make_branch_builder('source')
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1016
        self.builder.start_series()
1017
        self.builder.build_snapshot('initial', None,
1018
            [('add', ('', 'tree-root', 'directory', None))])
1019
        self.repo = self.builder.get_branch().repository
1020
        self.addCleanup(self.builder.finish_series)
3735.2.99 by John Arbash Meinel
Merge bzr.dev 4034. Whitespace cleanup
1021
4343.3.32 by John Arbash Meinel
Change the tests for _find_revision_outside_set to the new _find_parent_ids function.
1022
    def assertParentIds(self, expected_result, rev_set):
1023
        self.assertEqual(sorted(expected_result),
1024
            sorted(self.repo._find_parent_ids_of_revisions(rev_set)))
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1025
1026
    def test_simple(self):
1027
        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.
1028
        self.builder.build_snapshot('revid2', ['revid1'], [])
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1029
        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.
1030
        self.assertParentIds(['revid1'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1031
1032
    def test_not_first_parent(self):
1033
        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.
1034
        self.builder.build_snapshot('revid2', ['revid1'], [])
1035
        self.builder.build_snapshot('revid3', ['revid2'], [])
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1036
        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.
1037
        self.assertParentIds(['revid1'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1038
1039
    def test_not_null(self):
1040
        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.
1041
        self.assertParentIds([], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1042
1043
    def test_not_null_set(self):
1044
        self.builder.build_snapshot('revid1', None, [])
1045
        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.
1046
        self.assertParentIds([], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1047
1048
    def test_ghost(self):
1049
        self.builder.build_snapshot('revid1', None, [])
1050
        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.
1051
        self.assertParentIds(['initial'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1052
1053
    def test_ghost_parent(self):
1054
        self.builder.build_snapshot('revid1', None, [])
1055
        self.builder.build_snapshot('revid2', ['revid1', 'ghost'], [])
1056
        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.
1057
        self.assertParentIds(['ghost', 'initial'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1058
1059
    def test_righthand_parent(self):
1060
        self.builder.build_snapshot('revid1', None, [])
1061
        self.builder.build_snapshot('revid2a', ['revid1'], [])
1062
        self.builder.build_snapshot('revid2b', ['revid1'], [])
1063
        self.builder.build_snapshot('revid3', ['revid2a', 'revid2b'], [])
1064
        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.
1065
        self.assertParentIds(['revid1', 'revid2b'], rev_set)
3735.4.1 by Andrew Bennetts
Add _find_revision_outside_set.
1066
1067
2535.3.57 by Andrew Bennetts
Perform some sanity checking of data streams rather than blindly inserting them into our repository.
1068
class TestWithBrokenRepo(TestCaseWithTransport):
2592.3.214 by Robert Collins
Merge bzr.dev.
1069
    """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.
1070
1071
    def make_broken_repository(self):
1072
        # XXX: This function is borrowed from Aaron's "Reconcile can fix bad
1073
        # parent references" branch which is due to land in bzr.dev soon.  Once
1074
        # it does, this duplication should be removed.
1075
        repo = self.make_repository('broken-repo')
1076
        cleanups = []
1077
        try:
1078
            repo.lock_write()
1079
            cleanups.append(repo.unlock)
1080
            repo.start_write_group()
1081
            cleanups.append(repo.commit_write_group)
1082
            # make rev1a: A well-formed revision, containing 'file1'
1083
            inv = inventory.Inventory(revision_id='rev1a')
1084
            inv.root.revision = 'rev1a'
1085
            self.add_file(repo, inv, 'file1', 'rev1a', [])
4634.35.21 by Andrew Bennetts
Fix test_insert_from_broken_repo in test_repository.
1086
            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.
1087
            repo.add_inventory('rev1a', inv, [])
1088
            revision = _mod_revision.Revision('rev1a',
1089
                committer='jrandom@example.com', timestamp=0,
1090
                inventory_sha1='', timezone=0, message='foo', parent_ids=[])
1091
            repo.add_revision('rev1a',revision, inv)
1092
1093
            # make rev1b, which has no Revision, but has an Inventory, and
1094
            # file1
1095
            inv = inventory.Inventory(revision_id='rev1b')
1096
            inv.root.revision = 'rev1b'
1097
            self.add_file(repo, inv, 'file1', 'rev1b', [])
1098
            repo.add_inventory('rev1b', inv, [])
1099
1100
            # make rev2, with file1 and file2
1101
            # file2 is sane
1102
            # file1 has 'rev1b' as an ancestor, even though this is not
1103
            # mentioned by 'rev1a', making it an unreferenced ancestor
1104
            inv = inventory.Inventory()
1105
            self.add_file(repo, inv, 'file1', 'rev2', ['rev1a', 'rev1b'])
1106
            self.add_file(repo, inv, 'file2', 'rev2', [])
1107
            self.add_revision(repo, 'rev2', inv, ['rev1a'])
1108
1109
            # make ghost revision rev1c
1110
            inv = inventory.Inventory()
1111
            self.add_file(repo, inv, 'file2', 'rev1c', [])
1112
1113
            # make rev3 with file2
1114
            # file2 refers to 'rev1c', which is a ghost in this repository, so
1115
            # file2 cannot have rev1c as its ancestor.
1116
            inv = inventory.Inventory()
1117
            self.add_file(repo, inv, 'file2', 'rev3', ['rev1c'])
1118
            self.add_revision(repo, 'rev3', inv, ['rev1c'])
1119
            return repo
1120
        finally:
1121
            for cleanup in reversed(cleanups):
1122
                cleanup()
1123
1124
    def add_revision(self, repo, revision_id, inv, parent_ids):
1125
        inv.revision_id = revision_id
1126
        inv.root.revision = revision_id
4634.35.21 by Andrew Bennetts
Fix test_insert_from_broken_repo in test_repository.
1127
        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.
1128
        repo.add_inventory(revision_id, inv, parent_ids)
1129
        revision = _mod_revision.Revision(revision_id,
1130
            committer='jrandom@example.com', timestamp=0, inventory_sha1='',
1131
            timezone=0, message='foo', parent_ids=parent_ids)
1132
        repo.add_revision(revision_id,revision, inv)
1133
1134
    def add_file(self, repo, inv, filename, revision, parents):
1135
        file_id = filename + '-id'
1136
        entry = inventory.InventoryFile(file_id, filename, 'TREE_ROOT')
1137
        entry.revision = revision
2535.4.10 by Andrew Bennetts
Fix one failing test, disable another.
1138
        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.
1139
        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.
1140
        text_key = (file_id, revision)
1141
        parent_keys = [(file_id, parent) for parent in parents]
1142
        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.
1143
1144
    def test_insert_from_broken_repo(self):
1145
        """Inserting a data stream from a broken repository won't silently
1146
        corrupt the target repository.
1147
        """
1148
        broken_repo = self.make_broken_repository()
1149
        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.
1150
        try:
1151
            empty_repo.fetch(broken_repo)
1152
        except (errors.RevisionNotPresent, errors.BzrCheckError):
1153
            # Test successful: compression parent not being copied leads to
1154
            # error.
1155
            return
1156
        empty_repo.lock_read()
1157
        self.addCleanup(empty_repo.unlock)
1158
        text = empty_repo.texts.get_record_stream(
1159
            [('file2-id', 'rev3')], 'topological', True).next()
1160
        self.assertEqual('line\n', text.get_bytes_as('fulltext'))
2592.3.214 by Robert Collins
Merge bzr.dev.
1161
1162
2592.3.84 by Robert Collins
Start of autopacking logic.
1163
class TestRepositoryPackCollection(TestCaseWithTransport):
1164
1165
    def get_format(self):
3010.3.3 by Martin Pool
Merge trunk
1166
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
2592.3.84 by Robert Collins
Start of autopacking logic.
1167
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1168
    def get_packs(self):
1169
        format = self.get_format()
1170
        repo = self.make_repository('.', format=format)
1171
        return repo._pack_collection
1172
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1173
    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
1174
        """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.
1175
        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
1176
        tree.lock_write()
1177
        self.addCleanup(tree.unlock)
1178
        rev1 = tree.commit('one')
1179
        rev2 = tree.commit('two')
1180
        rev3 = tree.commit('three')
1181
        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.
1182
        if write_lock:
1183
            r.lock_write()
1184
        else:
1185
            r.lock_read()
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1186
        self.addCleanup(r.unlock)
1187
        packs = r._pack_collection
1188
        packs.ensure_loaded()
1189
        return tree, r, packs, [rev1, rev2, rev3]
1190
4634.127.1 by John Arbash Meinel
Partial fix for bug #507557.
1191
    def test__clear_obsolete_packs(self):
1192
        packs = self.get_packs()
1193
        obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1194
        obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1195
        obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1196
        obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1197
        obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1198
        obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1199
        res = packs._clear_obsolete_packs()
1200
        self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1201
        self.assertEqual([], obsolete_pack_trans.list_dir('.'))
1202
1203
    def test__clear_obsolete_packs_preserve(self):
1204
        packs = self.get_packs()
1205
        obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1206
        obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1207
        obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1208
        obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1209
        obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1210
        obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1211
        res = packs._clear_obsolete_packs(preserve=set(['a-pack']))
1212
        self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1213
        self.assertEqual(['a-pack.iix', 'a-pack.pack', 'a-pack.rix'],
1214
                         sorted(obsolete_pack_trans.list_dir('.')))
1215
2592.3.84 by Robert Collins
Start of autopacking logic.
1216
    def test__max_pack_count(self):
2592.3.219 by Robert Collins
Review feedback.
1217
        """The maximum pack count is a function of the number of revisions."""
2592.3.84 by Robert Collins
Start of autopacking logic.
1218
        # no revisions - one pack, so that we can have a revision free repo
1219
        # without it blowing up
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1220
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1221
        self.assertEqual(1, packs._max_pack_count(0))
1222
        # after that the sum of the digits, - check the first 1-9
1223
        self.assertEqual(1, packs._max_pack_count(1))
1224
        self.assertEqual(2, packs._max_pack_count(2))
1225
        self.assertEqual(3, packs._max_pack_count(3))
1226
        self.assertEqual(4, packs._max_pack_count(4))
1227
        self.assertEqual(5, packs._max_pack_count(5))
1228
        self.assertEqual(6, packs._max_pack_count(6))
1229
        self.assertEqual(7, packs._max_pack_count(7))
1230
        self.assertEqual(8, packs._max_pack_count(8))
1231
        self.assertEqual(9, packs._max_pack_count(9))
1232
        # check the boundary cases with two digits for the next decade
1233
        self.assertEqual(1, packs._max_pack_count(10))
1234
        self.assertEqual(2, packs._max_pack_count(11))
1235
        self.assertEqual(10, packs._max_pack_count(19))
1236
        self.assertEqual(2, packs._max_pack_count(20))
1237
        self.assertEqual(3, packs._max_pack_count(21))
1238
        # check some arbitrary big numbers
1239
        self.assertEqual(25, packs._max_pack_count(112894))
1240
4928.1.1 by Martin Pool
Give RepositoryPackCollection a repr
1241
    def test_repr(self):
1242
        packs = self.get_packs()
1243
        self.assertContainsRe(repr(packs),
1244
            'RepositoryPackCollection(.*Repository(.*))')
1245
4634.127.2 by John Arbash Meinel
Change the _obsolete_packs code to handle files that are already gone.
1246
    def test__obsolete_packs(self):
1247
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1248
        names = packs.names()
1249
        pack = packs.get_pack_by_name(names[0])
1250
        # Schedule this one for removal
1251
        packs._remove_pack_from_memory(pack)
1252
        # Simulate a concurrent update by renaming the .pack file and one of
1253
        # the indices
1254
        packs.transport.rename('packs/%s.pack' % (names[0],),
1255
                               'obsolete_packs/%s.pack' % (names[0],))
1256
        packs.transport.rename('indices/%s.iix' % (names[0],),
1257
                               'obsolete_packs/%s.iix' % (names[0],))
1258
        # Now trigger the obsoletion, and ensure that all the remaining files
1259
        # are still renamed
1260
        packs._obsolete_packs([pack])
1261
        self.assertEqual([n + '.pack' for n in names[1:]],
1262
                         sorted(packs._pack_transport.list_dir('.')))
1263
        # names[0] should not be present in the index anymore
1264
        self.assertEqual(names[1:],
1265
            sorted(set([osutils.splitext(n)[0] for n in
1266
                        packs._index_transport.list_dir('.')])))
1267
2592.3.84 by Robert Collins
Start of autopacking logic.
1268
    def test_pack_distribution_zero(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1269
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1270
        self.assertEqual([0], packs.pack_distribution(0))
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
1271
1272
    def test_ensure_loaded_unlocked(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1273
        packs = self.get_packs()
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
1274
        self.assertRaises(errors.ObjectNotLocked,
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1275
                          packs.ensure_loaded)
3052.1.6 by John Arbash Meinel
Change the lock check to raise ObjectNotLocked.
1276
2592.3.84 by Robert Collins
Start of autopacking logic.
1277
    def test_pack_distribution_one_to_nine(self):
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1278
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1279
        self.assertEqual([1],
1280
            packs.pack_distribution(1))
1281
        self.assertEqual([1, 1],
1282
            packs.pack_distribution(2))
1283
        self.assertEqual([1, 1, 1],
1284
            packs.pack_distribution(3))
1285
        self.assertEqual([1, 1, 1, 1],
1286
            packs.pack_distribution(4))
1287
        self.assertEqual([1, 1, 1, 1, 1],
1288
            packs.pack_distribution(5))
1289
        self.assertEqual([1, 1, 1, 1, 1, 1],
1290
            packs.pack_distribution(6))
1291
        self.assertEqual([1, 1, 1, 1, 1, 1, 1],
1292
            packs.pack_distribution(7))
1293
        self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1],
1294
            packs.pack_distribution(8))
1295
        self.assertEqual([1, 1, 1, 1, 1, 1, 1, 1, 1],
1296
            packs.pack_distribution(9))
1297
1298
    def test_pack_distribution_stable_at_boundaries(self):
1299
        """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,
1300
        packs = self.get_packs()
2592.3.84 by Robert Collins
Start of autopacking logic.
1301
        # in 10s:
1302
        self.assertEqual([10], packs.pack_distribution(10))
1303
        self.assertEqual([10, 1], packs.pack_distribution(11))
1304
        self.assertEqual([10, 10], packs.pack_distribution(20))
1305
        self.assertEqual([10, 10, 1], packs.pack_distribution(21))
1306
        # 100s
1307
        self.assertEqual([100], packs.pack_distribution(100))
1308
        self.assertEqual([100, 1], packs.pack_distribution(101))
1309
        self.assertEqual([100, 10, 1], packs.pack_distribution(111))
1310
        self.assertEqual([100, 100], packs.pack_distribution(200))
1311
        self.assertEqual([100, 100, 1], packs.pack_distribution(201))
1312
        self.assertEqual([100, 100, 10, 1], packs.pack_distribution(211))
1313
2592.3.85 by Robert Collins
Finish autopack corner cases.
1314
    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,
1315
        packs = self.get_packs()
2592.3.85 by Robert Collins
Finish autopack corner cases.
1316
        existing_packs = [(2000, "big"), (9, "medium")]
1317
        # rev count - 2009 -> 2x1000 + 9x1
1318
        pack_operations = packs.plan_autopack_combinations(
1319
            existing_packs, [1000, 1000, 1, 1, 1, 1, 1, 1, 1, 1, 1])
1320
        self.assertEqual([], pack_operations)
1321
1322
    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,
1323
        packs = self.get_packs()
2592.3.85 by Robert Collins
Finish autopack corner cases.
1324
        existing_packs = [(2000, "big"), (9, "medium"), (1, "single")]
1325
        # rev count - 2010 -> 2x1000 + 1x10
1326
        pack_operations = packs.plan_autopack_combinations(
1327
            existing_packs, [1000, 1000, 10])
1328
        self.assertEqual([], pack_operations)
1329
1330
    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,
1331
        packs = self.get_packs()
2592.3.85 by Robert Collins
Finish autopack corner cases.
1332
        existing_packs = [(1999, "big"), (9, "medium"), (1, "single2"),
1333
            (1, "single1")]
1334
        # rev count - 2010 -> 2x1000 + 1x10 (3)
1335
        pack_operations = packs.plan_autopack_combinations(
1336
            existing_packs, [1000, 1000, 10])
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1337
        self.assertEqual([[2, ["single2", "single1"]]], pack_operations)
2592.3.85 by Robert Collins
Finish autopack corner cases.
1338
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1339
    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,
1340
        packs = self.get_packs()
3711.4.2 by John Arbash Meinel
Change the logic to solve it in a different way.
1341
        existing_packs = [(50, 'a'), (40, 'b'), (30, 'c'), (10, 'd'),
1342
                          (10, 'e'), (6, 'f'), (4, 'g')]
1343
        # rev count 150 -> 1x100 and 5x10
1344
        # The two size 10 packs do not need to be touched. The 50, 40, 30 would
1345
        # be combined into a single 120 size pack, and the 6 & 4 would
1346
        # becombined into a size 10 pack. However, if we have to rewrite them,
1347
        # we save a pack file with no increased I/O by putting them into the
1348
        # same file.
1349
        distribution = packs.pack_distribution(150)
3711.4.1 by John Arbash Meinel
Fix bug #242510, when determining the autopack sequence,
1350
        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.
1351
                                                           distribution)
1352
        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,
1353
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1354
    def test_all_packs_none(self):
1355
        format = self.get_format()
1356
        tree = self.make_branch_and_tree('.', format=format)
1357
        tree.lock_read()
1358
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1359
        packs = tree.branch.repository._pack_collection
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1360
        packs.ensure_loaded()
1361
        self.assertEqual([], packs.all_packs())
1362
1363
    def test_all_packs_one(self):
1364
        format = self.get_format()
1365
        tree = self.make_branch_and_tree('.', format=format)
1366
        tree.commit('start')
1367
        tree.lock_read()
1368
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1369
        packs = tree.branch.repository._pack_collection
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1370
        packs.ensure_loaded()
2592.3.176 by Robert Collins
Various pack refactorings.
1371
        self.assertEqual([
1372
            packs.get_pack_by_name(packs.names()[0])],
1373
            packs.all_packs())
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1374
1375
    def test_all_packs_two(self):
1376
        format = self.get_format()
1377
        tree = self.make_branch_and_tree('.', format=format)
1378
        tree.commit('start')
1379
        tree.commit('continue')
1380
        tree.lock_read()
1381
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1382
        packs = tree.branch.repository._pack_collection
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1383
        packs.ensure_loaded()
1384
        self.assertEqual([
2592.3.176 by Robert Collins
Various pack refactorings.
1385
            packs.get_pack_by_name(packs.names()[0]),
1386
            packs.get_pack_by_name(packs.names()[1]),
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1387
            ], packs.all_packs())
1388
2592.3.176 by Robert Collins
Various pack refactorings.
1389
    def test_get_pack_by_name(self):
1390
        format = self.get_format()
1391
        tree = self.make_branch_and_tree('.', format=format)
1392
        tree.commit('start')
1393
        tree.lock_read()
1394
        self.addCleanup(tree.unlock)
2592.3.232 by Martin Pool
Disambiguate two member variables called _packs into _packs_by_name and _pack_collection
1395
        packs = tree.branch.repository._pack_collection
4145.1.6 by Robert Collins
More test fallout, but all caught now.
1396
        packs.reset()
2592.3.176 by Robert Collins
Various pack refactorings.
1397
        packs.ensure_loaded()
1398
        name = packs.names()[0]
1399
        pack_1 = packs.get_pack_by_name(name)
1400
        # the pack should be correctly initialised
3517.4.5 by Martin Pool
Correct use of packs._names in test_get_pack_by_name
1401
        sizes = packs._names[name]
3221.12.4 by Robert Collins
Implement basic repository supporting external references.
1402
        rev_index = GraphIndex(packs._index_transport, name + '.rix', sizes[0])
1403
        inv_index = GraphIndex(packs._index_transport, name + '.iix', sizes[1])
1404
        txt_index = GraphIndex(packs._index_transport, name + '.tix', sizes[2])
1405
        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.
1406
        self.assertEqual(pack_repo.ExistingPack(packs._pack_transport,
2592.3.219 by Robert Collins
Review feedback.
1407
            name, rev_index, inv_index, txt_index, sig_index), pack_1)
2592.3.176 by Robert Collins
Various pack refactorings.
1408
        # and the same instance should be returned on successive calls.
1409
        self.assertTrue(pack_1 is packs.get_pack_by_name(name))
1410
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1411
    def test_reload_pack_names_new_entry(self):
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1412
        tree, r, packs, revs = self.make_packs_and_alt_repo()
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1413
        names = packs.names()
1414
        # Add a new pack file into the repository
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1415
        rev4 = tree.commit('four')
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1416
        new_names = tree.branch.repository._pack_collection.names()
1417
        new_name = set(new_names).difference(names)
1418
        self.assertEqual(1, len(new_name))
1419
        new_name = new_name.pop()
1420
        # The old collection hasn't noticed yet
1421
        self.assertEqual(names, packs.names())
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1422
        self.assertTrue(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1423
        self.assertEqual(new_names, packs.names())
1424
        # And the repository can access the new revision
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1425
        self.assertEqual({rev4:(revs[-1],)}, r.get_parent_map([rev4]))
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1426
        self.assertFalse(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1427
1428
    def test_reload_pack_names_added_and_removed(self):
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1429
        tree, r, packs, revs = self.make_packs_and_alt_repo()
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1430
        names = packs.names()
1431
        # Now repack the whole thing
1432
        tree.branch.repository.pack()
1433
        new_names = tree.branch.repository._pack_collection.names()
1434
        # The other collection hasn't noticed yet
1435
        self.assertEqual(names, packs.names())
3789.1.8 by John Arbash Meinel
Change the api of reload_pack_names().
1436
        self.assertTrue(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1437
        self.assertEqual(new_names, packs.names())
3789.2.19 by John Arbash Meinel
Refactor to make the tests a bit simpler
1438
        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().
1439
        self.assertFalse(packs.reload_pack_names())
3789.1.2 by John Arbash Meinel
Add RepositoryPackCollection.reload_pack_names()
1440
4634.126.1 by John Arbash Meinel
(jam) Fix bug #507566, concurrent autopacking correctness.
1441
    def test_reload_pack_names_preserves_pending(self):
1442
        # TODO: Update this to also test for pending-deleted names
1443
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1444
        # We will add one pack (via start_write_group + insert_record_stream),
1445
        # and remove another pack (via _remove_pack_from_memory)
1446
        orig_names = packs.names()
1447
        orig_at_load = packs._packs_at_load
1448
        to_remove_name = iter(orig_names).next()
1449
        r.start_write_group()
1450
        self.addCleanup(r.abort_write_group)
1451
        r.texts.insert_record_stream([versionedfile.FulltextContentFactory(
1452
            ('text', 'rev'), (), None, 'content\n')])
1453
        new_pack = packs._new_pack
1454
        self.assertTrue(new_pack.data_inserted())
1455
        new_pack.finish()
1456
        packs.allocate(new_pack)
1457
        packs._new_pack = None
1458
        removed_pack = packs.get_pack_by_name(to_remove_name)
1459
        packs._remove_pack_from_memory(removed_pack)
1460
        names = packs.names()
4634.127.3 by John Arbash Meinel
Add code so we don't try to obsolete files someone else has 'claimed'.
1461
        all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
4634.126.1 by John Arbash Meinel
(jam) Fix bug #507566, concurrent autopacking correctness.
1462
        new_names = set([x[0][0] for x in new_nodes])
1463
        self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1464
        self.assertEqual(set(names) - set(orig_names), new_names)
1465
        self.assertEqual(set([new_pack.name]), new_names)
1466
        self.assertEqual([to_remove_name],
1467
                         sorted([x[0][0] for x in deleted_nodes]))
1468
        packs.reload_pack_names()
1469
        reloaded_names = packs.names()
1470
        self.assertEqual(orig_at_load, packs._packs_at_load)
1471
        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'.
1472
        all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
4634.126.1 by John Arbash Meinel
(jam) Fix bug #507566, concurrent autopacking correctness.
1473
        new_names = set([x[0][0] for x in new_nodes])
1474
        self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
1475
        self.assertEqual(set(names) - set(orig_names), new_names)
1476
        self.assertEqual(set([new_pack.name]), new_names)
1477
        self.assertEqual([to_remove_name],
1478
                         sorted([x[0][0] for x in deleted_nodes]))
1479
4634.127.5 by John Arbash Meinel
Possible fix for making sure packs triggering autopacking get cleaned up.
1480
    def test_autopack_obsoletes_new_pack(self):
1481
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1482
        packs._max_pack_count = lambda x: 1
1483
        packs.pack_distribution = lambda x: [10]
1484
        r.start_write_group()
1485
        r.revisions.insert_record_stream([versionedfile.FulltextContentFactory(
1486
            ('bogus-rev',), (), None, 'bogus-content\n')])
1487
        # This should trigger an autopack, which will combine everything into a
1488
        # single pack file.
1489
        new_names = r.commit_write_group()
1490
        names = packs.names()
1491
        self.assertEqual(1, len(names))
1492
        self.assertEqual([names[0] + '.pack'],
1493
                         packs._pack_transport.list_dir('.'))
1494
3789.2.20 by John Arbash Meinel
The autopack code can now trigger itself to retry when _copy_revision_texts fails.
1495
    def test_autopack_reloads_and_stops(self):
1496
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1497
        # After we have determined what needs to be autopacked, trigger a
1498
        # full-pack via the other repo which will cause us to re-evaluate and
1499
        # decide we don't need to do anything
1500
        orig_execute = packs._execute_pack_operations
1501
        def _munged_execute_pack_ops(*args, **kwargs):
1502
            tree.branch.repository.pack()
1503
            return orig_execute(*args, **kwargs)
1504
        packs._execute_pack_operations = _munged_execute_pack_ops
1505
        packs._max_pack_count = lambda x: 1
1506
        packs.pack_distribution = lambda x: [10]
1507
        self.assertFalse(packs.autopack())
1508
        self.assertEqual(1, len(packs.names()))
1509
        self.assertEqual(tree.branch.repository._pack_collection.names(),
1510
                         packs.names())
1511
4634.127.1 by John Arbash Meinel
Partial fix for bug #507557.
1512
    def test__save_pack_names(self):
1513
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1514
        names = packs.names()
1515
        pack = packs.get_pack_by_name(names[0])
1516
        packs._remove_pack_from_memory(pack)
1517
        packs._save_pack_names(obsolete_packs=[pack])
1518
        cur_packs = packs._pack_transport.list_dir('.')
1519
        self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1520
        # obsolete_packs will also have stuff like .rix and .iix present.
1521
        obsolete_packs = packs.transport.list_dir('obsolete_packs')
1522
        obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
1523
        self.assertEqual([pack.name], sorted(obsolete_names))
1524
1525
    def test__save_pack_names_already_obsoleted(self):
1526
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1527
        names = packs.names()
1528
        pack = packs.get_pack_by_name(names[0])
1529
        packs._remove_pack_from_memory(pack)
1530
        # We are going to simulate a concurrent autopack by manually obsoleting
1531
        # the pack directly.
1532
        packs._obsolete_packs([pack])
1533
        packs._save_pack_names(clear_obsolete_packs=True,
1534
                               obsolete_packs=[pack])
1535
        cur_packs = packs._pack_transport.list_dir('.')
1536
        self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1537
        # Note that while we set clear_obsolete_packs=True, it should not
1538
        # delete a pack file that we have also scheduled for obsoletion.
1539
        obsolete_packs = packs.transport.list_dir('obsolete_packs')
1540
        obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
1541
        self.assertEqual([pack.name], sorted(obsolete_names))
1542
4634.127.3 by John Arbash Meinel
Add code so we don't try to obsolete files someone else has 'claimed'.
1543
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1544
1545
class TestPack(TestCaseWithTransport):
1546
    """Tests for the Pack object."""
1547
1548
    def assertCurrentlyEqual(self, left, right):
1549
        self.assertTrue(left == right)
1550
        self.assertTrue(right == left)
1551
        self.assertFalse(left != right)
1552
        self.assertFalse(right != left)
1553
1554
    def assertCurrentlyNotEqual(self, left, right):
1555
        self.assertFalse(left == right)
1556
        self.assertFalse(right == left)
1557
        self.assertTrue(left != right)
1558
        self.assertTrue(right != left)
1559
1560
    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.
1561
        left = pack_repo.ExistingPack('', '', '', '', '', '')
1562
        right = pack_repo.ExistingPack('', '', '', '', '', '')
2592.3.173 by Robert Collins
Basic implementation of all_packs.
1563
        self.assertCurrentlyEqual(left, right)
1564
        # change all attributes and ensure equality changes as we do.
1565
        left.revision_index = 'a'
1566
        self.assertCurrentlyNotEqual(left, right)
1567
        right.revision_index = 'a'
1568
        self.assertCurrentlyEqual(left, right)
1569
        left.inventory_index = 'a'
1570
        self.assertCurrentlyNotEqual(left, right)
1571
        right.inventory_index = 'a'
1572
        self.assertCurrentlyEqual(left, right)
1573
        left.text_index = 'a'
1574
        self.assertCurrentlyNotEqual(left, right)
1575
        right.text_index = 'a'
1576
        self.assertCurrentlyEqual(left, right)
1577
        left.signature_index = 'a'
1578
        self.assertCurrentlyNotEqual(left, right)
1579
        right.signature_index = 'a'
1580
        self.assertCurrentlyEqual(left, right)
1581
        left.name = 'a'
1582
        self.assertCurrentlyNotEqual(left, right)
1583
        right.name = 'a'
1584
        self.assertCurrentlyEqual(left, right)
1585
        left.transport = 'a'
1586
        self.assertCurrentlyNotEqual(left, right)
1587
        right.transport = 'a'
1588
        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.
1589
1590
    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.
1591
        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.
1592
        self.assertEqual('a_name.pack', pack.file_name())
2592.3.192 by Robert Collins
Move new revision index management to NewPack.
1593
1594
1595
class TestNewPack(TestCaseWithTransport):
1596
    """Tests for pack_repo.NewPack."""
1597
2592.3.193 by Robert Collins
Move hash tracking of new packs into NewPack.
1598
    def test_new_instance_attributes(self):
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
1599
        upload_transport = self.get_transport('upload')
1600
        pack_transport = self.get_transport('pack')
1601
        index_transport = self.get_transport('index')
1602
        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)
1603
        collection = pack_repo.RepositoryPackCollection(
1604
            repo=None,
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
1605
            transport=self.get_transport('.'),
1606
            index_transport=index_transport,
1607
            upload_transport=upload_transport,
1608
            pack_transport=pack_transport,
1609
            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)
1610
            index_class=BTreeGraphIndex,
1611
            use_chk_index=False)
3830.3.1 by Martin Pool
NewPack should be constructed from the PackCollection, rather than attributes of it
1612
        pack = pack_repo.NewPack(collection)
4857.2.1 by John Arbash Meinel
2 test_repository tests weren't adding cleanups when opening files.
1613
        self.addCleanup(pack.abort) # Make sure the write stream gets closed
3735.1.1 by Robert Collins
Add development2 formats using BTree indices.
1614
        self.assertIsInstance(pack.revision_index, BTreeBuilder)
1615
        self.assertIsInstance(pack.inventory_index, BTreeBuilder)
2929.3.5 by Vincent Ladeuil
New files, same warnings, same fixes.
1616
        self.assertIsInstance(pack._hash, type(osutils.md5()))
2592.3.194 by Robert Collins
Output the revision index from NewPack.finish
1617
        self.assertTrue(pack.upload_transport is upload_transport)
1618
        self.assertTrue(pack.index_transport is index_transport)
1619
        self.assertTrue(pack.pack_transport is pack_transport)
1620
        self.assertEqual(None, pack.index_sizes)
1621
        self.assertEqual(20, len(pack.random_name))
1622
        self.assertIsInstance(pack.random_name, str)
1623
        self.assertIsInstance(pack.start_time, float)
2951.1.2 by Robert Collins
Partial refactoring of pack_repo to create a Packer object for packing.
1624
1625
1626
class TestPacker(TestCaseWithTransport):
1627
    """Tests for the packs repository Packer class."""
2951.1.10 by Robert Collins
Peer review feedback with Ian.
1628
3824.2.4 by John Arbash Meinel
Add a test that ensures the pack ordering changes as part of calling .pack()
1629
    def test_pack_optimizes_pack_order(self):
4617.8.1 by Robert Collins
Lock down another test assuming the default was a PackRepository.
1630
        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()
1631
        builder.start_series()
1632
        builder.build_snapshot('A', None, [
1633
            ('add', ('', 'root-id', 'directory', None)),
1634
            ('add', ('f', 'f-id', 'file', 'content\n'))])
1635
        builder.build_snapshot('B', ['A'],
1636
            [('modify', ('f-id', 'new-content\n'))])
1637
        builder.build_snapshot('C', ['B'],
1638
            [('modify', ('f-id', 'third-content\n'))])
1639
        builder.build_snapshot('D', ['C'],
1640
            [('modify', ('f-id', 'fourth-content\n'))])
1641
        b = builder.get_branch()
1642
        b.lock_read()
1643
        builder.finish_series()
1644
        self.addCleanup(b.unlock)
1645
        # At this point, we should have 4 pack files available
1646
        # Because of how they were built, they correspond to
1647
        # ['D', 'C', 'B', 'A']
1648
        packs = b.repository._pack_collection.packs
1649
        packer = pack_repo.Packer(b.repository._pack_collection,
1650
                                  packs, 'testing',
1651
                                  revision_ids=['B', 'C'])
1652
        # Now, when we are copying the B & C revisions, their pack files should
1653
        # be moved to the front of the stack
3824.2.5 by Andrew Bennetts
Minor tweaks to comments etc.
1654
        # The new ordering moves B & C to the front of the .packs attribute,
1655
        # 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()
1656
        new_packs = [packs[1], packs[2], packs[0], packs[3]]
1657
        new_pack = packer.pack()
1658
        self.assertEqual(new_packs, packer.packs)
3146.6.1 by Aaron Bentley
InterDifferingSerializer shows a progress bar
1659
1660
3777.5.4 by John Arbash Meinel
OptimisingPacker now sets the optimize flags for the indexes being built.
1661
class TestOptimisingPacker(TestCaseWithTransport):
1662
    """Tests for the OptimisingPacker class."""
1663
1664
    def get_pack_collection(self):
1665
        repo = self.make_repository('.')
1666
        return repo._pack_collection
1667
1668
    def test_open_pack_will_optimise(self):
1669
        packer = pack_repo.OptimisingPacker(self.get_pack_collection(),
1670
                                            [], '.test')
1671
        new_pack = packer.open_pack()
4857.2.1 by John Arbash Meinel
2 test_repository tests weren't adding cleanups when opening files.
1672
        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.
1673
        self.assertIsInstance(new_pack, pack_repo.NewPack)
1674
        self.assertTrue(new_pack.revision_index._optimize_for_size)
1675
        self.assertTrue(new_pack.inventory_index._optimize_for_size)
1676
        self.assertTrue(new_pack.text_index._optimize_for_size)
1677
        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.
1678
1679
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
1680
class TestCrossFormatPacks(TestCaseWithTransport):
1681
1682
    def log_pack(self, hint=None):
1683
        self.calls.append(('pack', hint))
1684
        self.orig_pack(hint=hint)
1685
        if self.expect_hint:
1686
            self.assertTrue(hint)
1687
1688
    def run_stream(self, src_fmt, target_fmt, expect_pack_called):
1689
        self.expect_hint = expect_pack_called
1690
        self.calls = []
1691
        source_tree = self.make_branch_and_tree('src', format=src_fmt)
1692
        source_tree.lock_write()
1693
        self.addCleanup(source_tree.unlock)
1694
        tip = source_tree.commit('foo')
1695
        target = self.make_repository('target', format=target_fmt)
1696
        target.lock_write()
1697
        self.addCleanup(target.unlock)
1698
        source = source_tree.branch.repository._get_source(target._format)
1699
        self.orig_pack = target.pack
1700
        target.pack = self.log_pack
1701
        search = target.search_missing_revision_ids(
5539.2.11 by Andrew Bennetts
Fix deprecation warning from test suite.
1702
            source_tree.branch.repository, revision_ids=[tip])
4431.3.7 by Jonathan Lange
Cherrypick bzr.dev 4470, resolving conflicts.
1703
        stream = source.get_stream(search)
1704
        from_format = source_tree.branch.repository._format
1705
        sink = target._get_sink()
1706
        sink.insert_stream(stream, from_format, [])
1707
        if expect_pack_called:
1708
            self.assertLength(1, self.calls)
1709
        else:
1710
            self.assertLength(0, self.calls)
1711
1712
    def run_fetch(self, src_fmt, target_fmt, expect_pack_called):
1713
        self.expect_hint = expect_pack_called
1714
        self.calls = []
1715
        source_tree = self.make_branch_and_tree('src', format=src_fmt)
1716
        source_tree.lock_write()
1717
        self.addCleanup(source_tree.unlock)
1718
        tip = source_tree.commit('foo')
1719
        target = self.make_repository('target', format=target_fmt)
1720
        target.lock_write()
1721
        self.addCleanup(target.unlock)
1722
        source = source_tree.branch.repository
1723
        self.orig_pack = target.pack
1724
        target.pack = self.log_pack
1725
        target.fetch(source)
1726
        if expect_pack_called:
1727
            self.assertLength(1, self.calls)
1728
        else:
1729
            self.assertLength(0, self.calls)
1730
1731
    def test_sink_format_hint_no(self):
1732
        # When the target format says packing makes no difference, pack is not
1733
        # called.
1734
        self.run_stream('1.9', 'rich-root-pack', False)
1735
1736
    def test_sink_format_hint_yes(self):
1737
        # When the target format says packing makes a difference, pack is
1738
        # called.
1739
        self.run_stream('1.9', '2a', True)
1740
1741
    def test_sink_format_same_no(self):
1742
        # When the formats are the same, pack is not called.
1743
        self.run_stream('2a', '2a', False)
1744
1745
    def test_IDS_format_hint_no(self):
1746
        # When the target format says packing makes no difference, pack is not
1747
        # called.
1748
        self.run_fetch('1.9', 'rich-root-pack', False)
1749
1750
    def test_IDS_format_hint_yes(self):
1751
        # When the target format says packing makes a difference, pack is
1752
        # called.
1753
        self.run_fetch('1.9', '2a', True)
1754
1755
    def test_IDS_format_same_no(self):
1756
        # When the formats are the same, pack is not called.
1757
        self.run_fetch('2a', '2a', False)