/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/tests/test_repository.py

  • Committer: Breezy landing bot
  • Author(s): Jelmer Vernooij
  • Date: 2018-09-13 12:50:28 UTC
  • mfrom: (7096.2.2 empty-port)
  • Revision ID: breezy.the.bot@gmail.com-20180913125028-mja5gz8xsams9iey
Allow port to be empty when parsing URLs.

Merged from https://code.launchpad.net/~jelmer/brz/empty-port/+merge/354640

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
23
23
"""
24
24
 
25
25
from stat import S_ISDIR
26
 
import sys
27
26
 
28
 
import bzrlib
29
 
from bzrlib.errors import (NoSuchFile,
30
 
                           UnknownFormatError,
31
 
                           UnsupportedFormatError,
32
 
                           )
33
 
from bzrlib import (
34
 
    graph,
 
27
import breezy
 
28
from breezy.errors import (
 
29
    UnknownFormatError,
 
30
    UnsupportedFormatError,
 
31
    )
 
32
from breezy import (
35
33
    tests,
36
 
    )
37
 
from bzrlib.btree_index import BTreeBuilder, BTreeGraphIndex
38
 
from bzrlib.index import GraphIndex
39
 
from bzrlib.repository import RepositoryFormat
40
 
from bzrlib.tests import (
 
34
    transport,
 
35
    )
 
36
from breezy.bzr import (
 
37
    bzrdir,
 
38
    btree_index,
 
39
    inventory,
 
40
    repository as bzrrepository,
 
41
    versionedfile,
 
42
    vf_repository,
 
43
    vf_search,
 
44
    )
 
45
from breezy.bzr.btree_index import BTreeBuilder, BTreeGraphIndex
 
46
from breezy.bzr.index import GraphIndex
 
47
from breezy.repository import RepositoryFormat
 
48
from breezy.tests import (
41
49
    TestCase,
42
50
    TestCaseWithTransport,
43
51
    )
44
 
from bzrlib.transport import (
45
 
    get_transport,
46
 
    )
47
 
from bzrlib import (
48
 
    bzrdir,
 
52
from breezy import (
 
53
    controldir,
49
54
    errors,
50
 
    inventory,
51
55
    osutils,
52
56
    repository,
53
57
    revision as _mod_revision,
54
58
    upgrade,
55
 
    versionedfile,
56
59
    workingtree,
57
60
    )
58
 
from bzrlib.repofmt import (
 
61
from breezy.bzr import (
59
62
    groupcompress_repo,
60
63
    knitrepo,
 
64
    knitpack_repo,
61
65
    pack_repo,
62
 
    weaverepo,
63
66
    )
64
67
 
65
68
 
66
69
class TestDefaultFormat(TestCase):
67
70
 
68
71
    def test_get_set_default_format(self):
69
 
        old_default = bzrdir.format_registry.get('default')
 
72
        old_default = controldir.format_registry.get('default')
70
73
        private_default = old_default().repository_format.__class__
71
 
        old_format = repository.RepositoryFormat.get_default_format()
 
74
        old_format = repository.format_registry.get_default()
72
75
        self.assertTrue(isinstance(old_format, private_default))
73
76
        def make_sample_bzrdir():
74
77
            my_bzrdir = bzrdir.BzrDirMetaFormat1()
75
78
            my_bzrdir.repository_format = SampleRepositoryFormat()
76
79
            return my_bzrdir
77
 
        bzrdir.format_registry.remove('default')
78
 
        bzrdir.format_registry.register('sample', make_sample_bzrdir, '')
79
 
        bzrdir.format_registry.set_default('sample')
 
80
        controldir.format_registry.remove('default')
 
81
        controldir.format_registry.register('sample', make_sample_bzrdir, '')
 
82
        controldir.format_registry.set_default('sample')
80
83
        # creating a repository should now create an instrumented dir.
81
84
        try:
82
85
            # the default branch format is used by the meta dir format
85
88
            result = dir.create_repository()
86
89
            self.assertEqual(result, 'A bzr repository dir')
87
90
        finally:
88
 
            bzrdir.format_registry.remove('default')
89
 
            bzrdir.format_registry.remove('sample')
90
 
            bzrdir.format_registry.register('default', old_default, '')
91
 
        self.assertIsInstance(repository.RepositoryFormat.get_default_format(),
 
91
            controldir.format_registry.remove('default')
 
92
            controldir.format_registry.remove('sample')
 
93
            controldir.format_registry.register('default', old_default, '')
 
94
        self.assertIsInstance(repository.format_registry.get_default(),
92
95
                              old_format.__class__)
93
96
 
94
97
 
95
 
class SampleRepositoryFormat(repository.RepositoryFormat):
 
98
class SampleRepositoryFormat(bzrrepository.RepositoryFormatMetaDir):
96
99
    """A sample format
97
100
 
98
101
    this format is initializable, unsupported to aid in testing the
99
102
    open and open(unsupported=True) routines.
100
103
    """
101
104
 
102
 
    def get_format_string(self):
 
105
    @classmethod
 
106
    def get_format_string(cls):
103
107
        """See RepositoryFormat.get_format_string()."""
104
 
        return "Sample .bzr repository format."
 
108
        return b"Sample .bzr repository format."
105
109
 
106
 
    def initialize(self, a_bzrdir, shared=False):
 
110
    def initialize(self, a_controldir, shared=False):
107
111
        """Initialize a repository in a BzrDir"""
108
 
        t = a_bzrdir.get_repository_transport(self)
 
112
        t = a_controldir.get_repository_transport(self)
109
113
        t.put_bytes('format', self.get_format_string())
110
114
        return 'A bzr repository dir'
111
115
 
112
116
    def is_supported(self):
113
117
        return False
114
118
 
115
 
    def open(self, a_bzrdir, _found=False):
 
119
    def open(self, a_controldir, _found=False):
116
120
        return "opened repository."
117
121
 
118
122
 
 
123
class SampleExtraRepositoryFormat(repository.RepositoryFormat):
 
124
    """A sample format that can not be used in a metadir
 
