/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: Breezy landing bot
  • Author(s): Martin
  • Date: 2017-06-05 01:55:02 UTC
  • mfrom: (6651.4.3 plugin_rewrite)
  • Revision ID: breezy.the.bot@gmail.com-20170605015502-tqiyvpz3qt00fge1
Rewrite of plugin module

Merged from https://code.launchpad.net/~gz/brz/plugin_rewrite/+merge/325033

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,
29
27
    bzrdir,
30
28
    config,
 
29
    controldir,
31
30
    errors,
32
31
    tests,
33
32
    trace,
34
 
    transport,
35
33
    urlutils,
36
34
    )
 
35
from ..branchfmt.fullhistory import (
 
36
    BzrBranch5,
 
37
    BzrBranchFormat5,
 
38
    )
 
39
from ..sixish import (
 
40
    BytesIO,
 
41
    )
37
42
 
38
43
 
39
44
class TestDefaultFormat(tests.TestCase):
40
45
 
41
46
    def test_default_format(self):
42
47
        # update this if you change the default branch format
43
 
        self.assertIsInstance(_mod_branch.BranchFormat.get_default_format(),
 
48
        self.assertIsInstance(_mod_branch.format_registry.get_default(),
44
49
                _mod_branch.BzrBranchFormat7)
45
50
 
46
51
    def test_default_format_is_same_as_bzrdir_default(self):
48
53
        # set, but at the moment that's not true -- mbp 20070814 --
49
54
        # https://bugs.launchpad.net/bzr/+bug/132376
50
55
        self.assertEqual(
51
 
            _mod_branch.BranchFormat.get_default_format(),
 
56
            _mod_branch.format_registry.get_default(),
52
57
            bzrdir.BzrDirFormat.get_default_format().get_branch_format())
53
58
 
54
59
    def test_get_set_default_format(self):
55
60
        # 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())
 
61
        old_format = _mod_branch.format_registry.get_default()
 
62
        _mod_branch.format_registry.set_default(SampleBranchFormat())
58
63
        try:
59
64
            # the default branch format is used by the meta dir format
60
65
            # which is not the default bzrdir format at this point
62
67
            result = dir.create_branch()
63
68
            self.assertEqual(result, 'A branch')
64
69
        finally:
65
 
            _mod_branch.BranchFormat.set_default_format(old_format)
 
70
            _mod_branch.format_registry.set_default(old_format)
66
71
        self.assertEqual(old_format,
67
 
                         _mod_branch.BranchFormat.get_default_format())
 
72
                         _mod_branch.format_registry.get_default())
68
73
 
69
74
 
70
75
class TestBranchFormat5(tests.TestCaseWithTransport):
74
79
        url = self.get_url()
75
80
        bdir = bzrdir.BzrDirMetaFormat1().initialize(url)
76
81
        bdir.create_repository()
77
 
        branch = bdir.create_branch()
 
82
        branch = BzrBranchFormat5().initialize(bdir)
78
83
        t = self.get_transport()
79
84
        self.log("branch instance is %r" % branch)
80
 
        self.assert_(isinstance(branch, _mod_branch.BzrBranch5))
 
85
        self.assertTrue(isinstance(branch, BzrBranch5))
81
86
        self.assertIsDirectory('.', t)
82
87
        self.assertIsDirectory('.bzr/branch', t)
83
88
        self.assertIsDirectory('.bzr/branch/lock', t)
86
91
        self.assertIsDirectory('.bzr/branch/lock/held', t)
87
92
 
88
93
    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()
 
94
        conf = config.LocationConfig.from_string('# comment\n', '.', save=True)
101
95
 
102
96
        branch = self.make_branch('.', format='knit')
103
97
        branch.set_push_location('foo')
106
100
                             "[%s]\n"
107
101
                             "push_location = foo\n"
108
102
                             "push_location:policy = norecurse\n" % local_path,
109
 
                             fn)
 
