/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_branch.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-10 01:35:53 UTC
  • mto: (6670.4.8 move-bzr)
  • mto: This revision was merged to the branch mainline in revision 6681.
  • Revision ID: jelmer@jelmer.uk-20170610013553-560y7mn3su4pp763
Fix remaining tests.

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
16
16
 
17
17
"""Tests for the Branch facility that are not interface  tests.
18
18
 
19
 
For interface tests see tests/per_branch/*.py.
 
19
For interface tests see `tests/per_branch/*.py`.
20
20
 
21
21
For concrete class tests see this file, and for meta-branch tests
22
22
also see this file.
23
23
"""
24
24
 
25
 
from cStringIO import StringIO
26
 
 
27
 
from bzrlib import (
 
25
from .. import (
28
26
    branch as _mod_branch,
 
27
    bzrbranch as _mod_bzrbranch,
29
28
    bzrdir,
30
29
    config,
 
30
    controldir,
31
31
    errors,
32
32
    tests,
33
33
    trace,
34
 
    transport,
35
34
    urlutils,
36
35
    )
 
36
from ..branchfmt.fullhistory import (
 
37
    BzrBranch5,
 
38
    BzrBranchFormat5,
 
39
    )
 
40
from ..sixish import (
 
41
    BytesIO,
 
42
    )
37
43
 
38
44
 
39
45
class TestDefaultFormat(tests.TestCase):
40
46
 
41
47
    def test_default_format(self):
42
48
        # update this if you change the default branch format
43
 
        self.assertIsInstance(_mod_branch.BranchFormat.get_default_format(),
44
 
                _mod_branch.BzrBranchFormat7)
 
49
        self.assertIsInstance(_mod_branch.format_registry.get_default(),
 
50
                _mod_bzrbranch.BzrBranchFormat7)
45
51
 
46
52
    def test_default_format_is_same_as_bzrdir_default(self):
47
53
        # XXX: it might be nice if there was only one place the default was
48
54
        # set, but at the moment that's not true -- mbp 20070814 --
49
55
        # https://bugs.launchpad.net/bzr/+bug/132376
50
56
        self.assertEqual(
51
 
            _mod_branch.BranchFormat.get_default_format(),
 
57
            _mod_branch.format_registry.get_default(),
52
58
            bzrdir.BzrDirFormat.get_default_format().get_branch_format())
53
59
 
54
60
    def test_get_set_default_format(self):
55
61
        # set the format and then set it back again
56
 
        old_format = _mod_branch.BranchFormat.get_default_format()
57
 
        _mod_branch.BranchFormat.set_default_format(SampleBranchFormat())
 
62
        old_format = _mod_branch.format_registry.get_default()
 
63
        _mod_branch.format_registry.set_default(
 
64
            SampleBranchFormat())
58
65
        try:
59
66
            # the default branch format is used by the meta dir format
60
67
            # which is not the default bzrdir format at this point
62
69
            result = dir.create_branch()
63
70
            self.assertEqual(result, 'A branch')
64
71
        finally:
65
 
            _mod_branch.BranchFormat.set_default_format(old_format)
 
72
            _mod_branch.format_registry.set_default(old_format)
66
73
        self.assertEqual(old_format,
67
 
                         _mod_branch.BranchFormat.get_default_format())
 
74
                         _mod_branch.format_registry.get_default())
68
75
 
69
76
 
70
77
class TestBranchFormat5(tests.TestCaseWithTransport):
74
81
        url = self.get_url()
75
82
        bdir = bzrdir.BzrDirMetaFormat1().initialize(url)
76
83
        bdir.create_repository()
77
 
        branch = bdir.create_branch()
 
84
        branch = BzrBranchFormat5().initialize(bdir)
78
85
        t = self.get_transport()
79
86
        self.log("branch instance is %r" % branch)
80
 
        self.assert_(isinstance(branch, _mod_branch.BzrBranch5))
 
87
        self.assertTrue(isinstance(branch, BzrBranch5))
81
88
        self.assertIsDirectory('.', t)
82
89
        self.assertIsDirectory('.bzr/branch', t)
83
90
        self.assertIsDirectory('.bzr/branch/lock', t)
86
93
        self.assertIsDirectory('.bzr/branch/lock/held', t)
87
94
 
88
95
    def test_set_push_location(self):
89
 
        from bzrlib.config import (locations_config_filename,
90
 
                                   ensure_config_dir_exists)
91
 
        ensure_config_dir_exists()