125
 
 
126
    """
 
127
 
 
128
    def get_format_string(self):
 
129
        raise NotImplementedError
 
130
 
 
131
 
119
132
class TestRepositoryFormat(TestCaseWithTransport):
120
133
    """Tests for the Repository format detection used by the bzr meta dir facility.BzrBranchFormat facility."""
121
134
 
125
138
        # this is not quite the same as
126
139
        self.build_tree(["foo/", "bar/"])
127
140
        def check_format(format, url):
128
 
            dir = format._matchingbzrdir.initialize(url)
 
141
            dir = format._matchingcontroldir.initialize(url)
129
142
            format.initialize(dir)
130
 
            t = get_transport(url)
131
 
            found_format = repository.RepositoryFormat.find_format(dir)
132
 
            self.failUnless(isinstance(found_format, format.__class__))
133
 
        check_format(weaverepo.RepositoryFormat7(), "bar")
 
143
            t = transport.get_transport_from_path(url)
 
144
            found_format = bzrrepository.RepositoryFormatMetaDir.find_format(dir)
 
145
            self.assertIsInstance(found_format, format.__class__)
 
146
        check_format(repository.format_registry.get_default(), "bar")
134
147
 
135
148
    def test_find_format_no_repository(self):
136
149
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
137
150
        self.assertRaises(errors.NoRepositoryPresent,
138
 
                          repository.RepositoryFormat.find_format,
 
151
                          bzrrepository.RepositoryFormatMetaDir.find_format,
139
152
                          dir)
140
153
 
 
154
    def test_from_string(self):
 
155
        self.assertIsInstance(
 
156
            SampleRepositoryFormat.from_string(
 
157
                b"Sample .bzr repository format."),
 
158
            SampleRepositoryFormat)
 
159
        self.assertRaises(AssertionError,
 
160
            SampleRepositoryFormat.from_string,
 
161
                b"Different .bzr repository format.")
 
162
 
141
163
    def test_find_format_unknown_format(self):
142
164
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
143
165
        SampleRepositoryFormat().initialize(dir)
144
166
        self.assertRaises(UnknownFormatError,
145
 
                          repository.RepositoryFormat.find_format,
 
167
                          bzrrepository.RepositoryFormatMetaDir.find_format,
146
168
                          dir)
147
169
 
 
170
    def test_find_format_with_features(self):
 
171
        tree = self.make_branch_and_tree('.', format='2a')
 
172
        tree.branch.repository.update_feature_flags({b"name": b"necessity"})
 
173
        found_format = bzrrepository.RepositoryFormatMetaDir.find_format(tree.controldir)
 
174
        self.assertIsInstance(found_format, bzrrepository.RepositoryFormatMetaDir)
 
175
        self.assertEqual(found_format.features.get(b"name"), b"necessity")
 
176
        self.assertRaises(bzrdir.MissingFeature, found_format.check_support_status,
 
177
            True)
 
178
        self.addCleanup(bzrrepository.RepositoryFormatMetaDir.unregister_feature,
 
179
            b"name")
 
180
        bzrrepository.RepositoryFormatMetaDir.register_feature(b"name")
 
181
        found_format.check_support_status(True)
 
182
 
 
183
 
 
184
class TestRepositoryFormatRegistry(TestCase):
 
185
 
 
186
    def setUp(self):
 
187
        super(TestRepositoryFormatRegistry, self).setUp()
 
188
        self.registry = repository.RepositoryFormatRegistry()
 
189
 
148
190
    def test_register_unregister_format(self):
149
191
        format = SampleRepositoryFormat()
150
 
        # make a control dir
151
 
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
152
 
        # make a repo
153
 
        format.initialize(dir)
154
 
        # register a format for it.
155
 
        repository.RepositoryFormat.register_format(format)
156
 
        # which repository.Open will refuse (not supported)
157
 
        self.assertRaises(UnsupportedFormatError, repository.Repository.open, self.get_url())
158
 
        # but open(unsupported) will work
159
 
        self.assertEqual(format.open(dir), "opened repository.")
160
 
        # unregister the format
161
 
        repository.RepositoryFormat.unregister_format(format)
162
 
 
163
 
 
164
 
class TestFormat6(TestCaseWithTransport):
165
 
 
166
 
    def test_attribute__fetch_order(self):
167
 
        """Weaves need topological data insertion."""
168
 
        control = bzrdir.BzrDirFormat6().initialize(self.get_url())
169
 
        repo = weaverepo.RepositoryFormat6().initialize(control)
170
 
        self.assertEqual('topological', repo._format._fetch_order)
171
 
 
172
 
    def test_attribute__fetch_uses_deltas(self):
173
 
        """Weaves do not reuse deltas."""
174
 
        control = bzrdir.BzrDirFormat6().initialize(self.get_url())
175
 
        repo = weaverepo.RepositoryFormat6().initialize(control)
176
 
        self.assertEqual(False, repo._format._fetch_uses_deltas)
177
 
 
178
 
    def test_attribute__fetch_reconcile(self):
179
 
        """Weave repositories need a reconcile after fetch."""
180
 
        control = bzrdir.BzrDirFormat6().initialize(self.get_url())
181
 
        repo = weaverepo.RepositoryFormat6().initialize(control)
182
 
        self.assertEqual(True, repo._format._fetch_reconcile)
183
 
 
184
 
    def test_no_ancestry_weave(self):
185
 
        control = bzrdir.BzrDirFormat6().initialize(self.get_url())
186
 
        repo = weaverepo.RepositoryFormat6().initialize(control)
187
 
        # We no longer need to create the ancestry.weave file
188
 
        # since it is *never* used.
189
 
        self.assertRaises(NoSuchFile,
190
 
                          control.transport.get,
191
 
                          'ancestry.weave')
192
 
 
193
 
    def test_supports_external_lookups(self):
194
 
        control = bzrdir.BzrDirFormat6().initialize(self.get_url())
195
 
        repo = weaverepo.RepositoryFormat6().initialize(control)
196
 
        self.assertFalse(repo._format.supports_external_lookups)
197
 
 
198
 
 
199
 
class TestFormat7(TestCaseWithTransport):
200
 
 
201
 
    def test_attribute__fetch_order(self):
202
 
        """Weaves need topological data insertion."""
203
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
204
 
        repo = weaverepo.RepositoryFormat7().initialize(control)
205
 
        self.assertEqual('topological', repo._format._fetch_order)
206
 
 
207
 
    def test_attribute__fetch_uses_deltas(self):
208
 
        """Weaves do not reuse deltas."""
209
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
210
 
        repo = weaverepo.RepositoryFormat7().initialize(control)
211
 
        self.assertEqual(False, repo._format._fetch_uses_deltas)
212
 
 
213
 
    def test_attribute__fetch_reconcile(self):
214
 
        """Weave repositories need a reconcile after fetch."""
215
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
216
 
        repo = weaverepo.RepositoryFormat7().initialize(control)
217
 
        self.assertEqual(True, repo._format._fetch_reconcile)
218
 
 
219
 
    def test_disk_layout(self):
220
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
221
 
        repo = weaverepo.RepositoryFormat7().initialize(control)
222
 
        # in case of side effects of locking.
223
 
        repo.lock_write()
224
 
        repo.unlock()
225
 
        # we want:
226
 
        # format 'Bazaar-NG Repository format 7'
227
 
        # lock ''
228
 
        # inventory.weave == empty_weave
229
 
        # empty revision-store directory
230
 
        # empty weaves directory
231
 
        t = control.get_repository_transport(None)
232
 
        self.assertEqualDiff('Bazaar-NG Repository format 7',
233
 
                             t.get('format').read())
234
 
        self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
235
 
        self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
236
 
        self.assertEqualDiff('# bzr weave file v5\n'
237
 
                             'w\n'
238
 
                             'W\n',
239
 
                             t.get('inventory.weave').read())
240
 
        # Creating a file with id Foo:Bar results in a non-escaped file name on
241
 
        # disk.
242
 
        control.create_branch()
243
 
        tree = control.create_workingtree()
244
 
        tree.add(['foo'], ['Foo:Bar'], ['file'])
245
 
        tree.put_file_bytes_non_atomic('Foo:Bar', 'content\n')
246
 
        try:
247
 
            tree.commit('first post', rev_id='first')
248
 
        except errors.IllegalPath:
249
 
            if sys.platform != 'win32':
250
 
                raise
251
 
            self.knownFailure('Foo:Bar cannot be used as a file-id on windows'
252
 
                              ' in repo format 7')
253
 
            return
254
 
        self.assertEqualDiff(
255
 
            '# bzr weave file v5\n'
256
 
            'i\n'
257
 
            '1 7fe70820e08a1aac0ef224d9c66ab66831cc4ab1\n'
258
 
            'n first\n'
259
 
            '\n'
260
 
            'w\n'
261
 
            '{ 0\n'
262
 
            '. content\n'
263
 
            '}\n'
264
 
            'W\n',
265
 
            t.get('weaves/74/Foo%3ABar.weave').read())
266
 
 
267
 
    def test_shared_disk_layout(self):
268
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
269
 
        repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
270
 
        # we want:
271
 
        # format 'Bazaar-NG Repository format 7'
272
 
        # inventory.weave == empty_weave
273
 
        # empty revision-store directory
274
 
        # empty weaves directory
275
 
        # a 'shared-storage' marker file.
276
 
        # lock is not present when unlocked
277
 
        t = control.get_repository_transport(None)
278
 
        self.assertEqualDiff('Bazaar-NG Repository format 7',
279
 
                             t.get('format').read())
280
 
        self.assertEqualDiff('', t.get('shared-storage').read())
281
 
        self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
282
 
        self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
283
 
        self.assertEqualDiff('# bzr weave file v5\n'
284
 
                             'w\n'
285
 
                             'W\n',
286
 
                             t.get('inventory.weave').read())
287
 
        self.assertFalse(t.has('branch-lock'))
288
 
 
289
 
    def test_creates_lockdir(self):
290
 
        """Make sure it appears to be controlled by a LockDir existence"""
291
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
292
 
        repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
293
 
        t = control.get_repository_transport(None)
294
 
        # TODO: Should check there is a 'lock' toplevel directory,
295
 
        # regardless of contents
296
 
        self.assertFalse(t.has('lock/held/info'))
297
 
        repo.lock_write()
298
 
        try:
299
 
            self.assertTrue(t.has('lock/held/info'))
300
 
        finally:
301
 
            # unlock so we don't get a warning about failing to do so
302
 
            repo.unlock()
303
 
 
304
 
    def test_uses_lockdir(self):
305
 
        """repo format 7 actually locks on lockdir"""
306
 
        base_url = self.get_url()
307
 
        control = bzrdir.BzrDirMetaFormat1().initialize(base_url)
308
 
        repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
309
 
        t = control.get_repository_transport(None)
310
 
        repo.lock_write()
311
 
        repo.unlock()
312
 
        del repo
313
 
        # make sure the same lock is created by opening it
314
 
        repo = repository.Repository.open(base_url)
315
 
        repo.lock_write()
316
 
        self.assertTrue(t.has('lock/held/info'))
317
 
        repo.unlock()
318
 
        self.assertFalse(t.has('lock/held/info'))
319
 
 
320
 
    def test_shared_no_tree_disk_layout(self):
321
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
322
 
        repo = weaverepo.RepositoryFormat7().initialize(control, shared=True)
323
 
        repo.set_make_working_trees(False)
324
 
        # we want:
325
 
        # format 'Bazaar-NG Repository format 7'
326
 
        # lock ''
327
 
        # inventory.weave == empty_weave
328
 
        # empty revision-store directory
329
 
        # empty weaves directory
330
 
        # a 'shared-storage' marker file.
331
 
        t = control.get_repository_transport(None)
332
 
        self.assertEqualDiff('Bazaar-NG Repository format 7',
333
 
                             t.get('format').read())
334
 
        ## self.assertEqualDiff('', t.get('lock').read())
335
 
        self.assertEqualDiff('', t.get('shared-storage').read())
336
 
        self.assertEqualDiff('', t.get('no-working-trees').read())
337
 
        repo.set_make_working_trees(True)
338
 
        self.assertFalse(t.has('no-working-trees'))
339
 
        self.assertTrue(S_ISDIR(t.stat('revision-store').st_mode))
340
 
        self.assertTrue(S_ISDIR(t.stat('weaves').st_mode))
341
 
        self.assertEqualDiff('# bzr weave file v5\n'
342
 
                             'w\n'
343
 
                             'W\n',
344
 
                             t.get('inventory.weave').read())
345
 
 
346
 
    def test_supports_external_lookups(self):
347
 
        control = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
348
 
        repo = weaverepo.RepositoryFormat7().initialize(control)
349
 
        self.assertFalse(repo._format.supports_external_lookups)
 
192
        self.registry.register(format)
 
193
        self.assertEqual(format, self.registry.get(b"Sample .bzr repository format."))
 
194
        self.registry.remove(format)
 
195
        self.assertRaises(KeyError, self.registry.get, b"Sample .bzr repository format.")
 
196
 
 
197
    def test_get_all(self):
 
198
        format = SampleRepositoryFormat()
 
199
        self.assertEqual([], self.registry._get_all())
 
200
        self.registry.register(format)
 
201
        self.assertEqual([format], self.registry._get_all())
 
202
 
 
203
    def test_register_extra(self):
 
204
        format = SampleExtraRepositoryFormat()
 
205
        self.assertEqual([], self.registry._get_all())
 
206
        self.registry.register_extra(format)
 
207
        self.assertEqual([format], self.registry._get_all())
 
208
 
 
209
    def test_register_extra_lazy(self):
 
210
        self.assertEqual([], self.registry._get_all())
 
211
        self.registry.register_extra_lazy("breezy.tests.test_repository",
 
212
            "SampleExtraRepositoryFormat")
 
213
        formats = self.registry._get_all()
 
214
        self.assertEqual(1, len(formats))
 
215
        self.assertIsInstance(formats[0], SampleExtraRepositoryFormat)
350
216
 
351
217
 
352
218
class TestFormatKnit1(TestCaseWithTransport):
354
220
    def test_attribute__fetch_order(self):
355
221
        """Knits need topological data insertion."""
356
222
        repo = self.make_repository('.',
357
 
                format=bzrdir.format_registry.get('knit')())
 
223
                format=controldir.format_registry.get('knit')())
358
224
        self.assertEqual('topological', repo._format._fetch_order)
359
225
 
360
226
    def test_attribute__fetch_uses_deltas(self):
361
227
        """Knits reuse deltas."""
362
228
        repo = self.make_repository('.',
363
 
                format=bzrdir.format_registry.get('knit')())
 
229
                format=controldir.format_registry.get('knit')())
364
230
        self.assertEqual(True, repo._format._fetch_uses_deltas)
365
231
 
366
232
    def test_disk_layout(self):
376
242
        # empty revision-store directory
377
243
        # empty weaves directory
378
244
        t = control.get_repository_transport(None)
379
 
        self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
380
 
                             t.get('format').read())
 
245
        with t.get('format') as f:
 
246
            self.assertEqualDiff(b'Bazaar-NG Knit Repository Format 1',
 
247
                                 f.read())
381
248
        # XXX: no locks left when unlocked at the moment
382
249
        # self.assertEqualDiff('', t.get('lock').read())
383
250
        self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
385
252
        # Check per-file knits.
386
253
        branch = control.create_branch()
387
254
        tree = control.create_workingtree()
388
 
        tree.add(['foo'], ['Nasty-IdC:'], ['file'])
389
 
        tree.put_file_bytes_non_atomic('Nasty-IdC:', '')
390
 
        tree.commit('1st post', rev_id='foo')
 
255
        tree.add(['foo'], [b'Nasty-IdC:'], ['file'])
 
256
        tree.put_file_bytes_non_atomic('foo', b'')
 
257
        tree.commit('1st post', rev_id=b'foo')
391
258
        self.assertHasKnit(t, 'knits/e8/%254easty-%2549d%2543%253a',
392
 
            '\nfoo fulltext 0 81  :')
 
259
            b'\nfoo fulltext 0 81  :')
393
260
 
394
 
    def assertHasKnit(self, t, knit_name, extra_content=''):
 
261
    def assertHasKnit(self, t, knit_name, extra_content=b''):
395
262
        """Assert that knit_name exists on t."""
396
 
        self.assertEqualDiff('# bzr knit index 8\n' + extra_content,
 
263
        self.assertEqualDiff(b'# bzr knit index 8\n' + extra_content,
397
264
                             t.get(knit_name + '.kndx').read())
398
265
 
399
266
    def check_knits(self, t):
413
280
        # empty weaves directory
414
281
        # a 'shared-storage' marker file.
415
282
        t = control.get_repository_transport(None)
416
 
        self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
417
 
                             t.get('format').read())
 
283
        with t.get('format') as f:
 
284
            self.assertEqualDiff(b'Bazaar-NG Knit Repository Format 1',
 
285
                                 f.read())
418
286
        # XXX: no locks left when unlocked at the moment
419
287
        # self.assertEqualDiff('', t.get('lock').read())
420
 
        self.assertEqualDiff('', t.get('shared-storage').read())
 
288
        self.assertEqualDiff(b'', t.get('shared-storage').read())
421
289
        self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
422
290
        self.check_knits(t)
423
291
 
433
301
        # empty weaves directory
434
302
        # a 'shared-storage' marker file.
435
303
        t = control.get_repository_transport(None)
436
 
        self.assertEqualDiff('Bazaar-NG Knit Repository Format 1',
437
 
                             t.get('format').read())
 
304
        with t.get('format') as f:
 
305
            self.assertEqualDiff(b'Bazaar-NG Knit Repository Format 1',
 
306
                                 f.read())
438
307
        # XXX: no locks left when unlocked at the moment
439
308
        # self.assertEqualDiff('', t.get('lock').read())
440
 
        self.assertEqualDiff('', t.get('shared-storage').read())
441
 
        self.assertEqualDiff('', t.get('no-working-trees').read())
 
309
        self.assertEqualDiff(b'', t.get('shared-storage').read())
 
310
        self.assertEqualDiff(b'', t.get('no-working-trees').read())
442
311
        repo.set_make_working_trees(True)
443
312
        self.assertFalse(t.has('no-working-trees'))
444
313
        self.assertTrue(S_ISDIR(t.stat('knits').st_mode))
452
321
        is valid when the api is not being abused.
453
322
        """