103
                             config.locations_config_filename())
110
104
 
111
105
    # TODO RBC 20051029 test getting a push location from a branch in a
112
106
    # recursive section - that is, it appends the branch name.
113
107
 
114
108
 
115
 
class SampleBranchFormat(_mod_branch.BranchFormat):
 
109
class SampleBranchFormat(_mod_branch.BranchFormatMetadir):
116
110
    """A sample format
117
111
 
118
112
    this format is initializable, unsupported to aid in testing the
119
113
    open and open_downlevel routines.
120
114
    """
121
115
 
122
 
    def get_format_string(self):
 
116
    @classmethod
 
117
    def get_format_string(cls):
123
118
        """See BzrBranchFormat.get_format_string()."""
124
119
        return "Sample branch format."
125
120
 
126
 
    def initialize(self, a_bzrdir, name=None):
 
121
    def initialize(self, a_bzrdir, name=None, repository=None,
 
122
                   append_revisions_only=None):
127
123
        """Format 4 branches cannot be created."""
128
124
        t = a_bzrdir.get_branch_transport(self, name=name)
129
125
        t.put_bytes('format', self.get_format_string())
132
128
    def is_supported(self):
133
129
        return False
134
130
 
135
 
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False):
 
131
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
 
132
             possible_transports=None):
136
133
        return "opened branch."
137
134
 
138
135
 
 
136
# Demonstrating how lazy loading is often implemented:
 
137
# A constant string is created.
 
138
SampleSupportedBranchFormatString = "Sample supported branch format."
 
139
 
 
140
# And the format class can then reference the constant to avoid skew.
 
141
class SampleSupportedBranchFormat(_mod_branch.BranchFormatMetadir):
 
142
    """A sample supported format."""
 
143
 
 
144
    @classmethod
 
145
    def get_format_string(cls):
 
146
        """See BzrBranchFormat.get_format_string()."""
 
147
        return SampleSupportedBranchFormatString
 
148
 
 
149
    def initialize(self, a_bzrdir, name=None, append_revisions_only=None):
 
150
        t = a_bzrdir.get_branch_transport(self, name=name)
 
151
        t.put_bytes('format', self.get_format_string())
 
152
        return 'A branch'
 
153
 
 
154
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
 
155
             possible_transports=None):
 
156
        return "opened supported branch."
 
157
 
 
158
 
 
159
class SampleExtraBranchFormat(_mod_branch.BranchFormat):
 
160
    """A sample format that is not usable in a metadir."""
 
161
 
 
162
    def get_format_string(self):
 
163
        # This format is not usable in a metadir.
 
164
        return None
 
165
 
 
166
    def network_name(self):
 
167
        # Network name always has to be provided.
 
168
        return "extra"
 
169
 
 
170
    def initialize(self, a_bzrdir, name=None):
 
171
        raise NotImplementedError(self.initialize)
 
172
 
 
173
    def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
 
174
             possible_transports=None):
 
175
        raise NotImplementedError(self.open)
 
176
 
 
177
 
139
178
class TestBzrBranchFormat(tests.TestCaseWithTransport):
140
179
    """Tests for the BzrBranchFormat facility."""
141
180
 
148
187
            dir = format._matchingbzrdir.initialize(url)
149
188
            dir.create_repository()
150
189
            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")
 
190
            found_format = _mod_branch.BranchFormatMetadir.find_format(dir)
 
191
            self.assertIsInstance(found_format, format.__class__)
 
192
        check_format(BzrBranchFormat5(), "bar")
 
193
 
 
194
    def test_find_format_factory(self):
 
195
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
 
196
        SampleSupportedBranchFormat().initialize(dir)
 
197
        factory = _mod_branch.MetaDirBranchFormatFactory(
 
198
            SampleSupportedBranchFormatString,
 
199
            "breezy.tests.test_branch", "SampleSupportedBranchFormat")
 
200
        _mod_branch.format_registry.register(factory)
 
