/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Andrew Bennetts
  • Date: 2009-03-12 08:50:04 UTC
  • mto: This revision was merged to the branch mainline in revision 4142.
  • Revision ID: andrew.bennetts@canonical.com-20090312085004-tshz11l4qpcmnxjc
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Tests for remote bzrdir/branch/repo/etc
 
18
 
 
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.
 
22
 
 
23
These tests correspond to tests.test_smart, which exercises the server side.
 
24
"""
 
25
 
 
26
import bz2
 
27
from cStringIO import StringIO
 
28
 
 
29
from bzrlib import (
 
30
    bzrdir,
 
31
    config,
 
32
    errors,
 
33
    graph,
 
34
    pack,
 
35
    remote,
 
36
    repository,
 
37
    smart,
 
38
    tests,
 
39
    urlutils,
 
40
    )
 
41
from bzrlib.branch import Branch
 
42
from bzrlib.bzrdir import BzrDir, BzrDirFormat
 
43
from bzrlib.remote import (
 
44
    RemoteBranch,
 
45
    RemoteBranchFormat,
 
46
    RemoteBzrDir,
 
47
    RemoteBzrDirFormat,
 
48
    RemoteRepository,
 
49
    )
 
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 (
 
55
    condition_isinstance,
 
56
    split_suite_by_condition,
 
57
    multiply_tests,
 
58
    )
 
59
from bzrlib.transport import get_transport, http
 
60
from bzrlib.transport.memory import MemoryTransport
 
61
from bzrlib.transport.remote import (
 
62
    RemoteTransport,
 
63
    RemoteSSHTransport,
 
64
    RemoteTCPTransport,
 
65
)
 
66
 
 
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 = [
 
71
        ('HPSS-v2', 
 
72
            {'transport_server': server.SmartTCPServer_for_testing_v2_only}),
 
73
        ('HPSS-v3', 
 
74
            {'transport_server': server.SmartTCPServer_for_testing})]
 
75
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
 
76
 
 
77
 
 
78
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
 
79
 
 
80
    def setUp(self):
 
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('.')
 
85
 
 
86
    def tearDown(self):
 
87
        self.transport.disconnect()
 
88
        tests.TestCaseWithTransport.tearDown(self)
 
89
 
 
90
    def test_create_remote_bzrdir(self):
 
91
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
92
        self.assertIsInstance(b, BzrDir)
 
93
 
 
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)
 
99
 
 
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))
 
107
 
 
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())
 
114
 
 
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)
 
121
 
 
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)
 
126
 
 
127
    def test_remote_branch_repr(self):
 
128
        b = BzrDir.open_from_transport(self.transport).open_branch()
 
129
        self.assertStartsWith(str(b), 'RemoteBranch(')
 
130
 
 
131
    def test_remote_branch_format_supports_stacking(self):
 
132
        t = self.transport
 
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())
 
139
 
 
140
    def test_remote_repo_format_supports_external_references(self):
 
141
        t = self.transport
 
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)
 
152
 
 
153
 
 
154
class FakeProtocol(object):
 
155
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
 
156
 
 
157
    def __init__(self, body, fake_client):
 
158
        self.body = body
 
159
        self._body_buffer = None
 
160
        self._fake_client = fake_client
 
161
 
 
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
 
168
        return bytes
 
169
 
 
170
    def cancel_read_body(self):
 
171
        self._fake_client.expecting_body = False
 
172
 
 
173
    def read_streamed_body(self):
 
174
        return self.body
 
175
 
 
176
 
 
177
class FakeClient(_SmartClient):
 
178
    """Lookalike for _SmartClient allowing testing."""
 
179
 
 
180
    def __init__(self, fake_medium_base='fake base'):
 
181
        """Create a FakeClient."""
 
182
        self.responses = []
 
183
        self._calls = []
 
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
 
188
        # be anything.
 
189
        self._expected_calls = None
 
190
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
 
191
 
 
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))
 
198
 
 
199
    def add_success_response(self, *args):
 
200
        self.responses.append(('success', args, None))
 
201
 
 
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)
 
206
 
 
207
    def add_error_response(self, *args):
 
208
        self.responses.append(('error', args))
 
209
 
 
210
    def add_unknown_method_response(self, verb):
 
211
        self.responses.append(('unknown', verb))
 
212
 
 
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]))
 
217
 
 
218
    def _get_next_response(self):
 
219
        try:
 
220
            response_tuple = self.responses.pop(0)
 
221
        except IndexError, e:
 
222
            raise AssertionError("%r didn't expect any more calls"
 
223
                % (self,))
 
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
 
229
 
 
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
 
233
            return
 
234
        try:
 
235
            next_call = self._expected_calls.pop(0)
 
236
        except IndexError:
 
237
            raise AssertionError("%r didn't expect any more calls "
 
238
                "but got %r%r"
 
239
                % (self, method, args,))
 
240
        if next_call is None:
 
241
            return
 
242
        if method != next_call[0] or args != next_call[1]:
 
243
            raise AssertionError("%r expected %r%r "
 
244
                "but got %r%r"
 
245
                % (self, next_call[0], next_call[1], method, args,))
 
246
 
 
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]
 
251
 
 
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)
 
258
 
 
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,
 
262
            args, body))
 
263
        result = self._get_next_response()
 
264
        self.expecting_body = True
 
265
        return result[1], FakeProtocol(result[2], self)
 
266
 
 
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]
 
274
 
 
275
 
 
276
class FakeMedium(medium.SmartClientMedium):
 
277
 
 
278
    def __init__(self, client_calls, base):
 
279
        medium.SmartClientMedium.__init__(self, base)
 
280
        self._client_calls = client_calls
 
281
 
 
282
    def disconnect(self):
 
283
        self._client_calls.append(('disconnect medium',))
 
284
 
 
285
 
 
286
class TestVfsHas(tests.TestCase):
 
287
 
 
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)
 
294
        self.assertEqual(
 
295
            [('call', 'has', (filename,))],
 
296
            client._calls)
 
297
        self.assertTrue(result)
 
298
 
 
299
 
 
300
class TestRemote(tests.TestCaseWithMemoryTransport):
 
301
 
 
302
    def get_branch_format(self):
 
303
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
304
        return reference_bzrdir_format.get_branch_format()
 
305
 
 
306
    def get_repo_format(self):
 
307
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
308
        return reference_bzrdir_format.repository_format
 
309
 
 
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)
 
315
        def restoreVerb():
 
316
            request_handlers.register(verb, orig_method)
 
317
        self.addCleanup(restoreVerb)
 
318
 
 
319
 
 
320
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
 
321
    """Tests for the behaviour of client_medium.remote_path_from_transport."""
 
322
 
 
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.
 
327
        """
 
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)
 
