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
25
from StringIO import StringIO
27
27
from bzrlib import (
28
28
branch as _mod_branch,
40
class TestDefaultFormat(tests.TestCase):
35
from bzrlib.branch import (
39
BranchReferenceFormat,
45
_run_with_write_locked_target,
47
from bzrlib.bzrdir import (BzrDirMetaFormat1, BzrDirMeta1,
49
from bzrlib.errors import (NotBranchError,
52
UnsupportedFormatError,
55
from bzrlib.tests import TestCase, TestCaseWithTransport
56
from bzrlib.transport import get_transport
59
class TestDefaultFormat(TestCase):
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(),
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
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())
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())
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')
66
_mod_branch.format_registry.set_default(old_format)
67
self.assertEqual(old_format,
68
_mod_branch.format_registry.get_default())
71
class TestBranchFormat5(tests.TestCaseWithTransport):
84
BranchFormat.set_default_format(old_format)
85
self.assertEqual(old_format, BranchFormat.get_default_format())
88
class TestBranchFormat5(TestCaseWithTransport):
72
89
"""Tests specific to branch format 5"""
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)
104
self.assertIsDirectory('.bzr/branch/lock/held', t)
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
118
f.write('# comment\n')
92
122
branch = self.make_branch('.', format='knit')
93
123
branch.set_push_location('foo')
97
127
"push_location = foo\n"
98
128
"push_location:policy = norecurse\n" % local_path,
99
config.locations_config_filename())
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.
105
class SampleBranchFormat(_mod_branch.BranchFormatMetadir):
135
class SampleBranchFormat(BranchFormat):
106
136
"""A sample format
108
138
this format is initializable, unsupported to aid in testing the
109
139
open and open_downlevel routines.
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."
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'
124
152
def is_supported(self):
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."
132
# Demonstrating how lazy loading is often implemented:
133
# A constant string is created.
134
SampleSupportedBranchFormatString = "Sample supported branch format."
136
# And the format class can then reference the constant to avoid skew.
137
class SampleSupportedBranchFormat(_mod_branch.BranchFormatMetadir):
138
"""A sample supported format."""
141
def get_format_string(cls):
142
"""See BzrBranchFormat.get_format_string()."""
143
return SampleSupportedBranchFormatString
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())
150
def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
151
possible_transports=None):
152
return "opened supported branch."
155
class SampleExtraBranchFormat(_mod_branch.BranchFormat):
156
"""A sample format that is not usable in a metadir."""
158
def get_format_string(self):
159
# This format is not usable in a metadir.
162
def network_name(self):
163
# Network name always has to be provided.
166
def initialize(self, a_bzrdir, name=None):
167
raise NotImplementedError(self.initialize)
169
def open(self, transport, name=None, _found=False, ignore_fallbacks=False,
170
possible_transports=None):
171
raise NotImplementedError(self.open)
174
class TestBzrBranchFormat(tests.TestCaseWithTransport):
159
class TestBzrBranchFormat(TestCaseWithTransport):
175
160
"""Tests for the BzrBranchFormat facility."""
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")
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.")
201
def test_from_string(self):
202
self.assertIsInstance(
203
SampleBranchFormat.from_string("Sample branch format."),
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")
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,
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,
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, {})
232
class TestBranchFormatRegistry(tests.TestCase):
235
super(TestBranchFormatRegistry, self).setUp()
236
self.registry = _mod_branch.BranchFormatRegistry()
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())
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.")
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())
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())
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)
274
#Used by TestMetaDirBranchFormatFactory
275
FakeLazyFormat = None
278
class TestMetaDirBranchFormatFactory(tests.TestCase):
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())
285
def test_call_loads(self):
286
# __call__ is used by the network_format_registry interface to get a
288
global FakeLazyFormat
290
factory = _mod_branch.MetaDirBranchFormatFactory(None,
291
"bzrlib.tests.test_branch", "FakeLazyFormat")
292
self.assertRaises(AttributeError, factory)
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())
191
dir = bzrdir.BzrDirMetaFormat1().initialize(self.get_url())
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')
302
206
class TestBranch67(object):
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')
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())
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))],
253
builder.build_snapshot('bar', None, [], message='bar')
254
branch = builder.get_branch()
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'])
343
262
def do_checkout_test(self, lightweight=False):
344
263
tree = self.make_branch_and_tree('source',
502
436
branch.lock_write()
503
437
branch.set_reference_info('file-id', 'path2', 'location2')
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'))
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):
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
520
class TestBranchReference(tests.TestCaseWithTransport):
444
class TestBranchReference(TestCaseWithTransport):
521
445
"""Tests for the branch reference facility."""
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('.'))
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)
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))
550
class TestHooks(tests.TestCaseWithTransport):
473
class TestHooks(TestCase):
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)
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)
574
def test_post_branch_init_hook(self):
576
_mod_branch.Branch.hooks.install_named_hook('post_branch_init',
578
self.assertLength(0, calls)
579
branch = self.make_branch('a')
580
self.assertLength(1, calls)
582
self.assertIsInstance(params, _mod_branch.BranchInitHookParams)
583
self.assertTrue(hasattr(params, 'bzrdir'))
584
self.assertTrue(hasattr(params, 'branch'))
586
def test_post_branch_init_hook_repr(self):
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 ')
595
def test_post_switch_hook(self):
596
from bzrlib import switch
598
_mod_branch.Branch.hooks.install_named_hook('post_switch',
600
tree = self.make_branch_and_tree('branch-1')
601
self.build_tree(['branch-1/file-1'])
604
to_branch = tree.bzrdir.sprout('branch-2').open_branch()
605
self.build_tree(['branch-1/file-2'])
607
tree.remove('file-1')
609
checkout = tree.branch.create_checkout('checkout')
610
self.assertLength(0, calls)
611
switch.switch(checkout.bzrdir, to_branch)
612
self.assertLength(1, calls)
614
self.assertIsInstance(params, _mod_branch.SwitchHookParams)
615
self.assertTrue(hasattr(params, 'to_branch'))
616
self.assertTrue(hasattr(params, 'revision_id'))
619
class TestBranchOptions(tests.TestCaseWithTransport):
622
super(TestBranchOptions, self).setUp()
623
self.branch = self.make_branch('.')
624
self.config_stack = self.branch.get_config_stack()
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())
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')
644
def test_invalid_append_revisions_only(self):
645
"""Ensure warning is noted on invalid settings"""
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)
653
'Value "not-a-bool" is not valid for "append_revisions_only"',
656
def test_use_fresh_values(self):
657
copy = _mod_branch.Branch.open(self.branch.base)
660
copy.get_config_stack().set('foo', 'bar')
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'))
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)
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'))
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)
702
class TestPullResult(tests.TestCase):
494
class TestPullResult(TestCase):
496
def test_pull_result_to_int(self):
497
# to support old code, the pull result can be used as an int
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")
704
507
def test_report_changed(self):
705
r = _mod_branch.PullResult()
706
509
r.old_revid = "old-revid"
708
511
r.new_revid = "new-revid"
712
515
self.assertEqual("Now on revision 20.\n", f.getvalue())
713
self.assertEqual("Now on revision 20.\n", f.getvalue())
715
517
def test_report_unchanged(self):
716
r = _mod_branch.PullResult()
717
519
r.old_revid = "same-revid"
718
520
r.new_revid = "same-revid"
721
self.assertEqual("No revisions or tags to pull.\n", f.getvalue())
523
self.assertEqual("No revisions to pull.\n", f.getvalue())
526
class _StubLockable(object):
527
"""Helper for TestRunWithWriteLockedTarget."""
529
def __init__(self, calls, unlock_exc=None):
531
self.unlock_exc = unlock_exc
533
def lock_write(self):
534
self.calls.append('lock_write')
537
self.calls.append('unlock')
538
if self.unlock_exc is not None:
539
raise self.unlock_exc
542
class _ErrorFromCallable(Exception):
543
"""Helper for TestRunWithWriteLockedTarget."""
546
class _ErrorFromUnlock(Exception):
547
"""Helper for TestRunWithWriteLockedTarget."""
550
class TestRunWithWriteLockedTarget(TestCase):
551
"""Tests for _run_with_write_locked_target."""
557
def func_that_returns_ok(self):
558
self._calls.append('func called')
561
def func_that_raises(self):
562
self._calls.append('func called')
563
raise _ErrorFromCallable()
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)
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)
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)
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)