454
323
        repo = self.make_repository('.',
455
 
                format=bzrdir.format_registry.get('knit')())
456
 
        inv_xml = '<inventory format="5">\n</inventory>\n'
457
 
        inv = repo._deserialise_inventory('test-rev-id', inv_xml)
458
 
        self.assertEqual('test-rev-id', inv.root.revision)
 
324
                format=controldir.format_registry.get('knit')())
 
325
        inv_xml = b'<inventory format="5">\n</inventory>\n'
 
326
        inv = repo._deserialise_inventory(b'test-rev-id', inv_xml)
 
327
        self.assertEqual(b'test-rev-id', inv.root.revision)
459
328
 
460
329
    def test_deserialise_uses_global_revision_id(self):
461
330
        """If it is set, then we re-use the global revision id"""
462
331
        repo = self.make_repository('.',
463
 
                format=bzrdir.format_registry.get('knit')())
464
 
        inv_xml = ('<inventory format="5" revision_id="other-rev-id">\n'
465
 
                   '</inventory>\n')
 
332
                format=controldir.format_registry.get('knit')())
 
333
        inv_xml = (b'<inventory format="5" revision_id="other-rev-id">\n'
 
334
                   b'</inventory>\n')
466
335
        # Arguably, the deserialise_inventory should detect a mismatch, and
467
336
        # raise an error, rather than silently using one revision_id over the
468
337
        # other.
469
338
        self.assertRaises(AssertionError, repo._deserialise_inventory,
470
 
            'test-rev-id', inv_xml)
471
 
        inv = repo._deserialise_inventory('other-rev-id', inv_xml)
472
 
        self.assertEqual('other-rev-id', inv.root.revision)
 
339
            b'test-rev-id', inv_xml)
 
340
        inv = repo._deserialise_inventory(b'other-rev-id', inv_xml)
 
341
        self.assertEqual(b'other-rev-id', inv.root.revision)
473
342
 
474
343
    def test_supports_external_lookups(self):
475
344
        repo = self.make_repository('.',
476
 
                format=bzrdir.format_registry.get('knit')())
 
345
                format=controldir.format_registry.get('knit')())
477
346
        self.assertFalse(repo._format.supports_external_lookups)
478
347
 
479
348
 
520
389
        # classes do not barf inappropriately when a surprising repository type
521
390
        # is handed to them.
522
391
        dummy_a = DummyRepository()
 
392
        dummy_a._format = RepositoryFormat()
 
393
        dummy_a._format.supports_full_versioned_files = True
523
394
        dummy_b = DummyRepository()
 
395
        dummy_b._format = RepositoryFormat()
 
396
        dummy_b._format.supports_full_versioned_files = True
524
397
        self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
525
398
 
526
399
    def assertGetsDefaultInterRepository(self, repo_a, repo_b):
530
403
        no actual sane default in the presence of incompatible data models.