332
 
 
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.
 
336
        """
 
337
        self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
 
338
        self.assertRemotePath(
 
339
            'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
 
340
 
 
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)
 
346
        """
 
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)
 
352
 
 
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.
 
357
        """
 
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/')
 
363
 
 
364
 
 
365
class Test_ClientMedium_remote_is_at_least(tests.TestCase):
 
366
    """Tests for the behaviour of client_medium.remote_is_at_least."""
 
367
 
 
368
    def test_initially_unlimited(self):
 
369
        """A fresh medium assumes that the remote side supports all
 
370
        versions.
 
371
        """
 
372
        client_medium = medium.SmartClientMedium('dummy base')
 
373
        self.assertFalse(client_medium._is_remote_before((99, 99)))
 
374
 
 
375
    def test__remember_remote_is_before(self):
 
376
        """Calling _remember_remote_is_before ratchets down the known remote
 
377
        version.
 
378
        """
 
379
        client_medium = medium.SmartClientMedium('dummy base')
 
380
        # Mark the remote side as being less than 1.6.  The remote side may
 
381
        # still be 1.5.
 
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.
 
389
        self.assertRaises(
 
390
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
 
391
 
 
392
 
 
393
class TestBzrDirCloningMetaDir(TestRemote):
 
394
 
 
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)
 
405
 
 
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(),
 
417
            _client=client)
 
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()
 
426
 
 
427
 
 
428
class TestBzrDirOpenBranch(TestRemote):
 
429
 
 
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)
 
441
 
 
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(),
 
460
            _client=client)
 
461
        result = bzrdir.open_branch()
 
462
        self.assertIsInstance(result, RemoteBranch)
 
463
        self.assertEqual(bzrdir, result.bzrdir)
 
464
        client.finished_test()
 
465
 
 
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(),
 
473
            _client=client)
 
474
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
 
475
        self.assertEqual(
 
476
            [('call', 'BzrDir.open_branchV2', ('quack/',))],
 
477
            client._calls)
 
478
 
 
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.
 
482
        calls = []
 
483
        def open_branch():
 
484
            calls.append("Called")
 
485
            return "a-branch"
 
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(),
 
490
            _client=client)
 
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)
 
496
 
 
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(),
 
515
            _client=client)
 
516
        result = bzrdir.open_branch()
 
517
        client.finished_test()
 
518
 
 
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')
 
525
        if rich_root:
 
526
            rich_response = 'yes'
 
527
        else:
 
528
            rich_response = 'no'
 
529
        if subtrees:
 
530
            subtree_response = 'yes'
 
531
        else:
 
532
            subtree_response = 'no'
 
533
        client = FakeClient(transport.base)
 
534
        client.add_success_response(
 
535
            'ok', '', rich_response, subtree_response, external_lookup,
 
536
            network_name)
 
537
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
538
            _client=client)
 
539
        result = bzrdir.open_repository()
 
540
        self.assertEqual(
 
541
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
 
542
            client._calls)
 
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)
 
547
 
 
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')
 
554
 
 
555
    def test_old_server(self):
 
556
        """RemoteBzrDirFormat should fail to probe if the server version is too
 
557
        old.
 