92
 
        fn = locations_config_filename()
93
 
        # write correct newlines to locations.conf
94
 
        # by default ConfigObj uses native line-endings for new files
95
 
        # but uses already existing line-endings if file is not empty
96
 
        f = open(fn, 'wb')
97
 
        try:
98
 
            f.write('# comment\n')
99
 
        finally:
100
 
            f.close()
 
96
        conf = config.LocationConfig.from_string('# comment\n', '.', save=True)
101
97
 
102
98
        branch = self.make_branch('.', format='knit')
103
99
        branch.set_push_location('foo')
106
102
                             "[%s]\n"
107
103
                             "push_location = foo\n"
108
104
                             "push_location:policy = norecurse\n" % local_path,
109
 
                             fn)
 
105
                             config.locations_config_filename())
110
106
 
111
107
    # TODO RBC 20051029 test getting a push location from a branch in a
112
108
    # recursive section - that is, it appends the branch name.
113
109
 
114
110
 
115
 
class SampleBranchFormat(_mod_branch.BranchFormat):
 
111
class SampleBranchFormat(_mod_bzrbranch.BranchFormatMetadir):
116
112
    """A sample format
117
113
 
118
114
    this format is initializable, unsupported to aid in testing the
119
115
    open and open_downlevel routines.
120
116
    """
121
117
 
122
 
    def get_format_string(self):
 
118
    @classmethod
 
119
    def get_format_string(cls):
123
120
        """See BzrBranchFormat.get_format_string()."""
124
121
        return "Sample branch format."
125
122
 
126
 
    def initialize(self, a_bzrdir, name=None):
 
123
    def initialize(self, a_controldir, name=None, repository=None,
 
124
                   append_revisions_only=None):
127
125
        """Format 4 branches cannot be created."""
128
 
        t = a_bzrdir.get_branch_transport(self, name=name)
 
126
        t = a_controldir.get_branch_transport(self, name=name)
129
127
        t.put_bytes('format', self.get_format_string())
130
128
        return 'A branch'
131
129
 
132
130
    def is_supported(self):
133
131
        return False
134
132
 
135
 
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False):
 
133
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
 
134
             possible_transports=None):
136
135
        return "opened branch."
137
136
 
138
137
 
 
138
# Demonstrating how lazy loading is often implemented:
 
139
# A constant string is created.
 
140
SampleSupportedBranchFormatString = "Sample supported branch format."
 
141
 
 
142
# And the format class can then reference the constant to avoid skew.
 
143
class SampleSupportedBranchFormat(_mod_bzrbranch.BranchFormatMetadir):
 
144
    """A sample supported format."""
 
145
 
 
146
    @classmethod
 
147
    def get_format_string(cls):
 
148
        """See BzrBranchFormat.get_format_string()."""
 
149
        return SampleSupportedBranchFormatString
 
150
 
 
151
    def initialize(self, a_controldir, name=None, append_revisions_only=None):
 
152
        t = a_controldir.get_branch_transport(self, name=name)
 
153
        t.put_bytes('format', self.get_format_string())
 
154
        return 'A branch'
 
155
 
 
156
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
 
157
             possible_transports=None):
 
158
        return "opened supported branch."
 
159
 
 
160
 
 
161
class SampleExtraBranchFormat(_mod_branch.BranchFormat):
 
162
    """A sample format that is not usable in a metadir."""
 
163
 
 
164
    def get_format_string(self):
 
165
        # This format is not usable in a metadir.
 
166
        return None
 
167
 
 
168
    def network_name(self):
 
169
        # Network name always has to be provided.
 
170
        return "extra"
 
171
 
 
172
    def initialize(self, a_controldir, name=None):
 
173
        raise NotImplementedError(self.initialize)
 
174
 
 
175
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
 
176
             possible_transports=None):
 
177
        raise NotImplementedError(self.open)
 
178
 
 
179
 
139
180
class TestBzrBranchFormat(tests.TestCaseWithTransport):
140
181
    """Tests for the BzrBranchFormat facility."""
141
182
 
148
189
            dir = format._matchingbzrdir.initialize(url)
149
190
            dir.create_repository()
150
191
            format.initialize(dir)
151
 
            found_format = _mod_branch.BranchFormat.find_format(dir)
152
 
            self.failUnless(isinstance(found_format, format.__class__))
153
 
        check_format(_mod_branch.BzrBranchFormat5(), "bar")
 