531
404
        """
532
405
        inter_repo = repository.InterRepository.get(repo_a, repo_b)
533
 
        self.assertEqual(repository.InterSameDataRepository,
 
406
        self.assertEqual(vf_repository.InterSameDataRepository,
534
407
                         inter_repo.__class__)
535
408
        self.assertEqual(repo_a, inter_repo.source)
536
409
        self.assertEqual(repo_b, inter_repo.target)
550
423
        dummy_a._serializer = repo._serializer
551
424
        dummy_a._format.supports_tree_reference = repo._format.supports_tree_reference
552
425
        dummy_a._format.rich_root_data = repo._format.rich_root_data
 
426
        dummy_a._format.supports_full_versioned_files = repo._format.supports_full_versioned_files
553
427
        dummy_b._serializer = repo._serializer
554
428
        dummy_b._format.supports_tree_reference = repo._format.supports_tree_reference
555
429
        dummy_b._format.rich_root_data = repo._format.rich_root_data
 
430
        dummy_b._format.supports_full_versioned_files = repo._format.supports_full_versioned_files
556
431
        repository.InterRepository.register_optimiser(InterDummy)
557
432
        try:
558
433
            # we should get the default for something InterDummy returns False
571
446
        self.assertGetsDefaultInterRepository(dummy_a, dummy_b)
572
447
 
573
448
 
574
 
class TestInterWeaveRepo(TestCaseWithTransport):
575
 
 
576
 
    def test_is_compatible_and_registered(self):
577
 
        # InterWeaveRepo is compatible when either side
578
 
        # is a format 5/6/7 branch
579
 
        from bzrlib.repofmt import knitrepo, weaverepo
580
 
        formats = [weaverepo.RepositoryFormat5(),
581
 
                   weaverepo.RepositoryFormat6(),
582
 
                   weaverepo.RepositoryFormat7()]
583
 
        incompatible_formats = [weaverepo.RepositoryFormat4(),
584
 
                                knitrepo.RepositoryFormatKnit1(),
585
 
                                ]
586
 
        repo_a = self.make_repository('a')
587
 
        repo_b = self.make_repository('b')
588
 
        is_compatible = repository.InterWeaveRepo.is_compatible
589
 
        for source in incompatible_formats:
590
 
            # force incompatible left then right
591
 
            repo_a._format = source
592
 
            repo_b._format = formats[0]
593
 
            self.assertFalse(is_compatible(repo_a, repo_b))
594
 
            self.assertFalse(is_compatible(repo_b, repo_a))
595
 
        for source in formats:
596
 
            repo_a._format = source
597
 
            for target in formats:
598
 
                repo_b._format = target
599
 
                self.assertTrue(is_compatible(repo_a, repo_b))
600
 
        self.assertEqual(repository.InterWeaveRepo,
601
 
                         repository.InterRepository.get(repo_a,
602
 
                                                        repo_b).__class__)
 
449
class TestRepositoryFormat1(knitrepo.RepositoryFormatKnit1):
 
450
 
 
451
    @classmethod
 
452
    def get_format_string(cls):
 
453
        return b"Test Format 1"
 
454
 
 
455
 
 
456
class TestRepositoryFormat2(knitrepo.RepositoryFormatKnit1):
 
457
 
 
458
    @classmethod
 
459
    def get_format_string(cls):
 
460
        return b"Test Format 2"
603
461
 
604
462
 
605
463
class TestRepositoryConverter(TestCaseWithTransport):
606
464
 
607
465
    def test_convert_empty(self):
608
 
        t = get_transport(self.get_url('.'))
 
466
        source_format = TestRepositoryFormat1()
 
467
        target_format = TestRepositoryFormat2()
 
468
        repository.format_registry.register(source_format)
 
469
        self.addCleanup(repository.format_registry.remove,
 
470
            source_format)
 
471
        repository.format_registry.register(target_format)
 
472
        self.addCleanup(repository.format_registry.remove,
 
473
            target_format)
 
474
        t = self.get_transport()
609
475
        t.mkdir('repository')
610
476
        repo_dir = bzrdir.BzrDirMetaFormat1().initialize('repository')
611
 
        repo = weaverepo.RepositoryFormat7().initialize(repo_dir)
612
 
        target_format = knitrepo.RepositoryFormatKnit1()
 
477
        repo = TestRepositoryFormat1().initialize(repo_dir)
613
478
        converter = repository.CopyConverter(target_format)
614
 
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
615
 
        try:
 
479
        with breezy.ui.ui_factory.nested_progress_bar() as pb:
616
480
            converter.convert(repo, pb)
617
 
        finally:
618
 
            pb.finished()
619
481
        repo = repo_dir.open_repository()
620
482
        self.assertTrue(isinstance(target_format, repo._format.__class__))
621
483
 
622
484
 
623
 
class TestMisc(TestCase):
624
 
 
625
 
    def test_unescape_xml(self):
626
 
        """We get some kind of error when malformed entities are passed"""
627
 
        self.assertRaises(KeyError, repository._unescape_xml, 'foo&bar;')
628
 
 
629
 
 
630
485
class TestRepositoryFormatKnit3(TestCaseWithTransport):
631
486
 
632
487
    def test_attribute__fetch_order(self):
648
503
        format = bzrdir.BzrDirMetaFormat1()
649
504
        format.repository_format = knitrepo.RepositoryFormatKnit1()
650
505
        tree = self.make_branch_and_tree('.', format)
651
 
        tree.commit("Dull commit", rev_id="dull")
652
 
        revision_tree = tree.branch.repository.revision_tree('dull')
 
506
        tree.commit("Dull commit", rev_id=b"dull")
 
507
        revision_tree = tree.branch.repository.revision_tree(b'dull')
653
508
        revision_tree.lock_read()
654
509
        try:
655
510
            self.assertRaises(errors.NoSuchFile, revision_tree.get_file_lines,
656
 
                revision_tree.inventory.root.file_id)
 
511
                u'', revision_tree.get_root_id())
657
512
        finally:
658
513
            revision_tree.unlock()
659
514
        format = bzrdir.BzrDirMetaFormat1()
660
515
        format.repository_format = knitrepo.RepositoryFormatKnit3()
661
516
        upgrade.Convert('.', format)
662
517
        tree = workingtree.WorkingTree.open('.')
663
 
        revision_tree = tree.branch.repository.revision_tree('dull')
 
518
        revision_tree = tree.branch.repository.revision_tree(b'dull')
664
519
        revision_tree.lock_read()
665
520
        try:
666
 
            revision_tree.get_file_lines(revision_tree.inventory.root.file_id)
 
521
            revision_tree.get_file_lines(u'', revision_tree.get_root_id())
667
522
        finally:
668
523
            revision_tree.unlock()
669
 
        tree.commit("Another dull commit", rev_id='dull2')
670
 
        revision_tree = tree.branch.repository.revision_tree('dull2')
 
524
        tree.commit("Another dull commit", rev_id=b'dull2')
 
525
        revision_tree = tree.branch.repository.revision_tree(b'dull2')
671
526
        revision_tree.lock_read()
672
527
        self.addCleanup(revision_tree.unlock)
673
 
        self.assertEqual('dull', revision_tree.inventory.root.revision)
 
528
        self.assertEqual(b'dull',
 
529
                revision_tree.get_file_revision(u'', revision_tree.get_root_id()))
674
530
 
675
531
    def test_supports_external_lookups(self):
676
532
        format = bzrdir.BzrDirMetaFormat1()
681
537
 
682
538
class Test2a(tests.TestCaseWithMemoryTransport):
683
539
 
684
 
    def test_fetch_combines_groups(self):
685
 
        builder = self.make_branch_builder('source', format='2a')
686
 
        builder.start_series()
687
 
        builder.build_snapshot('1', None, [
688
 
            ('add', ('', 'root-id', 'directory', '')),
689
 
            ('add', ('file', 'file-id', 'file', 'content\n'))])
690
 
        builder.build_snapshot('2', ['1'], [
691
 
            ('modify', ('file-id', 'content-2\n'))])
692
 
        builder.finish_series()
693
 
        source = builder.get_branch()
694
 
        target = self.make_repository('target', format='2a')
695
 
        target.fetch(source.repository)
696
 
        target.lock_read()
697
 
        self.addCleanup(target.unlock)
698
 
        details = target.texts._index.get_build_details(
699
 
            [('file-id', '1',), ('file-id', '2',)])
700
 
        file_1_details = details[('file-id', '1')]
701
 
        file_2_details = details[('file-id', '2')]
702
 
        # The index, and what to read off disk, should be the same for both
703
 
        # versions of the file.
704
 
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
705
 
 
706
 
    def test_fetch_combines_groups(self):
707
 
        builder = self.make_branch_builder('source', format='2a')
708
 
        builder.start_series()
709
 
        builder.build_snapshot('1', None, [
710
 
            ('add', ('', 'root-id', 'directory', '')),
711
 
            ('add', ('file', 'file-id', 'file', 'content\n'))])
712
 
        builder.build_snapshot('2', ['1'], [
713
 
            ('modify', ('file-id', 'content-2\n'))])
714
 
        builder.finish_series()
715
 
        source = builder.get_branch()
716
 
        target = self.make_repository('target', format='2a')
717
 
        target.fetch(source.repository)
718
 
        target.lock_read()
719
 
        self.addCleanup(target.unlock)
720
 
        details = target.texts._index.get_build_details(
721
 
            [('file-id', '1',), ('file-id', '2',)])
722
 
        file_1_details = details[('file-id', '1')]
723
 
        file_2_details = details[('file-id', '2')]
724
 
        # The index, and what to read off disk, should be the same for both
725
 
        # versions of the file.
726
 
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
727
 
 
728
 
    def test_fetch_combines_groups(self):
729
 
        builder = self.make_branch_builder('source', format='2a')
730
 
        builder.start_series()
731
 
        builder.build_snapshot('1', None, [
732
 
            ('add', ('', 'root-id', 'directory', '')),
733
 
            ('add', ('file', 'file-id', 'file', 'content\n'))])
734
 
        builder.build_snapshot('2', ['1'], [
735
 
            ('modify', ('file-id', 'content-2\n'))])
736
 
        builder.finish_series()
737
 
        source = builder.get_branch()
738
 
        target = self.make_repository('target', format='2a')
739
 
        target.fetch(source.repository)
740
 
        target.lock_read()
741
 
        self.addCleanup(target.unlock)
742
 
        details = target.texts._index.get_build_details(
743
 
            [('file-id', '1',), ('file-id', '2',)])
744
 
        file_1_details = details[('file-id', '1')]
745
 
        file_2_details = details[('file-id', '2')]
 
540
    def test_chk_bytes_uses_custom_btree_parser(self):
 
541
        mt = self.make_branch_and_memory_tree('test', format='2a')
 
542
        mt.lock_write()
 
543
        self.addCleanup(mt.unlock)
 
544
        mt.add([''], [b'root-id'])
 
545
        mt.commit('first')
 
546
        index = mt.branch.repository.chk_bytes._index._graph_index._indices[0]
 
547
        self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
 
548
        # It should also work if we re-open the repo
 
549
        repo = mt.branch.repository.controldir.open_repository()
 
550
        repo.lock_read()
 
551
        self.addCleanup(repo.unlock)
 
552
        index = repo.chk_bytes._index._graph_index._indices[0]
 
553
        self.assertEqual(btree_index._gcchk_factory, index._leaf_factory)
 
554
 
 
555
    def test_fetch_combines_groups(self):
 
556
        builder = self.make_branch_builder('source', format='2a')
 
557
        builder.start_series()
 
558
        builder.build_snapshot(None, [
 
559
            ('add', ('', b'root-id', 'directory', '')),
 
560
            ('add', ('file', b'file-id', 'file', b'content\n'))],
 
561
            revision_id=b'1')
 
562
        builder.build_snapshot([b'1'], [
 
563
            ('modify', ('file', b'content-2\n'))],
 
564
            revision_id=b'2')
 
565
        builder.finish_series()
 
566
        source = builder.get_branch()
 
567
        target = self.make_repository('target', format='2a')
 
568
        target.fetch(source.repository)
 
569
        target.lock_read()
 
570
        self.addCleanup(target.unlock)
 
571
        details = target.texts._index.get_build_details(
 
572
            [(b'file-id', b'1',), (b'file-id', b'2',)])
 
573
        file_1_details = details[(b'file-id', b'1')]
 
574
        file_2_details = details[(b'file-id', b'2')]
 
575
        # The index, and what to read off disk, should be the same for both
 
576
        # versions of the file.
 
577
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
 
578
 
 
579
    def test_fetch_combines_groups(self):
 
580
        builder = self.make_branch_builder('source', format='2a')
 
581
        builder.start_series()
 
582
        builder.build_snapshot(None, [
 
583
            ('add', ('', b'root-id', 'directory', '')),
 
584
            ('add', ('file', b'file-id', 'file', b'content\n'))],
 
585
            revision_id=b'1')
 
586
        builder.build_snapshot([b'1'], [
 
587
            ('modify', ('file', b'content-2\n'))],
 
588
            revision_id=b'2')
 
589
        builder.finish_series()
 
590
        source = builder.get_branch()
 
591
        target = self.make_repository('target', format='2a')
 
592
        target.fetch(source.repository)
 
593
        target.lock_read()
 
594
        self.addCleanup(target.unlock)
 
595
        details = target.texts._index.get_build_details(
 
596
            [(b'file-id', b'1',), (b'file-id', b'2',)])
 
597
        file_1_details = details[(b'file-id', b'1')]
 
598
        file_2_details = details[(b'file-id', b'2')]
 
599
        # The index, and what to read off disk, should be the same for both
 
600
        # versions of the file.
 
601
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
 
602
 
 
603
    def test_fetch_combines_groups(self):
 
604
        builder = self.make_branch_builder('source', format='2a')
 
605
        builder.start_series()
 
606
        builder.build_snapshot(None, [
 
607
            ('add', ('', b'root-id', 'directory', '')),
 
608
            ('add', ('file', b'file-id', 'file', b'content\n'))],
 
609
            revision_id=b'1')
 
610
        builder.build_snapshot([b'1'], [
 
611
            ('modify', ('file', b'content-2\n'))],
 
612
            revision_id=b'2')
 
613
        builder.finish_series()
 
614
        source = builder.get_branch()
 
615
        target = self.make_repository('target', format='2a')
 
616
        target.fetch(source.repository)
 
617
        target.lock_read()
 
618
        self.addCleanup(target.unlock)
 
619
        details = target.texts._index.get_build_details(
 
620
            [(b'file-id', b'1',), (b'file-id', b'2',)])
 
621
        file_1_details = details[(b'file-id', b'1')]
 
622
        file_2_details = details[(b'file-id', b'2')]
746
623
        # The index, and what to read off disk, should be the same for both
747
624
        # versions of the file.
748
625
        self.assertEqual(file_1_details[0][:3], file_2_details[0][:3])
754
631
    def test_inventories_use_chk_map_with_parent_base_dict(self):
755
632
        tree = self.make_branch_and_memory_tree('repo', format="2a")
756
633
        tree.lock_write()
757
 
        tree.add([''], ['TREE_ROOT'])
 
634
        tree.add([''], [b'TREE_ROOT'])
758
635
        revid = tree.commit("foo")
759
636
        tree.unlock()
760
637
        tree.lock_read()
775
652
        tree = self.make_branch_and_memory_tree('tree', format='2a')
776
653
        tree.lock_write()
777
654
        self.addCleanup(tree.unlock)
778
 
        tree.add([''], ['TREE_ROOT'])
 
655
        tree.add([''], [b'TREE_ROOT'])
779
656
        for pos in range(20):
780
657
            tree.commit(str(pos))
781
658
 
783
660
        tree = self.make_branch_and_memory_tree('tree', format='2a')
784
661
        tree.lock_write()
785
662
        self.addCleanup(tree.unlock)
786
 
        tree.add([''], ['TREE_ROOT'])
 
663
        tree.add([''], [b'TREE_ROOT'])
787
664
        # 1 commit to leave untouched
788
665
        tree.commit('1')
789
666
        to_keep = tree.branch.repository._pack_collection.names()
812
689
        target = self.make_repository('target', format='rich-root-pack')
813
690
        stream = source._get_source(target._format)
814
691
        # We don't want the child GroupCHKStreamSource
815
 
        self.assertIs(type(stream), repository.StreamSource)
 
692
        self.assertIs(type(stream), vf_repository.StreamSource)
816
693
 
817
694
    def test_get_stream_for_missing_keys_includes_all_chk_refs(self):
818
695
        source_builder = self.make_branch_builder('source',
819
696
                            format='2a')
820
697
        # We have to build a fairly large tree, so that we are sure the chk
821
698
        # pages will have split into multiple pages.
822
 
        entries = [('add', ('', 'a-root-id', 'directory', None))]
 
699
        entries = [('add', ('', b'a-root-id', 'directory', None))]
823
700
        for i in 'abcdefghijklmnopqrstuvwxyz123456789':
824
701
            for j in 'abcdefghijklmnopqrstuvwxyz123456789':
825
702
                fname = i + j
826
 
                fid = fname + '-id'
827
 
                content = 'content for %s\n' % (fname,)
 
703
                fid = fname.encode('utf-8') + b'-id'
 
704
                content = b'content for %s\n' % (fname.encode('utf-8'),)
828
705
                entries.append(('add', (fname, fid, 'file', content)))
829
706
        source_builder.start_series()
830
 
        source_builder.build_snapshot('rev-1', None, entries)
 
707
        source_builder.build_snapshot(None, entries, revision_id=b'rev-1')
831
708
        # Now change a few of them, so we get a few new pages for the second
832
709
        # revision
833
 
        source_builder.build_snapshot('rev-2', ['rev-1'], [
834
 
            ('modify', ('aa-id', 'new content for aa-id\n')),
835
 
            ('modify', ('cc-id', 'new content for cc-id\n')),
836
 
            ('modify', ('zz-id', 'new content for zz-id\n')),
837
 
            ])
 
710
        source_builder.build_snapshot([b'rev-1'], [
 
711
            ('modify', ('aa', b'new content for aa-id\n')),
 
712
            ('modify', ('cc', b'new content for cc-id\n')),
 
713
            ('modify', ('zz', b'new content for zz-id\n')),
 
714
            ], revision_id=b'rev-2')
838
715
        source_builder.finish_series()
839
716
        source_branch = source_builder.get_branch()
840
717
        source_branch.lock_read()
845
722
 
846
723
        # On a regular pass, getting the inventories and chk pages for rev-2
847
724
        # would only get the newly created chk pages
848
 
        search = graph.SearchResult(set(['rev-2']), set(['rev-1']), 1,
849
 
                                    set(['rev-2']))
850
 
        simple_chk_records = []
 
725
        search = vf_search.SearchResult({b'rev-2'}, {b'rev-1'}, 1,
 
726
                                    {b'rev-2'})
 
727
        simple_chk_records = set()
851
728
        for vf_name, substream in source.get_stream(search):
852
729
            if vf_name == 'chk_bytes':
853
730
                for record in substream:
854
 
                    simple_chk_records.append(record.key)
 
731
                    simple_chk_records.add(record.key)
855
732
            else:
856
733
                for _ in substream:
857
734
                    continue
858
735
        # 3 pages, the root (InternalNode), + 2 pages which actually changed
859
 
        self.assertEqual([('sha1:91481f539e802c76542ea5e4c83ad416bf219f73',),
860
 
                          ('sha1:4ff91971043668583985aec83f4f0ab10a907d3f',),
861
 
                          ('sha1:81e7324507c5ca132eedaf2d8414ee4bb2226187',),
862
 
                          ('sha1:b101b7da280596c71a4540e9a1eeba8045985ee0',)],
863
 
                         simple_chk_records)
 
736
        self.assertEqual({(b'sha1:91481f539e802c76542ea5e4c83ad416bf219f73',),
 
737
                          (b'sha1:4ff91971043668583985aec83f4f0ab10a907d3f',),
 
738
                          (b'sha1:81e7324507c5ca132eedaf2d8414ee4bb2226187',),
 
739
                          (b'sha1:b101b7da280596c71a4540e9a1eeba8045985ee0',)},
 
740
                         set(simple_chk_records))
864
741
        # Now, when we do a similar call using 'get_stream_for_missing_keys'
865
742
        # we should get a much larger set of pages.
866
 
        missing = [('inventories', 'rev-2')]
867
 
        full_chk_records = []
 
743
        missing = [('inventories', b'rev-2')]
 
744
        full_chk_records = set()
868
745
        for vf_name, substream in source.get_stream_for_missing_keys(missing):
869
746
            if vf_name == 'inventories':
870
747
                for record in substream:
871
 
                    self.assertEqual(('rev-2',), record.key)
 
748
                    self.assertEqual((b'rev-2',), record.key)
872
749
            elif vf_name == 'chk_bytes':
873
750
                for record in substream:
874
 
                    full_chk_records.append(record.key)
 
751
                    full_chk_records.add(record.key)
875
752
            else:
876
753
                self.fail('Should not be getting a stream of %s' % (vf_name,))
877
754
        # We have 257 records now. This is because we have 1 root page, and 256
894
771
        source = self.make_repository('source', format='pack-0.92')
895
772
        target = self.make_repository('target', format='pack-0.92')
896
773
        stream_source = source._get_source(target._format)
897
 
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
 
774
        self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
898
775
 
899
776
    def test_source_to_exact_pack_rich_root_pack(self):
900
777
        source = self.make_repository('source', format='rich-root-pack')
901
778
        target = self.make_repository('target', format='rich-root-pack')
902
779
        stream_source = source._get_source(target._format)
903
 
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
 
780
        self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
904
781
 
905
782
    def test_source_to_exact_pack_19(self):
906
783
        source = self.make_repository('source', format='1.9')
907
784
        target = self.make_repository('target', format='1.9')
908
785
        stream_source = source._get_source(target._format)
909
 
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
 
786
        self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
910
787
 
911
788
    def test_source_to_exact_pack_19_rich_root(self):
912
789
        source = self.make_repository('source', format='1.9-rich-root')
913
790
        target = self.make_repository('target', format='1.9-rich-root')
914
791
        stream_source = source._get_source(target._format)
915
 
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
 
792
        self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
916
793
 
917
794
    def test_source_to_remote_exact_pack_19(self):
918
795
        trans = self.make_smart_server('target')
921
798
        target = self.make_repository('target', format='1.9')
922
799
        target = repository.Repository.open(trans.base)
923
800
        stream_source = source._get_source(target._format)
924
 
        self.assertIsInstance(stream_source, pack_repo.KnitPackStreamSource)
 
801
        self.assertIsInstance(stream_source, knitpack_repo.KnitPackStreamSource)
925
802
 
926
803
    def test_stream_source_to_non_exact(self):
927
804
        source = self.make_repository('source', format='pack-0.92')
928
805
        target = self.make_repository('target', format='1.9')
929
806
        stream = source._get_source(target._format)
930
 
        self.assertIs(type(stream), repository.StreamSource)
 
807
        self.assertIs(type(stream), vf_repository.StreamSource)
931
808
 
932
809
    def test_stream_source_to_non_exact_rich_root(self):
933
810
        source = self.make_repository('source', format='1.9')
934
811
        target = self.make_repository('target', format='1.9-rich-root')
935
812
        stream = source._get_source(target._format)
936
 
        self.assertIs(type(stream), repository.StreamSource)
 
813
        self.assertIs(type(stream), vf_repository.StreamSource)
937
814
 
938
815
    def test_source_to_remote_non_exact_pack_19(self):
939
816
        trans = self.make_smart_server('target')
942
819
        target = self.make_repository('target', format='1.6')
943
820
        target = repository.Repository.open(trans.base)
944
821
        stream_source = source._get_source(target._format)
945
 
        self.assertIs(type(stream_source), repository.StreamSource)
 
822
        self.assertIs(type(stream_source), vf_repository.StreamSource)
946
823
 
947
824
    def test_stream_source_to_knit(self):
948
825
        source = self.make_repository('source', format='pack-0.92')
949
826
        target = self.make_repository('target', format='dirstate')
950
827
        stream = source._get_source(target._format)
951
 
        self.assertIs(type(stream), repository.StreamSource)
 
828
        self.assertIs(type(stream), vf_repository.StreamSource)
952
829
 
953
830
 
954
831
class TestDevelopment6FindParentIdsOfRevisions(TestCaseWithTransport):
956
833
 
957
834
    def setUp(self):
958
835
        super(TestDevelopment6FindParentIdsOfRevisions, self).setUp()
959
 
        self.builder = self.make_branch_builder('source',
960
 
            format='development6-rich-root')
 
836
        self.builder = self.make_branch_builder('source')
961
837
        self.builder.start_series()
962
 
        self.builder.build_snapshot('initial', None,
963
 
            [('add', ('', 'tree-root', 'directory', None))])
 
838
        self.builder.build_snapshot(None,
 
839
            [('add', ('', b'tree-root', 'directory', None))],
 
840
            revision_id=b'initial')
964
841
        self.repo = self.builder.get_branch().repository
965
842
        self.addCleanup(self.builder.finish_series)
966
843
 
969
846
            sorted(self.repo._find_parent_ids_of_revisions(rev_set)))
970
847
 
971
848
    def test_simple(self):
972
 
        self.builder.build_snapshot('revid1', None, [])
973
 
        self.builder.build_snapshot('revid2', ['revid1'], [])
974
 
        rev_set = ['revid2']
975
 
        self.assertParentIds(['revid1'], rev_set)
 
849
        self.builder.build_snapshot(None, [], revision_id=b'revid1')
 
850
        self.builder.build_snapshot([b'revid1'], [], revision_id=b'revid2')
 
851
        rev_set = [b'revid2']
 
852
        self.assertParentIds([b'revid1'], rev_set)
976
853
 
977
854
    def test_not_first_parent(self):
978
 
        self.builder.build_snapshot('revid1', None, [])
979
 
        self.builder.build_snapshot('revid2', ['revid1'], [])
980
 
        self.builder.build_snapshot('revid3', ['revid2'], [])
981
 
        rev_set = ['revid3', 'revid2']
982
 
        self.assertParentIds(['revid1'], rev_set)
 
855
        self.builder.build_snapshot(None, [], revision_id=b'revid1')
 
856
        self.builder.build_snapshot([b'revid1'], [], revision_id=b'revid2')
 
857
        self.builder.build_snapshot([b'revid2'], [], revision_id=b'revid3')
 
858
        rev_set = [b'revid3', b'revid2']
 
859
        self.assertParentIds([b'revid1'], rev_set)
983
860
 
984
861
    def test_not_null(self):
985
 
        rev_set = ['initial']
 
862
        rev_set = [b'initial']
986
863
        self.assertParentIds([], rev_set)
987
864
 
988
865
    def test_not_null_set(self):
989
 
        self.builder.build_snapshot('revid1', None, [])
 
866
        self.builder.build_snapshot(None, [], revision_id=b'revid1')
990
867
        rev_set = [_mod_revision.NULL_REVISION]
991
868
        self.assertParentIds([], rev_set)
992
869
 
993
870
    def test_ghost(self):
994
 
        self.builder.build_snapshot('revid1', None, [])
995
 
        rev_set = ['ghost', 'revid1']
996
 
        self.assertParentIds(['initial'], rev_set)
 
871
        self.builder.build_snapshot(None, [], revision_id=b'revid1')
 
872
        rev_set = [b'ghost', b'revid1']
 
873
        self.assertParentIds([b'initial'], rev_set)
997
874
 
998
875
    def test_ghost_parent(self):
999
 
        self.builder.build_snapshot('revid1', None, [])
1000
 
        self.builder.build_snapshot('revid2', ['revid1', 'ghost'], [])
1001
 
        rev_set = ['revid2', 'revid1']
1002
 
        self.assertParentIds(['ghost', 'initial'], rev_set)
 
876
        self.builder.build_snapshot(None, [], revision_id=b'revid1')
 
877
        self.builder.build_snapshot([b'revid1', b'ghost'], [], revision_id=b'revid2')
 
878
        rev_set = [b'revid2', b'revid1']
 
879
        self.assertParentIds([b'ghost', b'initial'], rev_set)
1003
880
 
1004
881
    def test_righthand_parent(self):
1005
 
        self.builder.build_snapshot('revid1', None, [])
1006
 
        self.builder.build_snapshot('revid2a', ['revid1'], [])
1007
 
        self.builder.build_snapshot('revid2b', ['revid1'], [])
1008
 
        self.builder.build_snapshot('revid3', ['revid2a', 'revid2b'], [])
1009
 
        rev_set = ['revid3', 'revid2a']
1010
 
        self.assertParentIds(['revid1', 'revid2b'], rev_set)
 
882
        self.builder.build_snapshot(None, [], revision_id=b'revid1')
 
883
        self.builder.build_snapshot([b'revid1'], [], revision_id=b'revid2a')
 
884
        self.builder.build_snapshot([b'revid1'], [], revision_id=b'revid2b')
 
885
        self.builder.build_snapshot([b'revid2a', b'revid2b'], [],
 
886
                                    revision_id=b'revid3')
 
887
        rev_set = [b'revid3', b'revid2a']
 
888
        self.assertParentIds([b'revid1', b'revid2b'], rev_set)
1011
889
 
1012
890
 
1013
891
class TestWithBrokenRepo(TestCaseWithTransport):
1025
903
            repo.start_write_group()
1026
904
            cleanups.append(repo.commit_write_group)
1027
905
            # make rev1a: A well-formed revision, containing 'file1'
1028
 
            inv = inventory.Inventory(revision_id='rev1a')
1029
 
            inv.root.revision = 'rev1a'
1030
 
            self.add_file(repo, inv, 'file1', 'rev1a', [])
1031
 
            repo.texts.add_lines((inv.root.file_id, 'rev1a'), [], [])
1032
 
            repo.add_inventory('rev1a', inv, [])
1033
 
            revision = _mod_revision.Revision('rev1a',
 
906
            inv = inventory.Inventory(revision_id=b'rev1a')
 
907
            inv.root.revision = b'rev1a'
 
908
            self.add_file(repo, inv, 'file1', b'rev1a', [])
 
909
            repo.texts.add_lines((inv.root.file_id, b'rev1a'), [], [])
 
910
            repo.add_inventory(b'rev1a', inv, [])
 
911
            revision = _mod_revision.Revision(b'rev1a',
1034
912
                committer='jrandom@example.com', timestamp=0,
1035
913
                inventory_sha1='', timezone=0, message='foo', parent_ids=[])
1036
 
            repo.add_revision('rev1a',revision, inv)
 
914
            repo.add_revision(b'rev1a', revision, inv)
1037
915
 
1038
916
            # make rev1b, which has no Revision, but has an Inventory, and
1039
917
            # file1
1040
 
            inv = inventory.Inventory(revision_id='rev1b')
1041
 
            inv.root.revision = 'rev1b'
1042
 
            self.add_file(repo, inv, 'file1', 'rev1b', [])
1043
 
            repo.add_inventory('rev1b', inv, [])
 
918
            inv = inventory.Inventory(revision_id=b'rev1b')
 
919
            inv.root.revision = b'rev1b'
 
920
            self.add_file(repo, inv, 'file1', b'rev1b', [])
 
921
            repo.add_inventory(b'rev1b', inv, [])
1044
922
 
1045
923
            # make rev2, with file1 and file2
1046
924
            # file2 is sane
1047
925
            # file1 has 'rev1b' as an ancestor, even though this is not
1048
926
            # mentioned by 'rev1a', making it an unreferenced ancestor
1049
927
            inv = inventory.Inventory()
1050
 
            self.add_file(repo, inv, 'file1', 'rev2', ['rev1a', 'rev1b'])
1051
 
            self.add_file(repo, inv, 'file2', 'rev2', [])
1052
 
            self.add_revision(repo, 'rev2', inv, ['rev1a'])
 
928
            self.add_file(repo, inv, 'file1', b'rev2', [b'rev1a', b'rev1b'])
 
929
            self.add_file(repo, inv, 'file2', b'rev2', [])
 
930
            self.add_revision(repo, b'rev2', inv, [b'rev1a'])
1053
931
 
1054
932
            # make ghost revision rev1c
1055
933
            inv = inventory.Inventory()
1056
 
            self.add_file(repo, inv, 'file2', 'rev1c', [])
 
934
            self.add_file(repo, inv, 'file2', b'rev1c', [])
1057
935
 
1058
936
            # make rev3 with file2
1059
937
            # file2 refers to 'rev1c', which is a ghost in this repository, so
1060
938
            # file2 cannot have rev1c as its ancestor.
1061
939
            inv = inventory.Inventory()
1062
 
            self.add_file(repo, inv, 'file2', 'rev3', ['rev1c'])
1063
 
            self.add_revision(repo, 'rev3', inv, ['rev1c'])
 
940
            self.add_file(repo, inv, 'file2', b'rev3', [b'rev1c'])
 
941
            self.add_revision(repo, b'rev3', inv, [b'rev1c'])
1064
942
            return repo
1065
943
        finally:
1066
944
            for cleanup in reversed(cleanups):
1074
952
        revision = _mod_revision.Revision(revision_id,
1075
953
            committer='jrandom@example.com', timestamp=0, inventory_sha1='',
1076
954
            timezone=0, message='foo', parent_ids=parent_ids)
1077
 
        repo.add_revision(revision_id,revision, inv)
 
955
        repo.add_revision(revision_id, revision, inv)
1078
956
 
1079
957
    def add_file(self, repo, inv, filename, revision, parents):
1080
 
        file_id = filename + '-id'
1081
 
        entry = inventory.InventoryFile(file_id, filename, 'TREE_ROOT')
 
958
        file_id = filename.encode('utf-8') + b'-id'
 
959
        content = [b'line\n']
 
960
        entry = inventory.InventoryFile(file_id, filename, b'TREE_ROOT')
1082
961
        entry.revision = revision
 
962
        entry.text_sha1 = osutils.sha_strings(content)
1083
963
        entry.text_size = 0
1084
964
        inv.add(entry)
1085
965
        text_key = (file_id, revision)
1086
966
        parent_keys = [(file_id, parent) for parent in parents]
1087
 
        repo.texts.add_lines(text_key, parent_keys, ['line\n'])
 
967
        repo.texts.add_lines(text_key, parent_keys, content)
1088
968
 
1089
969
    def test_insert_from_broken_repo(self):
1090
970
        """Inserting a data stream from a broken repository won't silently
