/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: Martin
  • Date: 2017-06-10 01:57:00 UTC
  • mto: This revision was merged to the branch mainline in revision 6679.
  • Revision ID: gzlist@googlemail.com-20170610015700-o3xeuyaqry2obiay
Go back to native str for urls and many other py3 changes

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006-2012, 2016 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
14
# along with this program; if not, write to the Free Software
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Tests for the Branch facility that are not interface  tests.
 
18
 
 
19
For interface tests see `tests/per_branch/*.py`.
 
20
 
 
21
For concrete class tests see this file, and for meta-branch tests
 
22
also see this file.
 
23
"""
 
24
 
 
25
from .. import (
 
26
    branch as _mod_branch,
 
27
    bzrbranch as _mod_bzrbranch,
 
28
    bzrdir,
 
29
    config,
 
30
    controldir,
 
31
    errors,
 
32
    tests,
 
33
    trace,
 
34
    urlutils,
 
35
    )
 
36
from ..branchfmt.fullhistory import (
 
37
    BzrBranch5,
 
38
    BzrBranchFormat5,
 
39
    )
 
40
from ..sixish import (
 
41
    BytesIO,
 
42
    )
 
43
 
 
44
 
 
45
class TestDefaultFormat(tests.TestCase):
 
46
 
 
47
    def test_default_format(self):
 
48
        # update this if you change the default branch format
 
49
        self.assertIsInstance(_mod_branch.format_registry.get_default(),
 
50
                _mod_bzrbranch.BzrBranchFormat7)
 
51
 
 
52
    def test_default_format_is_same_as_bzrdir_default(self):
 
53
        # XXX: it might be nice if there was only one place the default was
 
54
        # set, but at the moment that's not true -- mbp 20070814 --
 
55
        # https://bugs.launchpad.net/bzr/+bug/132376
 
56
        self.assertEqual(
 
57
            _mod_branch.format_registry.get_default(),
 
58
            bzrdir.BzrDirFormat.get_default_format().get_branch_format())
 
59
 
 
60
    def test_get_set_default_format(self):
 
61
        # set the format and then set it back again
 
62
        old_format = _mod_branch.format_registry.get_default()
 
63
        _mod_branch.format_registry.set_default(
 
64
            SampleBranchFormat())
 
65
        try:
 
66
            # the default branch format is used by the meta dir format
 
67
            # which is not the default bzrdir format at this point
 
68
            dir = bzrdir.BzrDirMetaFormat1().initialize('memory:///')
 
69
            result = dir.create_branch()
 
70
            self.assertEqual(result, 'A branch')
 
71
        finally:
 
72
            _mod_branch.format_registry.set_default(old_format)
 
73
        self.assertEqual(old_format,
 
74
                         _mod_branch.format_registry.get_default())
 
75
 
 
76
 
 
77
class TestBranchFormat5(tests.TestCaseWithTransport):
 
78
    """Tests specific to branch format 5"""
 
79
 
 
80
    def test_branch_format_5_uses_lockdir(self):
 
81
        url = self.get_url()
 
82
        bdir = bzrdir.BzrDirMetaFormat1().initialize(url)
 
83
        bdir.create_repository()
 
84
        branch = BzrBranchFormat5().initialize(bdir)
 
85
        t = self.get_transport()
 
86
        self.log("branch instance is %r" % branch)
 
87
        self.assertTrue(isinstance(branch, BzrBranch5))
 
88
        self.assertIsDirectory('.', t)
 
89
        self.assertIsDirectory('.bzr/branch', t)
 
90
        self.assertIsDirectory('.bzr/branch/lock', t)
 
91
        branch.lock_write()
 
92
        self.addCleanup(branch.unlock)
 
93
        self.assertIsDirectory('.bzr/branch/lock/held', t)
 
94
 
 
95
    def test_set_push_location(self):
 
96
        conf = config.LocationConfig.from_string('# comment\n', '.', save=True)
 
97
 
 
98
        branch = self.make_branch('.', format='knit')
 
99
        branch.set_push_location('foo')
 
100
        local_path = urlutils.local_path_from_url(branch.base[:-1])
 
101
        self.assertFileEqual("# comment\n"
 
102
                             "[%s]\n"
 
103
                             "push_location = foo\n"
 
104
                             "push_location:policy = norecurse\n" % local_path,
 
105
                             config.locations_config_filename())
 
106
 
 
107
    # TODO RBC 20051029 test getting a push location from a branch in a
 
108
    # recursive section - that is, it appends the branch name.
 
109
 
 
110
 
 
111
class SampleBranchFormat(_mod_bzrbranch.BranchFormatMetadir):
 
112
    """A sample format
 