558
        """
 
559
        self.assertRaises(errors.NotBranchError,
 
560
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
 
561
 
 
562
 
 
563
class TestBzrDirCreateBranch(TestRemote):
 
564
 
 
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)
 
574
 
 
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(),
 
590
            _client=client)
 
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())
 
597
 
 
598
 
 
599
class TestBzrDirCreateRepository(TestRemote):
 
600
 
 
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)
 
610
 
 
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(),
 
624
            _client=client)
 
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())
 
634
 
 
635
 
 
636
class TestBzrDirOpenRepository(TestRemote):
 
637
 
 
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
 
647
        # name.
 
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,
 
655
            _client=client)
 
656
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
657
            _client=client)
 
658
        repo = bzrdir.open_repository()
 
659
        self.assertEqual(
 
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',)),
 
666
             ],
 
667
            client._calls)
 
668
        self.assertEqual(network_name, repo._format.network_name())
 
669
 
 
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
 
678
        # name.
 
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,
 
686
            _client=client)
 
687
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
688
            _client=client)
 
689
        repo = bzrdir.open_repository()
 
690
        self.assertEqual(
 
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',)),
 
696
             ],
 
697
            client._calls)
 
698
        self.assertEqual(network_name, repo._format.network_name())
 
699
 
 
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(),
 
709
            _client=client)
 
710
        repo = bzrdir.open_repository()
 
711
        self.assertEqual(
 
712
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
 
713
            client._calls)
 
714
        self.assertEqual(network_name, repo._format.network_name())
 
715
 
 
716
 
 
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.
 
720
    """
 
721
 
 
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)
 
728
 
 
729
    def protocol_version(self):
 
730
        return 1
 
731
 
 
732
 
 
733
class OldServerTransport(object):
 
734
    """A fake transport for test_old_server that reports it's smart server
 
735
    protocol version as version one.
 
736
    """
 
737
 
 
738
    def __init__(self):
 
739
        self.base = 'fake:'
 
740
 
 
741
    def get_smart_client(self):
 
742
        return OldSmartClient()
 
743
 
 
744
 
 
745
class RemoteBranchTestCase(TestRemote):
 
746
 
 
747
    def make_remote_branch(self, transport, client):
 
748
        """Make a RemoteBranch using 'client' as its _SmartClient.
 
749
 
 
750
        A RemoteBzrDir and RemoteRepository will also be created to fill out
 
751
        the RemoteBranch, albeit with stub values for some of their attributes.
 
752
        """
 
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
 
755
        # immediately.
 
756
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
757
            _client=False)
 
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)
 
762
 
 
763
 
 
764
class TestBranchGetParent(RemoteBranchTestCase):
 
765
 
 
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/',),
 
775
            'success', ('',))
 
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)
 
782
 
 
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)
 
797
 
 
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)
 
812
 
 
813
 
 
814
class TestBranchGetTagsBytes(RemoteBranchTestCase):
 
815
 
 
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)
 
826
 
 
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/',),
 
835
            'success', ('',))
 
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)
 
842
 
 
843
 
 
844
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
 
845
 
 
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)
 
862
 
 
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)
 
879
 
 
880
 
 
881
class TestBranch_get_stacked_on_url(TestRemote):
 
882
    """Test Branch._get_stacked_on_url rpc"""
 
883
 
 
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
 
900
        # today.
 
901
        client.add_expected_call(
 
902
            'Branch.get_stacked_on_url', ('stacked/',),
 
903
            'success', ('ok', vfs_url))
 
904
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
905
            _client=client)
 
906
        branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, None),
 
907
            _client=client)
 
908
        result = branch.get_stacked_on_url()
 
909
        self.assertEqual(vfs_url, result)
 
910
 
 
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
 
941
        # repository
 
942
        self.assertEqual(1, len(branch.repository._fallback_repositories))
 
943
        self.assertEqual(1,
 
944
            len(branch.repository._real_repository._fallback_repositories))
 
945
 
 
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
 
974
        # repository
 
975
        self.assertEqual(1, len(branch.repository._fallback_repositories))
 
976
        self.assertEqual(1,
 
977
            len(branch.repository._real_repository._fallback_repositories))
 
978
 
 
979
 
 
980
class TestBranchSetLastRevision(RemoteBranchTestCase):
 
981
 
 
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')
 
988
 
 
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',
 
998
            ('branch/',),
 
999
            'success', ('ok', '0', 'null:'))
 
1000
        client.add_expected_call(
 
1001
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
 
1002
            'success', ('ok',))
 
1003
        client.add_expected_call(
 
1004
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
 
1005
            'success', ('ok',))
 
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
 
1010
        branch.lock_write()
 
1011
        result = branch.set_revision_history([])
 
1012
        branch.unlock()
 
1013
        self.assertEqual(None, result)
 
1014
        client.finished_test()
 
1015
 
 
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')
 
1022
 
 
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',
 
1032
            ('branch/',),
 
1033
            'success', ('ok', '0', 'null:'))
 
1034
        lines = ['rev-id2']
 
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',),
 
1039
            'success', ('ok',))
 
1040
        client.add_expected_call(
 
1041
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
 
1042
            'success', ('ok',))
 
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.
 
1048
        branch.lock_write()
 