192
            found_format = _mod_bzrbranch.BranchFormatMetadir.find_format(dir)
 
193
            self.assertIsInstance(found_format, format.__class__)
 
194
        check_format(BzrBranchFormat5(), "bar")
 
195
 
 
196
    def test_from_string(self):
 
197
        self.assertIsInstance(
 
198
            SampleBranchFormat.from_string("Sample branch format."),
 
199
            SampleBranchFormat)
 
200
        self.assertRaises(AssertionError,
 
201
            SampleBranchFormat.from_string, "Different branch format.")
154
202
 
155
203
    def test_find_format_not_branch(self):
156
204
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
157
205
        self.assertRaises(errors.NotBranchError,
158
 
                          _mod_branch.BranchFormat.find_format,
 
206
                          _mod_bzrbranch.BranchFormatMetadir.find_format,
159
207
                          dir)
160
208
 
161
209
    def test_find_format_unknown_format(self):
162
210
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
163
211
        SampleBranchFormat().initialize(dir)
164
212
        self.assertRaises(errors.UnknownFormatError,
165
 
                          _mod_branch.BranchFormat.find_format,
 
213
                          _mod_bzrbranch.BranchFormatMetadir.find_format,
166
214
                          dir)
167
215
 
 
216
    def test_find_format_with_features(self):
 
217
        tree = self.make_branch_and_tree('.', format='2a')
 
218
        tree.branch.update_feature_flags({"name": "optional"})
 
219
        found_format = _mod_bzrbranch.BranchFormatMetadir.find_format(tree.controldir)
 
220
        self.assertIsInstance(found_format, _mod_bzrbranch.BranchFormatMetadir)
 
221
        self.assertEqual(found_format.features.get("name"), "optional")
 
222
        tree.branch.update_feature_flags({"name": None})
 
223
        branch = _mod_branch.Branch.open('.')
 
224
        self.assertEqual(branch._format.features, {})
 
225
 
 
226
 
 
227
class TestBranchFormatRegistry(tests.TestCase):
 
228
 
 
229
    def setUp(self):
 
230
        super(TestBranchFormatRegistry, self).setUp()
 
231
        self.registry = _mod_branch.BranchFormatRegistry()
 
232
 
 
233
    def test_default(self):
 
234
        self.assertIs(None, self.registry.get_default())
 
235
        format = SampleBranchFormat()
 
236
        self.registry.set_default(format)
 
237
        self.assertEqual(format, self.registry.get_default())
 
238
 
168
239
    def test_register_unregister_format(self):
169
240
        format = SampleBranchFormat()
170
 
        # make a control dir
171
 
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
172
 
        # make a branch
173
 
        format.initialize(dir)
174
 
        # register a format for it.
175
 
        _mod_branch.BranchFormat.register_format(format)
176
 
        # which branch.Open will refuse (not supported)
177
 
        self.assertRaises(errors.UnsupportedFormatError,
178
 
                          _mod_branch.Branch.open, self.get_url())
179
 
        self.make_branch_and_tree('foo')
180
 
        # but open_downlevel will work
181
 
        self.assertEqual(
182
 
            format.open(dir),
183
 
            bzrdir.BzrDir.open(self.get_url()).open_branch(unsupported=True))
184
 
        # unregister the format
185
 
        _mod_branch.BranchFormat.unregister_format(format)
186
 
        self.make_branch_and_tree('bar')
 
241
        self.registry.register(format)
 
242
        self.assertEqual(format,
 
243
            self.registry.get("Sample branch format."))
 
244
        self.registry.remove(format)
 
245
        self.assertRaises(KeyError, self.registry.get,
 
246
            "Sample branch format.")
 
247
 
 
248
    def test_get_all(self):
 
249
        format = SampleBranchFormat()
 
250
        self.assertEqual([], self.registry._get_all())
 
251
        self.registry.register(format)
 
252
        self.assertEqual([format], self.registry._get_all())
 
253
 
 
254
    def test_register_extra(self):
 
255
        format = SampleExtraBranchFormat()
 
256
        self.assertEqual([], self.registry._get_all())
 
257
        self.registry.register_extra(format)
 
258
        self.assertEqual([format], self.registry._get_all())
 
259
 
 
260
    def test_register_extra_lazy(self):
 
261
        self.assertEqual([], self.registry._get_all())
 
262
        self.registry.register_extra_lazy("breezy.tests.test_branch",
 
263
            "SampleExtraBranchFormat")
 
264
        formats = self.registry._get_all()
 