201
        self.addCleanup(_mod_branch.format_registry.remove, factory)
 
202
        b = _mod_branch.Branch.open(self.get_url())
 
203
        self.assertEqual(b, "opened supported branch.")
 
204
 
 
205
    def test_from_string(self):
 
206
        self.assertIsInstance(
 
207
            SampleBranchFormat.from_string("Sample branch format."),
 
208
            SampleBranchFormat)
 
209
        self.assertRaises(AssertionError,
 
210
            SampleBranchFormat.from_string, "Different branch format.")
154
211
 
155
212
    def test_find_format_not_branch(self):
156
213
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
157
214
        self.assertRaises(errors.NotBranchError,
158
 
                          _mod_branch.BranchFormat.find_format,
 
215
                          _mod_branch.BranchFormatMetadir.find_format,
159
216
                          dir)
160
217
 
161
218
    def test_find_format_unknown_format(self):
162
219
        dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
163
220
        SampleBranchFormat().initialize(dir)
164
221
        self.assertRaises(errors.UnknownFormatError,
165
 
                          _mod_branch.BranchFormat.find_format,
 
222
                          _mod_branch.BranchFormatMetadir.find_format,
166
223
                          dir)
167
224
 
 
225
    def test_find_format_with_features(self):
 
226
        tree = self.make_branch_and_tree('.', format='2a')
 
227
        tree.branch.update_feature_flags({"name": "optional"})
 
228
        found_format = _mod_branch.BranchFormatMetadir.find_format(tree.bzrdir)
 
229
        self.assertIsInstance(found_format, _mod_branch.BranchFormatMetadir)
 
230
        self.assertEqual(found_format.features.get("name"), "optional")
 
231
        tree.branch.update_feature_flags({"name": None})
 
232
        branch = _mod_branch.Branch.open('.')
 
233
        self.assertEqual(branch._format.features, {})
 
234
 
 
235
 
 
236
class TestBranchFormatRegistry(tests.TestCase):
 
237
 
 
238
    def setUp(self):
 
239
        super(TestBranchFormatRegistry, self).setUp()
 
240
        self.registry = _mod_branch.BranchFormatRegistry()
 
241
 
 
242
    def test_default(self):
 
243
        self.assertIs(None, self.registry.get_default())
 
244
        format = SampleBranchFormat()
 
245
        self.registry.set_default(format)
 
246
        self.assertEqual(format, self.registry.get_default())
 
247
 
168
248
    def test_register_unregister_format(self):
169
249
        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')
 
250
        self.registry.register(format)
 
251
        self.assertEqual(format,
 
252
            self.registry.get("Sample branch format."))
 
253
        self.registry.remove(format)
 
254
        self.assertRaises(KeyError, self.registry.get,
 
255
            "Sample branch format.")
 
256
 
 
257
    def test_get_all(self):
 
258
        format = SampleBranchFormat()
 
259
        self.assertEqual([], self.registry._get_all())
 
260
        self.registry.register(format)
 
261
        self.assertEqual([format], self.registry._get_all())
 
262
 
 
263
    def test_register_extra(self):
 
264
        format = SampleExtraBranchFormat()
 
265
        self.assertEqual([], self.registry._get_all())
 
266
        self.registry.register_extra(format)
 
267
        self.assertEqual([format], self.registry._get_all())
 
268
 
 
269
    def test_register_extra_lazy(self):
 
270
        self.assertEqual([], self.registry._get_all())
 
271
        self.registry.register_extra_lazy("breezy.tests.test_branch",
 
272
            "SampleExtraBranchFormat")
 
273
        formats = self.registry._get_all()
 
274
        self.assertEqual(1, len(formats))
 
275
        self.assertIsInstance(formats[0], SampleExtraBranchFormat)
 
276
 
 
277
 
 
278
#Used by TestMetaDirBranchFormatFactory 
 
279
FakeLazyFormat = None
 