1049
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
 
1050
        branch.unlock()
 
1051
        self.assertEqual(None, result)
 
1052
        client.finished_test()
 
1053
 
 
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',
 
1068
            ('branch/',),
 
1069
            'success', ('ok', '0', 'null:'))
 
1070
        # get_graph calls to construct the revision history, for the set_rh
 
1071
        # hook
 
1072
        lines = ['rev-id']
 
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'),
 
1080
            'success', ('ok',))
 
1081
 
 
1082
        branch = self.make_remote_branch(transport, client)
 
1083
        branch.lock_write()
 
1084
        self.assertRaises(
 
1085
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
 
1086
        branch.unlock()
 
1087
        client.finished_test()
 
1088
 
 
1089
    def test_tip_change_rejected(self):
 
1090
        """TipChangeRejected responses cause a TipChangeRejected exception to
 
1091
        be raised.
 
1092
        """
 
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',
 
1107
            ('branch/',),
 
1108
            'success', ('ok', '0', 'null:'))
 
1109
        lines = ['rev-id']
 
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'),
 
1117
            'success', ('ok',))
 
1118
        branch = self.make_remote_branch(transport, client)
 
1119
        branch._ensure_real = lambda: None
 
1120
        branch.lock_write()
 
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
 
1126
        # object.
 
1127
        self.assertIsInstance(err.msg, unicode)
 
1128
        self.assertEqual(rejection_msg_unicode, err.msg)
 
1129
        branch.unlock()
 
1130
        client.finished_test()
 
1131
 
 
1132
 
 
1133
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
 
1134
 
 
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')
 
1144
        # lock_write
 
1145
        client.add_success_response('ok', 'branch token', 'repo token')
 
1146
        # query the current revision
 
1147
        client.add_success_response('ok', '0', 'null:')
 
1148
        # set_last_revision
 
1149
        client.add_success_response('ok')
 
1150
        # unlock
 
1151
        client.add_success_response('ok')
 
1152
 
 
1153
        branch = self.make_remote_branch(transport, client)
 
1154
        # Lock the branch, reset the record of remote calls.
 
1155
        branch.lock_write()
 
1156
        client._calls = []
 
1157
        result = branch.set_last_revision_info(1234, 'a-revision-id')
 
1158
        self.assertEqual(
 
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'))],
 
1163
            client._calls)
 
1164
        self.assertEqual(None, result)
 
1165
 
 
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')
 
1174
        # lock_write
 
1175
        client.add_success_response('ok', 'branch token', 'repo token')
 
1176
        # set_last_revision
 
1177
        client.add_error_response('NoSuchRevision', 'revid')
 
1178
        # unlock
 
1179
        client.add_success_response('ok')
 
1180
 
 
1181
        branch = self.make_remote_branch(transport, client)
 
1182
        # Lock the branch, reset the record of remote calls.
 
1183
        branch.lock_write()
 
1184
        client._calls = []
 