265
        self.assertEqual(1, len(formats))
 
266
        self.assertIsInstance(formats[0], SampleExtraBranchFormat)
187
267
 
188
268
 
189
269
class TestBranch67(object):
200
280
 
201
281
    def test_creation(self):
202
282
        format = bzrdir.BzrDirMetaFormat1()
203
 
        format.set_branch_format(_mod_branch.BzrBranchFormat6())
 
283
        format.set_branch_format(_mod_bzrbranch.BzrBranchFormat6())
204
284
        branch = self.make_branch('a', format=format)
205
285
        self.assertIsInstance(branch, self.get_class())
206
286
        branch = self.make_branch('b', format=self.get_format_name())
210
290
 
211
291
    def test_layout(self):
212
292
        branch = self.make_branch('a', format=self.get_format_name())
213
 
        self.failUnlessExists('a/.bzr/branch/last-revision')
214
 
        self.failIfExists('a/.bzr/branch/revision-history')
215
 
        self.failIfExists('a/.bzr/branch/references')
 
293
        self.assertPathExists('a/.bzr/branch/last-revision')
 
294
        self.assertPathDoesNotExist('a/.bzr/branch/revision-history')
 
295
        self.assertPathDoesNotExist('a/.bzr/branch/references')
216
296
 
217
297
    def test_config(self):
218
298
        """Ensure that all configuration data is stored in the branch"""
219
299
        branch = self.make_branch('a', format=self.get_format_name())
220
 
        branch.set_parent('http://bazaar-vcs.org')
221
 
        self.failIfExists('a/.bzr/branch/parent')
222
 
        self.assertEqual('http://bazaar-vcs.org', branch.get_parent())
223
 
        branch.set_push_location('sftp://bazaar-vcs.org')
224
 
        config = branch.get_config()._get_branch_data_config()
225
 
        self.assertEqual('sftp://bazaar-vcs.org',
226
 
                         config.get_user_option('push_location'))
227
 
        branch.set_bound_location('ftp://bazaar-vcs.org')
228
 
        self.failIfExists('a/.bzr/branch/bound')
229
 
        self.assertEqual('ftp://bazaar-vcs.org', branch.get_bound_location())
230
 
 
231
 
    def test_set_revision_history(self):
232
 
        builder = self.make_branch_builder('.', format=self.get_format_name())
233
 
        builder.build_snapshot('foo', None,
234
 
            [('add', ('', None, 'directory', None))],
235
 
            message='foo')
236
 
        builder.build_snapshot('bar', None, [], message='bar')
237
 
        branch = builder.get_branch()
238
 
        branch.lock_write()
239
 
        self.addCleanup(branch.unlock)
240
 
        branch.set_revision_history(['foo', 'bar'])
241
 
        branch.set_revision_history(['foo'])
242
 
        self.assertRaises(errors.NotLefthandHistory,
243
 
                          branch.set_revision_history, ['bar'])
 
300
        branch.set_parent('http://example.com')
 
301
        self.assertPathDoesNotExist('a/.bzr/branch/parent')
 
302
        self.assertEqual('http://example.com', branch.get_parent())
 
303
        branch.set_push_location('sftp://example.com')
 
304
        conf = branch.get_config_stack()
 
305
        self.assertEqual('sftp://example.com', conf.get('push_location'))
 
306
        branch.set_bound_location('ftp://example.com')
 
307
        self.assertPathDoesNotExist('a/.bzr/branch/bound')
 
308
        self.assertEqual('ftp://example.com', branch.get_bound_location())
244
309
 
245
310
    def do_checkout_test(self, lightweight=False):