280
 
 
281
 
 
282
class TestMetaDirBranchFormatFactory(tests.TestCase):
 
283
 
 
284
    def test_get_format_string_does_not_load(self):
 
285
        """Formats have a static format string."""
 
286
        factory = _mod_branch.MetaDirBranchFormatFactory("yo", None, None)
 
287
        self.assertEqual("yo", factory.get_format_string())
 
288
 
 
289
    def test_call_loads(self):
 
290
        # __call__ is used by the network_format_registry interface to get a
 
291
        # Format.
 
292
        global FakeLazyFormat
 
293
        del FakeLazyFormat
 
294
        factory = _mod_branch.MetaDirBranchFormatFactory(None,
 
295
            "breezy.tests.test_branch", "FakeLazyFormat")
 
296
        self.assertRaises(AttributeError, factory)
 
297
 
 
298
    def test_call_returns_call_of_referenced_object(self):
 
299
        global FakeLazyFormat
 
300
        FakeLazyFormat = lambda:'called'
 
301
        factory = _mod_branch.MetaDirBranchFormatFactory(None,
 
302
            "breezy.tests.test_branch", "FakeLazyFormat")
 
303
        self.assertEqual('called', factory())
187
304
 
188
305
 
189
306
class TestBranch67(object):
210
327
 
211
328
    def test_layout(self):
212
329
        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')
 
330
        self.assertPathExists('a/.bzr/branch/last-revision')
 
331
        self.assertPathDoesNotExist('a/.bzr/branch/revision-history')
 
332
        self.assertPathDoesNotExist('a/.bzr/branch/references')
216
333
 
217
334
    def test_config(self):
218
335
        """Ensure that all configuration data is stored in the branch"""
219
336
        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'])
 
337
        branch.set_parent('http://example.com')
 
338
        self.assertPathDoesNotExist('a/.bzr/branch/parent')
 
339
        self.assertEqual('http://example.com', branch.get_parent())
 
340
        branch.set_push_location('sftp://example.com')
 
341
        conf = branch.get_config_stack()
 
342
        self.assertEqual('sftp://example.com', conf.get('push_location'))
 
343
        branch.set_bound_location('ftp://example.com')
 
344
        self.assertPathDoesNotExist('a/.bzr/branch/bound')
 
345
        self.assertEqual('ftp://example.com', branch.get_bound_location())
244
346
 
245
347
    def do_checkout_test(self, lightweight=False):
