~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_branch.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-10-13 06:08:53 UTC
  • mfrom: (4737.1.1 merge-2.0-into-devel)
  • Revision ID: pqm@pqm.ubuntu.com-20091013060853-erk2aaj80fnkrv25
(andrew) Merge lp:bzr/2.0 into lp:bzr, including fixes for #322807,
        #389413, #402623 and documentation improvements.

Show diffs side-by-side

added added

removed removed

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