246
311
        tree = self.make_branch_and_tree('source',
259
324
        subtree.commit('a subtree file')
260
325
        subsubtree.commit('a subsubtree file')
261
326
        tree.branch.create_checkout('target', lightweight=lightweight)
262
 
        self.failUnlessExists('target')
263
 
        self.failUnlessExists('target/subtree')
264
 
        self.failUnlessExists('target/subtree/file')
265
 
        self.failUnlessExists('target/subtree/subsubtree/file')
 
327
        self.assertPathExists('target')
 
328
        self.assertPathExists('target/subtree')
 
329
        self.assertPathExists('target/subtree/file')
 
330
        self.assertPathExists('target/subtree/subsubtree/file')
266
331
        subbranch = _mod_branch.Branch.open('target/subtree/subsubtree')
267
332
        if lightweight:
268
333
            self.assertEndsWith(subbranch.base, 'source/subtree/subsubtree/')
275
340
    def test_light_checkout_with_references(self):
276
341
        self.do_checkout_test(lightweight=True)
277
342
 
278
 
    def test_set_push(self):
279
 
        branch = self.make_branch('source', format=self.get_format_name())
280
 
        branch.get_config().set_user_option('push_location', 'old',
281
 
            store=config.STORE_LOCATION)
282
 
        warnings = []
283
 
        def warning(*args):
284
 
            warnings.append(args[0] % args[1:])
285
 
        _warning = trace.warning
286
 
        trace.warning = warning
287
 
        try:
288
 
            branch.set_push_location('new')
289
 
        finally:
290
 
            trace.warning = _warning
291
 
        self.assertEqual(warnings[0], 'Value "new" is masked by "old" from '
292
 
                         'locations.conf')
293
 
 
294
343
 
295
344
class TestBranch6(TestBranch67, tests.TestCaseWithTransport):
296
345
 
297
346
    def get_class(self):
298
 
        return _mod_branch.BzrBranch6
 
347
        return _mod_bzrbranch.BzrBranch6
299
348
 
300
349
    def get_format_name(self):
301
350
        return "dirstate-tags"
316
365
class TestBranch7(TestBranch67, tests.TestCaseWithTransport):
317
366
 
318
367
    def get_class(self):
319
 
        return _mod_branch.BzrBranch7
 
368
        return _mod_bzrbranch.BzrBranch7
320
369
 
321
370
    def get_format_name(self):
322
371
        return "1.9"
326
375
 
327
376
    def test_set_stacked_on_url_unstackable_repo(self):
328
377
        repo = self.make_repository('a', format='dirstate-tags')
329
 
        control = repo.bzrdir
330
 
        branch = _mod_branch.BzrBranchFormat7().initialize(control)
 
378
        control = repo.controldir
 
379
        branch = _mod_bzrbranch.BzrBranchFormat7().initialize(control)
331
380
        target = self.make_branch('b')
332
381
        self.assertRaises(errors.UnstackableRepositoryFormat,
333
382
            branch.set_stacked_on_url, target.base)
334
383
 
335
384
    def test_clone_stacked_on_unstackable_repo(self):
336
385
        repo = self.make_repository('a', format='dirstate-tags')
337
 
        control = repo.bzrdir
338
 
        branch = _mod_branch.BzrBranchFormat7().initialize(control)
 
386
        control = repo.controldir
 
387
        branch = _mod_bzrbranch.BzrBranchFormat7().initialize(control)
339
388
        # Calling clone should not raise UnstackableRepositoryFormat.
340
389
        cloned_bzrdir = control.clone('cloned')
341
390
 
358
407
        branch = self.make_branch('a', format=self.get_format_name())
359
408
        target = self.make_branch_and_tree('b', format=self.get_format_name())
360
409
        branch.set_stacked_on_url(target.branch.base)
361
 
        branch = branch.bzrdir.open_branch()
 
410
        branch = branch.controldir.open_branch()
362
411
        revid = target.commit('foo')
363
412
        self.assertTrue(branch.repository.has_revision(revid))
364
413
 
367
416
 
368
417
    def make_branch(self, location, format=None):
369
418
        if format is None:
370
 
            format = bzrdir.format_registry.make_bzrdir('1.9')
371
 
            format.set_branch_format(_mod_branch.BzrBranchFormat8())
 
419
            format = controldir.format_registry.make_controldir('1.9')
 
420
            format.set_branch_format(_mod_bzrbranch.BzrBranchFormat8())
372
421
        return tests.TestCaseWithTransport.make_branch(
373
422
            self, location, format=format)
374
423
 
425
474
        self.assertEqual(('path3', 'location3'),
426
475
                         branch.get_reference_info('file-id'))
427
476
 
 
477
    def _recordParentMapCalls(self, repo):
 
478
        self._parent_map_calls = []
 
479
        orig_get_parent_map = repo.revisions.get_parent_map
 
480
        def get_parent_map(q):
 
481
            q = list(q)
 
482
            self._parent_map_calls.extend([e[0] for e in q])
 
483
            return orig_get_parent_map(q)
 
484
        repo.revisions.get_parent_map = get_parent_map
 
485
 
 
486
 
428
487
class TestBranchReference(tests.TestCaseWithTransport):
429
488
    """Tests for the branch reference facility."""
430
489
 
431
490
    def test_create_open_reference(self):
432
491
        bzrdirformat = bzrdir.BzrDirMetaFormat1()
433
 
        t = transport.get_transport(self.get_url('.'))
 
492
        t = self.get_transport()
434
493
        t.mkdir('repo')
435
494
        dir = bzrdirformat.initialize(self.get_url('repo'))
436
495
        dir.create_repository()
437
496
        target_branch = dir.create_branch()
438
497
        t.mkdir('branch')
439
498
        branch_dir = bzrdirformat.initialize(self.get_url('branch'))
440
 
        made_branch = _mod_branch.BranchReferenceFormat().initialize(
 
499
        made_branch = _mod_bzrbranch.BranchReferenceFormat().initialize(
441
500
            branch_dir, target_branch=target_branch)
442
501
        self.assertEqual(made_branch.base, target_branch.base)
443
502
        opened_branch = branch_dir.open_branch()
444
503
        self.assertEqual(opened_branch.base, target_branch.base)
445
504
 
446
505
    def test_get_reference(self):
447
 
        """For a BranchReference, get_reference should reutrn the location."""
 
506
        """For a BranchReference, get_reference should return the location."""
448
507
        branch = self.make_branch('target')
449
508
        checkout = branch.create_checkout('checkout', lightweight=True)
450
 
        reference_url = branch.bzrdir.root_transport.abspath('') + '/'
 
509
        reference_url = branch.controldir.root_transport.abspath('') + '/'
451
510
        # if the api for create_checkout changes to return different checkout types
452
511
        # then this file read will fail.
453
512
        self.assertFileEqual(reference_url, 'checkout/.bzr/branch/location')
454
513
        self.assertEqual(reference_url,
455
 
            _mod_branch.BranchReferenceFormat().get_reference(checkout.bzrdir))
 
514
            _mod_bzrbranch.BranchReferenceFormat().get_reference(checkout.controldir))
456
515
 
457
516
 
458
517
class TestHooks(tests.TestCaseWithTransport):
460
519
    def test_constructor(self):
461
520
        """Check that creating a BranchHooks instance has the right defaults."""
462
521
        hooks = _mod_branch.BranchHooks()
463
 
        self.assertTrue("set_rh" in hooks, "set_rh not in %s" % hooks)
464
522
        self.assertTrue("post_push" in hooks, "post_push not in %s" % hooks)
465
523
        self.assertTrue("post_commit" in hooks, "post_commit not in %s" % hooks)
466
524
        self.assertTrue("pre_commit" in hooks, "pre_commit not in %s" % hooks)
489
547
        self.assertLength(1, calls)
490
548
        params = calls[0]
491
549
        self.assertIsInstance(params, _mod_branch.BranchInitHookParams)
492
 
        self.assertTrue(hasattr(params, 'bzrdir'))
 
550
        self.assertTrue(hasattr(params, 'controldir'))
493
551
        self.assertTrue(hasattr(params, 'branch'))
494
552
 
 
553
    def test_post_branch_init_hook_repr(self):
 
554
        param_reprs = []
 
555
        _mod_branch.Branch.hooks.install_named_hook('post_branch_init',
 
556
            lambda params: param_reprs.append(repr(params)), None)
 
557
        branch = self.make_branch('a')
 
558
        self.assertLength(1, param_reprs)
 
559
        param_repr = param_reprs[0]
 
560
        self.assertStartsWith(param_repr, '<BranchInitHookParams of ')
 
561
 
495
562
    def test_post_switch_hook(self):
496
 
        from bzrlib import switch
 
563
        from .. import switch
497
564
        calls = []
498
565
        _mod_branch.Branch.hooks.install_named_hook('post_switch',
499
566
            calls.append, None)
501
568
        self.build_tree(['branch-1/file-1'])
502
569
        tree.add('file-1')
503
570
        tree.commit('rev1')
504
 
        to_branch = tree.bzrdir.sprout('branch-2').open_branch()
 
571
        to_branch = tree.controldir.sprout('branch-2').open_branch()
505
572
        self.build_tree(['branch-1/file-2'])
506
573
        tree.add('file-2')
507
574
        tree.remove('file-1')
508
575
        tree.commit('rev2')
509
576
        checkout = tree.branch.create_checkout('checkout')
510
577
        self.assertLength(0, calls)
511
 
        switch.switch(checkout.bzrdir, to_branch)
 
578
        switch.switch(checkout.controldir, to_branch)
512
579
        self.assertLength(1, calls)
513
580
        params = calls[0]
514
581
        self.assertIsInstance(params, _mod_branch.SwitchHookParams)
521
588
    def setUp(self):
522
589
        super(TestBranchOptions, self).setUp()
523
590
        self.branch = self.make_branch('.')
524
 
        self.config = self.branch.get_config()
 
591
        self.config_stack = self.branch.get_config_stack()
525
592
 
526
593
    def check_append_revisions_only(self, expected_value, value=None):
527
594
        """Set append_revisions_only in config and check its interpretation."""
528
595
        if value is not None:
529
 
            self.config.set_user_option('append_revisions_only', value)
 
596
            self.config_stack.set('append_revisions_only', value)
530
597
        self.assertEqual(expected_value,
531
 
                         self.branch._get_append_revisions_only())
 
598
                         self.branch.get_append_revisions_only())