1185
 
 
1186
        self.assertRaises(
 
1187
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
 
1188
        branch.unlock()
 
1189
 
 
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'
 
1199
 
 
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.
 
1203
        """
 
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(...).
 
1209
 
 
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',
 
1221
            ('branch/',),
 
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')
 
1227
 
 
1228
        branch = self.make_remote_branch(transport, client)
 
1229
        class StubRealBranch(object):
 
1230
            def __init__(self):
 
1231
                self.calls = []
 
1232
            def set_last_revision_info(self, revno, revision_id):
 
1233
                self.calls.append(
 
1234
                    ('set_last_revision_info', revno, revision_id))
 
1235
            def _clear_cached_state(self):
 
1236
                pass
 
1237
        real_branch = StubRealBranch()
 
1238
        branch._real_branch = real_branch
 
1239
        self.lock_remote_branch(branch)
 
1240
 
 
1241
        # Call set_last_revision_info, and verify it behaved as expected.
 
1242
        result = branch.set_last_revision_info(1234, 'a-revision-id')
 
1243
        self.assertEqual(
 
1244
            [('set_last_revision_info', 1234, 'a-revision-id')],
 
1245
            real_branch.calls)
 
1246
        client.finished_test()
 
1247
 
 
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')
 
1258
        # lock_write
 
1259
        client.add_success_response('ok', 'branch token', 'repo token')
 
1260
        # set_last_revision
 
1261
        client.add_error_response('UnexpectedError')
 
1262
        # unlock
 
1263
        client.add_success_response('ok')
 
1264
 
 
1265
        branch = self.make_remote_branch(transport, client)
 
1266
        # Lock the branch, reset the record of remote calls.
 
1267
        branch.lock_write()
 
1268
        client._calls = []
 
1269
 
 
1270
        err = self.assertRaises(
 
1271
            errors.UnknownErrorFromSmartServer,
 
1272
            branch.set_last_revision_info, 123, 'revid')
 
1273
        self.assertEqual(('UnexpectedError',), err.error_tuple)
 
1274
        branch.unlock()
 
1275
 
 
1276
    def test_tip_change_rejected(self):
 
1277
        """TipChangeRejected responses cause a TipChangeRejected exception to
 
1278
        be raised.
 
1279
        """
 
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')
 
1286
        # lock_write
 
1287
        client.add_success_response('ok', 'branch token', 'repo token')
 
1288
        # set_last_revision
 
1289
        client.add_error_response('TipChangeRejected', 'rejection message')
 
1290
        # unlock
 
1291
        client.add_success_response('ok')
 
1292
 
 
1293
        branch = self.make_remote_branch(transport, client)
 
1294
        # Lock the branch, reset the record of remote calls.
 
1295
        branch.lock_write()
 
1296
        self.addCleanup(branch.unlock)
 
1297
        client._calls = []
 
1298
 
 
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)
 
1305
 
 
1306
 
 
1307
class TestBranchControlGetBranchConf(tests.TestCaseWithMemoryTransport):
 
1308
    """Getting the branch configuration should use an abstract method not vfs.
 
1309
    """
 
1310
 
 
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.
 
1317
 
 
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/',))],
 
1330
        ##     client._calls)
 
1331
 
 
1332
 
 
1333
class TestBranchLockWrite(RemoteBranchTestCase):
 
1334
 
 
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()
 
1349
 
 
1350
 
 
1351
class TestTransportIsReadonly(tests.TestCase):
 
1352
 
 
1353
    def test_true(self):
 
1354
        client = FakeClient()
 
1355
        client.add_success_response('yes')
 
1356
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
1357
                                    _client=client)
 
1358
        self.assertEqual(True, transport.is_readonly())
 
1359
        self.assertEqual(
 
1360
            [('call', 'Transport.is_readonly', ())],
 
1361
            client._calls)
 
1362
 
 
1363
    def test_false(self):
 
1364
        client = FakeClient()
 
1365
        client.add_success_response('no')
 
1366
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
1367
                                    _client=client)
 
1368
        self.assertEqual(False, transport.is_readonly())
 
1369
        self.assertEqual(
 
1370
            [('call', 'Transport.is_readonly', ())],
 
1371
            client._calls)
 
1372
 
 
1373
    def test_error_from_old_server(self):
 
1374
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
 
1375
 
 
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).
 
1379
        """
 
1380
        client = FakeClient()
 
1381
        client.add_unknown_method_response('Transport.is_readonly')
 
1382
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
1383
                                    _client=client)
 
1384
        self.assertEqual(False, transport.is_readonly())
 
1385
        self.assertEqual(
 
1386
            [('call', 'Transport.is_readonly', ())],
 
1387
            client._calls)
 
1388
 
 
1389
 
 
1390
class TestTransportMkdir(tests.TestCase):
 
1391
 
 
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,
 
1396
                                    _client=client)
 
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)
 
1401
 
 
1402
 
 
1403
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
 
1404
 
 
1405
    def test_defaults_to_none(self):
 
1406
        t = RemoteSSHTransport('bzr+ssh://example.com')
 
1407
        self.assertIs(None, t._get_credentials()[0])
 
1408
 
 
1409
    def test_uses_authentication_config(self):
 
1410
        conf = config.AuthenticationConfig()
 
1411
        conf._get_config().update(
 
1412
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
 
1413
            'example.com'}})
 
1414
        conf._save()
 
1415
        t = RemoteSSHTransport('bzr+ssh://example.com')
 
1416
        self.assertEqual('bar', t._get_credentials()[0])
 
1417
 
 
1418
 
 
1419
class TestRemoteRepository(TestRemote):
 
1420
    """Base for testing RemoteRepository protocol usage.
 
1421
 
 
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.
 
1425
    """
 
1426
 
 
1427
    def setup_fake_client_and_repository(self, transport_path):
 
1428
        """Create the fake client and repository for testing with.
 
1429
 
 
1430
        There's no real server here; we just have canned responses sent
 
1431
        back one by one.
 
1432
 
 
1433
        :param transport_path: Path below the root of the MemoryTransport
 
1434
            where the repository will be created.
 
1435
        """
 
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(),
 
1442
            _client=False)
 
1443
        repo = RemoteRepository(bzrdir, None, _client=client)
 
1444
        return repo, client
 
1445
 
 
1446
 
 
1447
class TestRepositoryGatherStats(TestRemoteRepository):
 
1448
 
 
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)
 
1456
        self.assertEqual(
 
1457
            [('call_expecting_body', 'Repository.gather_stats',
 
1458
             ('quack/','','no'))],
 
1459
            client._calls)
 
1460
        self.assertEqual({'revisions': 2, 'size': 18}, result)
 
1461
 
 
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'
 
1466
                'revisions: 2\n'
 
1467
                'size: 18\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)
 
1473
        self.assertEqual(
 
1474
            [('call_expecting_body', 'Repository.gather_stats',
 
1475
              ('quick/', revid, 'no'))],
 
1476
            client._calls)
 
1477
        self.assertEqual({'revisions': 2, 'size': 18,
 
1478
                          'firstrev': (123456.300, 3600),
 
1479
                          'latestrev': (654231.400, 0),},
 
1480
                         result)
 