113
 
 
114
    this format is initializable, unsupported to aid in testing the
 
115
    open and open_downlevel routines.
 
116
    """
 
117
 
 
118
    @classmethod
 
119
    def get_format_string(cls):
 
120
        """See BzrBranchFormat.get_format_string()."""
 
121
        return "Sample branch format."
 
122
 
 
123
    def initialize(self, a_bzrdir, name=None, repository=None,
 
124
                   append_revisions_only=None):
 
125
        """Format 4 branches cannot be created."""
 
126
        t = a_bzrdir.get_branch_transport(self, name=name)
 
127
        t.put_bytes('format', self.get_format_string())
 
128
        return 'A branch'
 
129
 
 
130
    def is_supported(self):
 
131
        return False
 
132
 
 
133
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
 
134
             possible_transports=None):
 
135
        return "opened branch."
 
136
 
 
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_bzrdir, name=None, append_revisions_only=None):
 
152
        t = a_bzrdir.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_bzrdir, 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
 
 
180
class TestBzrBranchFormat(tests.TestCaseWithTransport):
 
181
    """Tests for the BzrBranchFormat facility."""
 
182
 
 
183
    def test_find_format(self):
 
184
        # is the right format object found for a branch?
 
185
        # create a branch with a few known format objects.
 
186
        # this is not quite the same as
 
187
        self.build_tree(["foo/", "bar/"])
 
188
        def check_format(format, url):
 
189
            dir = format._matchingbzrdir.initialize(url)
 
190
            dir.create_repository()
 
191
            format.initialize(dir)
 
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.")
 
202
 
 
203
    def test_find_format_not_branch(self):
 
204
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
 
205
        self.assertRaises(errors.NotBranchError,
 
206
                          _mod_bzrbranch.BranchFormatMetadir.find_format,
 
207
                          dir)
 
208
 
 
209
    def test_find_format_unknown_format(self):
 
210
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
 
211
        SampleBranchFormat().initialize(dir)
 
212
        self.assertRaises(errors.UnknownFormatError,
 
213
                          _mod_bzrbranch.BranchFormatMetadir.find_format,
 
214
                          dir)
 
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.bzrdir)
 
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
 
 
239
    def test_register_unregister_format(self):
 
240
        format = SampleBranchFormat()
 
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)
 
267
 
 
268
 
 
269
class TestBranch67(object):
 
270
    """Common tests for both branch 6 and 7 which are mostly the same."""
 
271
 
 
272
    def get_format_name(self):
 
273
        raise NotImplementedError(self.get_format_name)
 
274
 
 
275
    def get_format_name_subtree(self):
 
276
        raise NotImplementedError(self.get_format_name)
 
277
 
 
278
    def get_class(self):
 
279
        raise NotImplementedError(self.get_class)
 
280
 
 
281
    def test_creation(self):
 
282
        format = bzrdir.BzrDirMetaFormat1()
 
283
        format.set_branch_format(_mod_bzrbranch.BzrBranchFormat6())
 
284
        branch = self.make_branch('a', format=format)
 
285
        self.assertIsInstance(branch, self.get_class())
 
286
        branch = self.make_branch('b', format=self.get_format_name())
 
287
        self.assertIsInstance(branch, self.get_class())
 
288
        branch = _mod_branch.Branch.open('a')
 
289
        self.assertIsInstance(branch, self.get_class())
 
290
 
 
291
    def test_layout(self):
 
292
        branch = self.make_branch('a', format=self.get_format_name())
 
293
        self.assertPathExists('a/.bzr/branch/last-revision')
 
294
        self.assertPathDoesNotExist('a/.bzr/branch/revision-history')
 
295
        self.assertPathDoesNotExist('a/.bzr/branch/references')
 
296
 
 
297
    def test_config(self):
 
298
        """Ensure that all configuration data is stored in the branch"""
 
299
        branch = self.make_branch('a', format=self.get_format_name())
 
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())
 
309
 
 
310
    def do_checkout_test(self, lightweight=False):
 
311
        tree = self.make_branch_and_tree('source',
 
312
            format=self.get_format_name_subtree())
 
313
        subtree = self.make_branch_and_tree('source/subtree',
 
314
            format=self.get_format_name_subtree())
 
315
        subsubtree = self.make_branch_and_tree('source/subtree/subsubtree',
 
316
            format=self.get_format_name_subtree())
 
317
        self.build_tree(['source/subtree/file',
 
318
                         'source/subtree/subsubtree/file'])
 
319
        subsubtree.add('file')
 
320
        subtree.add('file')
 
321
        subtree.add_reference(subsubtree)
 
322
        tree.add_reference(subtree)
 
323
        tree.commit('a revision')
 
324
        subtree.commit('a subtree file')
 
325
        subsubtree.commit('a subsubtree file')
 
326
        tree.branch.create_checkout('target', lightweight=lightweight)
 
327
        self.assertPathExists('target')
 
328
        self.assertPathExists('target/subtree')
 
329
        self.assertPathExists('target/subtree/file')
 
330
        self.assertPathExists('target/subtree/subsubtree/file')
 
331
        subbranch = _mod_branch.Branch.open('target/subtree/subsubtree')
 
332
        if lightweight:
 
333
            self.assertEndsWith(subbranch.base, 'source/subtree/subsubtree/')
 
334
        else:
 
335
            self.assertEndsWith(subbranch.base, 'target/subtree/subsubtree/')
 
336
 
 
337
    def test_checkout_with_references(self):
 
338
        self.do_checkout_test()
 
339
 
 
340
    def test_light_checkout_with_references(self):
 
341
        self.do_checkout_test(lightweight=True)
 
342
 
 
343
 
 
344
class TestBranch6(TestBranch67, tests.TestCaseWithTransport):
 
345
 
 
346
    def get_class(self):
 
347
        return _mod_bzrbranch.BzrBranch6
 
348
 
 
349
    def get_format_name(self):
 
350
        return "dirstate-tags"
 
351
 
 
352
    def get_format_name_subtree(self):
 
353
        return "dirstate-with-subtree"
 
354
 
 
355
    def test_set_stacked_on_url_errors(self):
 
356
        branch = self.make_branch('a', format=self.get_format_name())
 
357
        self.assertRaises(errors.UnstackableBranchFormat,
 
358
            branch.set_stacked_on_url, None)
 
359
 
 
360
    def test_default_stacked_location(self):
 
361
        branch = self.make_branch('a', format=self.get_format_name())
 
362
        self.assertRaises(errors.UnstackableBranchFormat, branch.get_stacked_on_url)
 
363
 
 
364
 
 
365
class TestBranch7(TestBranch67, tests.TestCaseWithTransport):
 
366
 
 
367
    def get_class(self):
 
368
        return _mod_bzrbranch.BzrBranch7
 
369
 
 
370
    def get_format_name(self):
 
371
        return "1.9"
 
372
 
 
373
    def get_format_name_subtree(self):
 
374
        return "development-subtree"
 
375
 
 
376
    def test_set_stacked_on_url_unstackable_repo(self):
 
377
        repo = self.make_repository('a', format='dirstate-tags')
 
378
        control = repo.bzrdir
 
379
        branch = _mod_bzrbranch.BzrBranchFormat7().initialize(control)
 
380
        target = self.make_branch('b')
 
381
        self.assertRaises(errors.UnstackableRepositoryFormat,
 
382
            branch.set_stacked_on_url, target.base)
 
383
 
 
384
    def test_clone_stacked_on_unstackable_repo(self):
 
385
        repo = self.make_repository('a', format='dirstate-tags')
 
386
        control = repo.bzrdir
 
387
        branch = _mod_bzrbranch.BzrBranchFormat7().initialize(control)
 
388
        # Calling clone should not raise UnstackableRepositoryFormat.
 
389
        cloned_bzrdir = control.clone('cloned')
 
390
 
 
391
    def _test_default_stacked_location(self):
 
392
        branch = self.make_branch('a', format=self.get_format_name())
 
393
        self.assertRaises(errors.NotStacked, branch.get_stacked_on_url)
 
394
 
 
395
    def test_stack_and_unstack(self):
 
396
        branch = self.make_branch('a', format=self.get_format_name())
 
397
        target = self.make_branch_and_tree('b', format=self.get_format_name())
 
398
        branch.set_stacked_on_url(target.branch.base)
 
399
        self.assertEqual(target.branch.base, branch.get_stacked_on_url())
 
400
        revid = target.commit('foo')
 
401
        self.assertTrue(branch.repository.has_revision(revid))
 
402
        branch.set_stacked_on_url(None)
 
403
        self.assertRaises(errors.NotStacked, branch.get_stacked_on_url)
 
404
        self.assertFalse(branch.repository.has_revision(revid))
 
405
 
 
406
    def test_open_opens_stacked_reference(self):
 
407
        branch = self.make_branch('a', format=self.get_format_name())
 
408
        target = self.make_branch_and_tree('b', format=self.get_format_name())
 
409
        branch.set_stacked_on_url(target.branch.base)
 
410
        branch = branch.bzrdir.open_branch()
 
411
        revid = target.commit('foo')
 
412
        self.assertTrue(branch.repository.has_revision(revid))
 
413
 
 
414
 
 
415
class BzrBranch8(tests.TestCaseWithTransport):
 
416
 
 
417
    def make_branch(self, location, format=None):
 
418
        if format is None:
 
419
            format = controldir.format_registry.make_bzrdir('1.9')
 
420
            format.set_branch_format(_mod_bzrbranch.BzrBranchFormat8())
 
421
        return tests.TestCaseWithTransport.make_branch(
 
422
            self, location, format=format)
 
423
 
 
424
    def create_branch_with_reference(self):
 
425
        branch = self.make_branch('branch')
 
426
        branch._set_all_reference_info({'file-id': ('path', 'location')})
 
427
        return branch
 
428
 
 
429
    @staticmethod
 
430
    def instrument_branch(branch, gets):
 
431
        old_get = branch._transport.get
 
432
        def get(*args, **kwargs):
 
433
            gets.append((args, kwargs))
 
434
            return old_get(*args, **kwargs)
 
435
        branch._transport.get = get
 
436
 
 
437
    def test_reference_info_caching_read_locked(self):
 
438
        gets = []
 
439
        branch = self.create_branch_with_reference()
 
440
        branch.lock_read()
 
441
        self.addCleanup(branch.unlock)
 
442
        self.instrument_branch(branch, gets)
 
443
        branch.get_reference_info('file-id')
 
444
        branch.get_reference_info('file-id')
 
445
        self.assertEqual(1, len(gets))
 
446
 
 
447
    def test_reference_info_caching_read_unlocked(self):
 
448
        gets = []
 
449
        branch = self.create_branch_with_reference()
 
450
        self.instrument_branch(branch, gets)
 
451
        branch.get_reference_info('file-id')
 
452
        branch.get_reference_info('file-id')
 
453
        self.assertEqual(2, len(gets))
 
454
 
 
455
    def test_reference_info_caching_write_locked(self):
 
456
        gets = []
 
457
        branch = self.make_branch('branch')
 
458
        branch.lock_write()
 
459
        self.instrument_branch(branch, gets)
 
460
        self.addCleanup(branch.unlock)
 
461
        branch._set_all_reference_info({'file-id': ('path2', 'location2')})
 
462
        path, location = branch.get_reference_info('file-id')
 
463
        self.assertEqual(0, len(gets))
 
464
        self.assertEqual('path2', path)
 
465
        self.assertEqual('location2', location)
 
466
 
 
467
    def test_reference_info_caches_cleared(self):
 
468
        branch = self.make_branch('branch')
 
469
        branch.lock_write()
 
470
        branch.set_reference_info('file-id', 'path2', 'location2')
 
471
        branch.unlock()
 
472
        doppelganger = _mod_branch.Branch.open('branch')
 
473
        doppelganger.set_reference_info('file-id', 'path3', 'location3')
 
474
        self.assertEqual(('path3', 'location3'),
 
475
                         branch.get_reference_info('file-id'))
 
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
 
 
487
class TestBranchReference(tests.TestCaseWithTransport):
 
488
    """Tests for the branch reference facility."""
 
489
 
 
490
    def test_create_open_reference(self):
 
491
        bzrdirformat = bzrdir.BzrDirMetaFormat1()
 
492
        t = self.get_transport()
 
493
        t.mkdir('repo')
 
494
        dir = bzrdirformat.initialize(self.get_url('repo'))
 
495
        dir.create_repository()
 
496
        target_branch = dir.create_branch()
 
497
        t.mkdir('branch')
 
498
        branch_dir = bzrdirformat.initialize(self.get_url('branch'))
 
499
        made_branch = _mod_bzrbranch.BranchReferenceFormat().initialize(
 
500
            branch_dir, target_branch=target_branch)
 
501
        self.assertEqual(made_branch.base, target_branch.base)
 
502
        opened_branch = branch_dir.open_branch()
 
503
        self.assertEqual(opened_branch.base, target_branch.base)
 
504
 
 
505
    def test_get_reference(self):
 
506
        """For a BranchReference, get_reference should return the location."""
 
507
        branch = self.make_branch('target')
 
508
        checkout = branch.create_checkout('checkout', lightweight=True)
 
509
        reference_url = branch.bzrdir.root_transport.abspath('') + '/'
 
510
        # if the api for create_checkout changes to return different checkout types
 
511
        # then this file read will fail.
 
512
        self.assertFileEqual(reference_url, 'checkout/.bzr/branch/location')
 
513
        self.assertEqual(reference_url,
 
514
            _mod_bzrbranch.BranchReferenceFormat().get_reference(checkout.bzrdir))
 
515
 
 
516
 
 
517
class TestHooks(tests.TestCaseWithTransport):
 
518
 
 
519
    def test_constructor(self):
 
520
        """Check that creating a BranchHooks instance has the right defaults."""
 
521
        hooks = _mod_branch.BranchHooks()
 
522
        self.assertTrue("post_push" in hooks, "post_push not in %s" % hooks)
 
523
        self.assertTrue("post_commit" in hooks, "post_commit not in %s" % hooks)
 
524
        self.assertTrue("pre_commit" in hooks, "pre_commit not in %s" % hooks)
 
525
        self.assertTrue("post_pull" in hooks, "post_pull not in %s" % hooks)
 
526
        self.assertTrue("post_uncommit" in hooks,
 
527
                        "post_uncommit not in %s" % hooks)
 
528
        self.assertTrue("post_change_branch_tip" in hooks,
 
529
                        "post_change_branch_tip not in %s" % hooks)
 
530
        self.assertTrue("post_branch_init" in hooks,
 
531
                        "post_branch_init not in %s" % hooks)
 
532
        self.assertTrue("post_switch" in hooks,
 
533
                        "post_switch not in %s" % hooks)
 
534
 
 
535
    def test_installed_hooks_are_BranchHooks(self):
 
536
        """The installed hooks object should be a BranchHooks."""
 
537
        # the installed hooks are saved in self._preserved_hooks.
 
538
        self.assertIsInstance(self._preserved_hooks[_mod_branch.Branch][1],
 
539
                              _mod_branch.BranchHooks)
 
540
 
 
541
    def test_post_branch_init_hook(self):
 
542
        calls = []
 
543
        _mod_branch.Branch.hooks.install_named_hook('post_branch_init',
 
544
            calls.append, None)
 
545
        self.assertLength(0, calls)
 
546
        branch = self.make_branch('a')
 
547
        self.assertLength(1, calls)
 
548
        params = calls[0]
 
549
        self.assertIsInstance(params, _mod_branch.BranchInitHookParams)
 
550
        self.assertTrue(hasattr(params, 'bzrdir'))
 
551
        self.assertTrue(hasattr(params, 'branch'))
 
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
 
 
562
    def test_post_switch_hook(self):
 
563
        from .. import switch
 
564
        calls = []
 
565
        _mod_branch.Branch.hooks.install_named_hook('post_switch',
 
566
            calls.append, None)
 
567
        tree = self.make_branch_and_tree('branch-1')
 
568
        self.build_tree(['branch-1/file-1'])
 
569
        tree.add('file-1')
 
570
        tree.commit('rev1')
 
571
        to_branch = tree.bzrdir.sprout('branch-2').open_branch()
 
572
        self.build_tree(['branch-1/file-2'])
 
573
        tree.add('file-2')
 
574
        tree.remove('file-1')
 
575
        tree.commit('rev2')
 
576
        checkout = tree.branch.create_checkout('checkout')
 
577
        self.assertLength(0, calls)
 
578
        switch.switch(checkout.bzrdir, to_branch)
 
579
        self.assertLength(1, calls)
 
580
        params = calls[0]
 
581
        self.assertIsInstance(params, _mod_branch.SwitchHookParams)
 
582
        self.assertTrue(hasattr(params, 'to_branch'))
 
583
        self.assertTrue(hasattr(params, 'revision_id'))
 
584
 
 
585
 
 
586
class TestBranchOptions(tests.TestCaseWithTransport):
 
587
 
 
588
    def setUp(self):
 
589
        super(TestBranchOptions, self).setUp()
 
590
        self.branch = self.make_branch('.')
 
591
        self.config_stack = self.branch.get_config_stack()
 
592
 
 
593
    def check_append_revisions_only(self, expected_value, value=None):
 
594
        """Set append_revisions_only in config and check its interpretation."""
 
595
        if value is not None:
 
596
            self.config_stack.set('append_revisions_only', value)
 
597
        self.assertEqual(expected_value,
 
598
                         self.branch.get_append_revisions_only())
 
599
 
 
600
    def test_valid_append_revisions_only(self):
 
601
        self.assertEqual(None,
 
602
                          self.config_stack.get('append_revisions_only'))
 
603
        self.check_append_revisions_only(None)
 
604
        self.check_append_revisions_only(False, 'False')
 
605
        self.check_append_revisions_only(True, 'True')
 
606
        # The following values will cause compatibility problems on projects
 
607
        # using older bzr versions (<2.2) but are accepted
 
608
        self.check_append_revisions_only(False, 'false')
 
609
        self.check_append_revisions_only(True, 'true')
 
610
 
 
611
    def test_invalid_append_revisions_only(self):
 
612
        """Ensure warning is noted on invalid settings"""
 
613
        self.warnings = []
 
614
        def warning(*args):
 
615
            self.warnings.append(args[0] % args[1:])
 
616
        self.overrideAttr(trace, 'warning', warning)
 
617
        self.check_append_revisions_only(None, 'not-a-bool')
 
618
        self.assertLength(1, self.warnings)
 
619
        self.assertEqual(
 
620
            'Value "not-a-bool" is not valid for "append_revisions_only"',
 
621
            self.warnings[0])
 
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
 
 
668
 
 
669
class TestPullResult(tests.TestCase):
 
670
 
 
671
    def test_report_changed(self):
 
672
        r = _mod_branch.PullResult()
 
673
        r.old_revid = "old-revid"
 
674
        r.old_revno = 10
 
675
        r.new_revid = "new-revid"
 
676
        r.new_revno = 20
 
677
        f = BytesIO()
 
678
        r.report(f)
 
679
        self.assertEqual("Now on revision 20.\n", f.getvalue())
 
680
        self.assertEqual("Now on revision 20.\n", f.getvalue())
 
681
 
 
682
    def test_report_unchanged(self):
 
683
        r = _mod_branch.PullResult()
 
684
        r.old_revid = "same-revid"
 
685
        r.new_revid = "same-revid"
 
686
        f = BytesIO()
 
687
        r.report(f)
 
688
        self.assertEqual("No revisions or tags to pull.\n", f.getvalue())