246
348
        tree = self.make_branch_and_tree('source',
259
361
        subtree.commit('a subtree file')
260
362
        subsubtree.commit('a subsubtree file')
261
363
        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')
 
364
        self.assertPathExists('target')
 
365
        self.assertPathExists('target/subtree')
 
366
        self.assertPathExists('target/subtree/file')
 
367
        self.assertPathExists('target/subtree/subsubtree/file')
266
368
        subbranch = _mod_branch.Branch.open('target/subtree/subsubtree')
267
369
        if lightweight:
268
370
            self.assertEndsWith(subbranch.base, 'source/subtree/subsubtree/')
275
377
    def test_light_checkout_with_references(self):
276
378
        self.do_checkout_test(lightweight=True)
277
379
 
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
380
 
295
381
class TestBranch6(TestBranch67, tests.TestCaseWithTransport):
296
382
 
367
453
 
368
454
    def make_branch(self, location, format=None):
369
455
        if format is None:
370
 
            format = bzrdir.format_registry.make_bzrdir('1.9')
 
456
            format = controldir.format_registry.make_bzrdir('1.9')
371
457
            format.set_branch_format(_mod_branch.BzrBranchFormat8())
372
458
        return tests.TestCaseWithTransport.make_branch(
373
459
            self, location, format=format)
425
511
        self.assertEqual(('path3', 'location3'),
426
512
                         branch.get_reference_info('file-id'))
427
513
 
 
514
    def _recordParentMapCalls(self, repo):
 
515
        self._parent_map_calls = []
 
516
        orig_get_parent_map = repo.revisions.get_parent_map
 
517
        def get_parent_map(q):
 
518
            q = list(q)
 
519
            self._parent_map_calls.extend([e[0] for e in q])
 
520
            return orig_get_parent_map(q)
 
521
        repo.revisions.get_parent_map = get_parent_map
 
522
 
 
523
 
428
524
class TestBranchReference(tests.TestCaseWithTransport):
429
525
    """Tests for the branch reference facility."""
430
526
 
431
527
    def test_create_open_reference(self):
432
528
        bzrdirformat = bzrdir.BzrDirMetaFormat1()
433
 
        t = transport.get_transport(self.get_url('.'))
 
529
        t = self.get_transport()
434
530
        t.mkdir('repo')
435
531
        dir = bzrdirformat.initialize(self.get_url('repo'))
436
532
        dir.create_repository()
444
540
        self.assertEqual(opened_branch.base, target_branch.base)
445
541
 
446
542
    def test_get_reference(self):
447
 
        """For a BranchReference, get_reference should reutrn the location."""
 
543
        """For a BranchReference, get_reference should return the location."""
448
544
        branch = self.make_branch('target')
449
545
        checkout = branch.create_checkout('checkout', lightweight=True)
450
546
        reference_url = branch.bzrdir.root_transport.abspath('') + '/'
460
556
    def test_constructor(self):
461
557
        """Check that creating a BranchHooks instance has the right defaults."""
462
558
        hooks = _mod_branch.BranchHooks()
463
 
        self.assertTrue("set_rh" in hooks, "set_rh not in %s" % hooks)
464
559
        self.assertTrue("post_push" in hooks, "post_push not in %s" % hooks)
465
560
        self.assertTrue("post_commit" in hooks, "post_commit not in %s" % hooks)
466
561
        self.assertTrue("pre_commit" in hooks, "pre_commit not in %s" % hooks)
492
587
        self.assertTrue(hasattr(params, 'bzrdir'))
493
588
        self.assertTrue(hasattr(params, 'branch'))
494
589
 
 
590
    def test_post_branch_init_hook_repr(self):
 
591
        param_reprs = []
 
592
        _mod_branch.Branch.hooks.install_named_hook('post_branch_init',
 
593
            lambda params: param_reprs.append(repr(params)), None)
 
594
        branch = self.make_branch('a')
 
595
        self.assertLength(1, param_reprs)
 
596
        param_repr = param_reprs[0]
 
597
        self.assertStartsWith(param_repr, '<BranchInitHookParams of ')
 
598
 
495
599
    def test_post_switch_hook(self):
496
 
        from bzrlib import switch
 
600
        from .. import switch
497
601
        calls = []
498
602
        _mod_branch.Branch.hooks.install_named_hook('post_switch',
499
603
            calls.append, None)
521
625
    def setUp(self):
522
626
        super(TestBranchOptions, self).setUp()
523
627
        self.branch = self.make_branch('.')
524
 
        self.config = self.branch.get_config()
 
628
        self.config_stack = self.branch.get_config_stack()
525
629
 
526
630
    def check_append_revisions_only(self, expected_value, value=None):
527
631
        """Set append_revisions_only in config and check its interpretation."""
528
632
        if value is not None:
529
 
            self.config.set_user_option('append_revisions_only', value)
 
633
            self.config_stack.set('append_revisions_only', value)
530
634
        self.assertEqual(expected_value,
531
 
                         self.branch._get_append_revisions_only())
 
635
                         self.branch.get_append_revisions_only())
532
636
 
533
637
    def test_valid_append_revisions_only(self):
534
 
        self.assertEquals(None,
535
 
                          self.config.get_user_option('append_revisions_only'))
 
638
        self.assertEqual(None,
 
639
                          self.config_stack.get('append_revisions_only'))
536
640
        self.check_append_revisions_only(None)