1481
 
 
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'
 
1487
                'revisions: 2\n'
 
1488
                'size: 18\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)
 
1494
        self.assertEqual(
 
1495
            [('call_expecting_body', 'Repository.gather_stats',
 
1496
              ('buick/', revid, 'yes'))],
 
1497
            client._calls)
 
1498
        self.assertEqual({'revisions': 2, 'size': 18,
 
1499
                          'committers': 128,
 
1500
                          'firstrev': (123456.300, 3600),
 
1501
                          'latestrev': (654231.400, 0),},
 
1502
                         result)
 
1503
 
 
1504
 
 
1505
class TestRepositoryGetGraph(TestRemoteRepository):
 
1506
 
 
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)
 
1513
 
 
1514
 
 
1515
class TestRepositoryGetParentMap(TestRemoteRepository):
 
1516
 
 
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))
 
1524
 
 
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')
 
1529
        repo.lock_read()
 
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
 
1534
        repo.lock_read()
 
1535
        repo.unlock()
 
1536
        parents = graph.get_parent_map([r1])
 
1537
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
 
1538
        self.assertEqual(
 
1539
            [('call_with_body_bytes_expecting_body',
 
1540
              'Repository.get_parent_map', ('quack/', r2), '\n\n0')],
 
1541
            client._calls)
 
1542
        repo.unlock()
 
1543
        # now we call again, and it should use the second response.
 
1544
        repo.lock_read()
 
1545
        graph = repo.get_graph()
 
1546
        parents = graph.get_parent_map([r1])
 
1547
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
 
1548
        self.assertEqual(
 
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'),
 
1553
            ],
 
1554
            client._calls)
 
1555
        repo.unlock()
 
1556
 
 
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 '
 
1566
            'in version 1.4.']
 
1567
        parents = self.callDeprecated(
 
1568
            expected_deprecations, repo.get_parent_map, [rev_id])
 
1569
        self.assertEqual(
 
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',
 
1574
              ('quack/', ''))],
 
1575
            client._calls)
 
1576
        # The medium is now marked as being connected to an older server
 
1577
        self.assertTrue(client._medium._is_remote_before((1, 2)))
 
1578
 
 
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
 
1582
        API.
 
1583
 
 
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:',)}.
 
1587
 
 
1588
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
 