532
599
 
533
600
    def test_valid_append_revisions_only(self):
534
 
        self.assertEquals(None,
535
 
                          self.config.get_user_option('append_revisions_only'))
 
601
        self.assertEqual(None,
 
602
                          self.config_stack.get('append_revisions_only'))
536
603
        self.check_append_revisions_only(None)
537
604
        self.check_append_revisions_only(False, 'False')
538
605
        self.check_append_revisions_only(True, 'True')
550
617
        self.check_append_revisions_only(None, 'not-a-bool')
551
618
        self.assertLength(1, self.warnings)
552
619
        self.assertEqual(
553
 
            'Value "not-a-bool" is not a boolean for "append_revisions_only"',
 
620
            'Value "not-a-bool" is not valid for "append_revisions_only"',
554
621
            self.warnings[0])
555
622
 
 
623
    def test_use_fresh_values(self):
 
624
        copy = _mod_branch.Branch.open(self.branch.base)
 
625
        copy.lock_write()
 
626
        try:
 
627
            copy.get_config_stack().set('foo', 'bar')
 
628
        finally:
 
629
            copy.unlock()
 
630
        self.assertFalse(self.branch.is_locked())
 
631
        # Since the branch is locked, the option value won't be saved on disk
 
632
        # so trying to access the config of locked branch via another older
 