1100
980
            return
1101
981
        empty_repo.lock_read()
1102
982
        self.addCleanup(empty_repo.unlock)
1103
 
        text = empty_repo.texts.get_record_stream(
1104
 
            [('file2-id', 'rev3')], 'topological', True).next()
1105
 
        self.assertEqual('line\n', text.get_bytes_as('fulltext'))
 
983
        text = next(empty_repo.texts.get_record_stream(
 
984
            [(b'file2-id', b'rev3')], 'topological', True))
 
985
        self.assertEqual(b'line\n', text.get_bytes_as('fulltext'))
1106
986
 
1107
987
 
1108
988
class TestRepositoryPackCollection(TestCaseWithTransport):
1109
989
 
1110
990
    def get_format(self):
1111
 
        return bzrdir.format_registry.make_bzrdir('pack-0.92')
 
991
        return controldir.format_registry.make_controldir('pack-0.92')
1112
992
 
1113
993
    def get_packs(self):
1114
994
        format = self.get_format()
1136
1016
    def test__clear_obsolete_packs(self):
1137
1017
        packs = self.get_packs()
1138
1018
        obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1139
 
        obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1140
 
        obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1141
 
        obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1142
 
        obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1143
 
        obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
 
1019
        obsolete_pack_trans.put_bytes('a-pack.pack', b'content\n')
 