1589
        """
 
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 '
 
1597
            'in version 1.4.']
 
1598
        parents = self.callDeprecated(
 
1599
            expected_deprecations, repo.get_parent_map, [rev_id])
 
1600
        self.assertEqual(
 
1601
            [('call_expecting_body', 'Repository.get_revision_graph',
 
1602
             ('quack/', ''))],
 
1603
            client._calls)
 
1604
        self.assertEqual({rev_id: ('null:',)}, parents)
 
1605
 
 
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!')
 
1609
        self.assertRaises(
 
1610
            errors.UnexpectedSmartServerResponse,
 
1611
            repo.get_parent_map, ['a-revision-id'])
 
1612
 
 
1613
 
 
1614
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
 
1615
 
 
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)
 
1624
        tree.lock_write()
 
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']))
 
1632
 
 
1633
 
 
1634
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
 
1635
 
 
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,
 
1643
            NULL_REVISION)
 
1644
        self.assertEqual([], client._calls)
 
1645
        self.assertEqual({}, result)
 
1646
 
 
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)
 
1653
 
 
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)
 
1658
        self.assertEqual(
 
1659
            [('call_expecting_body', 'Repository.get_revision_graph',
 
1660
             ('sinhala/', ''))],
 
1661
            client._calls)
 
1662
        self.assertEqual({r1: (), r2: (r1, )}, result)
 
1663
 
 
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)
 
1672
 
 
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)
 
1677
        self.assertEqual(
 
1678
            [('call_expecting_body', 'Repository.get_revision_graph',
 
1679
             ('sinhala/', r2))],
 
1680
            client._calls)
 
1681
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
 
1682
 
 
1683
    def test_no_such_revision(self):
 
1684
        revid = '123'
 
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)
 
1691
        self.assertEqual(
 
1692
            [('call_expecting_body', 'Repository.get_revision_graph',
 
1693
             ('sinhala/', revid))],
 
1694
            client._calls)
 
1695
 
 
1696
    def test_unexpected_error(self):
 
1697
        revid = '123'
 
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)
 
1704
 
 
1705
 
 
1706
class TestRepositoryIsShared(TestRemoteRepository):
 
1707
 
 
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()
 
1714
        self.assertEqual(
 
1715
            [('call', 'Repository.is_shared', ('quack/',))],
 
1716
            client._calls)
 
1717
        self.assertEqual(True, result)
 
1718
 
 
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()
 
1725
        self.assertEqual(
 
1726
            [('call', 'Repository.is_shared', ('qwack/',))],
 
1727
            client._calls)
 
1728
        self.assertEqual(False, result)
 
1729
 
 
1730
 
 
1731
class TestRepositoryLockWrite(TestRemoteRepository):
 
1732
 
 
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()
 
1738
        self.assertEqual(
 
1739
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
1740
            client._calls)
 
1741
        self.assertEqual('a token', result)
 
1742
 
 
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)
 
1748
        self.assertEqual(
 
1749
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
1750
            client._calls)
 
1751
 
 
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)
 
1757
        self.assertEqual(
 
1758
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
1759
            client._calls)
 
1760
 
 
1761
 
 
1762
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
 
1763
 
 
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)
 
1774
 
 
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'),
 
1780
            'success', ('ok',))
 
1781
        client.add_expected_call(
 
1782
            'Repository.set_make_working_trees', ('quack/', 'False'),
 
1783
            'success', ('ok',))
 
1784
        repo.set_make_working_trees(True)
 
1785
        repo.set_make_working_trees(False)
 
1786
 
 
1787
 
 
1788
class TestRepositoryUnlock(TestRemoteRepository):
 
1789
 
 
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')
 
1795
        repo.lock_write()
 
1796
        repo.unlock()
 
1797
        self.assertEqual(
 
1798
            [('call', 'Repository.lock_write', ('quack/', '')),
 
1799
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
 
1800
            client._calls)
 
1801
 
 
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')
 
1808
        repo.lock_write()
 
1809
        self.assertRaises(errors.TokenMismatch, repo.unlock)
 
1810
 
 
1811
 
 
1812
class TestRepositoryHasRevision(TestRemoteRepository):
 
1813
 
 
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)
 
1818
 
 
1819
        # The null revision is always there, so has_revision(None) == True.
 
1820
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
 
1821
 
 
1822
        # The remote repo shouldn't be accessed.
 
1823
        self.assertEqual([], client._calls)
 
1824
 
 
1825
 
 
1826
class TestRepositoryTarball(TestRemoteRepository):
 
1827
 
 
1828
    # This is a canned tarball reponse we can validate against
 
1829
    tarball_content = (
 
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='
 
1842
        ).decode('base64')
 
1843
 
 
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',),),
 
1849
            ]
 
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')
 
1854
        try:
 
1855
            self.assertEqual(expected_calls, client._calls)
 
1856
            self.assertEqual(self.tarball_content, tarball_file.read())
 
1857
        finally:
 
1858
            tarball_file.close()
 
1859
 
 
1860
 
 
1861
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
 
1862
    """RemoteRepository.copy_content_into optimizations"""
 
1863
 
 
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)
 
1878
 
 
1879
 
 
1880
class _StubRealPackRepository(object):
 
1881
 
 
1882
    def __init__(self, calls):
 
1883
        self._pack_collection = _StubPackCollection(calls)
 
1884
 
 
1885
 
 
1886
class _StubPackCollection(object):
 
1887
 
 
1888
    def __init__(self, calls):
 
1889
        self.calls = calls
 
1890
 
 
1891
    def autopack(self):
 
1892
        self.calls.append(('pack collection autopack',))
 
1893
 
 
1894
    def reload_pack_names(self):
 
1895
        self.calls.append(('pack collection reload_pack_names',))
 
1896
 
 
1897
 
 
1898
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
 
1899
    """Tests for RemoteRepository.autopack implementation."""
 
1900
 
 
1901
    def test_ok(self):
 
1902
        """When the server returns 'ok' and there's no _real_repository, then
 
1903
        nothing else happens: the autopack method is done.
 
1904
        """
 
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',))
 
1909
        repo.autopack()
 
1910
        client.finished_test()
 
1911
 
 
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.
 
1915
        """
 
1916
        transport_path = 'quack'
 
1917
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1918
        client.add_expected_call(
 
1919
            'PackRepository.autopack', ('quack/',),
 
1920
            'success', ('ok',))
 
1921
        repo._real_repository = _StubRealPackRepository(client._calls)
 
1922
        repo.autopack()
 
1923
        self.assertEqual(
 
1924
            [('call', 'PackRepository.autopack', ('quack/',)),
 
1925
             ('pack collection reload_pack_names',)],
 
1926
            client._calls)
 
1927
 
 
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.
 
1931
        """
 
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
 
1939
        repo.autopack()
 
1940
        self.assertEqual(
 
1941
            [('call', 'PackRepository.autopack', ('quack/',)),
 
1942
             ('_ensure_real',),
 
1943
             ('pack collection autopack',)],
 
1944
            client._calls)
 
1945
 
 
1946
 
 
1947
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
 
1948
    """Base class for unit tests for bzrlib.remote._translate_error."""
 
1949
 
 
1950
    def translateTuple(self, error_tuple, **context):
 
1951
        """Call _translate_error with an ErrorFromSmartServer built from the
 
1952
        given error_tuple.
 
1953
 
 
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.
 
1957
 
 
1958
        :returns: The error raised by _translate_error.
 
1959
        """
 
1960
        # Raise the ErrorFromSmartServer before passing it as an argument,
 
1961
        # because _translate_error may need to re-raise it with a bare 'raise'
 
1962
        # statement.
 
1963
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
1964
        translated_error = self.translateErrorFromSmartServer(
 
1965
            server_error, **context)
 
1966
        return translated_error
 
1967
 
 
1968
    def translateErrorFromSmartServer(self, error_object, **context):
 
1969
        """Like translateTuple, but takes an already constructed
 