537
641
        self.check_append_revisions_only(False, 'False')
538
642
        self.check_append_revisions_only(True, 'True')
550
654
        self.check_append_revisions_only(None, 'not-a-bool')
551
655
        self.assertLength(1, self.warnings)
552
656
        self.assertEqual(
553
 
            'Value "not-a-bool" is not a boolean for "append_revisions_only"',
 
657
            'Value "not-a-bool" is not valid for "append_revisions_only"',
554
658
            self.warnings[0])
555
659
 
 
660
    def test_use_fresh_values(self):
 
661
        copy = _mod_branch.Branch.open(self.branch.base)
 
662
        copy.lock_write()
 
663
        try:
 
664
            copy.get_config_stack().set('foo', 'bar')
 
665
        finally:
 
666
            copy.unlock()
 
667
        self.assertFalse(self.branch.is_locked())
 
668
        # Since the branch is locked, the option value won't be saved on disk
 
669
        # so trying to access the config of locked branch via another older
 
670
        # non-locked branch object pointing to the same branch is not supported
 
671
        self.assertEqual(None, self.branch.get_config_stack().get('foo'))
 
672
        # Using a newly created branch object works as expected
 
673
        fresh = _mod_branch.Branch.open(self.branch.base)
 
674
        self.assertEqual('bar', fresh.get_config_stack().get('foo'))
 
675
 
 
676
    def test_set_from_config_get_from_config_stack(self):
 
677
        self.branch.lock_write()
 
678
        self.addCleanup(self.branch.unlock)
 
679
        self.branch.get_config().set_user_option('foo', 'bar')
 
680
        result = self.branch.get_config_stack().get('foo')
 
681
        # https://bugs.launchpad.net/bzr/+bug/948344
 
682
        self.expectFailure('BranchStack uses cache after set_user_option',
 
683
                           self.assertEqual, 'bar', result)
 
684
 
 
685
    def test_set_from_config_stack_get_from_config(self):
 
686
        self.branch.lock_write()
 
687
        self.addCleanup(self.branch.unlock)
 
688
        self.branch.get_config_stack().set('foo', 'bar')
 
689
        # Since the branch is locked, the option value won't be saved on disk
 
690
        # so mixing get() and get_user_option() is broken by design.
 
691
        self.assertEqual(None,
 
692
                         self.branch.get_config().get_user_option('foo'))
 
693
 
 
694
    def test_set_delays_write_when_branch_is_locked(self):
 
695
        self.branch.lock_write()
 
696
        self.addCleanup(self.branch.unlock)
 
697
        self.branch.get_config_stack().set('foo', 'bar')
 
698
        copy = _mod_branch.Branch.open(self.branch.base)
 
699
        result = copy.get_config_stack().get('foo')
 
700
        # Accessing from a different branch object is like accessing from a
 
701
        # different process: the option has not been saved yet and the new
 
702
        # value cannot be seen.
 
703
        self.assertIs(None, result)
 
704
 
556
705
 
557
706
class TestPullResult(tests.TestCase):
558
707
 
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
708
    def test_report_changed(self):
571
709
        r = _mod_branch.PullResult()
572
710
        r.old_revid = "old-revid"
573
711
        r.old_revno = 10
574
712
        r.new_revid = "new-revid"
575
713
        r.new_revno = 20
576
 
        f = StringIO()
 
714
        f = BytesIO()
577
715
        r.report(f)
578
716
        self.assertEqual("Now on revision 20.\n", f.getvalue())
 
717
        self.assertEqual("Now on revision 20.\n", f.getvalue())
579
718
 
580
719
    def test_report_unchanged(self):
581
720
        r = _mod_branch.PullResult()
582
721
        r.old_revid = "same-revid"
583
722
        r.new_revid = "same-revid"
584
 
        f = StringIO()
 
723
        f = BytesIO()
585
724
        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
 
 
 
725
        self.assertEqual("No revisions or tags to pull.\n", f.getvalue())