1020
        obsolete_pack_trans.put_bytes('a-pack.rix', b'content\n')
 
1021
        obsolete_pack_trans.put_bytes('a-pack.iix', b'content\n')
 
1022
        obsolete_pack_trans.put_bytes('another-pack.pack', b'foo\n')
 
1023
        obsolete_pack_trans.put_bytes('not-a-pack.rix', b'foo\n')
1144
1024
        res = packs._clear_obsolete_packs()
1145
1025
        self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1146
1026
        self.assertEqual([], obsolete_pack_trans.list_dir('.'))
1148
1028
    def test__clear_obsolete_packs_preserve(self):
1149
1029
        packs = self.get_packs()
1150
1030
        obsolete_pack_trans = packs.transport.clone('obsolete_packs')
1151
 
        obsolete_pack_trans.put_bytes('a-pack.pack', 'content\n')
1152
 
        obsolete_pack_trans.put_bytes('a-pack.rix', 'content\n')
1153
 
        obsolete_pack_trans.put_bytes('a-pack.iix', 'content\n')
1154
 
        obsolete_pack_trans.put_bytes('another-pack.pack', 'foo\n')
1155
 
        obsolete_pack_trans.put_bytes('not-a-pack.rix', 'foo\n')
1156
 
        res = packs._clear_obsolete_packs(preserve=set(['a-pack']))
 
