1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
"""Tests for remote bzrdir/branch/repo/etc
19
These are proxy objects which act on remote objects by sending messages
20
through a smart client. The proxies are to be created when attempting to open
21
the object given a transport that supports smartserver rpc operations.
23
These tests correspond to tests.test_smart, which exercises the server side.
27
from cStringIO import StringIO
41
from bzrlib.branch import Branch
42
from bzrlib.bzrdir import BzrDir, BzrDirFormat
43
from bzrlib.remote import (
50
from bzrlib.revision import NULL_REVISION
51
from bzrlib.smart import server, medium
52
from bzrlib.smart.client import _SmartClient
53
from bzrlib.symbol_versioning import one_four
54
from bzrlib.tests import (
56
split_suite_by_condition,
59
from bzrlib.transport import get_transport, http
60
from bzrlib.transport.memory import MemoryTransport
61
from bzrlib.transport.remote import (
67
def load_tests(standard_tests, module, loader):
68
to_adapt, result = split_suite_by_condition(
69
standard_tests, condition_isinstance(BasicRemoteObjectTests))
70
smart_server_version_scenarios = [
72
{'transport_server': server.SmartTCPServer_for_testing_v2_only}),
74
{'transport_server': server.SmartTCPServer_for_testing})]
75
return multiply_tests(to_adapt, smart_server_version_scenarios, result)
78
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
81
super(BasicRemoteObjectTests, self).setUp()
82
self.transport = self.get_transport()
83
# make a branch that can be opened over the smart transport
84
self.local_wt = BzrDir.create_standalone_workingtree('.')
87
self.transport.disconnect()
88
tests.TestCaseWithTransport.tearDown(self)
90
def test_create_remote_bzrdir(self):
91
b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
92
self.assertIsInstance(b, BzrDir)
94
def test_open_remote_branch(self):
95
# open a standalone branch in the working directory
96
b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
97
branch = b.open_branch()
98
self.assertIsInstance(branch, Branch)
100
def test_remote_repository(self):
101
b = BzrDir.open_from_transport(self.transport)
102
repo = b.open_repository()
103
revid = u'\xc823123123'.encode('utf8')
104
self.assertFalse(repo.has_revision(revid))
105
self.local_wt.commit(message='test commit', rev_id=revid)
106
self.assertTrue(repo.has_revision(revid))
108
def test_remote_branch_revision_history(self):
109
b = BzrDir.open_from_transport(self.transport).open_branch()
110
self.assertEqual([], b.revision_history())
111
r1 = self.local_wt.commit('1st commit')
112
r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
113
self.assertEqual([r1, r2], b.revision_history())
115
def test_find_correct_format(self):
116
"""Should open a RemoteBzrDir over a RemoteTransport"""
117
fmt = BzrDirFormat.find_format(self.transport)
118
self.assertTrue(RemoteBzrDirFormat
119
in BzrDirFormat._control_server_formats)
120
self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
122
def test_open_detected_smart_format(self):
123
fmt = BzrDirFormat.find_format(self.transport)
124
d = fmt.open(self.transport)
125
self.assertIsInstance(d, BzrDir)
127
def test_remote_branch_repr(self):
128
b = BzrDir.open_from_transport(self.transport).open_branch()
129
self.assertStartsWith(str(b), 'RemoteBranch(')
131
def test_remote_branch_format_supports_stacking(self):
133
self.make_branch('unstackable', format='pack-0.92')
134
b = BzrDir.open_from_transport(t.clone('unstackable')).open_branch()
135
self.assertFalse(b._format.supports_stacking())
136
self.make_branch('stackable', format='1.9')
137
b = BzrDir.open_from_transport(t.clone('stackable')).open_branch()
138
self.assertTrue(b._format.supports_stacking())
140
def test_remote_repo_format_supports_external_references(self):
142
bd = self.make_bzrdir('unstackable', format='pack-0.92')
143
r = bd.create_repository()
144
self.assertFalse(r._format.supports_external_lookups)
145
r = BzrDir.open_from_transport(t.clone('unstackable')).open_repository()
146
self.assertFalse(r._format.supports_external_lookups)
147
bd = self.make_bzrdir('stackable', format='1.9')
148
r = bd.create_repository()
149
self.assertTrue(r._format.supports_external_lookups)
150
r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
151
self.assertTrue(r._format.supports_external_lookups)
154
class FakeProtocol(object):
155
"""Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
157
def __init__(self, body, fake_client):
159
self._body_buffer = None
160
self._fake_client = fake_client
162
def read_body_bytes(self, count=-1):
163
if self._body_buffer is None:
164
self._body_buffer = StringIO(self.body)
165
bytes = self._body_buffer.read(count)
166
if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
167
self._fake_client.expecting_body = False
170
def cancel_read_body(self):
171
self._fake_client.expecting_body = False
173
def read_streamed_body(self):
177
class FakeClient(_SmartClient):
178
"""Lookalike for _SmartClient allowing testing."""
180
def __init__(self, fake_medium_base='fake base'):
181
"""Create a FakeClient."""
184
self.expecting_body = False
185
# if non-None, this is the list of expected calls, with only the
186
# method name and arguments included. the body might be hard to
187
# compute so is not included. If a call is None, that call can
189
self._expected_calls = None
190
_SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
192
def add_expected_call(self, call_name, call_args, response_type,
193
response_args, response_body=None):
194
if self._expected_calls is None:
195
self._expected_calls = []
196
self._expected_calls.append((call_name, call_args))
197
self.responses.append((response_type, response_args, response_body))
199
def add_success_response(self, *args):
200
self.responses.append(('success', args, None))
202
def add_success_response_with_body(self, body, *args):
203
self.responses.append(('success', args, body))
204
if self._expected_calls is not None:
205
self._expected_calls.append(None)
207
def add_error_response(self, *args):
208
self.responses.append(('error', args))
210
def add_unknown_method_response(self, verb):
211
self.responses.append(('unknown', verb))
213
def finished_test(self):
214
if self._expected_calls:
215
raise AssertionError("%r finished but was still expecting %r"
216
% (self, self._expected_calls[0]))
218
def _get_next_response(self):
220
response_tuple = self.responses.pop(0)
221
except IndexError, e:
222
raise AssertionError("%r didn't expect any more calls"
224
if response_tuple[0] == 'unknown':
225
raise errors.UnknownSmartMethod(response_tuple[1])
226
elif response_tuple[0] == 'error':
227
raise errors.ErrorFromSmartServer(response_tuple[1])
228
return response_tuple
230
def _check_call(self, method, args):
231
if self._expected_calls is None:
232
# the test should be updated to say what it expects
235
next_call = self._expected_calls.pop(0)
237
raise AssertionError("%r didn't expect any more calls "
239
% (self, method, args,))
240
if next_call is None:
242
if method != next_call[0] or args != next_call[1]:
243
raise AssertionError("%r expected %r%r "
245
% (self, next_call[0], next_call[1], method, args,))
247
def call(self, method, *args):
248
self._check_call(method, args)
249
self._calls.append(('call', method, args))
250
return self._get_next_response()[1]
252
def call_expecting_body(self, method, *args):
253
self._check_call(method, args)
254
self._calls.append(('call_expecting_body', method, args))
255
result = self._get_next_response()
256
self.expecting_body = True
257
return result[1], FakeProtocol(result[2], self)
259
def call_with_body_bytes_expecting_body(self, method, args, body):
260
self._check_call(method, args)
261
self._calls.append(('call_with_body_bytes_expecting_body', method,
263
result = self._get_next_response()
264
self.expecting_body = True
265
return result[1], FakeProtocol(result[2], self)
267
def call_with_body_stream(self, args, stream):
268
# Explicitly consume the stream before checking for an error, because
269
# that's what happens a real medium.
270
stream = list(stream)
271
self._check_call(args[0], args[1:])
272
self._calls.append(('call_with_body_stream', args[0], args[1:], stream))
273
return self._get_next_response()[1]
276
class FakeMedium(medium.SmartClientMedium):
278
def __init__(self, client_calls, base):
279
medium.SmartClientMedium.__init__(self, base)
280
self._client_calls = client_calls
282
def disconnect(self):
283
self._client_calls.append(('disconnect medium',))
286
class TestVfsHas(tests.TestCase):
288
def test_unicode_path(self):
289
client = FakeClient('/')
290
client.add_success_response('yes',)
291
transport = RemoteTransport('bzr://localhost/', _client=client)
292
filename = u'/hell\u00d8'.encode('utf8')
293
result = transport.has(filename)
295
[('call', 'has', (filename,))],
297
self.assertTrue(result)
300
class TestRemote(tests.TestCaseWithMemoryTransport):
302
def get_branch_format(self):
303
reference_bzrdir_format = bzrdir.format_registry.get('default')()
304
return reference_bzrdir_format.get_branch_format()
306
def get_repo_format(self):
307
reference_bzrdir_format = bzrdir.format_registry.get('default')()
308
return reference_bzrdir_format.repository_format
310
def disable_verb(self, verb):
311
"""Disable a verb for one test."""
312
request_handlers = smart.request.request_handlers
313
orig_method = request_handlers.get(verb)
314
request_handlers.remove(verb)
316
request_handlers.register(verb, orig_method)
317
self.addCleanup(restoreVerb)
320
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
321
"""Tests for the behaviour of client_medium.remote_path_from_transport."""
323
def assertRemotePath(self, expected, client_base, transport_base):
324
"""Assert that the result of
325
SmartClientMedium.remote_path_from_transport is the expected value for
326
a given client_base and transport_base.
328
client_medium = medium.SmartClientMedium(client_base)
329
transport = get_transport(transport_base)
330
result = client_medium.remote_path_from_transport(transport)
331
self.assertEqual(expected, result)
333
def test_remote_path_from_transport(self):
334
"""SmartClientMedium.remote_path_from_transport calculates a URL for
335
the given transport relative to the root of the client base URL.
337
self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
338
self.assertRemotePath(
339
'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
341
def assertRemotePathHTTP(self, expected, transport_base, relpath):
342
"""Assert that the result of
343
HttpTransportBase.remote_path_from_transport is the expected value for
344
a given transport_base and relpath of that transport. (Note that
345
HttpTransportBase is a subclass of SmartClientMedium)
347
base_transport = get_transport(transport_base)
348
client_medium = base_transport.get_smart_medium()
349
cloned_transport = base_transport.clone(relpath)
350
result = client_medium.remote_path_from_transport(cloned_transport)
351
self.assertEqual(expected, result)
353
def test_remote_path_from_transport_http(self):
354
"""Remote paths for HTTP transports are calculated differently to other
355
transports. They are just relative to the client base, not the root
356
directory of the host.
358
for scheme in ['http:', 'https:', 'bzr+http:', 'bzr+https:']:
359
self.assertRemotePathHTTP(
360
'../xyz/', scheme + '//host/path', '../xyz/')
361
self.assertRemotePathHTTP(
362
'xyz/', scheme + '//host/path', 'xyz/')
365
class Test_ClientMedium_remote_is_at_least(tests.TestCase):
366
"""Tests for the behaviour of client_medium.remote_is_at_least."""
368
def test_initially_unlimited(self):
369
"""A fresh medium assumes that the remote side supports all
372
client_medium = medium.SmartClientMedium('dummy base')
373
self.assertFalse(client_medium._is_remote_before((99, 99)))
375
def test__remember_remote_is_before(self):
376
"""Calling _remember_remote_is_before ratchets down the known remote
379
client_medium = medium.SmartClientMedium('dummy base')
380
# Mark the remote side as being less than 1.6. The remote side may
382
client_medium._remember_remote_is_before((1, 6))
383
self.assertTrue(client_medium._is_remote_before((1, 6)))
384
self.assertFalse(client_medium._is_remote_before((1, 5)))
385
# Calling _remember_remote_is_before again with a lower value works.
386
client_medium._remember_remote_is_before((1, 5))
387
self.assertTrue(client_medium._is_remote_before((1, 5)))
388
# You cannot call _remember_remote_is_before with a larger value.
390
AssertionError, client_medium._remember_remote_is_before, (1, 9))
393
class TestBzrDirCloningMetaDir(TestRemote):
395
def test_backwards_compat(self):
396
self.setup_smart_server_with_call_log()
397
a_dir = self.make_bzrdir('.')
398
self.reset_smart_call_log()
399
verb = 'BzrDir.cloning_metadir'
400
self.disable_verb(verb)
401
format = a_dir.cloning_metadir()
402
call_count = len([call for call in self.hpss_calls if
403
call.call.method == verb])
404
self.assertEqual(1, call_count)
406
def test_current_server(self):
407
transport = self.get_transport('.')
408
transport = transport.clone('quack')
409
self.make_bzrdir('quack')
410
client = FakeClient(transport.base)
411
reference_bzrdir_format = bzrdir.format_registry.get('default')()
412
control_name = reference_bzrdir_format.network_name()
413
client.add_expected_call(
414
'BzrDir.cloning_metadir', ('quack/', 'False'),
415
'success', (control_name, '', ('branch', ''))),
416
a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
418
result = a_bzrdir.cloning_metadir()
419
# We should have got a reference control dir with default branch and
420
# repository formats.
421
# This pokes a little, just to be sure.
422
self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
423
self.assertEqual(None, result._repository_format)
424
self.assertEqual(None, result._branch_format)
425
client.finished_test()
428
class TestBzrDirOpenBranch(TestRemote):
430
def test_backwards_compat(self):
431
self.setup_smart_server_with_call_log()
432
self.make_branch('.')
433
a_dir = BzrDir.open(self.get_url('.'))
434
self.reset_smart_call_log()
435
verb = 'BzrDir.open_branchV2'
436
self.disable_verb(verb)
437
format = a_dir.open_branch()
438
call_count = len([call for call in self.hpss_calls if
439
call.call.method == verb])
440
self.assertEqual(1, call_count)
442
def test_branch_present(self):
443
reference_format = self.get_repo_format()
444
network_name = reference_format.network_name()
445
branch_network_name = self.get_branch_format().network_name()
446
transport = MemoryTransport()
447
transport.mkdir('quack')
448
transport = transport.clone('quack')
449
client = FakeClient(transport.base)
450
client.add_expected_call(
451
'BzrDir.open_branchV2', ('quack/',),
452
'success', ('branch', branch_network_name))
453
client.add_expected_call(
454
'BzrDir.find_repositoryV3', ('quack/',),
455
'success', ('ok', '', 'no', 'no', 'no', network_name))
456
client.add_expected_call(
457
'Branch.get_stacked_on_url', ('quack/',),
458
'error', ('NotStacked',))
459
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
461
result = bzrdir.open_branch()
462
self.assertIsInstance(result, RemoteBranch)
463
self.assertEqual(bzrdir, result.bzrdir)
464
client.finished_test()
466
def test_branch_missing(self):
467
transport = MemoryTransport()
468
transport.mkdir('quack')
469
transport = transport.clone('quack')
470
client = FakeClient(transport.base)
471
client.add_error_response('nobranch')
472
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
474
self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
476
[('call', 'BzrDir.open_branchV2', ('quack/',))],
479
def test__get_tree_branch(self):
480
# _get_tree_branch is a form of open_branch, but it should only ask for
481
# branch opening, not any other network requests.
484
calls.append("Called")
486
transport = MemoryTransport()
487
# no requests on the network - catches other api calls being made.
488
client = FakeClient(transport.base)
489
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
491
# patch the open_branch call to record that it was called.
492
bzrdir.open_branch = open_branch
493
self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
494
self.assertEqual(["Called"], calls)
495
self.assertEqual([], client._calls)
497
def test_url_quoting_of_path(self):
498
# Relpaths on the wire should not be URL-escaped. So "~" should be
499
# transmitted as "~", not "%7E".
500
transport = RemoteTCPTransport('bzr://localhost/~hello/')
501
client = FakeClient(transport.base)
502
reference_format = self.get_repo_format()
503
network_name = reference_format.network_name()
504
branch_network_name = self.get_branch_format().network_name()
505
client.add_expected_call(
506
'BzrDir.open_branchV2', ('~hello/',),
507
'success', ('branch', branch_network_name))
508
client.add_expected_call(
509
'BzrDir.find_repositoryV3', ('~hello/',),
510
'success', ('ok', '', 'no', 'no', 'no', network_name))
511
client.add_expected_call(
512
'Branch.get_stacked_on_url', ('~hello/',),
513
'error', ('NotStacked',))
514
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
516
result = bzrdir.open_branch()
517
client.finished_test()
519
def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
520
reference_format = self.get_repo_format()
521
network_name = reference_format.network_name()
522
transport = MemoryTransport()
523
transport.mkdir('quack')
524
transport = transport.clone('quack')
526
rich_response = 'yes'
530
subtree_response = 'yes'
532
subtree_response = 'no'
533
client = FakeClient(transport.base)
534
client.add_success_response(
535
'ok', '', rich_response, subtree_response, external_lookup,
537
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
539
result = bzrdir.open_repository()
541
[('call', 'BzrDir.find_repositoryV3', ('quack/',))],
543
self.assertIsInstance(result, RemoteRepository)
544
self.assertEqual(bzrdir, result.bzrdir)
545
self.assertEqual(rich_root, result._format.rich_root_data)
546
self.assertEqual(subtrees, result._format.supports_tree_reference)
548
def test_open_repository_sets_format_attributes(self):
549
self.check_open_repository(True, True)
550
self.check_open_repository(False, True)
551
self.check_open_repository(True, False)
552
self.check_open_repository(False, False)
553
self.check_open_repository(False, False, 'yes')
555
def test_old_server(self):
556
"""RemoteBzrDirFormat should fail to probe if the server version is too
559
self.assertRaises(errors.NotBranchError,
560
RemoteBzrDirFormat.probe_transport, OldServerTransport())
563
class TestBzrDirCreateBranch(TestRemote):
565
def test_backwards_compat(self):
566
self.setup_smart_server_with_call_log()
567
repo = self.make_repository('.')
568
self.reset_smart_call_log()
569
self.disable_verb('BzrDir.create_branch')
570
branch = repo.bzrdir.create_branch()
571
create_branch_call_count = len([call for call in self.hpss_calls if
572
call.call.method == 'BzrDir.create_branch'])
573
self.assertEqual(1, create_branch_call_count)
575
def test_current_server(self):
576
transport = self.get_transport('.')
577
transport = transport.clone('quack')
578
self.make_repository('quack')
579
client = FakeClient(transport.base)
580
reference_bzrdir_format = bzrdir.format_registry.get('default')()
581
reference_format = reference_bzrdir_format.get_branch_format()
582
network_name = reference_format.network_name()
583
reference_repo_fmt = reference_bzrdir_format.repository_format
584
reference_repo_name = reference_repo_fmt.network_name()
585
client.add_expected_call(
586
'BzrDir.create_branch', ('quack/', network_name),
587
'success', ('ok', network_name, '', 'no', 'no', 'yes',
588
reference_repo_name))
589
a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
591
branch = a_bzrdir.create_branch()
592
# We should have got a remote branch
593
self.assertIsInstance(branch, remote.RemoteBranch)
594
# its format should have the settings from the response
595
format = branch._format
596
self.assertEqual(network_name, format.network_name())
599
class TestBzrDirCreateRepository(TestRemote):
601
def test_backwards_compat(self):
602
self.setup_smart_server_with_call_log()
603
bzrdir = self.make_bzrdir('.')
604
self.reset_smart_call_log()
605
self.disable_verb('BzrDir.create_repository')
606
repo = bzrdir.create_repository()
607
create_repo_call_count = len([call for call in self.hpss_calls if
608
call.call.method == 'BzrDir.create_repository'])
609
self.assertEqual(1, create_repo_call_count)
611
def test_current_server(self):
612
transport = self.get_transport('.')
613
transport = transport.clone('quack')
614
self.make_bzrdir('quack')
615
client = FakeClient(transport.base)
616
reference_bzrdir_format = bzrdir.format_registry.get('default')()
617
reference_format = reference_bzrdir_format.repository_format
618
network_name = reference_format.network_name()
619
client.add_expected_call(
620
'BzrDir.create_repository', ('quack/',
621
'Bazaar pack repository format 1 (needs bzr 0.92)\n', 'False'),
622
'success', ('ok', 'no', 'no', 'no', network_name))
623
a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
625
repo = a_bzrdir.create_repository()
626
# We should have got a remote repository
627
self.assertIsInstance(repo, remote.RemoteRepository)
628
# its format should have the settings from the response
629
format = repo._format
630
self.assertFalse(format.rich_root_data)
631
self.assertFalse(format.supports_tree_reference)
632
self.assertFalse(format.supports_external_lookups)
633
self.assertEqual(network_name, format.network_name())
636
class TestBzrDirOpenRepository(TestRemote):
638
def test_backwards_compat_1_2_3(self):
639
# fallback all the way to the first version.
640
reference_format = self.get_repo_format()
641
network_name = reference_format.network_name()
642
client = FakeClient('bzr://example.com/')
643
client.add_unknown_method_response('BzrDir.find_repositoryV3')
644
client.add_unknown_method_response('BzrDir.find_repositoryV2')
645
client.add_success_response('ok', '', 'no', 'no')
646
# A real repository instance will be created to determine the network
648
client.add_success_response_with_body(
649
"Bazaar-NG meta directory, format 1\n", 'ok')
650
client.add_success_response_with_body(
651
reference_format.get_format_string(), 'ok')
652
# PackRepository wants to do a stat
653
client.add_success_response('stat', '0', '65535')
654
remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
656
bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
658
repo = bzrdir.open_repository()
660
[('call', 'BzrDir.find_repositoryV3', ('quack/',)),
661
('call', 'BzrDir.find_repositoryV2', ('quack/',)),
662
('call', 'BzrDir.find_repository', ('quack/',)),
663
('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
664
('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
665
('call', 'stat', ('/quack/.bzr/repository',)),
668
self.assertEqual(network_name, repo._format.network_name())
670
def test_backwards_compat_2(self):
671
# fallback to find_repositoryV2
672
reference_format = self.get_repo_format()
673
network_name = reference_format.network_name()
674
client = FakeClient('bzr://example.com/')
675
client.add_unknown_method_response('BzrDir.find_repositoryV3')
676
client.add_success_response('ok', '', 'no', 'no', 'no')
677
# A real repository instance will be created to determine the network
679
client.add_success_response_with_body(
680
"Bazaar-NG meta directory, format 1\n", 'ok')
681
client.add_success_response_with_body(
682
reference_format.get_format_string(), 'ok')
683
# PackRepository wants to do a stat
684
client.add_success_response('stat', '0', '65535')
685
remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
687
bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
689
repo = bzrdir.open_repository()
691
[('call', 'BzrDir.find_repositoryV3', ('quack/',)),
692
('call', 'BzrDir.find_repositoryV2', ('quack/',)),
693
('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
694
('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
695
('call', 'stat', ('/quack/.bzr/repository',)),
698
self.assertEqual(network_name, repo._format.network_name())
700
def test_current_server(self):
701
reference_format = self.get_repo_format()
702
network_name = reference_format.network_name()
703
transport = MemoryTransport()
704
transport.mkdir('quack')
705
transport = transport.clone('quack')
706
client = FakeClient(transport.base)
707
client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
708
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
710
repo = bzrdir.open_repository()
712
[('call', 'BzrDir.find_repositoryV3', ('quack/',))],
714
self.assertEqual(network_name, repo._format.network_name())
717
class OldSmartClient(object):
718
"""A fake smart client for test_old_version that just returns a version one
719
response to the 'hello' (query version) command.
722
def get_request(self):
723
input_file = StringIO('ok\x011\n')
724
output_file = StringIO()
725
client_medium = medium.SmartSimplePipesClientMedium(
726
input_file, output_file)
727
return medium.SmartClientStreamMediumRequest(client_medium)
729
def protocol_version(self):
733
class OldServerTransport(object):
734
"""A fake transport for test_old_server that reports it's smart server
735
protocol version as version one.
741
def get_smart_client(self):
742
return OldSmartClient()
745
class RemoteBranchTestCase(TestRemote):
747
def make_remote_branch(self, transport, client):
748
"""Make a RemoteBranch using 'client' as its _SmartClient.
750
A RemoteBzrDir and RemoteRepository will also be created to fill out
751
the RemoteBranch, albeit with stub values for some of their attributes.
753
# we do not want bzrdir to make any remote calls, so use False as its
754
# _client. If it tries to make a remote call, this will fail
756
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
758
repo = RemoteRepository(bzrdir, None, _client=client)
759
branch_format = self.get_branch_format()
760
format = RemoteBranchFormat(network_name=branch_format.network_name())
761
return RemoteBranch(bzrdir, repo, _client=client, format=format)
764
class TestBranchGetParent(RemoteBranchTestCase):
766
def test_no_parent(self):
767
# in an empty branch we decode the response properly
768
transport = MemoryTransport()
769
client = FakeClient(transport.base)
770
client.add_expected_call(
771
'Branch.get_stacked_on_url', ('quack/',),
772
'error', ('NotStacked',))
773
client.add_expected_call(
774
'Branch.get_parent', ('quack/',),
776
transport.mkdir('quack')
777
transport = transport.clone('quack')
778
branch = self.make_remote_branch(transport, client)
779
result = branch.get_parent()
780
client.finished_test()
781
self.assertEqual(None, result)
783
def test_parent_relative(self):
784
transport = MemoryTransport()
785
client = FakeClient(transport.base)
786
client.add_expected_call(
787
'Branch.get_stacked_on_url', ('kwaak/',),
788
'error', ('NotStacked',))
789
client.add_expected_call(
790
'Branch.get_parent', ('kwaak/',),
791
'success', ('../foo/',))
792
transport.mkdir('kwaak')
793
transport = transport.clone('kwaak')
794
branch = self.make_remote_branch(transport, client)
795
result = branch.get_parent()
796
self.assertEqual(transport.clone('../foo').base, result)
798
def test_parent_absolute(self):
799
transport = MemoryTransport()
800
client = FakeClient(transport.base)
801
client.add_expected_call(
802
'Branch.get_stacked_on_url', ('kwaak/',),
803
'error', ('NotStacked',))
804
client.add_expected_call(
805
'Branch.get_parent', ('kwaak/',),
806
'success', ('http://foo/',))
807
transport.mkdir('kwaak')
808
transport = transport.clone('kwaak')
809
branch = self.make_remote_branch(transport, client)
810
result = branch.get_parent()
811
self.assertEqual('http://foo/', result)
814
class TestBranchGetTagsBytes(RemoteBranchTestCase):
816
def test_backwards_compat(self):
817
self.setup_smart_server_with_call_log()
818
branch = self.make_branch('.')
819
self.reset_smart_call_log()
820
verb = 'Branch.get_tags_bytes'
821
self.disable_verb(verb)
822
branch.tags.get_tag_dict()
823
call_count = len([call for call in self.hpss_calls if
824
call.call.method == verb])
825
self.assertEqual(1, call_count)
827
def test_trivial(self):
828
transport = MemoryTransport()
829
client = FakeClient(transport.base)
830
client.add_expected_call(
831
'Branch.get_stacked_on_url', ('quack/',),
832
'error', ('NotStacked',))
833
client.add_expected_call(
834
'Branch.get_tags_bytes', ('quack/',),
836
transport.mkdir('quack')
837
transport = transport.clone('quack')
838
branch = self.make_remote_branch(transport, client)
839
result = branch.tags.get_tag_dict()
840
client.finished_test()
841
self.assertEqual({}, result)
844
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
846
def test_empty_branch(self):
847
# in an empty branch we decode the response properly
848
transport = MemoryTransport()
849
client = FakeClient(transport.base)
850
client.add_expected_call(
851
'Branch.get_stacked_on_url', ('quack/',),
852
'error', ('NotStacked',))
853
client.add_expected_call(
854
'Branch.last_revision_info', ('quack/',),
855
'success', ('ok', '0', 'null:'))
856
transport.mkdir('quack')
857
transport = transport.clone('quack')
858
branch = self.make_remote_branch(transport, client)
859
result = branch.last_revision_info()
860
client.finished_test()
861
self.assertEqual((0, NULL_REVISION), result)
863
def test_non_empty_branch(self):
864
# in a non-empty branch we also decode the response properly
865
revid = u'\xc8'.encode('utf8')
866
transport = MemoryTransport()
867
client = FakeClient(transport.base)
868
client.add_expected_call(
869
'Branch.get_stacked_on_url', ('kwaak/',),
870
'error', ('NotStacked',))
871
client.add_expected_call(
872
'Branch.last_revision_info', ('kwaak/',),
873
'success', ('ok', '2', revid))
874
transport.mkdir('kwaak')
875
transport = transport.clone('kwaak')
876
branch = self.make_remote_branch(transport, client)
877
result = branch.last_revision_info()
878
self.assertEqual((2, revid), result)
881
class TestBranch_get_stacked_on_url(TestRemote):
882
"""Test Branch._get_stacked_on_url rpc"""
884
def test_get_stacked_on_invalid_url(self):
885
# test that asking for a stacked on url the server can't access works.
886
# This isn't perfect, but then as we're in the same process there
887
# really isn't anything we can do to be 100% sure that the server
888
# doesn't just open in - this test probably needs to be rewritten using
889
# a spawn()ed server.
890
stacked_branch = self.make_branch('stacked', format='1.9')
891
memory_branch = self.make_branch('base', format='1.9')
892
vfs_url = self.get_vfs_only_url('base')
893
stacked_branch.set_stacked_on_url(vfs_url)
894
transport = stacked_branch.bzrdir.root_transport
895
client = FakeClient(transport.base)
896
client.add_expected_call(
897
'Branch.get_stacked_on_url', ('stacked/',),
898
'success', ('ok', vfs_url))
899
# XXX: Multiple calls are bad, this second call documents what is
901
client.add_expected_call(
902
'Branch.get_stacked_on_url', ('stacked/',),
903
'success', ('ok', vfs_url))
904
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
906
branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, None),
908
result = branch.get_stacked_on_url()
909
self.assertEqual(vfs_url, result)
911
def test_backwards_compatible(self):
912
# like with bzr1.6 with no Branch.get_stacked_on_url rpc
913
base_branch = self.make_branch('base', format='1.6')
914
stacked_branch = self.make_branch('stacked', format='1.6')
915
stacked_branch.set_stacked_on_url('../base')
916
client = FakeClient(self.get_url())
917
branch_network_name = self.get_branch_format().network_name()
918
client.add_expected_call(
919
'BzrDir.open_branchV2', ('stacked/',),
920
'success', ('branch', branch_network_name))
921
client.add_expected_call(
922
'BzrDir.find_repositoryV3', ('stacked/',),
923
'success', ('ok', '', 'no', 'no', 'no',
924
stacked_branch.repository._format.network_name()))
925
# called twice, once from constructor and then again by us
926
client.add_expected_call(
927
'Branch.get_stacked_on_url', ('stacked/',),
928
'unknown', ('Branch.get_stacked_on_url',))
929
client.add_expected_call(
930
'Branch.get_stacked_on_url', ('stacked/',),
931
'unknown', ('Branch.get_stacked_on_url',))
932
# this will also do vfs access, but that goes direct to the transport
933
# and isn't seen by the FakeClient.
934
bzrdir = RemoteBzrDir(self.get_transport('stacked'),
935
remote.RemoteBzrDirFormat(), _client=client)
936
branch = bzrdir.open_branch()
937
result = branch.get_stacked_on_url()
938
self.assertEqual('../base', result)
939
client.finished_test()
940
# it's in the fallback list both for the RemoteRepository and its vfs
942
self.assertEqual(1, len(branch.repository._fallback_repositories))
944
len(branch.repository._real_repository._fallback_repositories))
946
def test_get_stacked_on_real_branch(self):
947
base_branch = self.make_branch('base', format='1.6')
948
stacked_branch = self.make_branch('stacked', format='1.6')
949
stacked_branch.set_stacked_on_url('../base')
950
reference_format = self.get_repo_format()
951
network_name = reference_format.network_name()
952
client = FakeClient(self.get_url())
953
branch_network_name = self.get_branch_format().network_name()
954
client.add_expected_call(
955
'BzrDir.open_branchV2', ('stacked/',),
956
'success', ('branch', branch_network_name))
957
client.add_expected_call(
958
'BzrDir.find_repositoryV3', ('stacked/',),
959
'success', ('ok', '', 'no', 'no', 'no', network_name))
960
# called twice, once from constructor and then again by us
961
client.add_expected_call(
962
'Branch.get_stacked_on_url', ('stacked/',),
963
'success', ('ok', '../base'))
964
client.add_expected_call(
965
'Branch.get_stacked_on_url', ('stacked/',),
966
'success', ('ok', '../base'))
967
bzrdir = RemoteBzrDir(self.get_transport('stacked'),
968
remote.RemoteBzrDirFormat(), _client=client)
969
branch = bzrdir.open_branch()
970
result = branch.get_stacked_on_url()
971
self.assertEqual('../base', result)
972
client.finished_test()
973
# it's in the fallback list both for the RemoteRepository and its vfs
975
self.assertEqual(1, len(branch.repository._fallback_repositories))
977
len(branch.repository._real_repository._fallback_repositories))
980
class TestBranchSetLastRevision(RemoteBranchTestCase):
982
def test_set_empty(self):
983
# set_revision_history([]) is translated to calling
984
# Branch.set_last_revision(path, '') on the wire.
985
transport = MemoryTransport()
986
transport.mkdir('branch')
987
transport = transport.clone('branch')
989
client = FakeClient(transport.base)
990
client.add_expected_call(
991
'Branch.get_stacked_on_url', ('branch/',),
992
'error', ('NotStacked',))
993
client.add_expected_call(
994
'Branch.lock_write', ('branch/', '', ''),
995
'success', ('ok', 'branch token', 'repo token'))
996
client.add_expected_call(
997
'Branch.last_revision_info',
999
'success', ('ok', '0', 'null:'))
1000
client.add_expected_call(
1001
'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
1003
client.add_expected_call(
1004
'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1006
branch = self.make_remote_branch(transport, client)
1007
# This is a hack to work around the problem that RemoteBranch currently
1008
# unnecessarily invokes _ensure_real upon a call to lock_write.
1009
branch._ensure_real = lambda: None
1011
result = branch.set_revision_history([])
1013
self.assertEqual(None, result)
1014
client.finished_test()
1016
def test_set_nonempty(self):
1017
# set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
1018
# Branch.set_last_revision(path, rev-idN) on the wire.
1019
transport = MemoryTransport()
1020
transport.mkdir('branch')
1021
transport = transport.clone('branch')
1023
client = FakeClient(transport.base)
1024
client.add_expected_call(
1025
'Branch.get_stacked_on_url', ('branch/',),
1026
'error', ('NotStacked',))
1027
client.add_expected_call(
1028
'Branch.lock_write', ('branch/', '', ''),
1029
'success', ('ok', 'branch token', 'repo token'))
1030
client.add_expected_call(
1031
'Branch.last_revision_info',
1033
'success', ('ok', '0', 'null:'))
1035
encoded_body = bz2.compress('\n'.join(lines))
1036
client.add_success_response_with_body(encoded_body, 'ok')
1037
client.add_expected_call(
1038
'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
1040
client.add_expected_call(
1041
'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1043
branch = self.make_remote_branch(transport, client)
1044
# This is a hack to work around the problem that RemoteBranch currently
1045
# unnecessarily invokes _ensure_real upon a call to lock_write.
1046
branch._ensure_real = lambda: None
1047
# Lock the branch, reset the record of remote calls.
1049
result = branch.set_revision_history(['rev-id1', 'rev-id2'])
1051
self.assertEqual(None, result)
1052
client.finished_test()
1054
def test_no_such_revision(self):
1055
transport = MemoryTransport()
1056
transport.mkdir('branch')
1057
transport = transport.clone('branch')
1058
# A response of 'NoSuchRevision' is translated into an exception.
1059
client = FakeClient(transport.base)
1060
client.add_expected_call(
1061
'Branch.get_stacked_on_url', ('branch/',),
1062
'error', ('NotStacked',))
1063
client.add_expected_call(
1064
'Branch.lock_write', ('branch/', '', ''),
1065
'success', ('ok', 'branch token', 'repo token'))
1066
client.add_expected_call(
1067
'Branch.last_revision_info',
1069
'success', ('ok', '0', 'null:'))
1070
# get_graph calls to construct the revision history, for the set_rh
1073
encoded_body = bz2.compress('\n'.join(lines))
1074
client.add_success_response_with_body(encoded_body, 'ok')
1075
client.add_expected_call(
1076
'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1077
'error', ('NoSuchRevision', 'rev-id'))
1078
client.add_expected_call(
1079
'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1082
branch = self.make_remote_branch(transport, client)
1085
errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
1087
client.finished_test()
1089
def test_tip_change_rejected(self):
1090
"""TipChangeRejected responses cause a TipChangeRejected exception to
1093
transport = MemoryTransport()
1094
transport.mkdir('branch')
1095
transport = transport.clone('branch')
1096
client = FakeClient(transport.base)
1097
rejection_msg_unicode = u'rejection message\N{INTERROBANG}'
1098
rejection_msg_utf8 = rejection_msg_unicode.encode('utf8')
1099
client.add_expected_call(
1100
'Branch.get_stacked_on_url', ('branch/',),
1101
'error', ('NotStacked',))
1102
client.add_expected_call(
1103
'Branch.lock_write', ('branch/', '', ''),
1104
'success', ('ok', 'branch token', 'repo token'))
1105
client.add_expected_call(
1106
'Branch.last_revision_info',
1108
'success', ('ok', '0', 'null:'))
1110
encoded_body = bz2.compress('\n'.join(lines))
1111
client.add_success_response_with_body(encoded_body, 'ok')
1112
client.add_expected_call(
1113
'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1114
'error', ('TipChangeRejected', rejection_msg_utf8))
1115
client.add_expected_call(
1116
'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1118
branch = self.make_remote_branch(transport, client)
1119
branch._ensure_real = lambda: None
1121
# The 'TipChangeRejected' error response triggered by calling
1122
# set_revision_history causes a TipChangeRejected exception.
1123
err = self.assertRaises(
1124
errors.TipChangeRejected, branch.set_revision_history, ['rev-id'])
1125
# The UTF-8 message from the response has been decoded into a unicode
1127
self.assertIsInstance(err.msg, unicode)
1128
self.assertEqual(rejection_msg_unicode, err.msg)
1130
client.finished_test()
1133
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
1135
def test_set_last_revision_info(self):
1136
# set_last_revision_info(num, 'rev-id') is translated to calling
1137
# Branch.set_last_revision_info(num, 'rev-id') on the wire.
1138
transport = MemoryTransport()
1139
transport.mkdir('branch')
1140
transport = transport.clone('branch')
1141
client = FakeClient(transport.base)
1142
# get_stacked_on_url
1143
client.add_error_response('NotStacked')
1145
client.add_success_response('ok', 'branch token', 'repo token')
1146
# query the current revision
1147
client.add_success_response('ok', '0', 'null:')
1149
client.add_success_response('ok')
1151
client.add_success_response('ok')
1153
branch = self.make_remote_branch(transport, client)
1154
# Lock the branch, reset the record of remote calls.
1157
result = branch.set_last_revision_info(1234, 'a-revision-id')
1159
[('call', 'Branch.last_revision_info', ('branch/',)),
1160
('call', 'Branch.set_last_revision_info',
1161
('branch/', 'branch token', 'repo token',
1162
'1234', 'a-revision-id'))],
1164
self.assertEqual(None, result)
1166
def test_no_such_revision(self):
1167
# A response of 'NoSuchRevision' is translated into an exception.
1168
transport = MemoryTransport()
1169
transport.mkdir('branch')
1170
transport = transport.clone('branch')
1171
client = FakeClient(transport.base)
1172
# get_stacked_on_url
1173
client.add_error_response('NotStacked')
1175
client.add_success_response('ok', 'branch token', 'repo token')
1177
client.add_error_response('NoSuchRevision', 'revid')
1179
client.add_success_response('ok')
1181
branch = self.make_remote_branch(transport, client)
1182
# Lock the branch, reset the record of remote calls.
1187
errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1190
def lock_remote_branch(self, branch):
1191
"""Trick a RemoteBranch into thinking it is locked."""
1192
branch._lock_mode = 'w'
1193
branch._lock_count = 2
1194
branch._lock_token = 'branch token'
1195
branch._repo_lock_token = 'repo token'
1196
branch.repository._lock_mode = 'w'
1197
branch.repository._lock_count = 2
1198
branch.repository._lock_token = 'repo token'
1200
def test_backwards_compatibility(self):
1201
"""If the server does not support the Branch.set_last_revision_info
1202
verb (which is new in 1.4), then the client falls back to VFS methods.
1204
# This test is a little messy. Unlike most tests in this file, it
1205
# doesn't purely test what a Remote* object sends over the wire, and
1206
# how it reacts to responses from the wire. It instead relies partly
1207
# on asserting that the RemoteBranch will call
1208
# self._real_branch.set_last_revision_info(...).
1210
# First, set up our RemoteBranch with a FakeClient that raises
1211
# UnknownSmartMethod, and a StubRealBranch that logs how it is called.
1212
transport = MemoryTransport()
1213
transport.mkdir('branch')
1214
transport = transport.clone('branch')
1215
client = FakeClient(transport.base)
1216
client.add_expected_call(
1217
'Branch.get_stacked_on_url', ('branch/',),
1218
'error', ('NotStacked',))
1219
client.add_expected_call(
1220
'Branch.last_revision_info',
1222
'success', ('ok', '0', 'null:'))
1223
client.add_expected_call(
1224
'Branch.set_last_revision_info',
1225
('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
1226
'unknown', 'Branch.set_last_revision_info')
1228
branch = self.make_remote_branch(transport, client)
1229
class StubRealBranch(object):
1232
def set_last_revision_info(self, revno, revision_id):
1234
('set_last_revision_info', revno, revision_id))
1235
def _clear_cached_state(self):
1237
real_branch = StubRealBranch()
1238
branch._real_branch = real_branch
1239
self.lock_remote_branch(branch)
1241
# Call set_last_revision_info, and verify it behaved as expected.
1242
result = branch.set_last_revision_info(1234, 'a-revision-id')
1244
[('set_last_revision_info', 1234, 'a-revision-id')],
1246
client.finished_test()
1248
def test_unexpected_error(self):
1249
# If the server sends an error the client doesn't understand, it gets
1250
# turned into an UnknownErrorFromSmartServer, which is presented as a
1251
# non-internal error to the user.
1252
transport = MemoryTransport()
1253
transport.mkdir('branch')
1254
transport = transport.clone('branch')
1255
client = FakeClient(transport.base)
1256
# get_stacked_on_url
1257
client.add_error_response('NotStacked')
1259
client.add_success_response('ok', 'branch token', 'repo token')
1261
client.add_error_response('UnexpectedError')
1263
client.add_success_response('ok')
1265
branch = self.make_remote_branch(transport, client)
1266
# Lock the branch, reset the record of remote calls.
1270
err = self.assertRaises(
1271
errors.UnknownErrorFromSmartServer,
1272
branch.set_last_revision_info, 123, 'revid')
1273
self.assertEqual(('UnexpectedError',), err.error_tuple)
1276
def test_tip_change_rejected(self):
1277
"""TipChangeRejected responses cause a TipChangeRejected exception to
1280
transport = MemoryTransport()
1281
transport.mkdir('branch')
1282
transport = transport.clone('branch')
1283
client = FakeClient(transport.base)
1284
# get_stacked_on_url
1285
client.add_error_response('NotStacked')
1287
client.add_success_response('ok', 'branch token', 'repo token')
1289
client.add_error_response('TipChangeRejected', 'rejection message')
1291
client.add_success_response('ok')
1293
branch = self.make_remote_branch(transport, client)
1294
# Lock the branch, reset the record of remote calls.
1296
self.addCleanup(branch.unlock)
1299
# The 'TipChangeRejected' error response triggered by calling
1300
# set_last_revision_info causes a TipChangeRejected exception.
1301
err = self.assertRaises(
1302
errors.TipChangeRejected,
1303
branch.set_last_revision_info, 123, 'revid')
1304
self.assertEqual('rejection message', err.msg)
1307
class TestBranchControlGetBranchConf(tests.TestCaseWithMemoryTransport):
1308
"""Getting the branch configuration should use an abstract method not vfs.
1311
def test_get_branch_conf(self):
1312
raise tests.KnownFailure('branch.conf is not retrieved by get_config_file')
1313
## # We should see that branch.get_config() does a single rpc to get the
1314
## # remote configuration file, abstracting away where that is stored on
1315
## # the server. However at the moment it always falls back to using the
1316
## # vfs, and this would need some changes in config.py.
1318
## # in an empty branch we decode the response properly
1319
## client = FakeClient([(('ok', ), '# config file body')], self.get_url())
1320
## # we need to make a real branch because the remote_branch.control_files
1321
## # will trigger _ensure_real.
1322
## branch = self.make_branch('quack')
1323
## transport = branch.bzrdir.root_transport
1324
## # we do not want bzrdir to make any remote calls
1325
## bzrdir = RemoteBzrDir(transport, _client=False)
1326
## branch = RemoteBranch(bzrdir, None, _client=client)
1327
## config = branch.get_config()
1328
## self.assertEqual(
1329
## [('call_expecting_body', 'Branch.get_config_file', ('quack/',))],
1333
class TestBranchLockWrite(RemoteBranchTestCase):
1335
def test_lock_write_unlockable(self):
1336
transport = MemoryTransport()
1337
client = FakeClient(transport.base)
1338
client.add_expected_call(
1339
'Branch.get_stacked_on_url', ('quack/',),
1340
'error', ('NotStacked',),)
1341
client.add_expected_call(
1342
'Branch.lock_write', ('quack/', '', ''),
1343
'error', ('UnlockableTransport',))
1344
transport.mkdir('quack')
1345
transport = transport.clone('quack')
1346
branch = self.make_remote_branch(transport, client)
1347
self.assertRaises(errors.UnlockableTransport, branch.lock_write)
1348
client.finished_test()
1351
class TestTransportIsReadonly(tests.TestCase):
1353
def test_true(self):
1354
client = FakeClient()
1355
client.add_success_response('yes')
1356
transport = RemoteTransport('bzr://example.com/', medium=False,
1358
self.assertEqual(True, transport.is_readonly())
1360
[('call', 'Transport.is_readonly', ())],
1363
def test_false(self):
1364
client = FakeClient()
1365
client.add_success_response('no')
1366
transport = RemoteTransport('bzr://example.com/', medium=False,
1368
self.assertEqual(False, transport.is_readonly())
1370
[('call', 'Transport.is_readonly', ())],
1373
def test_error_from_old_server(self):
1374
"""bzr 0.15 and earlier servers don't recognise the is_readonly verb.
1376
Clients should treat it as a "no" response, because is_readonly is only
1377
advisory anyway (a transport could be read-write, but then the
1378
underlying filesystem could be readonly anyway).
1380
client = FakeClient()
1381
client.add_unknown_method_response('Transport.is_readonly')
1382
transport = RemoteTransport('bzr://example.com/', medium=False,
1384
self.assertEqual(False, transport.is_readonly())
1386
[('call', 'Transport.is_readonly', ())],
1390
class TestTransportMkdir(tests.TestCase):
1392
def test_permissiondenied(self):
1393
client = FakeClient()
1394
client.add_error_response('PermissionDenied', 'remote path', 'extra')
1395
transport = RemoteTransport('bzr://example.com/', medium=False,
1397
exc = self.assertRaises(
1398
errors.PermissionDenied, transport.mkdir, 'client path')
1399
expected_error = errors.PermissionDenied('/client path', 'extra')
1400
self.assertEqual(expected_error, exc)
1403
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
1405
def test_defaults_to_none(self):
1406
t = RemoteSSHTransport('bzr+ssh://example.com')
1407
self.assertIs(None, t._get_credentials()[0])
1409
def test_uses_authentication_config(self):
1410
conf = config.AuthenticationConfig()
1411
conf._get_config().update(
1412
{'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
1415
t = RemoteSSHTransport('bzr+ssh://example.com')
1416
self.assertEqual('bar', t._get_credentials()[0])
1419
class TestRemoteRepository(TestRemote):
1420
"""Base for testing RemoteRepository protocol usage.
1422
These tests contain frozen requests and responses. We want any changes to
1423
what is sent or expected to be require a thoughtful update to these tests
1424
because they might break compatibility with different-versioned servers.
1427
def setup_fake_client_and_repository(self, transport_path):
1428
"""Create the fake client and repository for testing with.
1430
There's no real server here; we just have canned responses sent
1433
:param transport_path: Path below the root of the MemoryTransport
1434
where the repository will be created.
1436
transport = MemoryTransport()
1437
transport.mkdir(transport_path)
1438
client = FakeClient(transport.base)
1439
transport = transport.clone(transport_path)
1440
# we do not want bzrdir to make any remote calls
1441
bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
1443
repo = RemoteRepository(bzrdir, None, _client=client)
1447
class TestRepositoryGatherStats(TestRemoteRepository):
1449
def test_revid_none(self):
1450
# ('ok',), body with revisions and size
1451
transport_path = 'quack'
1452
repo, client = self.setup_fake_client_and_repository(transport_path)
1453
client.add_success_response_with_body(
1454
'revisions: 2\nsize: 18\n', 'ok')
1455
result = repo.gather_stats(None)
1457
[('call_expecting_body', 'Repository.gather_stats',
1458
('quack/','','no'))],
1460
self.assertEqual({'revisions': 2, 'size': 18}, result)
1462
def test_revid_no_committers(self):
1463
# ('ok',), body without committers
1464
body = ('firstrev: 123456.300 3600\n'
1465
'latestrev: 654231.400 0\n'
1468
transport_path = 'quick'
1469
revid = u'\xc8'.encode('utf8')
1470
repo, client = self.setup_fake_client_and_repository(transport_path)
1471
client.add_success_response_with_body(body, 'ok')
1472
result = repo.gather_stats(revid)
1474
[('call_expecting_body', 'Repository.gather_stats',
1475
('quick/', revid, 'no'))],
1477
self.assertEqual({'revisions': 2, 'size': 18,
1478
'firstrev': (123456.300, 3600),
1479
'latestrev': (654231.400, 0),},
1482
def test_revid_with_committers(self):
1483
# ('ok',), body with committers
1484
body = ('committers: 128\n'
1485
'firstrev: 123456.300 3600\n'
1486
'latestrev: 654231.400 0\n'
1489
transport_path = 'buick'
1490
revid = u'\xc8'.encode('utf8')
1491
repo, client = self.setup_fake_client_and_repository(transport_path)
1492
client.add_success_response_with_body(body, 'ok')
1493
result = repo.gather_stats(revid, True)
1495
[('call_expecting_body', 'Repository.gather_stats',
1496
('buick/', revid, 'yes'))],
1498
self.assertEqual({'revisions': 2, 'size': 18,
1500
'firstrev': (123456.300, 3600),
1501
'latestrev': (654231.400, 0),},
1505
class TestRepositoryGetGraph(TestRemoteRepository):
1507
def test_get_graph(self):
1508
# get_graph returns a graph with a custom parents provider.
1509
transport_path = 'quack'
1510
repo, client = self.setup_fake_client_and_repository(transport_path)
1511
graph = repo.get_graph()
1512
self.assertNotEqual(graph._parents_provider, repo)
1515
class TestRepositoryGetParentMap(TestRemoteRepository):
1517
def test_get_parent_map_caching(self):
1518
# get_parent_map returns from cache until unlock()
1519
# setup a reponse with two revisions
1520
r1 = u'\u0e33'.encode('utf8')
1521
r2 = u'\u0dab'.encode('utf8')
1522
lines = [' '.join([r2, r1]), r1]
1523
encoded_body = bz2.compress('\n'.join(lines))
1525
transport_path = 'quack'
1526
repo, client = self.setup_fake_client_and_repository(transport_path)
1527
client.add_success_response_with_body(encoded_body, 'ok')
1528
client.add_success_response_with_body(encoded_body, 'ok')
1530
graph = repo.get_graph()
1531
parents = graph.get_parent_map([r2])
1532
self.assertEqual({r2: (r1,)}, parents)
1533
# locking and unlocking deeper should not reset
1536
parents = graph.get_parent_map([r1])
1537
self.assertEqual({r1: (NULL_REVISION,)}, parents)
1539
[('call_with_body_bytes_expecting_body',
1540
'Repository.get_parent_map', ('quack/', r2), '\n\n0')],
1543
# now we call again, and it should use the second response.
1545
graph = repo.get_graph()
1546
parents = graph.get_parent_map([r1])
1547
self.assertEqual({r1: (NULL_REVISION,)}, parents)
1549
[('call_with_body_bytes_expecting_body',
1550
'Repository.get_parent_map', ('quack/', r2), '\n\n0'),
1551
('call_with_body_bytes_expecting_body',
1552
'Repository.get_parent_map', ('quack/', r1), '\n\n0'),
1557
def test_get_parent_map_reconnects_if_unknown_method(self):
1558
transport_path = 'quack'
1559
repo, client = self.setup_fake_client_and_repository(transport_path)
1560
client.add_unknown_method_response('Repository,get_parent_map')
1561
client.add_success_response_with_body('', 'ok')
1562
self.assertFalse(client._medium._is_remote_before((1, 2)))
1563
rev_id = 'revision-id'
1564
expected_deprecations = [
1565
'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1567
parents = self.callDeprecated(
1568
expected_deprecations, repo.get_parent_map, [rev_id])
1570
[('call_with_body_bytes_expecting_body',
1571
'Repository.get_parent_map', ('quack/', rev_id), '\n\n0'),
1572
('disconnect medium',),
1573
('call_expecting_body', 'Repository.get_revision_graph',
1576
# The medium is now marked as being connected to an older server
1577
self.assertTrue(client._medium._is_remote_before((1, 2)))
1579
def test_get_parent_map_fallback_parentless_node(self):
1580
"""get_parent_map falls back to get_revision_graph on old servers. The
1581
results from get_revision_graph are tweaked to match the get_parent_map
1584
Specifically, a {key: ()} result from get_revision_graph means "no
1585
parents" for that key, which in get_parent_map results should be
1586
represented as {key: ('null:',)}.
1588
This is the test for https://bugs.launchpad.net/bzr/+bug/214894
1590
rev_id = 'revision-id'
1591
transport_path = 'quack'
1592
repo, client = self.setup_fake_client_and_repository(transport_path)
1593
client.add_success_response_with_body(rev_id, 'ok')
1594
client._medium._remember_remote_is_before((1, 2))
1595
expected_deprecations = [
1596
'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1598
parents = self.callDeprecated(
1599
expected_deprecations, repo.get_parent_map, [rev_id])
1601
[('call_expecting_body', 'Repository.get_revision_graph',
1604
self.assertEqual({rev_id: ('null:',)}, parents)
1606
def test_get_parent_map_unexpected_response(self):
1607
repo, client = self.setup_fake_client_and_repository('path')
1608
client.add_success_response('something unexpected!')
1610
errors.UnexpectedSmartServerResponse,
1611
repo.get_parent_map, ['a-revision-id'])
1614
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
1616
def test_allows_new_revisions(self):
1617
"""get_parent_map's results can be updated by commit."""
1618
smart_server = server.SmartTCPServer_for_testing()
1619
smart_server.setUp()
1620
self.addCleanup(smart_server.tearDown)
1621
self.make_branch('branch')
1622
branch = Branch.open(smart_server.get_url() + '/branch')
1623
tree = branch.create_checkout('tree', lightweight=True)
1625
self.addCleanup(tree.unlock)
1626
graph = tree.branch.repository.get_graph()
1627
# This provides an opportunity for the missing rev-id to be cached.
1628
self.assertEqual({}, graph.get_parent_map(['rev1']))
1629
tree.commit('message', rev_id='rev1')
1630
graph = tree.branch.repository.get_graph()
1631
self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
1634
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
1636
def test_null_revision(self):
1637
# a null revision has the predictable result {}, we should have no wire
1638
# traffic when calling it with this argument
1639
transport_path = 'empty'
1640
repo, client = self.setup_fake_client_and_repository(transport_path)
1641
client.add_success_response('notused')
1642
result = self.applyDeprecated(one_four, repo.get_revision_graph,
1644
self.assertEqual([], client._calls)
1645
self.assertEqual({}, result)
1647
def test_none_revision(self):
1648
# with none we want the entire graph
1649
r1 = u'\u0e33'.encode('utf8')
1650
r2 = u'\u0dab'.encode('utf8')
1651
lines = [' '.join([r2, r1]), r1]
1652
encoded_body = '\n'.join(lines)
1654
transport_path = 'sinhala'
1655
repo, client = self.setup_fake_client_and_repository(transport_path)
1656
client.add_success_response_with_body(encoded_body, 'ok')
1657
result = self.applyDeprecated(one_four, repo.get_revision_graph)
1659
[('call_expecting_body', 'Repository.get_revision_graph',
1662
self.assertEqual({r1: (), r2: (r1, )}, result)
1664
def test_specific_revision(self):
1665
# with a specific revision we want the graph for that
1666
# with none we want the entire graph
1667
r11 = u'\u0e33'.encode('utf8')
1668
r12 = u'\xc9'.encode('utf8')
1669
r2 = u'\u0dab'.encode('utf8')
1670
lines = [' '.join([r2, r11, r12]), r11, r12]
1671
encoded_body = '\n'.join(lines)
1673
transport_path = 'sinhala'
1674
repo, client = self.setup_fake_client_and_repository(transport_path)
1675
client.add_success_response_with_body(encoded_body, 'ok')
1676
result = self.applyDeprecated(one_four, repo.get_revision_graph, r2)
1678
[('call_expecting_body', 'Repository.get_revision_graph',
1681
self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
1683
def test_no_such_revision(self):
1685
transport_path = 'sinhala'
1686
repo, client = self.setup_fake_client_and_repository(transport_path)
1687
client.add_error_response('nosuchrevision', revid)
1688
# also check that the right revision is reported in the error
1689
self.assertRaises(errors.NoSuchRevision,
1690
self.applyDeprecated, one_four, repo.get_revision_graph, revid)
1692
[('call_expecting_body', 'Repository.get_revision_graph',
1693
('sinhala/', revid))],
1696
def test_unexpected_error(self):
1698
transport_path = 'sinhala'
1699
repo, client = self.setup_fake_client_and_repository(transport_path)
1700
client.add_error_response('AnUnexpectedError')
1701
e = self.assertRaises(errors.UnknownErrorFromSmartServer,
1702
self.applyDeprecated, one_four, repo.get_revision_graph, revid)
1703
self.assertEqual(('AnUnexpectedError',), e.error_tuple)
1706
class TestRepositoryIsShared(TestRemoteRepository):
1708
def test_is_shared(self):
1709
# ('yes', ) for Repository.is_shared -> 'True'.
1710
transport_path = 'quack'
1711
repo, client = self.setup_fake_client_and_repository(transport_path)
1712
client.add_success_response('yes')
1713
result = repo.is_shared()
1715
[('call', 'Repository.is_shared', ('quack/',))],
1717
self.assertEqual(True, result)
1719
def test_is_not_shared(self):
1720
# ('no', ) for Repository.is_shared -> 'False'.
1721
transport_path = 'qwack'
1722
repo, client = self.setup_fake_client_and_repository(transport_path)
1723
client.add_success_response('no')
1724
result = repo.is_shared()
1726
[('call', 'Repository.is_shared', ('qwack/',))],
1728
self.assertEqual(False, result)
1731
class TestRepositoryLockWrite(TestRemoteRepository):
1733
def test_lock_write(self):
1734
transport_path = 'quack'
1735
repo, client = self.setup_fake_client_and_repository(transport_path)
1736
client.add_success_response('ok', 'a token')
1737
result = repo.lock_write()
1739
[('call', 'Repository.lock_write', ('quack/', ''))],
1741
self.assertEqual('a token', result)
1743
def test_lock_write_already_locked(self):
1744
transport_path = 'quack'
1745
repo, client = self.setup_fake_client_and_repository(transport_path)
1746
client.add_error_response('LockContention')
1747
self.assertRaises(errors.LockContention, repo.lock_write)
1749
[('call', 'Repository.lock_write', ('quack/', ''))],
1752
def test_lock_write_unlockable(self):
1753
transport_path = 'quack'
1754
repo, client = self.setup_fake_client_and_repository(transport_path)
1755
client.add_error_response('UnlockableTransport')
1756
self.assertRaises(errors.UnlockableTransport, repo.lock_write)
1758
[('call', 'Repository.lock_write', ('quack/', ''))],
1762
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
1764
def test_backwards_compat(self):
1765
self.setup_smart_server_with_call_log()
1766
repo = self.make_repository('.')
1767
self.reset_smart_call_log()
1768
verb = 'Repository.set_make_working_trees'
1769
self.disable_verb(verb)
1770
repo.set_make_working_trees(True)
1771
call_count = len([call for call in self.hpss_calls if
1772
call.call.method == verb])
1773
self.assertEqual(1, call_count)
1775
def test_current(self):
1776
transport_path = 'quack'
1777
repo, client = self.setup_fake_client_and_repository(transport_path)
1778
client.add_expected_call(
1779
'Repository.set_make_working_trees', ('quack/', 'True'),
1781
client.add_expected_call(
1782
'Repository.set_make_working_trees', ('quack/', 'False'),
1784
repo.set_make_working_trees(True)
1785
repo.set_make_working_trees(False)
1788
class TestRepositoryUnlock(TestRemoteRepository):
1790
def test_unlock(self):
1791
transport_path = 'quack'
1792
repo, client = self.setup_fake_client_and_repository(transport_path)
1793
client.add_success_response('ok', 'a token')
1794
client.add_success_response('ok')
1798
[('call', 'Repository.lock_write', ('quack/', '')),
1799
('call', 'Repository.unlock', ('quack/', 'a token'))],
1802
def test_unlock_wrong_token(self):
1803
# If somehow the token is wrong, unlock will raise TokenMismatch.
1804
transport_path = 'quack'
1805
repo, client = self.setup_fake_client_and_repository(transport_path)
1806
client.add_success_response('ok', 'a token')
1807
client.add_error_response('TokenMismatch')
1809
self.assertRaises(errors.TokenMismatch, repo.unlock)
1812
class TestRepositoryHasRevision(TestRemoteRepository):
1814
def test_none(self):
1815
# repo.has_revision(None) should not cause any traffic.
1816
transport_path = 'quack'
1817
repo, client = self.setup_fake_client_and_repository(transport_path)
1819
# The null revision is always there, so has_revision(None) == True.
1820
self.assertEqual(True, repo.has_revision(NULL_REVISION))
1822
# The remote repo shouldn't be accessed.
1823
self.assertEqual([], client._calls)
1826
class TestRepositoryTarball(TestRemoteRepository):
1828
# This is a canned tarball reponse we can validate against
1830
'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
1831
'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
1832
'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
1833
'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
1834
'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
1835
'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
1836
'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
1837
'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
1838
'0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
1839
'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
1840
'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
1841
'nWQ7QH/F3JFOFCQ0aSPfA='
1844
def test_repository_tarball(self):
1845
# Test that Repository.tarball generates the right operations
1846
transport_path = 'repo'
1847
expected_calls = [('call_expecting_body', 'Repository.tarball',
1848
('repo/', 'bz2',),),
1850
repo, client = self.setup_fake_client_and_repository(transport_path)
1851
client.add_success_response_with_body(self.tarball_content, 'ok')
1852
# Now actually ask for the tarball
1853
tarball_file = repo._get_tarball('bz2')
1855
self.assertEqual(expected_calls, client._calls)
1856
self.assertEqual(self.tarball_content, tarball_file.read())
1858
tarball_file.close()
1861
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
1862
"""RemoteRepository.copy_content_into optimizations"""
1864
def test_copy_content_remote_to_local(self):
1865
self.transport_server = server.SmartTCPServer_for_testing
1866
src_repo = self.make_repository('repo1')
1867
src_repo = repository.Repository.open(self.get_url('repo1'))
1868
# At the moment the tarball-based copy_content_into can't write back
1869
# into a smart server. It would be good if it could upload the
1870
# tarball; once that works we'd have to create repositories of
1871
# different formats. -- mbp 20070410
1872
dest_url = self.get_vfs_only_url('repo2')
1873
dest_bzrdir = BzrDir.create(dest_url)
1874
dest_repo = dest_bzrdir.create_repository()
1875
self.assertFalse(isinstance(dest_repo, RemoteRepository))
1876
self.assertTrue(isinstance(src_repo, RemoteRepository))
1877
src_repo.copy_content_into(dest_repo)
1880
class _StubRealPackRepository(object):
1882
def __init__(self, calls):
1883
self._pack_collection = _StubPackCollection(calls)
1886
class _StubPackCollection(object):
1888
def __init__(self, calls):
1892
self.calls.append(('pack collection autopack',))
1894
def reload_pack_names(self):
1895
self.calls.append(('pack collection reload_pack_names',))
1898
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
1899
"""Tests for RemoteRepository.autopack implementation."""
1902
"""When the server returns 'ok' and there's no _real_repository, then
1903
nothing else happens: the autopack method is done.
1905
transport_path = 'quack'
1906
repo, client = self.setup_fake_client_and_repository(transport_path)
1907
client.add_expected_call(
1908
'PackRepository.autopack', ('quack/',), 'success', ('ok',))
1910
client.finished_test()
1912
def test_ok_with_real_repo(self):
1913
"""When the server returns 'ok' and there is a _real_repository, then
1914
the _real_repository's reload_pack_name's method will be called.
1916
transport_path = 'quack'
1917
repo, client = self.setup_fake_client_and_repository(transport_path)
1918
client.add_expected_call(
1919
'PackRepository.autopack', ('quack/',),
1921
repo._real_repository = _StubRealPackRepository(client._calls)
1924
[('call', 'PackRepository.autopack', ('quack/',)),
1925
('pack collection reload_pack_names',)],
1928
def test_backwards_compatibility(self):
1929
"""If the server does not recognise the PackRepository.autopack verb,
1930
fallback to the real_repository's implementation.
1932
transport_path = 'quack'
1933
repo, client = self.setup_fake_client_and_repository(transport_path)
1934
client.add_unknown_method_response('PackRepository.autopack')
1935
def stub_ensure_real():
1936
client._calls.append(('_ensure_real',))
1937
repo._real_repository = _StubRealPackRepository(client._calls)
1938
repo._ensure_real = stub_ensure_real
1941
[('call', 'PackRepository.autopack', ('quack/',)),
1943
('pack collection autopack',)],
1947
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
1948
"""Base class for unit tests for bzrlib.remote._translate_error."""
1950
def translateTuple(self, error_tuple, **context):
1951
"""Call _translate_error with an ErrorFromSmartServer built from the
1954
:param error_tuple: A tuple of a smart server response, as would be
1955
passed to an ErrorFromSmartServer.
1956
:kwargs context: context items to call _translate_error with.
1958
:returns: The error raised by _translate_error.
1960
# Raise the ErrorFromSmartServer before passing it as an argument,
1961
# because _translate_error may need to re-raise it with a bare 'raise'
1963
server_error = errors.ErrorFromSmartServer(error_tuple)
1964
translated_error = self.translateErrorFromSmartServer(
1965
server_error, **context)
1966
return translated_error
1968
def translateErrorFromSmartServer(self, error_object, **context):
1969
"""Like translateTuple, but takes an already constructed
1970
ErrorFromSmartServer rather than a tuple.
1974
except errors.ErrorFromSmartServer, server_error:
1975
translated_error = self.assertRaises(
1976
errors.BzrError, remote._translate_error, server_error,
1978
return translated_error
1981
class TestErrorTranslationSuccess(TestErrorTranslationBase):
1982
"""Unit tests for bzrlib.remote._translate_error.
1984
Given an ErrorFromSmartServer (which has an error tuple from a smart
1985
server) and some context, _translate_error raises more specific errors from
1988
This test case covers the cases where _translate_error succeeds in
1989
translating an ErrorFromSmartServer to something better. See
1990
TestErrorTranslationRobustness for other cases.
1993
def test_NoSuchRevision(self):
1994
branch = self.make_branch('')
1996
translated_error = self.translateTuple(
1997
('NoSuchRevision', revid), branch=branch)
1998
expected_error = errors.NoSuchRevision(branch, revid)
1999
self.assertEqual(expected_error, translated_error)
2001
def test_nosuchrevision(self):
2002
repository = self.make_repository('')
2004
translated_error = self.translateTuple(
2005
('nosuchrevision', revid), repository=repository)
2006
expected_error = errors.NoSuchRevision(repository, revid)
2007
self.assertEqual(expected_error, translated_error)
2009
def test_nobranch(self):
2010
bzrdir = self.make_bzrdir('')
2011
translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
2012
expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
2013
self.assertEqual(expected_error, translated_error)
2015
def test_LockContention(self):
2016
translated_error = self.translateTuple(('LockContention',))
2017
expected_error = errors.LockContention('(remote lock)')
2018
self.assertEqual(expected_error, translated_error)
2020
def test_UnlockableTransport(self):
2021
bzrdir = self.make_bzrdir('')
2022
translated_error = self.translateTuple(
2023
('UnlockableTransport',), bzrdir=bzrdir)
2024
expected_error = errors.UnlockableTransport(bzrdir.root_transport)
2025
self.assertEqual(expected_error, translated_error)
2027
def test_LockFailed(self):
2028
lock = 'str() of a server lock'
2029
why = 'str() of why'
2030
translated_error = self.translateTuple(('LockFailed', lock, why))
2031
expected_error = errors.LockFailed(lock, why)
2032
self.assertEqual(expected_error, translated_error)
2034
def test_TokenMismatch(self):
2035
token = 'a lock token'
2036
translated_error = self.translateTuple(('TokenMismatch',), token=token)
2037
expected_error = errors.TokenMismatch(token, '(remote token)')
2038
self.assertEqual(expected_error, translated_error)
2040
def test_Diverged(self):
2041
branch = self.make_branch('a')
2042
other_branch = self.make_branch('b')
2043
translated_error = self.translateTuple(
2044
('Diverged',), branch=branch, other_branch=other_branch)
2045
expected_error = errors.DivergedBranches(branch, other_branch)
2046
self.assertEqual(expected_error, translated_error)
2048
def test_ReadError_no_args(self):
2050
translated_error = self.translateTuple(('ReadError',), path=path)
2051
expected_error = errors.ReadError(path)
2052
self.assertEqual(expected_error, translated_error)
2054
def test_ReadError(self):
2056
translated_error = self.translateTuple(('ReadError', path))
2057
expected_error = errors.ReadError(path)
2058
self.assertEqual(expected_error, translated_error)
2060
def test_PermissionDenied_no_args(self):
2062
translated_error = self.translateTuple(('PermissionDenied',), path=path)
2063
expected_error = errors.PermissionDenied(path)
2064
self.assertEqual(expected_error, translated_error)
2066
def test_PermissionDenied_one_arg(self):
2068
translated_error = self.translateTuple(('PermissionDenied', path))
2069
expected_error = errors.PermissionDenied(path)
2070
self.assertEqual(expected_error, translated_error)
2072
def test_PermissionDenied_one_arg_and_context(self):
2073
"""Given a choice between a path from the local context and a path on
2074
the wire, _translate_error prefers the path from the local context.
2076
local_path = 'local path'
2077
remote_path = 'remote path'
2078
translated_error = self.translateTuple(
2079
('PermissionDenied', remote_path), path=local_path)
2080
expected_error = errors.PermissionDenied(local_path)
2081
self.assertEqual(expected_error, translated_error)
2083
def test_PermissionDenied_two_args(self):
2085
extra = 'a string with extra info'
2086
translated_error = self.translateTuple(
2087
('PermissionDenied', path, extra))
2088
expected_error = errors.PermissionDenied(path, extra)
2089
self.assertEqual(expected_error, translated_error)
2092
class TestErrorTranslationRobustness(TestErrorTranslationBase):
2093
"""Unit tests for bzrlib.remote._translate_error's robustness.
2095
TestErrorTranslationSuccess is for cases where _translate_error can
2096
translate successfully. This class about how _translate_err behaves when
2097
it fails to translate: it re-raises the original error.
2100
def test_unrecognised_server_error(self):
2101
"""If the error code from the server is not recognised, the original
2102
ErrorFromSmartServer is propagated unmodified.
2104
error_tuple = ('An unknown error tuple',)
2105
server_error = errors.ErrorFromSmartServer(error_tuple)
2106
translated_error = self.translateErrorFromSmartServer(server_error)
2107
expected_error = errors.UnknownErrorFromSmartServer(server_error)
2108
self.assertEqual(expected_error, translated_error)
2110
def test_context_missing_a_key(self):
2111
"""In case of a bug in the client, or perhaps an unexpected response
2112
from a server, _translate_error returns the original error tuple from
2113
the server and mutters a warning.
2115
# To translate a NoSuchRevision error _translate_error needs a 'branch'
2116
# in the context dict. So let's give it an empty context dict instead
2117
# to exercise its error recovery.
2119
error_tuple = ('NoSuchRevision', 'revid')
2120
server_error = errors.ErrorFromSmartServer(error_tuple)
2121
translated_error = self.translateErrorFromSmartServer(server_error)
2122
self.assertEqual(server_error, translated_error)
2123
# In addition to re-raising ErrorFromSmartServer, some debug info has
2124
# been muttered to the log file for developer to look at.
2125
self.assertContainsRe(
2126
self._get_log(keep_log_file=True),
2127
"Missing key 'branch' in context")
2129
def test_path_missing(self):
2130
"""Some translations (PermissionDenied, ReadError) can determine the
2131
'path' variable from either the wire or the local context. If neither
2132
has it, then an error is raised.
2134
error_tuple = ('ReadError',)
2135
server_error = errors.ErrorFromSmartServer(error_tuple)
2136
translated_error = self.translateErrorFromSmartServer(server_error)
2137
self.assertEqual(server_error, translated_error)
2138
# In addition to re-raising ErrorFromSmartServer, some debug info has
2139
# been muttered to the log file for developer to look at.
2140
self.assertContainsRe(
2141
self._get_log(keep_log_file=True), "Missing key 'path' in context")
2144
class TestStacking(tests.TestCaseWithTransport):
2145
"""Tests for operations on stacked remote repositories.
2147
The underlying format type must support stacking.
2150
def test_access_stacked_remote(self):
2151
# based on <http://launchpad.net/bugs/261315>
2152
# make a branch stacked on another repository containing an empty
2153
# revision, then open it over hpss - we should be able to see that
2155
base_transport = self.get_transport()
2156
base_builder = self.make_branch_builder('base', format='1.6')
2157
base_builder.start_series()
2158
base_revid = base_builder.build_snapshot('rev-id', None,
2159
[('add', ('', None, 'directory', None))],
2161
base_builder.finish_series()
2162
stacked_branch = self.make_branch('stacked', format='1.6')
2163
stacked_branch.set_stacked_on_url('../base')
2164
# start a server looking at this
2165
smart_server = server.SmartTCPServer_for_testing()
2166
smart_server.setUp()
2167
self.addCleanup(smart_server.tearDown)
2168
remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
2169
# can get its branch and repository
2170
remote_branch = remote_bzrdir.open_branch()
2171
remote_repo = remote_branch.repository
2172
remote_repo.lock_read()
2174
# it should have an appropriate fallback repository, which should also
2175
# be a RemoteRepository
2176
self.assertEquals(len(remote_repo._fallback_repositories), 1)
2177
self.assertIsInstance(remote_repo._fallback_repositories[0],
2179
# and it has the revision committed to the underlying repository;
2180
# these have varying implementations so we try several of them
2181
self.assertTrue(remote_repo.has_revisions([base_revid]))
2182
self.assertTrue(remote_repo.has_revision(base_revid))
2183
self.assertEqual(remote_repo.get_revision(base_revid).message,
2186
remote_repo.unlock()
2188
def prepare_stacked_remote_branch(self):
2189
smart_server = server.SmartTCPServer_for_testing()
2190
smart_server.setUp()
2191
self.addCleanup(smart_server.tearDown)
2192
tree1 = self.make_branch_and_tree('tree1')
2193
tree1.commit('rev1', rev_id='rev1')
2194
tree2 = self.make_branch_and_tree('tree2', format='1.6')
2195
tree2.branch.set_stacked_on_url(tree1.branch.base)
2196
branch2 = Branch.open(smart_server.get_url() + '/tree2')
2198
self.addCleanup(branch2.unlock)
2201
def test_stacked_get_parent_map(self):
2202
# the public implementation of get_parent_map obeys stacking
2203
branch = self.prepare_stacked_remote_branch()
2204
repo = branch.repository
2205
self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
2207
def test_unstacked_get_parent_map(self):
2208
# _unstacked_provider.get_parent_map ignores stacking
2209
branch = self.prepare_stacked_remote_branch()
2210
provider = branch.repository._unstacked_provider
2211
self.assertEqual([], provider.get_parent_map(['rev1']).keys())
2214
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
2217
super(TestRemoteBranchEffort, self).setUp()
2218
# Create a smart server that publishes whatever the backing VFS server
2220
self.smart_server = server.SmartTCPServer_for_testing()
2221
self.smart_server.setUp(self.get_server())
2222
self.addCleanup(self.smart_server.tearDown)
2223
# Log all HPSS calls into self.hpss_calls.
2224
_SmartClient.hooks.install_named_hook(
2225
'call', self.capture_hpss_call, None)
2226
self.hpss_calls = []
2228
def capture_hpss_call(self, params):
2229
self.hpss_calls.append(params.method)
2231
def test_copy_content_into_avoids_revision_history(self):
2232
local = self.make_branch('local')
2233
remote_backing_tree = self.make_branch_and_tree('remote')
2234
remote_backing_tree.commit("Commit.")
2235
remote_branch_url = self.smart_server.get_url() + 'remote'
2236
remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
2237
local.repository.fetch(remote_branch.repository)
2238
self.hpss_calls = []
2239
remote_branch.copy_content_into(local)
2240
self.assertFalse('Branch.revision_history' in self.hpss_calls)