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