1031
        obsolete_pack_trans.put_bytes('a-pack.pack', b'content\n')
 
1032
        obsolete_pack_trans.put_bytes('a-pack.rix', b'content\n')
 
1033
        obsolete_pack_trans.put_bytes('a-pack.iix', b'content\n')
 
1034
        obsolete_pack_trans.put_bytes('another-pack.pack', b'foo\n')
 
1035
        obsolete_pack_trans.put_bytes('not-a-pack.rix', b'foo\n')
 
1036
        res = packs._clear_obsolete_packs(preserve={'a-pack'})
1157
1037
        self.assertEqual(['a-pack', 'another-pack'], sorted(res))
1158
1038
        self.assertEqual(['a-pack.iix', 'a-pack.pack', 'a-pack.rix'],
1159
1039
                         sorted(obsolete_pack_trans.list_dir('.')))
1207
1087
                         sorted(packs._pack_transport.list_dir('.')))
1208
1088
        # names[0] should not be present in the index anymore
1209
1089
        self.assertEqual(names[1:],
1210
 
            sorted(set([osutils.splitext(n)[0] for n in
1211
 
                        packs._index_transport.list_dir('.')])))
 
1090
            sorted({osutils.splitext(n)[0] for n in
 
1091
                        packs._index_transport.list_dir('.')}))
 
1092
 
 
1093
    def test__obsolete_packs_missing_directory(self):
 
1094
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
 
1095
        r.control_transport.rmdir('obsolete_packs')
 
1096
        names = packs.names()
 
1097
        pack = packs.get_pack_by_name(names[0])
 
1098
        # Schedule this one for removal
 
1099
        packs._remove_pack_from_memory(pack)
 
1100
        # Now trigger the obsoletion, and ensure that all the remaining files
 
1101
        # are still renamed
 
1102
        packs._obsolete_packs([pack])
 
1103
        self.assertEqual([n + '.pack' for n in names[1:]],
 
1104
                         sorted(packs._pack_transport.list_dir('.')))
 
1105
        # names[0] should not be present in the index anymore
 
1106
        self.assertEqual(names[1:],
 
1107
            sorted({osutils.splitext(n)[0] for n in
 
1108
                        packs._index_transport.list_dir('.')}))
1212
1109
 
1213
1110
    def test_pack_distribution_zero(self):
1214
1111
        packs = self.get_packs()
1390
1287
        # and remove another pack (via _remove_pack_from_memory)
1391
1288
        orig_names = packs.names()
1392
1289
        orig_at_load = packs._packs_at_load
1393
 
        to_remove_name = iter(orig_names).next()
 
1290
        to_remove_name = next(iter(orig_names))
1394
1291
        r.start_write_group()
1395
1292
        self.addCleanup(r.abort_write_group)
1396
1293
        r.texts.insert_record_stream([versionedfile.FulltextContentFactory(
1397
 
            ('text', 'rev'), (), None, 'content\n')])
 
1294
            (b'text', b'rev'), (), None, b'content\n')])
1398
1295
        new_pack = packs._new_pack
1399
1296
        self.assertTrue(new_pack.data_inserted())
1400
1297
        new_pack.finish()
1404
1301
        packs._remove_pack_from_memory(removed_pack)
1405
1302
        names = packs.names()
1406
1303
        all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
1407
 
        new_names = set([x[0][0] for x in new_nodes])
1408
 
        self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
 
1304
        new_names = {x[0] for x in new_nodes}
 
1305
        self.assertEqual(names, sorted([x[0] for x in all_nodes]))
1409
1306
        self.assertEqual(set(names) - set(orig_names), new_names)
1410
 
        self.assertEqual(set([new_pack.name]), new_names)
 
1307
        self.assertEqual({new_pack.name}, new_names)
1411
1308
        self.assertEqual([to_remove_name],
1412
 
                         sorted([x[0][0] for x in deleted_nodes]))
 
1309
                         sorted([x[0] for x in deleted_nodes]))
1413
1310
        packs.reload_pack_names()
1414
1311
        reloaded_names = packs.names()
1415
1312
        self.assertEqual(orig_at_load, packs._packs_at_load)
1416
1313
        self.assertEqual(names, reloaded_names)
1417
1314
        all_nodes, deleted_nodes, new_nodes, _ = packs._diff_pack_names()
1418
 
        new_names = set([x[0][0] for x in new_nodes])
1419
 
        self.assertEqual(names, sorted([x[0][0] for x in all_nodes]))
 
1315
        new_names = {x[0] for x in new_nodes}
 
1316
        self.assertEqual(names, sorted([x[0] for x in all_nodes]))
1420
1317
        self.assertEqual(set(names) - set(orig_names), new_names)
1421
 
        self.assertEqual(set([new_pack.name]), new_names)
 
1318
        self.assertEqual({new_pack.name}, new_names)
1422
1319
        self.assertEqual([to_remove_name],
1423
 
                         sorted([x[0][0] for x in deleted_nodes]))
 
1320
                         sorted([x[0] for x in deleted_nodes]))
1424
1321
 
1425
1322
    def test_autopack_obsoletes_new_pack(self):
1426
1323
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
1428
1325
        packs.pack_distribution = lambda x: [10]
1429
1326
        r.start_write_group()
1430
1327
        r.revisions.insert_record_stream([versionedfile.FulltextContentFactory(
1431
 
            ('bogus-rev',), (), None, 'bogus-content\n')])
 
1328
            (b'bogus-rev',), (), None, b'bogus-content\n')])
1432
1329
        # This should trigger an autopack, which will combine everything into a
1433
1330
        # single pack file.
1434
1331
        new_names = r.commit_write_group()
1464
1361
        self.assertEqual([n + '.pack' for n in names[1:]], sorted(cur_packs))
1465
1362
        # obsolete_packs will also have stuff like .rix and .iix present.
1466
1363
        obsolete_packs = packs.transport.list_dir('obsolete_packs')
1467
 
        obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
 
1364
        obsolete_names = {osutils.splitext(n)[0] for n in obsolete_packs}
1468
1365
        self.assertEqual([pack.name], sorted(obsolete_names))
1469
1366
 
1470
1367
    def test__save_pack_names_already_obsoleted(self):
1482
1379
        # Note that while we set clear_obsolete_packs=True, it should not
1483
1380
        # delete a pack file that we have also scheduled for obsoletion.
1484
1381
        obsolete_packs = packs.transport.list_dir('obsolete_packs')
1485
 
        obsolete_names = set([osutils.splitext(n)[0] for n in obsolete_packs])
 
1382
        obsolete_names = {osutils.splitext(n)[0] for n in obsolete_packs}
1486
1383
        self.assertEqual([pack.name], sorted(obsolete_names))
1487
1384
 
 
1385
    def test_pack_no_obsolete_packs_directory(self):
 
1386
        """Bug #314314, don't fail if obsolete_packs directory does
 
1387
        not exist."""
 
1388
        tree, r, packs, revs = self.make_packs_and_alt_repo(write_lock=True)
 
1389
        r.control_transport.rmdir('obsolete_packs')
 
1390
        packs._clear_obsolete_packs()
1488
1391
 
1489
1392
 
1490
1393
class TestPack(TestCaseWithTransport):
1574
1477
    def test_pack_optimizes_pack_order(self):
1575
1478
        builder = self.make_branch_builder('.', format="1.9")
1576
1479
        builder.start_series()
1577
 
        builder.build_snapshot('A', None, [
1578
 
            ('add', ('', 'root-id', 'directory', None)),
1579
 
            ('add', ('f', 'f-id', 'file', 'content\n'))])
1580
 
        builder.build_snapshot('B', ['A'],
1581
 
            [('modify', ('f-id', 'new-content\n'))])
1582
 
        builder.build_snapshot('C', ['B'],
1583
 
            [('modify', ('f-id', 'third-content\n'))])
1584
 
        builder.build_snapshot('D', ['C'],
1585
 
            [('modify', ('f-id', 'fourth-content\n'))])
 
1480
        builder.build_snapshot(None, [
 
1481
            ('add', ('', b'root-id', 'directory', None)),
 
1482
            ('add', ('f', b'f-id', 'file', b'content\n'))],
 
1483
            revision_id=b'A')
 
1484
        builder.build_snapshot([b'A'],
 
1485
            [('modify', ('f', b'new-content\n'))],
 
1486
            revision_id=b'B')
 
1487
        builder.build_snapshot([b'B'],
 
1488
            [('modify', ('f', b'third-content\n'))],
 
1489
            revision_id=b'C')
 
1490
        builder.build_snapshot([b'C'],
 
1491
            [('modify', ('f', b'fourth-content\n'))],
 
1492
            revision_id=b'D')
