17
17
"""Tests for the Branch facility that are not interface tests.
19
For interface tests see tests/per_branch/*.py.
19
For interface tests see `tests/per_branch/*.py`.
21
21
For concrete class tests see this file, and for meta-branch tests
22
22
also see this file.
25
from cStringIO import StringIO
28
26
branch as _mod_branch,
27
bzrbranch as _mod_bzrbranch,
36
from ..branchfmt.fullhistory import (
40
from ..sixish import (
39
45
class TestDefaultFormat(tests.TestCase):
41
47
def test_default_format(self):
42
48
# update this if you change the default branch format
43
self.assertIsInstance(_mod_branch.BranchFormat.get_default_format(),
44
_mod_branch.BzrBranchFormat7)
49
self.assertIsInstance(_mod_branch.format_registry.get_default(),
50
_mod_bzrbranch.BzrBranchFormat7)
46
52
def test_default_format_is_same_as_bzrdir_default(self):
47
53
# XXX: it might be nice if there was only one place the default was
48
54
# set, but at the moment that's not true -- mbp 20070814 --
49
55
# https://bugs.launchpad.net/bzr/+bug/132376
51
_mod_branch.BranchFormat.get_default_format(),
57
_mod_branch.format_registry.get_default(),
52
58
bzrdir.BzrDirFormat.get_default_format().get_branch_format())
54
60
def test_get_set_default_format(self):
55
61
# set the format and then set it back again
56
old_format = _mod_branch.BranchFormat.get_default_format()
57
_mod_branch.BranchFormat.set_default_format(SampleBranchFormat())
62
old_format = _mod_branch.format_registry.get_default()
63
_mod_branch.format_registry.set_default(
59
66
# the default branch format is used by the meta dir format
60
67
# which is not the default bzrdir format at this point
107
103
"push_location = foo\n"
108
104
"push_location:policy = norecurse\n" % local_path,
105
config.locations_config_filename())
111
107
# TODO RBC 20051029 test getting a push location from a branch in a
112
108
# recursive section - that is, it appends the branch name.
115
class SampleBranchFormat(_mod_branch.BranchFormat):
111
class SampleBranchFormat(_mod_bzrbranch.BranchFormatMetadir):
116
112
"""A sample format
118
114
this format is initializable, unsupported to aid in testing the
119
115
open and open_downlevel routines.
122
def get_format_string(self):
119
def get_format_string(cls):
123
120
"""See BzrBranchFormat.get_format_string()."""
124
121
return "Sample branch format."
126
def initialize(self, a_bzrdir, name=None):
123
def initialize(self, a_controldir, name=None, repository=None,
124
append_revisions_only=None):
127
125
"""Format 4 branches cannot be created."""
128
t = a_bzrdir.get_branch_transport(self, name=name)
126
t = a_controldir.get_branch_transport(self, name=name)
129
127
t.put_bytes('format', self.get_format_string())
130
128
return 'A branch'
132
130
def is_supported(self):
135
def open(self, transport, name=None, _found=False, ignore_fallbacks=False):
133
def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
134
possible_transports=None):
136
135
return "opened branch."
138
# Demonstrating how lazy loading is often implemented:
139
# A constant string is created.
140
SampleSupportedBranchFormatString = "Sample supported branch format."
142
# And the format class can then reference the constant to avoid skew.
143
class SampleSupportedBranchFormat(_mod_bzrbranch.BranchFormatMetadir):
144
"""A sample supported format."""
147
def get_format_string(cls):
148
"""See BzrBranchFormat.get_format_string()."""
149
return SampleSupportedBranchFormatString
151
def initialize(self, a_controldir, name=None, append_revisions_only=None):
152
t = a_controldir.get_branch_transport(self, name=name)
153
t.put_bytes('format', self.get_format_string())
156
def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
157
possible_transports=None):
158
return "opened supported branch."
161
class SampleExtraBranchFormat(_mod_branch.BranchFormat):
162
"""A sample format that is not usable in a metadir."""
164
def get_format_string(self):
165
# This format is not usable in a metadir.
168
def network_name(self):
169
# Network name always has to be provided.
172
def initialize(self, a_controldir, name=None):
173
raise NotImplementedError(self.initialize)
175
def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
176
possible_transports=None):
177
raise NotImplementedError(self.open)
139
180
class TestBzrBranchFormat(tests.TestCaseWithTransport):
140
181
"""Tests for the BzrBranchFormat facility."""
148
189
dir = format._matchingbzrdir.initialize(url)
149
190
dir.create_repository()
150
191
format.initialize(dir)
151
found_format = _mod_branch.BranchFormat.find_format(dir)
152
self.failUnless(isinstance(found_format, format.__class__))
153
check_format(_mod_branch.BzrBranchFormat5(), "bar")
192
found_format = _mod_bzrbranch.BranchFormatMetadir.find_format(dir)
193
self.assertIsInstance(found_format, format.__class__)
194
check_format(BzrBranchFormat5(), "bar")
196
def test_from_string(self):
197
self.assertIsInstance(
198
SampleBranchFormat.from_string("Sample branch format."),
200
self.assertRaises(AssertionError,
201
SampleBranchFormat.from_string, "Different branch format.")
155
203
def test_find_format_not_branch(self):
156
204
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
157
205
self.assertRaises(errors.NotBranchError,
158
_mod_branch.BranchFormat.find_format,
206
_mod_bzrbranch.BranchFormatMetadir.find_format,
161
209
def test_find_format_unknown_format(self):
162
210
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
163
211
SampleBranchFormat().initialize(dir)
164
212
self.assertRaises(errors.UnknownFormatError,
165
_mod_branch.BranchFormat.find_format,
213
_mod_bzrbranch.BranchFormatMetadir.find_format,
216
def test_find_format_with_features(self):
217
tree = self.make_branch_and_tree('.', format='2a')
218
tree.branch.update_feature_flags({"name": "optional"})
219
found_format = _mod_bzrbranch.BranchFormatMetadir.find_format(tree.controldir)
220
self.assertIsInstance(found_format, _mod_bzrbranch.BranchFormatMetadir)
221
self.assertEqual(found_format.features.get("name"), "optional")
222
tree.branch.update_feature_flags({"name": None})
223
branch = _mod_branch.Branch.open('.')
224
self.assertEqual(branch._format.features, {})
227
class TestBranchFormatRegistry(tests.TestCase):
230
super(TestBranchFormatRegistry, self).setUp()
231
self.registry = _mod_branch.BranchFormatRegistry()
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())
168
239
def test_register_unregister_format(self):
169
240
format = SampleBranchFormat()
171
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
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
183
bzrdir.BzrDir.open(self.get_url()).open_branch(unsupported=True))
184
# unregister the format
185
_mod_branch.BranchFormat.unregister_format(format)
186
self.make_branch_and_tree('bar')
241
self.registry.register(format)
242
self.assertEqual(format,
243
self.registry.get("Sample branch format."))
244
self.registry.remove(format)
245
self.assertRaises(KeyError, self.registry.get,
246
"Sample branch format.")
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())
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())
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)
189
269
class TestBranch67(object):
211
291
def test_layout(self):
212
292
branch = self.make_branch('a', format=self.get_format_name())
213
self.failUnlessExists('a/.bzr/branch/last-revision')
214
self.failIfExists('a/.bzr/branch/revision-history')
215
self.failIfExists('a/.bzr/branch/references')
293
self.assertPathExists('a/.bzr/branch/last-revision')
294
self.assertPathDoesNotExist('a/.bzr/branch/revision-history')
295
self.assertPathDoesNotExist('a/.bzr/branch/references')
217
297
def test_config(self):
218
298
"""Ensure that all configuration data is stored in the branch"""
219
299
branch = self.make_branch('a', format=self.get_format_name())
220
branch.set_parent('http://bazaar-vcs.org')
221
self.failIfExists('a/.bzr/branch/parent')
222
self.assertEqual('http://bazaar-vcs.org', branch.get_parent())
223
branch.set_push_location('sftp://bazaar-vcs.org')
224
config = branch.get_config()._get_branch_data_config()
225
self.assertEqual('sftp://bazaar-vcs.org',
226
config.get_user_option('push_location'))
227
branch.set_bound_location('ftp://bazaar-vcs.org')
228
self.failIfExists('a/.bzr/branch/bound')
229
self.assertEqual('ftp://bazaar-vcs.org', branch.get_bound_location())
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))],
236
builder.build_snapshot('bar', None, [], message='bar')
237
branch = builder.get_branch()
239
self.addCleanup(branch.unlock)
240
branch.set_revision_history(['foo', 'bar'])
241
branch.set_revision_history(['foo'])
242
self.assertRaises(errors.NotLefthandHistory,
243
branch.set_revision_history, ['bar'])
300
branch.set_parent('http://example.com')
301
self.assertPathDoesNotExist('a/.bzr/branch/parent')
302
self.assertEqual('http://example.com', branch.get_parent())
303
branch.set_push_location('sftp://example.com')
304
conf = branch.get_config_stack()
305
self.assertEqual('sftp://example.com', conf.get('push_location'))
306
branch.set_bound_location('ftp://example.com')
307
self.assertPathDoesNotExist('a/.bzr/branch/bound')
308
self.assertEqual('ftp://example.com', branch.get_bound_location())
245
310
def do_checkout_test(self, lightweight=False):
246
311
tree = self.make_branch_and_tree('source',
425
474
self.assertEqual(('path3', 'location3'),
426
475
branch.get_reference_info('file-id'))
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):
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
428
487
class TestBranchReference(tests.TestCaseWithTransport):
429
488
"""Tests for the branch reference facility."""
431
490
def test_create_open_reference(self):
432
491
bzrdirformat = bzrdir.BzrDirMetaFormat1()
433
t = transport.get_transport(self.get_url('.'))
492
t = self.get_transport()
435
494
dir = bzrdirformat.initialize(self.get_url('repo'))
436
495
dir.create_repository()
437
496
target_branch = dir.create_branch()
438
497
t.mkdir('branch')
439
498
branch_dir = bzrdirformat.initialize(self.get_url('branch'))
440
made_branch = _mod_branch.BranchReferenceFormat().initialize(
499
made_branch = _mod_bzrbranch.BranchReferenceFormat().initialize(
441
500
branch_dir, target_branch=target_branch)
442
501
self.assertEqual(made_branch.base, target_branch.base)
443
502
opened_branch = branch_dir.open_branch()
444
503
self.assertEqual(opened_branch.base, target_branch.base)
446
505
def test_get_reference(self):
447
"""For a BranchReference, get_reference should reutrn the location."""
506
"""For a BranchReference, get_reference should return the location."""
448
507
branch = self.make_branch('target')
449
508
checkout = branch.create_checkout('checkout', lightweight=True)
450
reference_url = branch.bzrdir.root_transport.abspath('') + '/'
509
reference_url = branch.controldir.root_transport.abspath('') + '/'
451
510
# if the api for create_checkout changes to return different checkout types
452
511
# then this file read will fail.
453
512
self.assertFileEqual(reference_url, 'checkout/.bzr/branch/location')
454
513
self.assertEqual(reference_url,
455
_mod_branch.BranchReferenceFormat().get_reference(checkout.bzrdir))
514
_mod_bzrbranch.BranchReferenceFormat().get_reference(checkout.controldir))
458
517
class TestHooks(tests.TestCaseWithTransport):
550
617
self.check_append_revisions_only(None, 'not-a-bool')
551
618
self.assertLength(1, self.warnings)
552
619
self.assertEqual(
553
'Value "not-a-bool" is not a boolean for "append_revisions_only"',
620
'Value "not-a-bool" is not valid for "append_revisions_only"',
554
621
self.warnings[0])
623
def test_use_fresh_values(self):
624
copy = _mod_branch.Branch.open(self.branch.base)
627
copy.get_config_stack().set('foo', 'bar')
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'))
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)
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'))
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)
557
669
class TestPullResult(tests.TestCase):
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()
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")
570
671
def test_report_changed(self):
571
672
r = _mod_branch.PullResult()
572
673
r.old_revid = "old-revid"
574
675
r.new_revid = "new-revid"
578
679
self.assertEqual("Now on revision 20.\n", f.getvalue())
680
self.assertEqual("Now on revision 20.\n", f.getvalue())
580
682
def test_report_unchanged(self):
581
683
r = _mod_branch.PullResult()
582
684
r.old_revid = "same-revid"
583
685
r.new_revid = "same-revid"
586
self.assertEqual("No revisions to pull.\n", f.getvalue())
589
class _StubLockable(object):
590
"""Helper for TestRunWithWriteLockedTarget."""
592
def __init__(self, calls, unlock_exc=None):
594
self.unlock_exc = unlock_exc
596
def lock_write(self):
597
self.calls.append('lock_write')
600
self.calls.append('unlock')
601
if self.unlock_exc is not None:
602
raise self.unlock_exc
605
class _ErrorFromCallable(Exception):
606
"""Helper for TestRunWithWriteLockedTarget."""
609
class _ErrorFromUnlock(Exception):
610
"""Helper for TestRunWithWriteLockedTarget."""
613
class TestRunWithWriteLockedTarget(tests.TestCase):
614
"""Tests for _run_with_write_locked_target."""
617
tests.TestCase.setUp(self)
620
def func_that_returns_ok(self):
621
self._calls.append('func called')
624
def func_that_raises(self):
625
self._calls.append('func called')
626
raise _ErrorFromCallable()
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)
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)
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)
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)
688
self.assertEqual("No revisions or tags to pull.\n", f.getvalue())