1970
        ErrorFromSmartServer rather than a tuple.
 
1971
        """
 
1972
        try:
 
1973
            raise error_object
 
1974
        except errors.ErrorFromSmartServer, server_error:
 
1975
            translated_error = self.assertRaises(
 
1976
                errors.BzrError, remote._translate_error, server_error,
 
1977
                **context)
 
1978
        return translated_error
 
1979
 
 
1980
 
 
1981
class TestErrorTranslationSuccess(TestErrorTranslationBase):
 
1982
    """Unit tests for bzrlib.remote._translate_error.
 
1983
 
 
1984
    Given an ErrorFromSmartServer (which has an error tuple from a smart
 
1985
    server) and some context, _translate_error raises more specific errors from
 
1986
    bzrlib.errors.
 
1987
 
 
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.
 
1991
    """
 
1992
 
 
1993
    def test_NoSuchRevision(self):
 
1994
        branch = self.make_branch('')
 
1995
        revid = 'revid'
 
1996
        translated_error = self.translateTuple(
 
1997
            ('NoSuchRevision', revid), branch=branch)
 
1998
        expected_error = errors.NoSuchRevision(branch, revid)
 
1999
        self.assertEqual(expected_error, translated_error)
 
2000
 
 
2001
    def test_nosuchrevision(self):
 
2002
        repository = self.make_repository('')
 
2003
        revid = 'revid'
 
2004
        translated_error = self.translateTuple(
 
2005
            ('nosuchrevision', revid), repository=repository)
 
2006
        expected_error = errors.NoSuchRevision(repository, revid)
 
2007
        self.assertEqual(expected_error, translated_error)
 
2008
 
 
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)
 
2014
 
 
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)
 
2019
 
 
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)
 
2026
 
 
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)
 
2033
 
 
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)
 
2039
 
 
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)
 
2047
 
 
2048
    def test_ReadError_no_args(self):
 
2049
        path = 'a path'
 
2050
        translated_error = self.translateTuple(('ReadError',), path=path)
 
2051
        expected_error = errors.ReadError(path)
 
2052
        self.assertEqual(expected_error, translated_error)
 
2053
 
 
2054
    def test_ReadError(self):
 
2055
        path = 'a path'
 
2056
        translated_error = self.translateTuple(('ReadError', path))
 
2057
        expected_error = errors.ReadError(path)
 
2058
        self.assertEqual(expected_error, translated_error)
 
2059
 
 
2060
    def test_PermissionDenied_no_args(self):
 
2061
        path = 'a path'
 
2062
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
 
2063
        expected_error = errors.PermissionDenied(path)
 
2064
        self.assertEqual(expected_error, translated_error)
 
2065
 
 
2066
    def test_PermissionDenied_one_arg(self):
 
2067
        path = 'a path'
 
2068
        translated_error = self.translateTuple(('PermissionDenied', path))
 
2069
        expected_error = errors.PermissionDenied(path)
 
2070
        self.assertEqual(expected_error, translated_error)
 
2071
 
 
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.
 
2075
        """
 
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)
 
2082
 
 
2083
    def test_PermissionDenied_two_args(self):
 
2084
        path = 'a path'
 
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)
 
2090
 
 
2091
 
 
2092
class TestErrorTranslationRobustness(TestErrorTranslationBase):
 
2093
    """Unit tests for bzrlib.remote._translate_error's robustness.
 
2094
 
 
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.
 
2098
    """
 
2099
 
 
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.
 
2103
        """
 
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)
 
2109
 
 
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.
 
2114
        """
 
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.
 
2118
        empty_context = {}
 
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")
 
2128
 
 
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.
 
2133
        """
 
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")
 
2142
 
 
2143
 
 
2144
class TestStacking(tests.TestCaseWithTransport):
 
2145
    """Tests for operations on stacked remote repositories.
 
2146
 
 
2147
    The underlying format type must support stacking.
 
2148
    """
 
2149
 
 
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
 
2154
        # revision.
 
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))],
 
2160
            'message')
 
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()
 
2173
        try:
 
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],
 
2178
                RemoteRepository)
 
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,
 
2184
                'message')
 
2185
        finally:
 
2186
            remote_repo.unlock()
 
2187
 
 
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')
 
2197
        branch2.lock_read()
 
2198
        self.addCleanup(branch2.unlock)
 
2199
        return branch2
 
2200
 
 
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())
 
2206
 
 
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())
 
2212
 
 
2213
 
 
2214
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
 
2215
 
 
2216
    def setUp(self):
 
2217
        super(TestRemoteBranchEffort, self).setUp()
 
2218
        # Create a smart server that publishes whatever the backing VFS server
 
2219
        # does.
 
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 = []
 
2227
 
 
2228
    def capture_hpss_call(self, params):
 
2229
        self.hpss_calls.append(params.method)
 
2230
 
 
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)