633
        # non-locked branch object pointing to the same branch is not supported
 
634
        self.assertEqual(None, self.branch.get_config_stack().get('foo'))
 
635
        # Using a newly created branch object works as expected
 
636
        fresh = _mod_branch.Branch.open(self.branch.base)
 
637
        self.assertEqual('bar', fresh.get_config_stack().get('foo'))
 
638
 
 
639
    def test_set_from_config_get_from_config_stack(self):
 
640
        self.branch.lock_write()
 
641
        self.addCleanup(self.branch.unlock)
 
642
        self.branch.get_config().set_user_option('foo', 'bar')
 
643
        result = self.branch.get_config_stack().get('foo')
 
644
        # https://bugs.launchpad.net/bzr/+bug/948344
 
645
        self.expectFailure('BranchStack uses cache after set_user_option',
 
646
                           self.assertEqual, 'bar', result)
 
647
 
 
648
    def test_set_from_config_stack_get_from_config(self):
 
649
        self.branch.lock_write()
 
650
        self.addCleanup(self.branch.unlock)
 
651
        self.branch.get_config_stack().set('foo', 'bar')
 
652
        # Since the branch is locked, the option value won't be saved on disk
 
653
        # so mixing get() and get_user_option() is broken by design.
 
654
        self.assertEqual(None,
 
655
                         self.branch.get_config().get_user_option('foo'))
 
656
 
 
657
    def test_set_delays_write_when_branch_is_locked(self):
 
658
        self.branch.lock_write()
 
659
        self.addCleanup(self.branch.unlock)
 
660
        self.branch.get_config_stack().set('foo', 'bar')
 
661
        copy = _mod_branch.Branch.open(self.branch.base)
 
662
        result = copy.get_config_stack().get('foo')
 
663
        # Accessing from a different branch object is like accessing from a
 
664
        # different process: the option has not been saved yet and the new
 
665
        # value cannot be seen.
 
666
        self.assertIs(None, result)
 
667
 
556
668
 
557
669
class TestPullResult(tests.TestCase):
558
670
 
559
 
    def test_pull_result_to_int(self):
560
 
        # to support old code, the pull result can be used as an int
561
 
        r = _mod_branch.PullResult()
562
 
        r.old_revno = 10
563
 
        r.new_revno = 20