1586
1493
        b = builder.get_branch()
1587
1494
        b.lock_read()
1588
1495
        builder.finish_series()
1591
1498
        # Because of how they were built, they correspond to
1592
1499
        # ['D', 'C', 'B', 'A']
1593
1500
        packs = b.repository._pack_collection.packs
1594
 
        packer = pack_repo.Packer(b.repository._pack_collection,
 
1501
        packer = knitpack_repo.KnitPacker(b.repository._pack_collection,
1595
1502
                                  packs, 'testing',
1596
 
                                  revision_ids=['B', 'C'])
 
1503
                                  revision_ids=[b'B', b'C'])
1597
1504
        # Now, when we are copying the B & C revisions, their pack files should
1598
1505
        # be moved to the front of the stack
1599
1506
        # The new ordering moves B & C to the front of the .packs attribute,
1611
1518
        return repo._pack_collection
1612
1519
 
1613
1520
    def test_open_pack_will_optimise(self):
1614
 
        packer = pack_repo.OptimisingPacker(self.get_pack_collection(),
 
1521
        packer = knitpack_repo.OptimisingKnitPacker(self.get_pack_collection(),
1615
1522
                                            [], '.test')
1616
1523
        new_pack = packer.open_pack()
1617
1524
        self.addCleanup(new_pack.abort) # ensure cleanup
1622
1529
        self.assertTrue(new_pack.signature_index._optimize_for_size)
1623
1530
 
1624
1531
 
 
1532
class TestGCCHKPacker(TestCaseWithTransport):
 
1533
 
 
1534
    def make_abc_branch(self):
 
1535
        builder = self.make_branch_builder('source')
 
1536
        builder.start_series()
 
1537
        builder.build_snapshot(None, [
 
1538
            ('add', ('', b'root-id', 'directory', None)),
 
1539
            ('add', ('file', b'file-id', 'file', b'content\n')),
 
1540
            ], revision_id=b'A')
 
1541
        builder.build_snapshot([b'A'], [
 
1542
            ('add', ('dir', b'dir-id', 'directory', None))],
 
1543
            revision_id=b'B')
 
1544
        builder.build_snapshot([b'B'], [
 
1545
            ('modify', ('file', b'new content\n'))],
 
1546
            revision_id=b'C')
 
1547
        builder.finish_series()
 
1548
        return builder.get_branch()
 
1549
 
 
1550
    def make_branch_with_disjoint_inventory_and_revision(self):
 
1551
        """a repo with separate packs for a revisions Revision and Inventory.
 
1552
 
 
1553
        There will be one pack file that holds the Revision content, and one
 
1554
        for the Inventory content.
 
1555
 
 
1556
        :return: (repository,
 
1557
                  pack_name_with_rev_A_Revision,
 
1558
                  pack_name_with_rev_A_Inventory,
 
1559
                  pack_name_with_rev_C_content)
 
1560
        """
 
1561
        b_source = self.make_abc_branch()
 
1562
        b_base = b_source.controldir.sprout('base', revision_id=b'A').open_branch()
 
1563
        b_stacked = b_base.controldir.sprout('stacked', stacked=True).open_branch()
 
1564
        b_stacked.lock_write()
 
1565
        self.addCleanup(b_stacked.unlock)
 
1566
        b_stacked.fetch(b_source, b'B')
 
1567
        # Now re-open the stacked repo directly (no fallbacks) so that we can
 
1568
        # fill in the A rev.
 
1569
        repo_not_stacked = b_stacked.controldir.open_repository()
 
1570
        repo_not_stacked.lock_write()
 
1571
        self.addCleanup(repo_not_stacked.unlock)
 
1572
        # Now we should have a pack file with A's inventory, but not its
 
1573
        # Revision
 
1574
        self.assertEqual([(b'A',), (b'B',)],
 
1575
                         sorted(repo_not_stacked.inventories.keys()))
 
1576
        self.assertEqual([(b'B',)],
 
1577
                         sorted(repo_not_stacked.revisions.keys()))
 
1578
        stacked_pack_names = repo_not_stacked._pack_collection.names()
 
1579
        # We have a couple names here, figure out which has A's inventory
 
1580
        for name in stacked_pack_names:
 
1581
            pack = repo_not_stacked._pack_collection.get_pack_by_name(name)
 
1582
            keys = [n[1] for n in pack.inventory_index.iter_all_entries()]
 
1583
            if (b'A',) in keys:
 
1584
                inv_a_pack_name = name
 
1585
                break
 
1586
        else:
 
1587
            self.fail('Could not find pack containing A\'s inventory')
 
1588
        repo_not_stacked.fetch(b_source.repository, b'A')
 
1589
        self.assertEqual([(b'A',), (b'B',)],
 
1590
                         sorted(repo_not_stacked.revisions.keys()))
 
1591
        new_pack_names = set(repo_not_stacked._pack_collection.names())
 
1592
        rev_a_pack_names = new_pack_names.difference(stacked_pack_names)
 
1593
        self.assertEqual(1, len(rev_a_pack_names))
 
1594
        rev_a_pack_name = list(rev_a_pack_names)[0]
 
1595
        # Now fetch 'C', so we have a couple pack files to join
 
1596
        repo_not_stacked.fetch(b_source.repository, b'C')
 
1597
        rev_c_pack_names = set(repo_not_stacked._pack_collection.names())
 
1598
        rev_c_pack_names = rev_c_pack_names.difference(new_pack_names)
 
1599
        self.assertEqual(1, len(rev_c_pack_names))
 
1600
        rev_c_pack_name = list(rev_c_pack_names)[0]
 
1601
        return (repo_not_stacked, rev_a_pack_name, inv_a_pack_name,
 
1602
                rev_c_pack_name)
 
1603
 
 
1604
    def test_pack_with_distant_inventories(self):
 
1605
        # See https://bugs.launchpad.net/bzr/+bug/437003
 
1606
        # When repacking, it is possible to have an inventory in a different
 
1607
        # pack file than the associated revision. An autopack can then come
 
1608
        # along, and miss that inventory, and complain.
 
1609
        (repo, rev_a_pack_name, inv_a_pack_name, rev_c_pack_name
 
1610
         ) = self.make_branch_with_disjoint_inventory_and_revision()
 
1611
        a_pack = repo._pack_collection.get_pack_by_name(rev_a_pack_name)
 
1612
        c_pack = repo._pack_collection.get_pack_by_name(rev_c_pack_name)
 
1613
        packer = groupcompress_repo.GCCHKPacker(repo._pack_collection,
 
1614
                    [a_pack, c_pack], '.test-pack')
 
1615
        # This would raise ValueError in bug #437003, but should not raise an
 
1616
        # error once fixed.
 
1617
        packer.pack()
 
1618
 
 
1619
    def test_pack_with_missing_inventory(self):
 
1620
        # Similar to test_pack_with_missing_inventory, but this time, we force
 
1621
        # the A inventory to actually be gone from the repository.
 
1622
        (repo, rev_a_pack_name, inv_a_pack_name, rev_c_pack_name
 
1623
         ) = self.make_branch_with_disjoint_inventory_and_revision()
 
1624
        inv_a_pack = repo._pack_collection.get_pack_by_name(inv_a_pack_name)
 
1625
        repo._pack_collection._remove_pack_from_memory(inv_a_pack)
 
1626
        packer = groupcompress_repo.GCCHKPacker(repo._pack_collection,
 
1627
            repo._pack_collection.all_packs(), '.test-pack')
 
1628
        e = self.assertRaises(ValueError, packer.pack)
 
1629
        packer.new_pack.abort()
 
1630
        self.assertContainsRe(str(e),
 
1631
            r"We are missing inventories for revisions: .*'A'")
 
1632
 
 
1633
 
1625
1634
class TestCrossFormatPacks(TestCaseWithTransport):
1626
1635
 
1627
1636
    def log_pack(self, hint=None):
1642
1651
        self.addCleanup(target.unlock)
1643
1652
        source = source_tree.branch.repository._get_source(target._format)
1644
1653
        self.orig_pack = target.pack
1645
 
        target.pack = self.log_pack
 
1654
        self.overrideAttr(target, "pack", self.log_pack)
1646
1655
        search = target.search_missing_revision_ids(
1647
 
            source_tree.branch.repository, tip)
 
1656
            source_tree.branch.repository, revision_ids=[tip])
1648
1657
        stream = source.get_stream(search)
1649
1658
        from_format = source_tree.branch.repository._format
1650
1659
        sink = target._get_sink()
1666
1675
        self.addCleanup(target.unlock)
1667
1676
        source = source_tree.branch.repository
1668
1677
        self.orig_pack = target.pack
1669
 
        target.pack = self.log_pack
 
1678
        self.overrideAttr(target, "pack", self.log_pack)
1670
1679
        target.fetch(source)
1671
1680
        if expect_pack_called:
1672
1681
            self.assertLength(1, self.calls)
1700
1709
    def test_IDS_format_same_no(self):
1701
1710
        # When the formats are the same, pack is not called.
1702
1711
        self.run_fetch('2a', '2a', False)
 
1712
 
 
1713
 
 
1714
class Test_LazyListJoin(tests.TestCase):
 
1715
 
 
1716
    def test__repr__(self):
 
1717
        lazy = repository._LazyListJoin(['a'], ['b'])
 
1718
        self.assertEqual("breezy.repository._LazyListJoin((['a'], ['b']))",
 
1719
                         repr(lazy))
 
1720
 
 
1721
 
 
1722
class TestFeatures(tests.TestCaseWithTransport):
 
1723
 
 
1724
    def test_open_with_present_feature(self):
 
1725
        self.addCleanup(
 
1726
            bzrrepository.RepositoryFormatMetaDir.unregister_feature,
 
1727
            b"makes-cheese-sandwich")
 
1728
        bzrrepository.RepositoryFormatMetaDir.register_feature(
 
1729
            b"makes-cheese-sandwich")
 
1730
        repo = self.make_repository('.')
 
1731
        repo.lock_write()
 
1732
        repo._format.features[b"makes-cheese-sandwich"] = b"required"
 
1733
        repo._format.check_support_status(False)
 
1734
        repo.unlock()
 
1735
 
 
1736
    def test_open_with_missing_required_feature(self):
 
1737
        repo = self.make_repository('.')
 
1738
        repo.lock_write()
 
1739
        repo._format.features[b"makes-cheese-sandwich"] = b"required"
 
1740
        self.assertRaises(bzrdir.MissingFeature,
 
1741
            repo._format.check_support_status, False)