564
 
        # this usage of results is not recommended for new code (because it
565
 
        # doesn't describe very well what happened), but for api stability
566
 
        # it's still supported
567
 
        a = "%d revisions pulled" % r
568
 
        self.assertEqual(a, "10 revisions pulled")
569
 
 
570
671
    def test_report_changed(self):
571
672
        r = _mod_branch.PullResult()
572
673
        r.old_revid = "old-revid"
573
674
        r.old_revno = 10
574
675
        r.new_revid = "new-revid"
575
676
        r.new_revno = 20
576
 
        f = StringIO()
 
677
        f = BytesIO()
577
678
        r.report(f)
578
679
        self.assertEqual("Now on revision 20.\n", f.getvalue())
 
680
        self.assertEqual("Now on revision 20.\n", f.getvalue())
579
681
 
580
682
    def test_report_unchanged(self):
581
683
        r = _mod_branch.PullResult()
582
684
        r.old_revid = "same-revid"
583
685
        r.new_revid = "same-revid"
584
 
        f = StringIO()
 
686
        f = BytesIO()
585
687
        r.report(f)
586
 
        self.assertEqual("No revisions to pull.\n", f.getvalue())
587
 
 
588
 
 
589
 
class _StubLockable(object):
590
 
    """Helper for TestRunWithWriteLockedTarget."""
591
 
 
592
 
    def __init__(self, calls, unlock_exc=None):
593
 
        self.calls = calls
594
 
        self.unlock_exc = unlock_exc
595
 
 
596
 
    def lock_write(self):
597
 
        self.calls.append('lock_write')
598
 
 
599
 
    def unlock(self):
600
 
        self.calls.append('unlock')
601
 
        if self.unlock_exc is not None:
602
 
            raise self.unlock_exc
603
 
 
604
 
 
605
 
class _ErrorFromCallable(Exception):
606
 
    """Helper for TestRunWithWriteLockedTarget."""
607
 
 
608
 
 
609
 
class _ErrorFromUnlock(Exception):
610
 
    """Helper for TestRunWithWriteLockedTarget."""
611
 
 
612
 
 
613
 
class TestRunWithWriteLockedTarget(tests.TestCase):
614
 
    """Tests for _run_with_write_locked_target."""
615
 
 
616
 
    def setUp(self):
617
 
        tests.TestCase.setUp(self)
618
 
        self._calls = []
619
 
 
620
 
    def func_that_returns_ok(self):
621
 
        self._calls.append('func called')
622
 
        return 'ok'
623
 
 
624
 
    def func_that_raises(self):
625
 
        self._calls.append('func called')
626
 
        raise _ErrorFromCallable()
627
 
 
628
 
    def test_success_unlocks(self):
629
 
        lockable = _StubLockable(self._calls)
630
 
        result = _mod_branch._run_with_write_locked_target(
631
 
            lockable, self.func_that_returns_ok)
632
 
        self.assertEqual('ok', result)
633
 
        self.assertEqual(['lock_write', 'func called', 'unlock'], self._calls)
634
 
 
635
 
    def test_exception_unlocks_and_propagates(self):
636
 
        lockable = _StubLockable(self._calls)
637
 
        self.assertRaises(_ErrorFromCallable,
638
 
                          _mod_branch._run_with_write_locked_target,
639
 
                          lockable, self.func_that_raises)
640
 
        self.assertEqual(['lock_write', 'func called', 'unlock'], self._calls)
641
 
 
642
 
    def test_callable_succeeds_but_error_during_unlock(self):
643
 
        lockable = _StubLockable(self._calls, unlock_exc=_ErrorFromUnlock())
644
 
        self.assertRaises(_ErrorFromUnlock,
645
 
                          _mod_branch._run_with_write_locked_target,
646
 
                          lockable, self.func_that_returns_ok)
647
 
        self.assertEqual(['lock_write', 'func called', 'unlock'], self._calls)
648
 
 
649
 
    def test_error_during_unlock_does_not_mask_original_error(self):
650
 
        lockable = _StubLockable(self._calls, unlock_exc=_ErrorFromUnlock())
651
 
        self.assertRaises(_ErrorFromCallable,
652
 
                          _mod_branch._run_with_write_locked_target,
653
 
                          lockable, self.func_that_raises)
654
 
        self.assertEqual(['lock_write', 'func called', 'unlock'], self._calls)
655
 
 
656
 
 
 
688
        self.assertEqual("No revisions or tags to pull.\n", f.getvalue())