/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: Martin Pool
  • Date: 2009-09-18 01:08:24 UTC
  • mto: This revision was merged to the branch mainline in revision 4712.
  • Revision ID: mbp@sourcefrog.net-20090918010824-o96afvwbbxhw4d5p
Unhandled smart-server exceptions are reported using generic report_exception

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007, 2008, 2009 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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
    inventory,
 
35
    inventory_delta,
 
36
    pack,
 
37
    remote,
 
38
    repository,
 
39
    smart,
 
40
    tests,
 
41
    treebuilder,
 
42
    urlutils,
 
43
    versionedfile,
 
44
    )
 
45
from bzrlib.branch import Branch
 
46
from bzrlib.bzrdir import BzrDir, BzrDirFormat
 
47
from bzrlib.remote import (
 
48
    RemoteBranch,
 
49
    RemoteBranchFormat,
 
50
    RemoteBzrDir,
 
51
    RemoteBzrDirFormat,
 
52
    RemoteRepository,
 
53
    RemoteRepositoryFormat,
 
54
    )
 
55
from bzrlib.repofmt import groupcompress_repo, pack_repo
 
56
from bzrlib.revision import NULL_REVISION
 
57
from bzrlib.smart import server, medium
 
58
from bzrlib.smart.client import _SmartClient
 
59
from bzrlib.smart.repository import SmartServerRepositoryGetParentMap
 
60
from bzrlib.tests import (
 
61
    condition_isinstance,
 
62
    split_suite_by_condition,
 
63
    multiply_tests,
 
64
    KnownFailure,
 
65
    )
 
66
from bzrlib.transport import get_transport, http
 
67
from bzrlib.transport.memory import MemoryTransport
 
68
from bzrlib.transport.remote import (
 
69
    RemoteTransport,
 
70
    RemoteSSHTransport,
 
71
    RemoteTCPTransport,
 
72
)
 
73
 
 
74
def load_tests(standard_tests, module, loader):
 
75
    to_adapt, result = split_suite_by_condition(
 
76
        standard_tests, condition_isinstance(BasicRemoteObjectTests))
 
77
    smart_server_version_scenarios = [
 
78
        ('HPSS-v2',
 
79
            {'transport_server': server.SmartTCPServer_for_testing_v2_only}),
 
80
        ('HPSS-v3',
 
81
            {'transport_server': server.SmartTCPServer_for_testing})]
 
82
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
 
83
 
 
84
 
 
85
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
 
86
 
 
87
    def setUp(self):
 
88
        super(BasicRemoteObjectTests, self).setUp()
 
89
        self.transport = self.get_transport()
 
90
        # make a branch that can be opened over the smart transport
 
91
        self.local_wt = BzrDir.create_standalone_workingtree('.')
 
92
 
 
93
    def tearDown(self):
 
94
        self.transport.disconnect()
 
95
        tests.TestCaseWithTransport.tearDown(self)
 
96
 
 
97
    def test_create_remote_bzrdir(self):
 
98
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
99
        self.assertIsInstance(b, BzrDir)
 
100
 
 
101
    def test_open_remote_branch(self):
 
102
        # open a standalone branch in the working directory
 
103
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
104
        branch = b.open_branch()
 
105
        self.assertIsInstance(branch, Branch)
 
106
 
 
107
    def test_remote_repository(self):
 
108
        b = BzrDir.open_from_transport(self.transport)
 
109
        repo = b.open_repository()
 
110
        revid = u'\xc823123123'.encode('utf8')
 
111
        self.assertFalse(repo.has_revision(revid))
 
112
        self.local_wt.commit(message='test commit', rev_id=revid)
 
113
        self.assertTrue(repo.has_revision(revid))
 
114
 
 
115
    def test_remote_branch_revision_history(self):
 
116
        b = BzrDir.open_from_transport(self.transport).open_branch()
 
117
        self.assertEqual([], b.revision_history())
 
118
        r1 = self.local_wt.commit('1st commit')
 
119
        r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
 
120
        self.assertEqual([r1, r2], b.revision_history())
 
121
 
 
122
    def test_find_correct_format(self):
 
123
        """Should open a RemoteBzrDir over a RemoteTransport"""
 
124
        fmt = BzrDirFormat.find_format(self.transport)
 
125
        self.assertTrue(RemoteBzrDirFormat
 
126
                        in BzrDirFormat._control_server_formats)
 
127
        self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
 
128
 
 
129
    def test_open_detected_smart_format(self):
 
130
        fmt = BzrDirFormat.find_format(self.transport)
 
131
        d = fmt.open(self.transport)
 
132
        self.assertIsInstance(d, BzrDir)
 
133
 
 
134
    def test_remote_branch_repr(self):
 
135
        b = BzrDir.open_from_transport(self.transport).open_branch()
 
136
        self.assertStartsWith(str(b), 'RemoteBranch(')
 
137
 
 
138
    def test_remote_branch_format_supports_stacking(self):
 
139
        t = self.transport
 
140
        self.make_branch('unstackable', format='pack-0.92')
 
141
        b = BzrDir.open_from_transport(t.clone('unstackable')).open_branch()
 
142
        self.assertFalse(b._format.supports_stacking())
 
143
        self.make_branch('stackable', format='1.9')
 
144
        b = BzrDir.open_from_transport(t.clone('stackable')).open_branch()
 
145
        self.assertTrue(b._format.supports_stacking())
 
146
 
 
147
    def test_remote_repo_format_supports_external_references(self):
 
148
        t = self.transport
 
149
        bd = self.make_bzrdir('unstackable', format='pack-0.92')
 
150
        r = bd.create_repository()
 
151
        self.assertFalse(r._format.supports_external_lookups)
 
152
        r = BzrDir.open_from_transport(t.clone('unstackable')).open_repository()
 
153
        self.assertFalse(r._format.supports_external_lookups)
 
154
        bd = self.make_bzrdir('stackable', format='1.9')
 
155
        r = bd.create_repository()
 
156
        self.assertTrue(r._format.supports_external_lookups)
 
157
        r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
 
158
        self.assertTrue(r._format.supports_external_lookups)
 
159
 
 
160
    def test_remote_branch_set_append_revisions_only(self):
 
161
        # Make a format 1.9 branch, which supports append_revisions_only
 
162
        branch = self.make_branch('branch', format='1.9')
 
163
        config = branch.get_config()
 
164
        branch.set_append_revisions_only(True)
 
165
        self.assertEqual(
 
166
            'True', config.get_user_option('append_revisions_only'))
 
167
        branch.set_append_revisions_only(False)
 
168
        self.assertEqual(
 
169
            'False', config.get_user_option('append_revisions_only'))
 
170
 
 
171
    def test_remote_branch_set_append_revisions_only_upgrade_reqd(self):
 
172
        branch = self.make_branch('branch', format='knit')
 
173
        config = branch.get_config()
 
174
        self.assertRaises(
 
175
            errors.UpgradeRequired, branch.set_append_revisions_only, True)
 
176
 
 
177
 
 
178
class FakeProtocol(object):
 
179
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
 
180
 
 
181
    def __init__(self, body, fake_client):
 
182
        self.body = body
 
183
        self._body_buffer = None
 
184
        self._fake_client = fake_client
 
185
 
 
186
    def read_body_bytes(self, count=-1):
 
187
        if self._body_buffer is None:
 
188
            self._body_buffer = StringIO(self.body)
 
189
        bytes = self._body_buffer.read(count)
 
190
        if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
 
191
            self._fake_client.expecting_body = False
 
192
        return bytes
 
193
 
 
194
    def cancel_read_body(self):
 
195
        self._fake_client.expecting_body = False
 
196
 
 
197
    def read_streamed_body(self):
 
198
        return self.body
 
199
 
 
200
 
 
201
class FakeClient(_SmartClient):
 
202
    """Lookalike for _SmartClient allowing testing."""
 
203
 
 
204
    def __init__(self, fake_medium_base='fake base'):
 
205
        """Create a FakeClient."""
 
206
        self.responses = []
 
207
        self._calls = []
 
208
        self.expecting_body = False
 
209
        # if non-None, this is the list of expected calls, with only the
 
210
        # method name and arguments included.  the body might be hard to
 
211
        # compute so is not included. If a call is None, that call can
 
212
        # be anything.
 
213
        self._expected_calls = None
 
214
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
 
215
 
 
216
    def add_expected_call(self, call_name, call_args, response_type,
 
217
        response_args, response_body=None):
 
218
        if self._expected_calls is None:
 
219
            self._expected_calls = []
 
220
        self._expected_calls.append((call_name, call_args))
 
221
        self.responses.append((response_type, response_args, response_body))
 
222
 
 
223
    def add_success_response(self, *args):
 
224
        self.responses.append(('success', args, None))
 
225
 
 
226
    def add_success_response_with_body(self, body, *args):
 
227
        self.responses.append(('success', args, body))
 
228
        if self._expected_calls is not None:
 
229
            self._expected_calls.append(None)
 
230
 
 
231
    def add_error_response(self, *args):
 
232
        self.responses.append(('error', args))
 
233
 
 
234
    def add_unknown_method_response(self, verb):
 
235
        self.responses.append(('unknown', verb))
 
236
 
 
237
    def finished_test(self):
 
238
        if self._expected_calls:
 
239
            raise AssertionError("%r finished but was still expecting %r"
 
240
                % (self, self._expected_calls[0]))
 
241
 
 
242
    def _get_next_response(self):
 
243
        try:
 
244
            response_tuple = self.responses.pop(0)
 
245
        except IndexError, e:
 
246
            raise AssertionError("%r didn't expect any more calls"
 
247
                % (self,))
 
248
        if response_tuple[0] == 'unknown':
 
249
            raise errors.UnknownSmartMethod(response_tuple[1])
 
250
        elif response_tuple[0] == 'error':
 
251
            raise errors.ErrorFromSmartServer(response_tuple[1])
 
252
        return response_tuple
 
253
 
 
254
    def _check_call(self, method, args):
 
255
        if self._expected_calls is None:
 
256
            # the test should be updated to say what it expects
 
257
            return
 
258
        try:
 
259
            next_call = self._expected_calls.pop(0)
 
260
        except IndexError:
 
261
            raise AssertionError("%r didn't expect any more calls "
 
262
                "but got %r%r"
 
263
                % (self, method, args,))
 
264
        if next_call is None:
 
265
            return
 
266
        if method != next_call[0] or args != next_call[1]:
 
267
            raise AssertionError("%r expected %r%r "
 
268
                "but got %r%r"
 
269
                % (self, next_call[0], next_call[1], method, args,))
 
270
 
 
271
    def call(self, method, *args):
 
272
        self._check_call(method, args)
 
273
        self._calls.append(('call', method, args))
 
274
        return self._get_next_response()[1]
 
275
 
 
276
    def call_expecting_body(self, method, *args):
 
277
        self._check_call(method, args)
 
278
        self._calls.append(('call_expecting_body', method, args))
 
279
        result = self._get_next_response()
 
280
        self.expecting_body = True
 
281
        return result[1], FakeProtocol(result[2], self)
 
282
 
 
283
    def call_with_body_bytes(self, method, args, body):
 
284
        self._check_call(method, args)
 
285
        self._calls.append(('call_with_body_bytes', method, args, body))
 
286
        result = self._get_next_response()
 
287
        return result[1], FakeProtocol(result[2], self)
 
288
 
 
289
    def call_with_body_bytes_expecting_body(self, method, args, body):
 
290
        self._check_call(method, args)
 
291
        self._calls.append(('call_with_body_bytes_expecting_body', method,
 
292
            args, body))
 
293
        result = self._get_next_response()
 
294
        self.expecting_body = True
 
295
        return result[1], FakeProtocol(result[2], self)
 
296
 
 
297
    def call_with_body_stream(self, args, stream):
 
298
        # Explicitly consume the stream before checking for an error, because
 
299
        # that's what happens a real medium.
 
300
        stream = list(stream)
 
301
        self._check_call(args[0], args[1:])
 
302
        self._calls.append(('call_with_body_stream', args[0], args[1:], stream))
 
303
        result = self._get_next_response()
 
304
        # The second value returned from call_with_body_stream is supposed to
 
305
        # be a response_handler object, but so far no tests depend on that.
 
306
        response_handler = None 
 
307
        return result[1], response_handler
 
308
 
 
309
 
 
310
class FakeMedium(medium.SmartClientMedium):
 
311
 
 
312
    def __init__(self, client_calls, base):
 
313
        medium.SmartClientMedium.__init__(self, base)
 
314
        self._client_calls = client_calls
 
315
 
 
316
    def disconnect(self):
 
317
        self._client_calls.append(('disconnect medium',))
 
318
 
 
319
 
 
320
class TestVfsHas(tests.TestCase):
 
321
 
 
322
    def test_unicode_path(self):
 
323
        client = FakeClient('/')
 
324
        client.add_success_response('yes',)
 
325
        transport = RemoteTransport('bzr://localhost/', _client=client)
 
326
        filename = u'/hell\u00d8'.encode('utf8')
 
327
        result = transport.has(filename)
 
328
        self.assertEqual(
 
329
            [('call', 'has', (filename,))],
 
330
            client._calls)
 
331
        self.assertTrue(result)
 
332
 
 
333
 
 
334
class TestRemote(tests.TestCaseWithMemoryTransport):
 
335
 
 
336
    def get_branch_format(self):
 
337
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
338
        return reference_bzrdir_format.get_branch_format()
 
339
 
 
340
    def get_repo_format(self):
 
341
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
342
        return reference_bzrdir_format.repository_format
 
343
 
 
344
    def assertFinished(self, fake_client):
 
345
        """Assert that all of a FakeClient's expected calls have occurred."""
 
346
        fake_client.finished_test()
 
347
 
 
348
 
 
349
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
 
350
    """Tests for the behaviour of client_medium.remote_path_from_transport."""
 
351
 
 
352
    def assertRemotePath(self, expected, client_base, transport_base):
 
353
        """Assert that the result of
 
354
        SmartClientMedium.remote_path_from_transport is the expected value for
 
355
        a given client_base and transport_base.
 
356
        """
 
357
        client_medium = medium.SmartClientMedium(client_base)
 
358
        transport = get_transport(transport_base)
 
359
        result = client_medium.remote_path_from_transport(transport)
 
360
        self.assertEqual(expected, result)
 
361
 
 
362
    def test_remote_path_from_transport(self):
 
363
        """SmartClientMedium.remote_path_from_transport calculates a URL for
 
364
        the given transport relative to the root of the client base URL.
 
365
        """
 
366
        self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
 
367
        self.assertRemotePath(
 
368
            'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
 
369
 
 
370
    def assertRemotePathHTTP(self, expected, transport_base, relpath):
 
371
        """Assert that the result of
 
372
        HttpTransportBase.remote_path_from_transport is the expected value for
 
373
        a given transport_base and relpath of that transport.  (Note that
 
374
        HttpTransportBase is a subclass of SmartClientMedium)
 
375
        """
 
376
        base_transport = get_transport(transport_base)
 
377
        client_medium = base_transport.get_smart_medium()
 
378
        cloned_transport = base_transport.clone(relpath)
 
379
        result = client_medium.remote_path_from_transport(cloned_transport)
 
380
        self.assertEqual(expected, result)
 
381
 
 
382
    def test_remote_path_from_transport_http(self):
 
383
        """Remote paths for HTTP transports are calculated differently to other
 
384
        transports.  They are just relative to the client base, not the root
 
385
        directory of the host.
 
386
        """
 
387
        for scheme in ['http:', 'https:', 'bzr+http:', 'bzr+https:']:
 
388
            self.assertRemotePathHTTP(
 
389
                '../xyz/', scheme + '//host/path', '../xyz/')
 
390
            self.assertRemotePathHTTP(
 
391
                'xyz/', scheme + '//host/path', 'xyz/')
 
392
 
 
393
 
 
394
class Test_ClientMedium_remote_is_at_least(tests.TestCase):
 
395
    """Tests for the behaviour of client_medium.remote_is_at_least."""
 
396
 
 
397
    def test_initially_unlimited(self):
 
398
        """A fresh medium assumes that the remote side supports all
 
399
        versions.
 
400
        """
 
401
        client_medium = medium.SmartClientMedium('dummy base')
 
402
        self.assertFalse(client_medium._is_remote_before((99, 99)))
 
403
 
 
404
    def test__remember_remote_is_before(self):
 
405
        """Calling _remember_remote_is_before ratchets down the known remote
 
406
        version.
 
407
        """
 
408
        client_medium = medium.SmartClientMedium('dummy base')
 
409
        # Mark the remote side as being less than 1.6.  The remote side may
 
410
        # still be 1.5.
 
411
        client_medium._remember_remote_is_before((1, 6))
 
412
        self.assertTrue(client_medium._is_remote_before((1, 6)))
 
413
        self.assertFalse(client_medium._is_remote_before((1, 5)))
 
414
        # Calling _remember_remote_is_before again with a lower value works.
 
415
        client_medium._remember_remote_is_before((1, 5))
 
416
        self.assertTrue(client_medium._is_remote_before((1, 5)))
 
417
        # You cannot call _remember_remote_is_before with a larger value.
 
418
        self.assertRaises(
 
419
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
 
420
 
 
421
 
 
422
class TestBzrDirCloningMetaDir(TestRemote):
 
423
 
 
424
    def test_backwards_compat(self):
 
425
        self.setup_smart_server_with_call_log()
 
426
        a_dir = self.make_bzrdir('.')
 
427
        self.reset_smart_call_log()
 
428
        verb = 'BzrDir.cloning_metadir'
 
429
        self.disable_verb(verb)
 
430
        format = a_dir.cloning_metadir()
 
431
        call_count = len([call for call in self.hpss_calls if
 
432
            call.call.method == verb])
 
433
        self.assertEqual(1, call_count)
 
434
 
 
435
    def test_branch_reference(self):
 
436
        transport = self.get_transport('quack')
 
437
        referenced = self.make_branch('referenced')
 
438
        expected = referenced.bzrdir.cloning_metadir()
 
439
        client = FakeClient(transport.base)
 
440
        client.add_expected_call(
 
441
            'BzrDir.cloning_metadir', ('quack/', 'False'),
 
442
            'error', ('BranchReference',)),
 
443
        client.add_expected_call(
 
444
            'BzrDir.open_branchV2', ('quack/',),
 
445
            'success', ('ref', self.get_url('referenced'))),
 
446
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
447
            _client=client)
 
448
        result = a_bzrdir.cloning_metadir()
 
449
        # We should have got a control dir matching the referenced branch.
 
450
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
 
451
        self.assertEqual(expected._repository_format, result._repository_format)
 
452
        self.assertEqual(expected._branch_format, result._branch_format)
 
453
        self.assertFinished(client)
 
454
 
 
455
    def test_current_server(self):
 
456
        transport = self.get_transport('.')
 
457
        transport = transport.clone('quack')
 
458
        self.make_bzrdir('quack')
 
459
        client = FakeClient(transport.base)
 
460
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
461
        control_name = reference_bzrdir_format.network_name()
 
462
        client.add_expected_call(
 
463
            'BzrDir.cloning_metadir', ('quack/', 'False'),
 
464
            'success', (control_name, '', ('branch', ''))),
 
465
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
466
            _client=client)
 
467
        result = a_bzrdir.cloning_metadir()
 
468
        # We should have got a reference control dir with default branch and
 
469
        # repository formats.
 
470
        # This pokes a little, just to be sure.
 
471
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
 
472
        self.assertEqual(None, result._repository_format)
 
473
        self.assertEqual(None, result._branch_format)
 
474
        self.assertFinished(client)
 
475
 
 
476
 
 
477
class TestBzrDirOpenBranch(TestRemote):
 
478
 
 
479
    def test_backwards_compat(self):
 
480
        self.setup_smart_server_with_call_log()
 
481
        self.make_branch('.')
 
482
        a_dir = BzrDir.open(self.get_url('.'))
 
483
        self.reset_smart_call_log()
 
484
        verb = 'BzrDir.open_branchV2'
 
485
        self.disable_verb(verb)
 
486
        format = a_dir.open_branch()
 
487
        call_count = len([call for call in self.hpss_calls if
 
488
            call.call.method == verb])
 
489
        self.assertEqual(1, call_count)
 
490
 
 
491
    def test_branch_present(self):
 
492
        reference_format = self.get_repo_format()
 
493
        network_name = reference_format.network_name()
 
494
        branch_network_name = self.get_branch_format().network_name()
 
495
        transport = MemoryTransport()
 
496
        transport.mkdir('quack')
 
497
        transport = transport.clone('quack')
 
498
        client = FakeClient(transport.base)
 
499
        client.add_expected_call(
 
500
            'BzrDir.open_branchV2', ('quack/',),
 
501
            'success', ('branch', branch_network_name))
 
502
        client.add_expected_call(
 
503
            'BzrDir.find_repositoryV3', ('quack/',),
 
504
            'success', ('ok', '', 'no', 'no', 'no', network_name))
 
505
        client.add_expected_call(
 
506
            'Branch.get_stacked_on_url', ('quack/',),
 
507
            'error', ('NotStacked',))
 
508
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
509
            _client=client)
 
510
        result = bzrdir.open_branch()
 
511
        self.assertIsInstance(result, RemoteBranch)
 
512
        self.assertEqual(bzrdir, result.bzrdir)
 
513
        self.assertFinished(client)
 
514
 
 
515
    def test_branch_missing(self):
 
516
        transport = MemoryTransport()
 
517
        transport.mkdir('quack')
 
518
        transport = transport.clone('quack')
 
519
        client = FakeClient(transport.base)
 
520
        client.add_error_response('nobranch')
 
521
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
522
            _client=client)
 
523
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
 
524
        self.assertEqual(
 
525
            [('call', 'BzrDir.open_branchV2', ('quack/',))],
 
526
            client._calls)
 
527
 
 
528
    def test__get_tree_branch(self):
 
529
        # _get_tree_branch is a form of open_branch, but it should only ask for
 
530
        # branch opening, not any other network requests.
 
531
        calls = []
 
532
        def open_branch():
 
533
            calls.append("Called")
 
534
            return "a-branch"
 
535
        transport = MemoryTransport()
 
536
        # no requests on the network - catches other api calls being made.
 
537
        client = FakeClient(transport.base)
 
538
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
539
            _client=client)
 
540
        # patch the open_branch call to record that it was called.
 
541
        bzrdir.open_branch = open_branch
 
542
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
 
543
        self.assertEqual(["Called"], calls)
 
544
        self.assertEqual([], client._calls)
 
545
 
 
546
    def test_url_quoting_of_path(self):
 
547
        # Relpaths on the wire should not be URL-escaped.  So "~" should be
 
548
        # transmitted as "~", not "%7E".
 
549
        transport = RemoteTCPTransport('bzr://localhost/~hello/')
 
550
        client = FakeClient(transport.base)
 
551
        reference_format = self.get_repo_format()
 
552
        network_name = reference_format.network_name()
 
553
        branch_network_name = self.get_branch_format().network_name()
 
554
        client.add_expected_call(
 
555
            'BzrDir.open_branchV2', ('~hello/',),
 
556
            'success', ('branch', branch_network_name))
 
557
        client.add_expected_call(
 
558
            'BzrDir.find_repositoryV3', ('~hello/',),
 
559
            'success', ('ok', '', 'no', 'no', 'no', network_name))
 
560
        client.add_expected_call(
 
561
            'Branch.get_stacked_on_url', ('~hello/',),
 
562
            'error', ('NotStacked',))
 
563
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
564
            _client=client)
 
565
        result = bzrdir.open_branch()
 
566
        self.assertFinished(client)
 
567
 
 
568
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
 
569
        reference_format = self.get_repo_format()
 
570
        network_name = reference_format.network_name()
 
571
        transport = MemoryTransport()
 
572
        transport.mkdir('quack')
 
573
        transport = transport.clone('quack')
 
574
        if rich_root:
 
575
            rich_response = 'yes'
 
576
        else:
 
577
            rich_response = 'no'
 
578
        if subtrees:
 
579
            subtree_response = 'yes'
 
580
        else:
 
581
            subtree_response = 'no'
 
582
        client = FakeClient(transport.base)
 
583
        client.add_success_response(
 
584
            'ok', '', rich_response, subtree_response, external_lookup,
 
585
            network_name)
 
586
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
587
            _client=client)
 
588
        result = bzrdir.open_repository()
 
589
        self.assertEqual(
 
590
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
 
591
            client._calls)
 
592
        self.assertIsInstance(result, RemoteRepository)
 
593
        self.assertEqual(bzrdir, result.bzrdir)
 
594
        self.assertEqual(rich_root, result._format.rich_root_data)
 
595
        self.assertEqual(subtrees, result._format.supports_tree_reference)
 
596
 
 
597
    def test_open_repository_sets_format_attributes(self):
 
598
        self.check_open_repository(True, True)
 
599
        self.check_open_repository(False, True)
 
600
        self.check_open_repository(True, False)
 
601
        self.check_open_repository(False, False)
 
602
        self.check_open_repository(False, False, 'yes')
 
603
 
 
604
    def test_old_server(self):
 
605
        """RemoteBzrDirFormat should fail to probe if the server version is too
 
606
        old.
 
607
        """
 
608
        self.assertRaises(errors.NotBranchError,
 
609
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
 
610
 
 
611
 
 
612
class TestBzrDirCreateBranch(TestRemote):
 
613
 
 
614
    def test_backwards_compat(self):
 
615
        self.setup_smart_server_with_call_log()
 
616
        repo = self.make_repository('.')
 
617
        self.reset_smart_call_log()
 
618
        self.disable_verb('BzrDir.create_branch')
 
619
        branch = repo.bzrdir.create_branch()
 
620
        create_branch_call_count = len([call for call in self.hpss_calls if
 
621
            call.call.method == 'BzrDir.create_branch'])
 
622
        self.assertEqual(1, create_branch_call_count)
 
623
 
 
624
    def test_current_server(self):
 
625
        transport = self.get_transport('.')
 
626
        transport = transport.clone('quack')
 
627
        self.make_repository('quack')
 
628
        client = FakeClient(transport.base)
 
629
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
630
        reference_format = reference_bzrdir_format.get_branch_format()
 
631
        network_name = reference_format.network_name()
 
632
        reference_repo_fmt = reference_bzrdir_format.repository_format
 
633
        reference_repo_name = reference_repo_fmt.network_name()
 
634
        client.add_expected_call(
 
635
            'BzrDir.create_branch', ('quack/', network_name),
 
636
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
 
637
            reference_repo_name))
 
638
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
639
            _client=client)
 
640
        branch = a_bzrdir.create_branch()
 
641
        # We should have got a remote branch
 
642
        self.assertIsInstance(branch, remote.RemoteBranch)
 
643
        # its format should have the settings from the response
 
644
        format = branch._format
 
645
        self.assertEqual(network_name, format.network_name())
 
646
 
 
647
 
 
648
class TestBzrDirCreateRepository(TestRemote):
 
649
 
 
650
    def test_backwards_compat(self):
 
651
        self.setup_smart_server_with_call_log()
 
652
        bzrdir = self.make_bzrdir('.')
 
653
        self.reset_smart_call_log()
 
654
        self.disable_verb('BzrDir.create_repository')
 
655
        repo = bzrdir.create_repository()
 
656
        create_repo_call_count = len([call for call in self.hpss_calls if
 
657
            call.call.method == 'BzrDir.create_repository'])
 
658
        self.assertEqual(1, create_repo_call_count)
 
659
 
 
660
    def test_current_server(self):
 
661
        transport = self.get_transport('.')
 
662
        transport = transport.clone('quack')
 
663
        self.make_bzrdir('quack')
 
664
        client = FakeClient(transport.base)
 
665
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
666
        reference_format = reference_bzrdir_format.repository_format
 
667
        network_name = reference_format.network_name()
 
668
        client.add_expected_call(
 
669
            'BzrDir.create_repository', ('quack/',
 
670
                'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
671
                'False'),
 
672
            'success', ('ok', 'yes', 'yes', 'yes', network_name))
 
673
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
674
            _client=client)
 
675
        repo = a_bzrdir.create_repository()
 
676
        # We should have got a remote repository
 
677
        self.assertIsInstance(repo, remote.RemoteRepository)
 
678
        # its format should have the settings from the response
 
679
        format = repo._format
 
680
        self.assertTrue(format.rich_root_data)
 
681
        self.assertTrue(format.supports_tree_reference)
 
682
        self.assertTrue(format.supports_external_lookups)
 
683
        self.assertEqual(network_name, format.network_name())
 
684
 
 
685
 
 
686
class TestBzrDirOpenRepository(TestRemote):
 
687
 
 
688
    def test_backwards_compat_1_2_3(self):
 
689
        # fallback all the way to the first version.
 
690
        reference_format = self.get_repo_format()
 
691
        network_name = reference_format.network_name()
 
692
        client = FakeClient('bzr://example.com/')
 
693
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
 
694
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
 
695
        client.add_success_response('ok', '', 'no', 'no')
 
696
        # A real repository instance will be created to determine the network
 
697
        # name.
 
698
        client.add_success_response_with_body(
 
699
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
700
        client.add_success_response_with_body(
 
701
            reference_format.get_format_string(), 'ok')
 
702
        # PackRepository wants to do a stat
 
703
        client.add_success_response('stat', '0', '65535')
 
704
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
 
705
            _client=client)
 
706
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
707
            _client=client)
 
708
        repo = bzrdir.open_repository()
 
709
        self.assertEqual(
 
710
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
 
711
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
 
712
             ('call', 'BzrDir.find_repository', ('quack/',)),
 
713
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
714
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
 
715
             ('call', 'stat', ('/quack/.bzr/repository',)),
 
716
             ],
 
717
            client._calls)
 
718
        self.assertEqual(network_name, repo._format.network_name())
 
719
 
 
720
    def test_backwards_compat_2(self):
 
721
        # fallback to find_repositoryV2
 
722
        reference_format = self.get_repo_format()
 
723
        network_name = reference_format.network_name()
 
724
        client = FakeClient('bzr://example.com/')
 
725
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
 
726
        client.add_success_response('ok', '', 'no', 'no', 'no')
 
727
        # A real repository instance will be created to determine the network
 
728
        # name.
 
729
        client.add_success_response_with_body(
 
730
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
731
        client.add_success_response_with_body(
 
732
            reference_format.get_format_string(), 'ok')
 
733
        # PackRepository wants to do a stat
 
734
        client.add_success_response('stat', '0', '65535')
 
735
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
 
736
            _client=client)
 
737
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
738
            _client=client)
 
739
        repo = bzrdir.open_repository()
 
740
        self.assertEqual(
 
741
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
 
742
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
 
743
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
744
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
 
745
             ('call', 'stat', ('/quack/.bzr/repository',)),
 
746
             ],
 
747
            client._calls)
 
748
        self.assertEqual(network_name, repo._format.network_name())
 
749
 
 
750
    def test_current_server(self):
 
751
        reference_format = self.get_repo_format()
 
752
        network_name = reference_format.network_name()
 
753
        transport = MemoryTransport()
 
754
        transport.mkdir('quack')
 
755
        transport = transport.clone('quack')
 
756
        client = FakeClient(transport.base)
 
757
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
 
758
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
759
            _client=client)
 
760
        repo = bzrdir.open_repository()
 
761
        self.assertEqual(
 
762
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
 
763
            client._calls)
 
764
        self.assertEqual(network_name, repo._format.network_name())
 
765
 
 
766
 
 
767
class TestBzrDirFormatInitializeEx(TestRemote):
 
768
 
 
769
    def test_success(self):
 
770
        """Simple test for typical successful call."""
 
771
        fmt = bzrdir.RemoteBzrDirFormat()
 
772
        default_format_name = BzrDirFormat.get_default_format().network_name()
 
773
        transport = self.get_transport()
 
774
        client = FakeClient(transport.base)
 
775
        client.add_expected_call(
 
776
            'BzrDirFormat.initialize_ex_1.16',
 
777
                (default_format_name, 'path', 'False', 'False', 'False', '',
 
778
                 '', '', '', 'False'),
 
779
            'success',
 
780
                ('.', 'no', 'no', 'yes', 'repo fmt', 'repo bzrdir fmt',
 
781
                 'bzrdir fmt', 'False', '', '', 'repo lock token'))
 
782
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
 
783
        # it's currently hard to test that without supplying a real remote
 
784
        # transport connected to a real server.
 
785
        result = fmt._initialize_on_transport_ex_rpc(client, 'path',
 
786
            transport, False, False, False, None, None, None, None, False)
 
787
        self.assertFinished(client)
 
788
 
 
789
    def test_error(self):
 
790
        """Error responses are translated, e.g. 'PermissionDenied' raises the
 
791
        corresponding error from the client.
 
792
        """
 
793
        fmt = bzrdir.RemoteBzrDirFormat()
 
794
        default_format_name = BzrDirFormat.get_default_format().network_name()
 
795
        transport = self.get_transport()
 
796
        client = FakeClient(transport.base)
 
797
        client.add_expected_call(
 
798
            'BzrDirFormat.initialize_ex_1.16',
 
799
                (default_format_name, 'path', 'False', 'False', 'False', '',
 
800
                 '', '', '', 'False'),
 
801
            'error',
 
802
                ('PermissionDenied', 'path', 'extra info'))
 
803
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
 
804
        # it's currently hard to test that without supplying a real remote
 
805
        # transport connected to a real server.
 
806
        err = self.assertRaises(errors.PermissionDenied,
 
807
            fmt._initialize_on_transport_ex_rpc, client, 'path', transport,
 
808
            False, False, False, None, None, None, None, False)
 
809
        self.assertEqual('path', err.path)
 
810
        self.assertEqual(': extra info', err.extra)
 
811
        self.assertFinished(client)
 
812
 
 
813
    def test_error_from_real_server(self):
 
814
        """Integration test for error translation."""
 
815
        transport = self.make_smart_server('foo')
 
816
        transport = transport.clone('no-such-path')
 
817
        fmt = bzrdir.RemoteBzrDirFormat()
 
818
        err = self.assertRaises(errors.NoSuchFile,
 
819
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
 
820
 
 
821
 
 
822
class OldSmartClient(object):
 
823
    """A fake smart client for test_old_version that just returns a version one
 
824
    response to the 'hello' (query version) command.
 
825
    """
 
826
 
 
827
    def get_request(self):
 
828
        input_file = StringIO('ok\x011\n')
 
829
        output_file = StringIO()
 
830
        client_medium = medium.SmartSimplePipesClientMedium(
 
831
            input_file, output_file)
 
832
        return medium.SmartClientStreamMediumRequest(client_medium)
 
833
 
 
834
    def protocol_version(self):
 
835
        return 1
 
836
 
 
837
 
 
838
class OldServerTransport(object):
 
839
    """A fake transport for test_old_server that reports it's smart server
 
840
    protocol version as version one.
 
841
    """
 
842
 
 
843
    def __init__(self):
 
844
        self.base = 'fake:'
 
845
 
 
846
    def get_smart_client(self):
 
847
        return OldSmartClient()
 
848
 
 
849
 
 
850
class RemoteBzrDirTestCase(TestRemote):
 
851
 
 
852
    def make_remote_bzrdir(self, transport, client):
 
853
        """Make a RemotebzrDir using 'client' as the _client."""
 
854
        return RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
855
            _client=client)
 
856
 
 
857
 
 
858
class RemoteBranchTestCase(RemoteBzrDirTestCase):
 
859
 
 
860
    def lock_remote_branch(self, branch):
 
861
        """Trick a RemoteBranch into thinking it is locked."""
 
862
        branch._lock_mode = 'w'
 
863
        branch._lock_count = 2
 
864
        branch._lock_token = 'branch token'
 
865
        branch._repo_lock_token = 'repo token'
 
866
        branch.repository._lock_mode = 'w'
 
867
        branch.repository._lock_count = 2
 
868
        branch.repository._lock_token = 'repo token'
 
869
 
 
870
    def make_remote_branch(self, transport, client):
 
871
        """Make a RemoteBranch using 'client' as its _SmartClient.
 
872
 
 
873
        A RemoteBzrDir and RemoteRepository will also be created to fill out
 
874
        the RemoteBranch, albeit with stub values for some of their attributes.
 
875
        """
 
876
        # we do not want bzrdir to make any remote calls, so use False as its
 
877
        # _client.  If it tries to make a remote call, this will fail
 
878
        # immediately.
 
879
        bzrdir = self.make_remote_bzrdir(transport, False)
 
880
        repo = RemoteRepository(bzrdir, None, _client=client)
 
881
        branch_format = self.get_branch_format()
 
882
        format = RemoteBranchFormat(network_name=branch_format.network_name())
 
883
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
 
884
 
 
885
 
 
886
class TestBranchGetParent(RemoteBranchTestCase):
 
887
 
 
888
    def test_no_parent(self):
 
889
        # in an empty branch we decode the response properly
 
890
        transport = MemoryTransport()
 
891
        client = FakeClient(transport.base)
 
892
        client.add_expected_call(
 
893
            'Branch.get_stacked_on_url', ('quack/',),
 
894
            'error', ('NotStacked',))
 
895
        client.add_expected_call(
 
896
            'Branch.get_parent', ('quack/',),
 
897
            'success', ('',))
 
898
        transport.mkdir('quack')
 
899
        transport = transport.clone('quack')
 
900
        branch = self.make_remote_branch(transport, client)
 
901
        result = branch.get_parent()
 
902
        self.assertFinished(client)
 
903
        self.assertEqual(None, result)
 
904
 
 
905
    def test_parent_relative(self):
 
906
        transport = MemoryTransport()
 
907
        client = FakeClient(transport.base)
 
908
        client.add_expected_call(
 
909
            'Branch.get_stacked_on_url', ('kwaak/',),
 
910
            'error', ('NotStacked',))
 
911
        client.add_expected_call(
 
912
            'Branch.get_parent', ('kwaak/',),
 
913
            'success', ('../foo/',))
 
914
        transport.mkdir('kwaak')
 
915
        transport = transport.clone('kwaak')
 
916
        branch = self.make_remote_branch(transport, client)
 
917
        result = branch.get_parent()
 
918
        self.assertEqual(transport.clone('../foo').base, result)
 
919
 
 
920
    def test_parent_absolute(self):
 
921
        transport = MemoryTransport()
 
922
        client = FakeClient(transport.base)
 
923
        client.add_expected_call(
 
924
            'Branch.get_stacked_on_url', ('kwaak/',),
 
925
            'error', ('NotStacked',))
 
926
        client.add_expected_call(
 
927
            'Branch.get_parent', ('kwaak/',),
 
928
            'success', ('http://foo/',))
 
929
        transport.mkdir('kwaak')
 
930
        transport = transport.clone('kwaak')
 
931
        branch = self.make_remote_branch(transport, client)
 
932
        result = branch.get_parent()
 
933
        self.assertEqual('http://foo/', result)
 
934
        self.assertFinished(client)
 
935
 
 
936
 
 
937
class TestBranchSetParentLocation(RemoteBranchTestCase):
 
938
 
 
939
    def test_no_parent(self):
 
940
        # We call the verb when setting parent to None
 
941
        transport = MemoryTransport()
 
942
        client = FakeClient(transport.base)
 
943
        client.add_expected_call(
 
944
            'Branch.get_stacked_on_url', ('quack/',),
 
945
            'error', ('NotStacked',))
 
946
        client.add_expected_call(
 
947
            'Branch.set_parent_location', ('quack/', 'b', 'r', ''),
 
948
            'success', ())
 
949
        transport.mkdir('quack')
 
950
        transport = transport.clone('quack')
 
951
        branch = self.make_remote_branch(transport, client)
 
952
        branch._lock_token = 'b'
 
953
        branch._repo_lock_token = 'r'
 
954
        branch._set_parent_location(None)
 
955
        self.assertFinished(client)
 
956
 
 
957
    def test_parent(self):
 
958
        transport = MemoryTransport()
 
959
        client = FakeClient(transport.base)
 
960
        client.add_expected_call(
 
961
            'Branch.get_stacked_on_url', ('kwaak/',),
 
962
            'error', ('NotStacked',))
 
963
        client.add_expected_call(
 
964
            'Branch.set_parent_location', ('kwaak/', 'b', 'r', 'foo'),
 
965
            'success', ())
 
966
        transport.mkdir('kwaak')
 
967
        transport = transport.clone('kwaak')
 
968
        branch = self.make_remote_branch(transport, client)
 
969
        branch._lock_token = 'b'
 
970
        branch._repo_lock_token = 'r'
 
971
        branch._set_parent_location('foo')
 
972
        self.assertFinished(client)
 
973
 
 
974
    def test_backwards_compat(self):
 
975
        self.setup_smart_server_with_call_log()
 
976
        branch = self.make_branch('.')
 
977
        self.reset_smart_call_log()
 
978
        verb = 'Branch.set_parent_location'
 
979
        self.disable_verb(verb)
 
980
        branch.set_parent('http://foo/')
 
981
        self.assertLength(12, self.hpss_calls)
 
982
 
 
983
 
 
984
class TestBranchGetTagsBytes(RemoteBranchTestCase):
 
985
 
 
986
    def test_backwards_compat(self):
 
987
        self.setup_smart_server_with_call_log()
 
988
        branch = self.make_branch('.')
 
989
        self.reset_smart_call_log()
 
990
        verb = 'Branch.get_tags_bytes'
 
991
        self.disable_verb(verb)
 
992
        branch.tags.get_tag_dict()
 
993
        call_count = len([call for call in self.hpss_calls if
 
994
            call.call.method == verb])
 
995
        self.assertEqual(1, call_count)
 
996
 
 
997
    def test_trivial(self):
 
998
        transport = MemoryTransport()
 
999
        client = FakeClient(transport.base)
 
1000
        client.add_expected_call(
 
1001
            'Branch.get_stacked_on_url', ('quack/',),
 
1002
            'error', ('NotStacked',))
 
1003
        client.add_expected_call(
 
1004
            'Branch.get_tags_bytes', ('quack/',),
 
1005
            'success', ('',))
 
1006
        transport.mkdir('quack')
 
1007
        transport = transport.clone('quack')
 
1008
        branch = self.make_remote_branch(transport, client)
 
1009
        result = branch.tags.get_tag_dict()
 
1010
        self.assertFinished(client)
 
1011
        self.assertEqual({}, result)
 
1012
 
 
1013
 
 
1014
class TestBranchSetTagsBytes(RemoteBranchTestCase):
 
1015
 
 
1016
    def test_trivial(self):
 
1017
        transport = MemoryTransport()
 
1018
        client = FakeClient(transport.base)
 
1019
        client.add_expected_call(
 
1020
            'Branch.get_stacked_on_url', ('quack/',),
 
1021
            'error', ('NotStacked',))
 
1022
        client.add_expected_call(
 
1023
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
 
1024
            'success', ('',))
 
1025
        transport.mkdir('quack')
 
1026
        transport = transport.clone('quack')
 
1027
        branch = self.make_remote_branch(transport, client)
 
1028
        self.lock_remote_branch(branch)
 
1029
        branch._set_tags_bytes('tags bytes')
 
1030
        self.assertFinished(client)
 
1031
        self.assertEqual('tags bytes', client._calls[-1][-1])
 
1032
 
 
1033
    def test_backwards_compatible(self):
 
1034
        transport = MemoryTransport()
 
1035
        client = FakeClient(transport.base)
 
1036
        client.add_expected_call(
 
1037
            'Branch.get_stacked_on_url', ('quack/',),
 
1038
            'error', ('NotStacked',))
 
1039
        client.add_expected_call(
 
1040
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
 
1041
            'unknown', ('Branch.set_tags_bytes',))
 
1042
        transport.mkdir('quack')
 
1043
        transport = transport.clone('quack')
 
1044
        branch = self.make_remote_branch(transport, client)
 
1045
        self.lock_remote_branch(branch)
 
1046
        class StubRealBranch(object):
 
1047
            def __init__(self):
 
1048
                self.calls = []
 
1049
            def _set_tags_bytes(self, bytes):
 
1050
                self.calls.append(('set_tags_bytes', bytes))
 
1051
        real_branch = StubRealBranch()
 
1052
        branch._real_branch = real_branch
 
1053
        branch._set_tags_bytes('tags bytes')
 
1054
        # Call a second time, to exercise the 'remote version already inferred'
 
1055
        # code path.
 
1056
        branch._set_tags_bytes('tags bytes')
 
1057
        self.assertFinished(client)
 
1058
        self.assertEqual(
 
1059
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
 
1060
 
 
1061
 
 
1062
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
 
1063
 
 
1064
    def test_empty_branch(self):
 
1065
        # in an empty branch we decode the response properly
 
1066
        transport = MemoryTransport()
 
1067
        client = FakeClient(transport.base)
 
1068
        client.add_expected_call(
 
1069
            'Branch.get_stacked_on_url', ('quack/',),
 
1070
            'error', ('NotStacked',))
 
1071
        client.add_expected_call(
 
1072
            'Branch.last_revision_info', ('quack/',),
 
1073
            'success', ('ok', '0', 'null:'))
 
1074
        transport.mkdir('quack')
 
1075
        transport = transport.clone('quack')
 
1076
        branch = self.make_remote_branch(transport, client)
 
1077
        result = branch.last_revision_info()
 
1078
        self.assertFinished(client)
 
1079
        self.assertEqual((0, NULL_REVISION), result)
 
1080
 
 
1081
    def test_non_empty_branch(self):
 
1082
        # in a non-empty branch we also decode the response properly
 
1083
        revid = u'\xc8'.encode('utf8')
 
1084
        transport = MemoryTransport()
 
1085
        client = FakeClient(transport.base)
 
1086
        client.add_expected_call(
 
1087
            'Branch.get_stacked_on_url', ('kwaak/',),
 
1088
            'error', ('NotStacked',))
 
1089
        client.add_expected_call(
 
1090
            'Branch.last_revision_info', ('kwaak/',),
 
1091
            'success', ('ok', '2', revid))
 
1092
        transport.mkdir('kwaak')
 
1093
        transport = transport.clone('kwaak')
 
1094
        branch = self.make_remote_branch(transport, client)
 
1095
        result = branch.last_revision_info()
 
1096
        self.assertEqual((2, revid), result)
 
1097
 
 
1098
 
 
1099
class TestBranch_get_stacked_on_url(TestRemote):
 
1100
    """Test Branch._get_stacked_on_url rpc"""
 
1101
 
 
1102
    def test_get_stacked_on_invalid_url(self):
 
1103
        # test that asking for a stacked on url the server can't access works.
 
1104
        # This isn't perfect, but then as we're in the same process there
 
1105
        # really isn't anything we can do to be 100% sure that the server
 
1106
        # doesn't just open in - this test probably needs to be rewritten using
 
1107
        # a spawn()ed server.
 
1108
        stacked_branch = self.make_branch('stacked', format='1.9')
 
1109
        memory_branch = self.make_branch('base', format='1.9')
 
1110
        vfs_url = self.get_vfs_only_url('base')
 
1111
        stacked_branch.set_stacked_on_url(vfs_url)
 
1112
        transport = stacked_branch.bzrdir.root_transport
 
1113
        client = FakeClient(transport.base)
 
1114
        client.add_expected_call(
 
1115
            'Branch.get_stacked_on_url', ('stacked/',),
 
1116
            'success', ('ok', vfs_url))
 
1117
        # XXX: Multiple calls are bad, this second call documents what is
 
1118
        # today.
 
1119
        client.add_expected_call(
 
1120
            'Branch.get_stacked_on_url', ('stacked/',),
 
1121
            'success', ('ok', vfs_url))
 
1122
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1123
            _client=client)
 
1124
        repo_fmt = remote.RemoteRepositoryFormat()
 
1125
        repo_fmt._custom_format = stacked_branch.repository._format
 
1126
        branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, repo_fmt),
 
1127
            _client=client)
 
1128
        result = branch.get_stacked_on_url()
 
1129
        self.assertEqual(vfs_url, result)
 
1130
 
 
1131
    def test_backwards_compatible(self):
 
1132
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
 
1133
        base_branch = self.make_branch('base', format='1.6')
 
1134
        stacked_branch = self.make_branch('stacked', format='1.6')
 
1135
        stacked_branch.set_stacked_on_url('../base')
 
1136
        client = FakeClient(self.get_url())
 
1137
        branch_network_name = self.get_branch_format().network_name()
 
1138
        client.add_expected_call(
 
1139
            'BzrDir.open_branchV2', ('stacked/',),
 
1140
            'success', ('branch', branch_network_name))
 
1141
        client.add_expected_call(
 
1142
            'BzrDir.find_repositoryV3', ('stacked/',),
 
1143
            'success', ('ok', '', 'no', 'no', 'yes',
 
1144
                stacked_branch.repository._format.network_name()))
 
1145
        # called twice, once from constructor and then again by us
 
1146
        client.add_expected_call(
 
1147
            'Branch.get_stacked_on_url', ('stacked/',),
 
1148
            'unknown', ('Branch.get_stacked_on_url',))
 
1149
        client.add_expected_call(
 
1150
            'Branch.get_stacked_on_url', ('stacked/',),
 
1151
            'unknown', ('Branch.get_stacked_on_url',))
 
1152
        # this will also do vfs access, but that goes direct to the transport
 
1153
        # and isn't seen by the FakeClient.
 
1154
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
 
1155
            remote.RemoteBzrDirFormat(), _client=client)
 
1156
        branch = bzrdir.open_branch()
 
1157
        result = branch.get_stacked_on_url()
 
1158
        self.assertEqual('../base', result)
 
1159
        self.assertFinished(client)
 
1160
        # it's in the fallback list both for the RemoteRepository and its vfs
 
1161
        # repository
 
1162
        self.assertEqual(1, len(branch.repository._fallback_repositories))
 
1163
        self.assertEqual(1,
 
1164
            len(branch.repository._real_repository._fallback_repositories))
 
1165
 
 
1166
    def test_get_stacked_on_real_branch(self):
 
1167
        base_branch = self.make_branch('base', format='1.6')
 
1168
        stacked_branch = self.make_branch('stacked', format='1.6')
 
1169
        stacked_branch.set_stacked_on_url('../base')
 
1170
        reference_format = self.get_repo_format()
 
1171
        network_name = reference_format.network_name()
 
1172
        client = FakeClient(self.get_url())
 
1173
        branch_network_name = self.get_branch_format().network_name()
 
1174
        client.add_expected_call(
 
1175
            'BzrDir.open_branchV2', ('stacked/',),
 
1176
            'success', ('branch', branch_network_name))
 
1177
        client.add_expected_call(
 
1178
            'BzrDir.find_repositoryV3', ('stacked/',),
 
1179
            'success', ('ok', '', 'no', 'no', 'yes', network_name))
 
1180
        # called twice, once from constructor and then again by us
 
1181
        client.add_expected_call(
 
1182
            'Branch.get_stacked_on_url', ('stacked/',),
 
1183
            'success', ('ok', '../base'))
 
1184
        client.add_expected_call(
 
1185
            'Branch.get_stacked_on_url', ('stacked/',),
 
1186
            'success', ('ok', '../base'))
 
1187
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
 
1188
            remote.RemoteBzrDirFormat(), _client=client)
 
1189
        branch = bzrdir.open_branch()
 
1190
        result = branch.get_stacked_on_url()
 
1191
        self.assertEqual('../base', result)
 
1192
        self.assertFinished(client)
 
1193
        # it's in the fallback list both for the RemoteRepository.
 
1194
        self.assertEqual(1, len(branch.repository._fallback_repositories))
 
1195
        # And we haven't had to construct a real repository.
 
1196
        self.assertEqual(None, branch.repository._real_repository)
 
1197
 
 
1198
 
 
1199
class TestBranchSetLastRevision(RemoteBranchTestCase):
 
1200
 
 
1201
    def test_set_empty(self):
 
1202
        # set_revision_history([]) is translated to calling
 
1203
        # Branch.set_last_revision(path, '') on the wire.
 
1204
        transport = MemoryTransport()
 
1205
        transport.mkdir('branch')
 
1206
        transport = transport.clone('branch')
 
1207
 
 
1208
        client = FakeClient(transport.base)
 
1209
        client.add_expected_call(
 
1210
            'Branch.get_stacked_on_url', ('branch/',),
 
1211
            'error', ('NotStacked',))
 
1212
        client.add_expected_call(
 
1213
            'Branch.lock_write', ('branch/', '', ''),
 
1214
            'success', ('ok', 'branch token', 'repo token'))
 
1215
        client.add_expected_call(
 
1216
            'Branch.last_revision_info',
 
1217
            ('branch/',),
 
1218
            'success', ('ok', '0', 'null:'))
 
1219
        client.add_expected_call(
 
1220
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
 
1221
            'success', ('ok',))
 
1222
        client.add_expected_call(
 
1223
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
 
1224
            'success', ('ok',))
 
1225
        branch = self.make_remote_branch(transport, client)
 
1226
        # This is a hack to work around the problem that RemoteBranch currently
 
1227
        # unnecessarily invokes _ensure_real upon a call to lock_write.
 
1228
        branch._ensure_real = lambda: None
 
1229
        branch.lock_write()
 
1230
        result = branch.set_revision_history([])
 
1231
        branch.unlock()
 
1232
        self.assertEqual(None, result)
 
1233
        self.assertFinished(client)
 
1234
 
 
1235
    def test_set_nonempty(self):
 
1236
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
 
1237
        # Branch.set_last_revision(path, rev-idN) on the wire.
 
1238
        transport = MemoryTransport()
 
1239
        transport.mkdir('branch')
 
1240
        transport = transport.clone('branch')
 
1241
 
 
1242
        client = FakeClient(transport.base)
 
1243
        client.add_expected_call(
 
1244
            'Branch.get_stacked_on_url', ('branch/',),
 
1245
            'error', ('NotStacked',))
 
1246
        client.add_expected_call(
 
1247
            'Branch.lock_write', ('branch/', '', ''),
 
1248
            'success', ('ok', 'branch token', 'repo token'))
 
1249
        client.add_expected_call(
 
1250
            'Branch.last_revision_info',
 
1251
            ('branch/',),
 
1252
            'success', ('ok', '0', 'null:'))
 
1253
        lines = ['rev-id2']
 
1254
        encoded_body = bz2.compress('\n'.join(lines))
 
1255
        client.add_success_response_with_body(encoded_body, 'ok')
 
1256
        client.add_expected_call(
 
1257
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
 
1258
            'success', ('ok',))
 
1259
        client.add_expected_call(
 
1260
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
 
1261
            'success', ('ok',))
 
1262
        branch = self.make_remote_branch(transport, client)
 
1263
        # This is a hack to work around the problem that RemoteBranch currently
 
1264
        # unnecessarily invokes _ensure_real upon a call to lock_write.
 
1265
        branch._ensure_real = lambda: None
 
1266
        # Lock the branch, reset the record of remote calls.
 
1267
        branch.lock_write()
 
1268
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
 
1269
        branch.unlock()
 
1270
        self.assertEqual(None, result)
 
1271
        self.assertFinished(client)
 
1272
 
 
1273
    def test_no_such_revision(self):
 
1274
        transport = MemoryTransport()
 
1275
        transport.mkdir('branch')
 
1276
        transport = transport.clone('branch')
 
1277
        # A response of 'NoSuchRevision' is translated into an exception.
 
1278
        client = FakeClient(transport.base)
 
1279
        client.add_expected_call(
 
1280
            'Branch.get_stacked_on_url', ('branch/',),
 
1281
            'error', ('NotStacked',))
 
1282
        client.add_expected_call(
 
1283
            'Branch.lock_write', ('branch/', '', ''),
 
1284
            'success', ('ok', 'branch token', 'repo token'))
 
1285
        client.add_expected_call(
 
1286
            'Branch.last_revision_info',
 
1287
            ('branch/',),
 
1288
            'success', ('ok', '0', 'null:'))
 
1289
        # get_graph calls to construct the revision history, for the set_rh
 
1290
        # hook
 
1291
        lines = ['rev-id']
 
1292
        encoded_body = bz2.compress('\n'.join(lines))
 
1293
        client.add_success_response_with_body(encoded_body, 'ok')
 
1294
        client.add_expected_call(
 
1295
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
 
1296
            'error', ('NoSuchRevision', 'rev-id'))
 
1297
        client.add_expected_call(
 
1298
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
 
1299
            'success', ('ok',))
 
1300
 
 
1301
        branch = self.make_remote_branch(transport, client)
 
1302
        branch.lock_write()
 
1303
        self.assertRaises(
 
1304
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
 
1305
        branch.unlock()
 
1306
        self.assertFinished(client)
 
1307
 
 
1308
    def test_tip_change_rejected(self):
 
1309
        """TipChangeRejected responses cause a TipChangeRejected exception to
 
1310
        be raised.
 
1311
        """
 
1312
        transport = MemoryTransport()
 
1313
        transport.mkdir('branch')
 
1314
        transport = transport.clone('branch')
 
1315
        client = FakeClient(transport.base)
 
1316
        rejection_msg_unicode = u'rejection message\N{INTERROBANG}'
 
1317
        rejection_msg_utf8 = rejection_msg_unicode.encode('utf8')
 
1318
        client.add_expected_call(
 
1319
            'Branch.get_stacked_on_url', ('branch/',),
 
1320
            'error', ('NotStacked',))
 
1321
        client.add_expected_call(
 
1322
            'Branch.lock_write', ('branch/', '', ''),
 
1323
            'success', ('ok', 'branch token', 'repo token'))
 
1324
        client.add_expected_call(
 
1325
            'Branch.last_revision_info',
 
1326
            ('branch/',),
 
1327
            'success', ('ok', '0', 'null:'))
 
1328
        lines = ['rev-id']
 
1329
        encoded_body = bz2.compress('\n'.join(lines))
 
1330
        client.add_success_response_with_body(encoded_body, 'ok')
 
1331
        client.add_expected_call(
 
1332
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
 
1333
            'error', ('TipChangeRejected', rejection_msg_utf8))
 
1334
        client.add_expected_call(
 
1335
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
 
1336
            'success', ('ok',))
 
1337
        branch = self.make_remote_branch(transport, client)
 
1338
        branch._ensure_real = lambda: None
 
1339
        branch.lock_write()
 
1340
        # The 'TipChangeRejected' error response triggered by calling
 
1341
        # set_revision_history causes a TipChangeRejected exception.
 
1342
        err = self.assertRaises(
 
1343
            errors.TipChangeRejected, branch.set_revision_history, ['rev-id'])
 
1344
        # The UTF-8 message from the response has been decoded into a unicode
 
1345
        # object.
 
1346
        self.assertIsInstance(err.msg, unicode)
 
1347
        self.assertEqual(rejection_msg_unicode, err.msg)
 
1348
        branch.unlock()
 
1349
        self.assertFinished(client)
 
1350
 
 
1351
 
 
1352
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
 
1353
 
 
1354
    def test_set_last_revision_info(self):
 
1355
        # set_last_revision_info(num, 'rev-id') is translated to calling
 
1356
        # Branch.set_last_revision_info(num, 'rev-id') on the wire.
 
1357
        transport = MemoryTransport()
 
1358
        transport.mkdir('branch')
 
1359
        transport = transport.clone('branch')
 
1360
        client = FakeClient(transport.base)
 
1361
        # get_stacked_on_url
 
1362
        client.add_error_response('NotStacked')
 
1363
        # lock_write
 
1364
        client.add_success_response('ok', 'branch token', 'repo token')
 
1365
        # query the current revision
 
1366
        client.add_success_response('ok', '0', 'null:')
 
1367
        # set_last_revision
 
1368
        client.add_success_response('ok')
 
1369
        # unlock
 
1370
        client.add_success_response('ok')
 
1371
 
 
1372
        branch = self.make_remote_branch(transport, client)
 
1373
        # Lock the branch, reset the record of remote calls.
 
1374
        branch.lock_write()
 
1375
        client._calls = []
 
1376
        result = branch.set_last_revision_info(1234, 'a-revision-id')
 
1377
        self.assertEqual(
 
1378
            [('call', 'Branch.last_revision_info', ('branch/',)),
 
1379
             ('call', 'Branch.set_last_revision_info',
 
1380
                ('branch/', 'branch token', 'repo token',
 
1381
                 '1234', 'a-revision-id'))],
 
1382
            client._calls)
 
1383
        self.assertEqual(None, result)
 
1384
 
 
1385
    def test_no_such_revision(self):
 
1386
        # A response of 'NoSuchRevision' is translated into an exception.
 
1387
        transport = MemoryTransport()
 
1388
        transport.mkdir('branch')
 
1389
        transport = transport.clone('branch')
 
1390
        client = FakeClient(transport.base)
 
1391
        # get_stacked_on_url
 
1392
        client.add_error_response('NotStacked')
 
1393
        # lock_write
 
1394
        client.add_success_response('ok', 'branch token', 'repo token')
 
1395
        # set_last_revision
 
1396
        client.add_error_response('NoSuchRevision', 'revid')
 
1397
        # unlock
 
1398
        client.add_success_response('ok')
 
1399
 
 
1400
        branch = self.make_remote_branch(transport, client)
 
1401
        # Lock the branch, reset the record of remote calls.
 
1402
        branch.lock_write()
 
1403
        client._calls = []
 
1404
 
 
1405
        self.assertRaises(
 
1406
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
 
1407
        branch.unlock()
 
1408
 
 
1409
    def test_backwards_compatibility(self):
 
1410
        """If the server does not support the Branch.set_last_revision_info
 
1411
        verb (which is new in 1.4), then the client falls back to VFS methods.
 
1412
        """
 
1413
        # This test is a little messy.  Unlike most tests in this file, it
 
1414
        # doesn't purely test what a Remote* object sends over the wire, and
 
1415
        # how it reacts to responses from the wire.  It instead relies partly
 
1416
        # on asserting that the RemoteBranch will call
 
1417
        # self._real_branch.set_last_revision_info(...).
 
1418
 
 
1419
        # First, set up our RemoteBranch with a FakeClient that raises
 
1420
        # UnknownSmartMethod, and a StubRealBranch that logs how it is called.
 
1421
        transport = MemoryTransport()
 
1422
        transport.mkdir('branch')
 
1423
        transport = transport.clone('branch')
 
1424
        client = FakeClient(transport.base)
 
1425
        client.add_expected_call(
 
1426
            'Branch.get_stacked_on_url', ('branch/',),
 
1427
            'error', ('NotStacked',))
 
1428
        client.add_expected_call(
 
1429
            'Branch.last_revision_info',
 
1430
            ('branch/',),
 
1431
            'success', ('ok', '0', 'null:'))
 
1432
        client.add_expected_call(
 
1433
            'Branch.set_last_revision_info',
 
1434
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
 
1435
            'unknown', 'Branch.set_last_revision_info')
 
1436
 
 
1437
        branch = self.make_remote_branch(transport, client)
 
1438
        class StubRealBranch(object):
 
1439
            def __init__(self):
 
1440
                self.calls = []
 
1441
            def set_last_revision_info(self, revno, revision_id):
 
1442
                self.calls.append(
 
1443
                    ('set_last_revision_info', revno, revision_id))
 
1444
            def _clear_cached_state(self):
 
1445
                pass
 
1446
        real_branch = StubRealBranch()
 
1447
        branch._real_branch = real_branch
 
1448
        self.lock_remote_branch(branch)
 
1449
 
 
1450
        # Call set_last_revision_info, and verify it behaved as expected.
 
1451
        result = branch.set_last_revision_info(1234, 'a-revision-id')
 
1452
        self.assertEqual(
 
1453
            [('set_last_revision_info', 1234, 'a-revision-id')],
 
1454
            real_branch.calls)
 
1455
        self.assertFinished(client)
 
1456
 
 
1457
    def test_unexpected_error(self):
 
1458
        # If the server sends an error the client doesn't understand, it gets
 
1459
        # turned into an UnknownErrorFromSmartServer, which is presented as a
 
1460
        # non-internal error to the user.
 
1461
        transport = MemoryTransport()
 
1462
        transport.mkdir('branch')
 
1463
        transport = transport.clone('branch')
 
1464
        client = FakeClient(transport.base)
 
1465
        # get_stacked_on_url
 
1466
        client.add_error_response('NotStacked')
 
1467
        # lock_write
 
1468
        client.add_success_response('ok', 'branch token', 'repo token')
 
1469
        # set_last_revision
 
1470
        client.add_error_response('UnexpectedError')
 
1471
        # unlock
 
1472
        client.add_success_response('ok')
 
1473
 
 
1474
        branch = self.make_remote_branch(transport, client)
 
1475
        # Lock the branch, reset the record of remote calls.
 
1476
        branch.lock_write()
 
1477
        client._calls = []
 
1478
 
 
1479
        err = self.assertRaises(
 
1480
            errors.UnknownErrorFromSmartServer,
 
1481
            branch.set_last_revision_info, 123, 'revid')
 
1482
        self.assertEqual(('UnexpectedError',), err.error_tuple)
 
1483
        branch.unlock()
 
1484
 
 
1485
    def test_tip_change_rejected(self):
 
1486
        """TipChangeRejected responses cause a TipChangeRejected exception to
 
1487
        be raised.
 
1488
        """
 
1489
        transport = MemoryTransport()
 
1490
        transport.mkdir('branch')
 
1491
        transport = transport.clone('branch')
 
1492
        client = FakeClient(transport.base)
 
1493
        # get_stacked_on_url
 
1494
        client.add_error_response('NotStacked')
 
1495
        # lock_write
 
1496
        client.add_success_response('ok', 'branch token', 'repo token')
 
1497
        # set_last_revision
 
1498
        client.add_error_response('TipChangeRejected', 'rejection message')
 
1499
        # unlock
 
1500
        client.add_success_response('ok')
 
1501
 
 
1502
        branch = self.make_remote_branch(transport, client)
 
1503
        # Lock the branch, reset the record of remote calls.
 
1504
        branch.lock_write()
 
1505
        self.addCleanup(branch.unlock)
 
1506
        client._calls = []
 
1507
 
 
1508
        # The 'TipChangeRejected' error response triggered by calling
 
1509
        # set_last_revision_info causes a TipChangeRejected exception.
 
1510
        err = self.assertRaises(
 
1511
            errors.TipChangeRejected,
 
1512
            branch.set_last_revision_info, 123, 'revid')
 
1513
        self.assertEqual('rejection message', err.msg)
 
1514
 
 
1515
 
 
1516
class TestBranchGetSetConfig(RemoteBranchTestCase):
 
1517
 
 
1518
    def test_get_branch_conf(self):
 
1519
        # in an empty branch we decode the response properly
 
1520
        client = FakeClient()
 
1521
        client.add_expected_call(
 
1522
            'Branch.get_stacked_on_url', ('memory:///',),
 
1523
            'error', ('NotStacked',),)
 
1524
        client.add_success_response_with_body('# config file body', 'ok')
 
1525
        transport = MemoryTransport()
 
1526
        branch = self.make_remote_branch(transport, client)
 
1527
        config = branch.get_config()
 
1528
        config.has_explicit_nickname()
 
1529
        self.assertEqual(
 
1530
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
 
1531
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
 
1532
            client._calls)
 
1533
 
 
1534
    def test_get_multi_line_branch_conf(self):
 
1535
        # Make sure that multiple-line branch.conf files are supported
 
1536
        #
 
1537
        # https://bugs.edge.launchpad.net/bzr/+bug/354075
 
1538
        client = FakeClient()
 
1539
        client.add_expected_call(
 
1540
            'Branch.get_stacked_on_url', ('memory:///',),
 
1541
            'error', ('NotStacked',),)
 
1542
        client.add_success_response_with_body('a = 1\nb = 2\nc = 3\n', 'ok')
 
1543
        transport = MemoryTransport()
 
1544
        branch = self.make_remote_branch(transport, client)
 
1545
        config = branch.get_config()
 
1546
        self.assertEqual(u'2', config.get_user_option('b'))
 
1547
 
 
1548
    def test_set_option(self):
 
1549
        client = FakeClient()
 
1550
        client.add_expected_call(
 
1551
            'Branch.get_stacked_on_url', ('memory:///',),
 
1552
            'error', ('NotStacked',),)
 
1553
        client.add_expected_call(
 
1554
            'Branch.lock_write', ('memory:///', '', ''),
 
1555
            'success', ('ok', 'branch token', 'repo token'))
 
1556
        client.add_expected_call(
 
1557
            'Branch.set_config_option', ('memory:///', 'branch token',
 
1558
            'repo token', 'foo', 'bar', ''),
 
1559
            'success', ())
 
1560
        client.add_expected_call(
 
1561
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
 
1562
            'success', ('ok',))
 
1563
        transport = MemoryTransport()
 
1564
        branch = self.make_remote_branch(transport, client)
 
1565
        branch.lock_write()
 
1566
        config = branch._get_config()
 
1567
        config.set_option('foo', 'bar')
 
1568
        branch.unlock()
 
1569
        self.assertFinished(client)
 
1570
 
 
1571
    def test_backwards_compat_set_option(self):
 
1572
        self.setup_smart_server_with_call_log()
 
1573
        branch = self.make_branch('.')
 
1574
        verb = 'Branch.set_config_option'
 
1575
        self.disable_verb(verb)
 
1576
        branch.lock_write()
 
1577
        self.addCleanup(branch.unlock)
 
1578
        self.reset_smart_call_log()
 
1579
        branch._get_config().set_option('value', 'name')
 
1580
        self.assertLength(10, self.hpss_calls)
 
1581
        self.assertEqual('value', branch._get_config().get_option('name'))
 
1582
 
 
1583
 
 
1584
class TestBranchLockWrite(RemoteBranchTestCase):
 
1585
 
 
1586
    def test_lock_write_unlockable(self):
 
1587
        transport = MemoryTransport()
 
1588
        client = FakeClient(transport.base)
 
1589
        client.add_expected_call(
 
1590
            'Branch.get_stacked_on_url', ('quack/',),
 
1591
            'error', ('NotStacked',),)
 
1592
        client.add_expected_call(
 
1593
            'Branch.lock_write', ('quack/', '', ''),
 
1594
            'error', ('UnlockableTransport',))
 
1595
        transport.mkdir('quack')
 
1596
        transport = transport.clone('quack')
 
1597
        branch = self.make_remote_branch(transport, client)
 
1598
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
 
1599
        self.assertFinished(client)
 
1600
 
 
1601
 
 
1602
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
 
1603
 
 
1604
    def test__get_config(self):
 
1605
        client = FakeClient()
 
1606
        client.add_success_response_with_body('default_stack_on = /\n', 'ok')
 
1607
        transport = MemoryTransport()
 
1608
        bzrdir = self.make_remote_bzrdir(transport, client)
 
1609
        config = bzrdir.get_config()
 
1610
        self.assertEqual('/', config.get_default_stack_on())
 
1611
        self.assertEqual(
 
1612
            [('call_expecting_body', 'BzrDir.get_config_file', ('memory:///',))],
 
1613
            client._calls)
 
1614
 
 
1615
    def test_set_option_uses_vfs(self):
 
1616
        self.setup_smart_server_with_call_log()
 
1617
        bzrdir = self.make_bzrdir('.')
 
1618
        self.reset_smart_call_log()
 
1619
        config = bzrdir.get_config()
 
1620
        config.set_default_stack_on('/')
 
1621
        self.assertLength(3, self.hpss_calls)
 
1622
 
 
1623
    def test_backwards_compat_get_option(self):
 
1624
        self.setup_smart_server_with_call_log()
 
1625
        bzrdir = self.make_bzrdir('.')
 
1626
        verb = 'BzrDir.get_config_file'
 
1627
        self.disable_verb(verb)
 
1628
        self.reset_smart_call_log()
 
1629
        self.assertEqual(None,
 
1630
            bzrdir._get_config().get_option('default_stack_on'))
 
1631
        self.assertLength(3, self.hpss_calls)
 
1632
 
 
1633
 
 
1634
class TestTransportIsReadonly(tests.TestCase):
 
1635
 
 
1636
    def test_true(self):
 
1637
        client = FakeClient()
 
1638
        client.add_success_response('yes')
 
1639
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
1640
                                    _client=client)
 
1641
        self.assertEqual(True, transport.is_readonly())
 
1642
        self.assertEqual(
 
1643
            [('call', 'Transport.is_readonly', ())],
 
1644
            client._calls)
 
1645
 
 
1646
    def test_false(self):
 
1647
        client = FakeClient()
 
1648
        client.add_success_response('no')
 
1649
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
1650
                                    _client=client)
 
1651
        self.assertEqual(False, transport.is_readonly())
 
1652
        self.assertEqual(
 
1653
            [('call', 'Transport.is_readonly', ())],
 
1654
            client._calls)
 
1655
 
 
1656
    def test_error_from_old_server(self):
 
1657
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
 
1658
 
 
1659
        Clients should treat it as a "no" response, because is_readonly is only
 
1660
        advisory anyway (a transport could be read-write, but then the
 
1661
        underlying filesystem could be readonly anyway).
 
1662
        """
 
1663
        client = FakeClient()
 
1664
        client.add_unknown_method_response('Transport.is_readonly')
 
1665
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
1666
                                    _client=client)
 
1667
        self.assertEqual(False, transport.is_readonly())
 
1668
        self.assertEqual(
 
1669
            [('call', 'Transport.is_readonly', ())],
 
1670
            client._calls)
 
1671
 
 
1672
 
 
1673
class TestTransportMkdir(tests.TestCase):
 
1674
 
 
1675
    def test_permissiondenied(self):
 
1676
        client = FakeClient()
 
1677
        client.add_error_response('PermissionDenied', 'remote path', 'extra')
 
1678
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
1679
                                    _client=client)
 
1680
        exc = self.assertRaises(
 
1681
            errors.PermissionDenied, transport.mkdir, 'client path')
 
1682
        expected_error = errors.PermissionDenied('/client path', 'extra')
 
1683
        self.assertEqual(expected_error, exc)
 
1684
 
 
1685
 
 
1686
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
 
1687
 
 
1688
    def test_defaults_to_none(self):
 
1689
        t = RemoteSSHTransport('bzr+ssh://example.com')
 
1690
        self.assertIs(None, t._get_credentials()[0])
 
1691
 
 
1692
    def test_uses_authentication_config(self):
 
1693
        conf = config.AuthenticationConfig()
 
1694
        conf._get_config().update(
 
1695
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
 
1696
            'example.com'}})
 
1697
        conf._save()
 
1698
        t = RemoteSSHTransport('bzr+ssh://example.com')
 
1699
        self.assertEqual('bar', t._get_credentials()[0])
 
1700
 
 
1701
 
 
1702
class TestRemoteRepository(TestRemote):
 
1703
    """Base for testing RemoteRepository protocol usage.
 
1704
 
 
1705
    These tests contain frozen requests and responses.  We want any changes to
 
1706
    what is sent or expected to be require a thoughtful update to these tests
 
1707
    because they might break compatibility with different-versioned servers.
 
1708
    """
 
1709
 
 
1710
    def setup_fake_client_and_repository(self, transport_path):
 
1711
        """Create the fake client and repository for testing with.
 
1712
 
 
1713
        There's no real server here; we just have canned responses sent
 
1714
        back one by one.
 
1715
 
 
1716
        :param transport_path: Path below the root of the MemoryTransport
 
1717
            where the repository will be created.
 
1718
        """
 
1719
        transport = MemoryTransport()
 
1720
        transport.mkdir(transport_path)
 
1721
        client = FakeClient(transport.base)
 
1722
        transport = transport.clone(transport_path)
 
1723
        # we do not want bzrdir to make any remote calls
 
1724
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1725
            _client=False)
 
1726
        repo = RemoteRepository(bzrdir, None, _client=client)
 
1727
        return repo, client
 
1728
 
 
1729
 
 
1730
class TestRepositoryFormat(TestRemoteRepository):
 
1731
 
 
1732
    def test_fast_delta(self):
 
1733
        true_name = groupcompress_repo.RepositoryFormatCHK1().network_name()
 
1734
        true_format = RemoteRepositoryFormat()
 
1735
        true_format._network_name = true_name
 
1736
        self.assertEqual(True, true_format.fast_deltas)
 
1737
        false_name = pack_repo.RepositoryFormatKnitPack1().network_name()
 
1738
        false_format = RemoteRepositoryFormat()
 
1739
        false_format._network_name = false_name
 
1740
        self.assertEqual(False, false_format.fast_deltas)
 
1741
 
 
1742
 
 
1743
class TestRepositoryGatherStats(TestRemoteRepository):
 
1744
 
 
1745
    def test_revid_none(self):
 
1746
        # ('ok',), body with revisions and size
 
1747
        transport_path = 'quack'
 
1748
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1749
        client.add_success_response_with_body(
 
1750
            'revisions: 2\nsize: 18\n', 'ok')
 
1751
        result = repo.gather_stats(None)
 
1752
        self.assertEqual(
 
1753
            [('call_expecting_body', 'Repository.gather_stats',
 
1754
             ('quack/','','no'))],
 
1755
            client._calls)
 
1756
        self.assertEqual({'revisions': 2, 'size': 18}, result)
 
1757
 
 
1758
    def test_revid_no_committers(self):
 
1759
        # ('ok',), body without committers
 
1760
        body = ('firstrev: 123456.300 3600\n'
 
1761
                'latestrev: 654231.400 0\n'
 
1762
                'revisions: 2\n'
 
1763
                'size: 18\n')
 
1764
        transport_path = 'quick'
 
1765
        revid = u'\xc8'.encode('utf8')
 
1766
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1767
        client.add_success_response_with_body(body, 'ok')
 
1768
        result = repo.gather_stats(revid)
 
1769
        self.assertEqual(
 
1770
            [('call_expecting_body', 'Repository.gather_stats',
 
1771
              ('quick/', revid, 'no'))],
 
1772
            client._calls)
 
1773
        self.assertEqual({'revisions': 2, 'size': 18,
 
1774
                          'firstrev': (123456.300, 3600),
 
1775
                          'latestrev': (654231.400, 0),},
 
1776
                         result)
 
1777
 
 
1778
    def test_revid_with_committers(self):
 
1779
        # ('ok',), body with committers
 
1780
        body = ('committers: 128\n'
 
1781
                'firstrev: 123456.300 3600\n'
 
1782
                'latestrev: 654231.400 0\n'
 
1783
                'revisions: 2\n'
 
1784
                'size: 18\n')
 
1785
        transport_path = 'buick'
 
1786
        revid = u'\xc8'.encode('utf8')
 
1787
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1788
        client.add_success_response_with_body(body, 'ok')
 
1789
        result = repo.gather_stats(revid, True)
 
1790
        self.assertEqual(
 
1791
            [('call_expecting_body', 'Repository.gather_stats',
 
1792
              ('buick/', revid, 'yes'))],
 
1793
            client._calls)
 
1794
        self.assertEqual({'revisions': 2, 'size': 18,
 
1795
                          'committers': 128,
 
1796
                          'firstrev': (123456.300, 3600),
 
1797
                          'latestrev': (654231.400, 0),},
 
1798
                         result)
 
1799
 
 
1800
 
 
1801
class TestRepositoryGetGraph(TestRemoteRepository):
 
1802
 
 
1803
    def test_get_graph(self):
 
1804
        # get_graph returns a graph with a custom parents provider.
 
1805
        transport_path = 'quack'
 
1806
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1807
        graph = repo.get_graph()
 
1808
        self.assertNotEqual(graph._parents_provider, repo)
 
1809
 
 
1810
 
 
1811
class TestRepositoryGetParentMap(TestRemoteRepository):
 
1812
 
 
1813
    def test_get_parent_map_caching(self):
 
1814
        # get_parent_map returns from cache until unlock()
 
1815
        # setup a reponse with two revisions
 
1816
        r1 = u'\u0e33'.encode('utf8')
 
1817
        r2 = u'\u0dab'.encode('utf8')
 
1818
        lines = [' '.join([r2, r1]), r1]
 
1819
        encoded_body = bz2.compress('\n'.join(lines))
 
1820
 
 
1821
        transport_path = 'quack'
 
1822
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1823
        client.add_success_response_with_body(encoded_body, 'ok')
 
1824
        client.add_success_response_with_body(encoded_body, 'ok')
 
1825
        repo.lock_read()
 
1826
        graph = repo.get_graph()
 
1827
        parents = graph.get_parent_map([r2])
 
1828
        self.assertEqual({r2: (r1,)}, parents)
 
1829
        # locking and unlocking deeper should not reset
 
1830
        repo.lock_read()
 
1831
        repo.unlock()
 
1832
        parents = graph.get_parent_map([r1])
 
1833
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
 
1834
        self.assertEqual(
 
1835
            [('call_with_body_bytes_expecting_body',
 
1836
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
 
1837
              '\n\n0')],
 
1838
            client._calls)
 
1839
        repo.unlock()
 
1840
        # now we call again, and it should use the second response.
 
1841
        repo.lock_read()
 
1842
        graph = repo.get_graph()
 
1843
        parents = graph.get_parent_map([r1])
 
1844
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
 
1845
        self.assertEqual(
 
1846
            [('call_with_body_bytes_expecting_body',
 
1847
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
 
1848
              '\n\n0'),
 
1849
             ('call_with_body_bytes_expecting_body',
 
1850
              'Repository.get_parent_map', ('quack/', 'include-missing:', r1),
 
1851
              '\n\n0'),
 
1852
            ],
 
1853
            client._calls)
 
1854
        repo.unlock()
 
1855
 
 
1856
    def test_get_parent_map_reconnects_if_unknown_method(self):
 
1857
        transport_path = 'quack'
 
1858
        rev_id = 'revision-id'
 
1859
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1860
        client.add_unknown_method_response('Repository.get_parent_map')
 
1861
        client.add_success_response_with_body(rev_id, 'ok')
 
1862
        self.assertFalse(client._medium._is_remote_before((1, 2)))
 
1863
        parents = repo.get_parent_map([rev_id])
 
1864
        self.assertEqual(
 
1865
            [('call_with_body_bytes_expecting_body',
 
1866
              'Repository.get_parent_map', ('quack/', 'include-missing:',
 
1867
              rev_id), '\n\n0'),
 
1868
             ('disconnect medium',),
 
1869
             ('call_expecting_body', 'Repository.get_revision_graph',
 
1870
              ('quack/', ''))],
 
1871
            client._calls)
 
1872
        # The medium is now marked as being connected to an older server
 
1873
        self.assertTrue(client._medium._is_remote_before((1, 2)))
 
1874
        self.assertEqual({rev_id: ('null:',)}, parents)
 
1875
 
 
1876
    def test_get_parent_map_fallback_parentless_node(self):
 
1877
        """get_parent_map falls back to get_revision_graph on old servers.  The
 
1878
        results from get_revision_graph are tweaked to match the get_parent_map
 
1879
        API.
 
1880
 
 
1881
        Specifically, a {key: ()} result from get_revision_graph means "no
 
1882
        parents" for that key, which in get_parent_map results should be
 
1883
        represented as {key: ('null:',)}.
 
1884
 
 
1885
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
 
1886
        """
 
1887
        rev_id = 'revision-id'
 
1888
        transport_path = 'quack'
 
1889
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
1890
        client.add_success_response_with_body(rev_id, 'ok')
 
1891
        client._medium._remember_remote_is_before((1, 2))
 
1892
        parents = repo.get_parent_map([rev_id])
 
1893
        self.assertEqual(
 
1894
            [('call_expecting_body', 'Repository.get_revision_graph',
 
1895
             ('quack/', ''))],
 
1896
            client._calls)
 
1897
        self.assertEqual({rev_id: ('null:',)}, parents)
 
1898
 
 
1899
    def test_get_parent_map_unexpected_response(self):
 
1900
        repo, client = self.setup_fake_client_and_repository('path')
 
1901
        client.add_success_response('something unexpected!')
 
1902
        self.assertRaises(
 
1903
            errors.UnexpectedSmartServerResponse,
 
1904
            repo.get_parent_map, ['a-revision-id'])
 
1905
 
 
1906
    def test_get_parent_map_negative_caches_missing_keys(self):
 
1907
        self.setup_smart_server_with_call_log()
 
1908
        repo = self.make_repository('foo')
 
1909
        self.assertIsInstance(repo, RemoteRepository)
 
1910
        repo.lock_read()
 
1911
        self.addCleanup(repo.unlock)
 
1912
        self.reset_smart_call_log()
 
1913
        graph = repo.get_graph()
 
1914
        self.assertEqual({},
 
1915
            graph.get_parent_map(['some-missing', 'other-missing']))
 
1916
        self.assertLength(1, self.hpss_calls)
 
1917
        # No call if we repeat this
 
1918
        self.reset_smart_call_log()
 
1919
        graph = repo.get_graph()
 
1920
        self.assertEqual({},
 
1921
            graph.get_parent_map(['some-missing', 'other-missing']))
 
1922
        self.assertLength(0, self.hpss_calls)
 
1923
        # Asking for more unknown keys makes a request.
 
1924
        self.reset_smart_call_log()
 
1925
        graph = repo.get_graph()
 
1926
        self.assertEqual({},
 
1927
            graph.get_parent_map(['some-missing', 'other-missing',
 
1928
                'more-missing']))
 
1929
        self.assertLength(1, self.hpss_calls)
 
1930
 
 
1931
    def disableExtraResults(self):
 
1932
        old_flag = SmartServerRepositoryGetParentMap.no_extra_results
 
1933
        SmartServerRepositoryGetParentMap.no_extra_results = True
 
1934
        def reset_values():
 
1935
            SmartServerRepositoryGetParentMap.no_extra_results = old_flag
 
1936
        self.addCleanup(reset_values)
 
1937
 
 
1938
    def test_null_cached_missing_and_stop_key(self):
 
1939
        self.setup_smart_server_with_call_log()
 
1940
        # Make a branch with a single revision.
 
1941
        builder = self.make_branch_builder('foo')
 
1942
        builder.start_series()
 
1943
        builder.build_snapshot('first', None, [
 
1944
            ('add', ('', 'root-id', 'directory', ''))])
 
1945
        builder.finish_series()
 
1946
        branch = builder.get_branch()
 
1947
        repo = branch.repository
 
1948
        self.assertIsInstance(repo, RemoteRepository)
 
1949
        # Stop the server from sending extra results.
 
1950
        self.disableExtraResults()
 
1951
        repo.lock_read()
 
1952
        self.addCleanup(repo.unlock)
 
1953
        self.reset_smart_call_log()
 
1954
        graph = repo.get_graph()
 
1955
        # Query for 'first' and 'null:'.  Because 'null:' is a parent of
 
1956
        # 'first' it will be a candidate for the stop_keys of subsequent
 
1957
        # requests, and because 'null:' was queried but not returned it will be
 
1958
        # cached as missing.
 
1959
        self.assertEqual({'first': ('null:',)},
 
1960
            graph.get_parent_map(['first', 'null:']))
 
1961
        # Now query for another key.  This request will pass along a recipe of
 
1962
        # start and stop keys describing the already cached results, and this
 
1963
        # recipe's revision count must be correct (or else it will trigger an
 
1964
        # error from the server).
 
1965
        self.assertEqual({}, graph.get_parent_map(['another-key']))
 
1966
        # This assertion guards against disableExtraResults silently failing to
 
1967
        # work, thus invalidating the test.
 
1968
        self.assertLength(2, self.hpss_calls)
 
1969
 
 
1970
    def test_get_parent_map_gets_ghosts_from_result(self):
 
1971
        # asking for a revision should negatively cache close ghosts in its
 
1972
        # ancestry.
 
1973
        self.setup_smart_server_with_call_log()
 
1974
        tree = self.make_branch_and_memory_tree('foo')
 
1975
        tree.lock_write()
 
1976
        try:
 
1977
            builder = treebuilder.TreeBuilder()
 
1978
            builder.start_tree(tree)
 
1979
            builder.build([])
 
1980
            builder.finish_tree()
 
1981
            tree.set_parent_ids(['non-existant'], allow_leftmost_as_ghost=True)
 
1982
            rev_id = tree.commit('')
 
1983
        finally:
 
1984
            tree.unlock()
 
1985
        tree.lock_read()
 
1986
        self.addCleanup(tree.unlock)
 
1987
        repo = tree.branch.repository
 
1988
        self.assertIsInstance(repo, RemoteRepository)
 
1989
        # ask for rev_id
 
1990
        repo.get_parent_map([rev_id])
 
1991
        self.reset_smart_call_log()
 
1992
        # Now asking for rev_id's ghost parent should not make calls
 
1993
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
 
1994
        self.assertLength(0, self.hpss_calls)
 
1995
 
 
1996
 
 
1997
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
 
1998
 
 
1999
    def test_allows_new_revisions(self):
 
2000
        """get_parent_map's results can be updated by commit."""
 
2001
        smart_server = server.SmartTCPServer_for_testing()
 
2002
        self.start_server(smart_server)
 
2003
        self.make_branch('branch')
 
2004
        branch = Branch.open(smart_server.get_url() + '/branch')
 
2005
        tree = branch.create_checkout('tree', lightweight=True)
 
2006
        tree.lock_write()
 
2007
        self.addCleanup(tree.unlock)
 
2008
        graph = tree.branch.repository.get_graph()
 
2009
        # This provides an opportunity for the missing rev-id to be cached.
 
2010
        self.assertEqual({}, graph.get_parent_map(['rev1']))
 
2011
        tree.commit('message', rev_id='rev1')
 
2012
        graph = tree.branch.repository.get_graph()
 
2013
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
 
2014
 
 
2015
 
 
2016
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
 
2017
 
 
2018
    def test_null_revision(self):
 
2019
        # a null revision has the predictable result {}, we should have no wire
 
2020
        # traffic when calling it with this argument
 
2021
        transport_path = 'empty'
 
2022
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2023
        client.add_success_response('notused')
 
2024
        # actual RemoteRepository.get_revision_graph is gone, but there's an
 
2025
        # equivalent private method for testing
 
2026
        result = repo._get_revision_graph(NULL_REVISION)
 
2027
        self.assertEqual([], client._calls)
 
2028
        self.assertEqual({}, result)
 
2029
 
 
2030
    def test_none_revision(self):
 
2031
        # with none we want the entire graph
 
2032
        r1 = u'\u0e33'.encode('utf8')
 
2033
        r2 = u'\u0dab'.encode('utf8')
 
2034
        lines = [' '.join([r2, r1]), r1]
 
2035
        encoded_body = '\n'.join(lines)
 
2036
 
 
2037
        transport_path = 'sinhala'
 
2038
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2039
        client.add_success_response_with_body(encoded_body, 'ok')
 
2040
        # actual RemoteRepository.get_revision_graph is gone, but there's an
 
2041
        # equivalent private method for testing
 
2042
        result = repo._get_revision_graph(None)
 
2043
        self.assertEqual(
 
2044
            [('call_expecting_body', 'Repository.get_revision_graph',
 
2045
             ('sinhala/', ''))],
 
2046
            client._calls)
 
2047
        self.assertEqual({r1: (), r2: (r1, )}, result)
 
2048
 
 
2049
    def test_specific_revision(self):
 
2050
        # with a specific revision we want the graph for that
 
2051
        # with none we want the entire graph
 
2052
        r11 = u'\u0e33'.encode('utf8')
 
2053
        r12 = u'\xc9'.encode('utf8')
 
2054
        r2 = u'\u0dab'.encode('utf8')
 
2055
        lines = [' '.join([r2, r11, r12]), r11, r12]
 
2056
        encoded_body = '\n'.join(lines)
 
2057
 
 
2058
        transport_path = 'sinhala'
 
2059
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2060
        client.add_success_response_with_body(encoded_body, 'ok')
 
2061
        result = repo._get_revision_graph(r2)
 
2062
        self.assertEqual(
 
2063
            [('call_expecting_body', 'Repository.get_revision_graph',
 
2064
             ('sinhala/', r2))],
 
2065
            client._calls)
 
2066
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
 
2067
 
 
2068
    def test_no_such_revision(self):
 
2069
        revid = '123'
 
2070
        transport_path = 'sinhala'
 
2071
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2072
        client.add_error_response('nosuchrevision', revid)
 
2073
        # also check that the right revision is reported in the error
 
2074
        self.assertRaises(errors.NoSuchRevision,
 
2075
            repo._get_revision_graph, revid)
 
2076
        self.assertEqual(
 
2077
            [('call_expecting_body', 'Repository.get_revision_graph',
 
2078
             ('sinhala/', revid))],
 
2079
            client._calls)
 
2080
 
 
2081
    def test_unexpected_error(self):
 
2082
        revid = '123'
 
2083
        transport_path = 'sinhala'
 
2084
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2085
        client.add_error_response('AnUnexpectedError')
 
2086
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
 
2087
            repo._get_revision_graph, revid)
 
2088
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
 
2089
 
 
2090
 
 
2091
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
 
2092
 
 
2093
    def test_ok(self):
 
2094
        repo, client = self.setup_fake_client_and_repository('quack')
 
2095
        client.add_expected_call(
 
2096
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2097
            'success', ('ok', 'rev-five'))
 
2098
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
 
2099
        self.assertEqual((True, 'rev-five'), result)
 
2100
        self.assertFinished(client)
 
2101
 
 
2102
    def test_history_incomplete(self):
 
2103
        repo, client = self.setup_fake_client_and_repository('quack')
 
2104
        client.add_expected_call(
 
2105
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2106
            'success', ('history-incomplete', 10, 'rev-ten'))
 
2107
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
 
2108
        self.assertEqual((False, (10, 'rev-ten')), result)
 
2109
        self.assertFinished(client)
 
2110
 
 
2111
    def test_history_incomplete_with_fallback(self):
 
2112
        """A 'history-incomplete' response causes the fallback repository to be
 
2113
        queried too, if one is set.
 
2114
        """
 
2115
        # Make a repo with a fallback repo, both using a FakeClient.
 
2116
        format = remote.response_tuple_to_repo_format(
 
2117
            ('yes', 'no', 'yes', 'fake-network-name'))
 
2118
        repo, client = self.setup_fake_client_and_repository('quack')
 
2119
        repo._format = format
 
2120
        fallback_repo, ignored = self.setup_fake_client_and_repository(
 
2121
            'fallback')
 
2122
        fallback_repo._client = client
 
2123
        repo.add_fallback_repository(fallback_repo)
 
2124
        # First the client should ask the primary repo
 
2125
        client.add_expected_call(
 
2126
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
 
2127
            'success', ('history-incomplete', 2, 'rev-two'))
 
2128
        # Then it should ask the fallback, using revno/revid from the
 
2129
        # history-incomplete response as the known revno/revid.
 
2130
        client.add_expected_call(
 
2131
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
 
2132
            'success', ('ok', 'rev-one'))
 
2133
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
 
2134
        self.assertEqual((True, 'rev-one'), result)
 
2135
        self.assertFinished(client)
 
2136
 
 
2137
    def test_nosuchrevision(self):
 
2138
        # 'nosuchrevision' is returned when the known-revid is not found in the
 
2139
        # remote repo.  The client translates that response to NoSuchRevision.
 
2140
        repo, client = self.setup_fake_client_and_repository('quack')
 
2141
        client.add_expected_call(
 
2142
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2143
            'error', ('nosuchrevision', 'rev-foo'))
 
2144
        self.assertRaises(
 
2145
            errors.NoSuchRevision,
 
2146
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
 
2147
        self.assertFinished(client)
 
2148
 
 
2149
 
 
2150
class TestRepositoryIsShared(TestRemoteRepository):
 
2151
 
 
2152
    def test_is_shared(self):
 
2153
        # ('yes', ) for Repository.is_shared -> 'True'.
 
2154
        transport_path = 'quack'
 
2155
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2156
        client.add_success_response('yes')
 
2157
        result = repo.is_shared()
 
2158
        self.assertEqual(
 
2159
            [('call', 'Repository.is_shared', ('quack/',))],
 
2160
            client._calls)
 
2161
        self.assertEqual(True, result)
 
2162
 
 
2163
    def test_is_not_shared(self):
 
2164
        # ('no', ) for Repository.is_shared -> 'False'.
 
2165
        transport_path = 'qwack'
 
2166
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2167
        client.add_success_response('no')
 
2168
        result = repo.is_shared()
 
2169
        self.assertEqual(
 
2170
            [('call', 'Repository.is_shared', ('qwack/',))],
 
2171
            client._calls)
 
2172
        self.assertEqual(False, result)
 
2173
 
 
2174
 
 
2175
class TestRepositoryLockWrite(TestRemoteRepository):
 
2176
 
 
2177
    def test_lock_write(self):
 
2178
        transport_path = 'quack'
 
2179
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2180
        client.add_success_response('ok', 'a token')
 
2181
        result = repo.lock_write()
 
2182
        self.assertEqual(
 
2183
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
2184
            client._calls)
 
2185
        self.assertEqual('a token', result)
 
2186
 
 
2187
    def test_lock_write_already_locked(self):
 
2188
        transport_path = 'quack'
 
2189
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2190
        client.add_error_response('LockContention')
 
2191
        self.assertRaises(errors.LockContention, repo.lock_write)
 
2192
        self.assertEqual(
 
2193
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
2194
            client._calls)
 
2195
 
 
2196
    def test_lock_write_unlockable(self):
 
2197
        transport_path = 'quack'
 
2198
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2199
        client.add_error_response('UnlockableTransport')
 
2200
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
 
2201
        self.assertEqual(
 
2202
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
2203
            client._calls)
 
2204
 
 
2205
 
 
2206
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
 
2207
 
 
2208
    def test_backwards_compat(self):
 
2209
        self.setup_smart_server_with_call_log()
 
2210
        repo = self.make_repository('.')
 
2211
        self.reset_smart_call_log()
 
2212
        verb = 'Repository.set_make_working_trees'
 
2213
        self.disable_verb(verb)
 
2214
        repo.set_make_working_trees(True)
 
2215
        call_count = len([call for call in self.hpss_calls if
 
2216
            call.call.method == verb])
 
2217
        self.assertEqual(1, call_count)
 
2218
 
 
2219
    def test_current(self):
 
2220
        transport_path = 'quack'
 
2221
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2222
        client.add_expected_call(
 
2223
            'Repository.set_make_working_trees', ('quack/', 'True'),
 
2224
            'success', ('ok',))
 
2225
        client.add_expected_call(
 
2226
            'Repository.set_make_working_trees', ('quack/', 'False'),
 
2227
            'success', ('ok',))
 
2228
        repo.set_make_working_trees(True)
 
2229
        repo.set_make_working_trees(False)
 
2230
 
 
2231
 
 
2232
class TestRepositoryUnlock(TestRemoteRepository):
 
2233
 
 
2234
    def test_unlock(self):
 
2235
        transport_path = 'quack'
 
2236
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2237
        client.add_success_response('ok', 'a token')
 
2238
        client.add_success_response('ok')
 
2239
        repo.lock_write()
 
2240
        repo.unlock()
 
2241
        self.assertEqual(
 
2242
            [('call', 'Repository.lock_write', ('quack/', '')),
 
2243
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
 
2244
            client._calls)
 
2245
 
 
2246
    def test_unlock_wrong_token(self):
 
2247
        # If somehow the token is wrong, unlock will raise TokenMismatch.
 
2248
        transport_path = 'quack'
 
2249
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2250
        client.add_success_response('ok', 'a token')
 
2251
        client.add_error_response('TokenMismatch')
 
2252
        repo.lock_write()
 
2253
        self.assertRaises(errors.TokenMismatch, repo.unlock)
 
2254
 
 
2255
 
 
2256
class TestRepositoryHasRevision(TestRemoteRepository):
 
2257
 
 
2258
    def test_none(self):
 
2259
        # repo.has_revision(None) should not cause any traffic.
 
2260
        transport_path = 'quack'
 
2261
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2262
 
 
2263
        # The null revision is always there, so has_revision(None) == True.
 
2264
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
 
2265
 
 
2266
        # The remote repo shouldn't be accessed.
 
2267
        self.assertEqual([], client._calls)
 
2268
 
 
2269
 
 
2270
class TestRepositoryInsertStreamBase(TestRemoteRepository):
 
2271
    """Base class for Repository.insert_stream and .insert_stream_1.19
 
2272
    tests.
 
2273
    """
 
2274
    
 
2275
    def checkInsertEmptyStream(self, repo, client):
 
2276
        """Insert an empty stream, checking the result.
 
2277
 
 
2278
        This checks that there are no resume_tokens or missing_keys, and that
 
2279
        the client is finished.
 
2280
        """
 
2281
        sink = repo._get_sink()
 
2282
        fmt = repository.RepositoryFormat.get_default_format()
 
2283
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
 
2284
        self.assertEqual([], resume_tokens)
 
2285
        self.assertEqual(set(), missing_keys)
 
2286
        self.assertFinished(client)
 
2287
 
 
2288
 
 
2289
class TestRepositoryInsertStream(TestRepositoryInsertStreamBase):
 
2290
    """Tests for using Repository.insert_stream verb when the _1.19 variant is
 
2291
    not available.
 
2292
 
 
2293
    This test case is very similar to TestRepositoryInsertStream_1_19.
 
2294
    """
 
2295
 
 
2296
    def setUp(self):
 
2297
        TestRemoteRepository.setUp(self)
 
2298
        self.disable_verb('Repository.insert_stream_1.19')
 
2299
 
 
2300
    def test_unlocked_repo(self):
 
2301
        transport_path = 'quack'
 
2302
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2303
        client.add_expected_call(
 
2304
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2305
            'unknown', ('Repository.insert_stream_1.19',))
 
2306
        client.add_expected_call(
 
2307
            'Repository.insert_stream', ('quack/', ''),
 
2308
            'success', ('ok',))
 
2309
        client.add_expected_call(
 
2310
            'Repository.insert_stream', ('quack/', ''),
 
2311
            'success', ('ok',))
 
2312
        self.checkInsertEmptyStream(repo, client)
 
2313
 
 
2314
    def test_locked_repo_with_no_lock_token(self):
 
2315
        transport_path = 'quack'
 
2316
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2317
        client.add_expected_call(
 
2318
            'Repository.lock_write', ('quack/', ''),
 
2319
            'success', ('ok', ''))
 
2320
        client.add_expected_call(
 
2321
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2322
            'unknown', ('Repository.insert_stream_1.19',))
 
2323
        client.add_expected_call(
 
2324
            'Repository.insert_stream', ('quack/', ''),
 
2325
            'success', ('ok',))
 
2326
        client.add_expected_call(
 
2327
            'Repository.insert_stream', ('quack/', ''),
 
2328
            'success', ('ok',))
 
2329
        repo.lock_write()
 
2330
        self.checkInsertEmptyStream(repo, client)
 
2331
 
 
2332
    def test_locked_repo_with_lock_token(self):
 
2333
        transport_path = 'quack'
 
2334
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2335
        client.add_expected_call(
 
2336
            'Repository.lock_write', ('quack/', ''),
 
2337
            'success', ('ok', 'a token'))
 
2338
        client.add_expected_call(
 
2339
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2340
            'unknown', ('Repository.insert_stream_1.19',))
 
2341
        client.add_expected_call(
 
2342
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2343
            'success', ('ok',))
 
2344
        client.add_expected_call(
 
2345
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2346
            'success', ('ok',))
 
2347
        repo.lock_write()
 
2348
        self.checkInsertEmptyStream(repo, client)
 
2349
 
 
2350
    def test_stream_with_inventory_deltas(self):
 
2351
        """'inventory-deltas' substreams cannot be sent to the
 
2352
        Repository.insert_stream verb, because not all servers that implement
 
2353
        that verb will accept them.  So when one is encountered the RemoteSink
 
2354
        immediately stops using that verb and falls back to VFS insert_stream.
 
2355
        """
 
2356
        transport_path = 'quack'
 
2357
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2358
        client.add_expected_call(
 
2359
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2360
            'unknown', ('Repository.insert_stream_1.19',))
 
2361
        client.add_expected_call(
 
2362
            'Repository.insert_stream', ('quack/', ''),
 
2363
            'success', ('ok',))
 
2364
        client.add_expected_call(
 
2365
            'Repository.insert_stream', ('quack/', ''),
 
2366
            'success', ('ok',))
 
2367
        # Create a fake real repository for insert_stream to fall back on, so
 
2368
        # that we can directly see the records the RemoteSink passes to the
 
2369
        # real sink.
 
2370
        class FakeRealSink:
 
2371
            def __init__(self):
 
2372
                self.records = []
 
2373
            def insert_stream(self, stream, src_format, resume_tokens):
 
2374
                for substream_kind, substream in stream:
 
2375
                    self.records.append(
 
2376
                        (substream_kind, [record.key for record in substream]))
 
2377
                return ['fake tokens'], ['fake missing keys']
 
2378
        fake_real_sink = FakeRealSink()
 
2379
        class FakeRealRepository:
 
2380
            def _get_sink(self):
 
2381
                return fake_real_sink
 
2382
            def is_in_write_group(self):
 
2383
                return False
 
2384
            def refresh_data(self):
 
2385
                return True
 
2386
        repo._real_repository = FakeRealRepository()
 
2387
        sink = repo._get_sink()
 
2388
        fmt = repository.RepositoryFormat.get_default_format()
 
2389
        stream = self.make_stream_with_inv_deltas(fmt)
 
2390
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
 
2391
        # Every record from the first inventory delta should have been sent to
 
2392
        # the VFS sink.
 
2393
        expected_records = [
 
2394
            ('inventory-deltas', [('rev2',), ('rev3',)]),
 
2395
            ('texts', [('some-rev', 'some-file')])]
 
2396
        self.assertEqual(expected_records, fake_real_sink.records)
 
2397
        # The return values from the real sink's insert_stream are propagated
 
2398
        # back to the original caller.
 
2399
        self.assertEqual(['fake tokens'], resume_tokens)
 
2400
        self.assertEqual(['fake missing keys'], missing_keys)
 
2401
        self.assertFinished(client)
 
2402
 
 
2403
    def make_stream_with_inv_deltas(self, fmt):
 
2404
        """Make a simple stream with an inventory delta followed by more
 
2405
        records and more substreams to test that all records and substreams
 
2406
        from that point on are used.
 
2407
 
 
2408
        This sends, in order:
 
2409
           * inventories substream: rev1, rev2, rev3.  rev2 and rev3 are
 
2410
             inventory-deltas.
 
2411
           * texts substream: (some-rev, some-file)
 
2412
        """
 
2413
        # Define a stream using generators so that it isn't rewindable.
 
2414
        inv = inventory.Inventory(revision_id='rev1')
 
2415
        inv.root.revision = 'rev1'
 
2416
        def stream_with_inv_delta():
 
2417
            yield ('inventories', inventories_substream())
 
2418
            yield ('inventory-deltas', inventory_delta_substream())
 
2419
            yield ('texts', [
 
2420
                versionedfile.FulltextContentFactory(
 
2421
                    ('some-rev', 'some-file'), (), None, 'content')])
 
2422
        def inventories_substream():
 
2423
            # An empty inventory fulltext.  This will be streamed normally.
 
2424
            text = fmt._serializer.write_inventory_to_string(inv)
 
2425
            yield versionedfile.FulltextContentFactory(
 
2426
                ('rev1',), (), None, text)
 
2427
        def inventory_delta_substream():
 
2428
            # An inventory delta.  This can't be streamed via this verb, so it
 
2429
            # will trigger a fallback to VFS insert_stream.
 
2430
            entry = inv.make_entry(
 
2431
                'directory', 'newdir', inv.root.file_id, 'newdir-id')
 
2432
            entry.revision = 'ghost'
 
2433
            delta = [(None, 'newdir', 'newdir-id', entry)]
 
2434
            serializer = inventory_delta.InventoryDeltaSerializer(
 
2435
                versioned_root=True, tree_references=False)
 
2436
            lines = serializer.delta_to_lines('rev1', 'rev2', delta)
 
2437
            yield versionedfile.ChunkedContentFactory(
 
2438
                ('rev2',), (('rev1',)), None, lines)
 
2439
            # Another delta.
 
2440
            lines = serializer.delta_to_lines('rev1', 'rev3', delta)
 
2441
            yield versionedfile.ChunkedContentFactory(
 
2442
                ('rev3',), (('rev1',)), None, lines)
 
2443
        return stream_with_inv_delta()
 
2444
 
 
2445
 
 
2446
class TestRepositoryInsertStream_1_19(TestRepositoryInsertStreamBase):
 
2447
 
 
2448
    def test_unlocked_repo(self):
 
2449
        transport_path = 'quack'
 
2450
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2451
        client.add_expected_call(
 
2452
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2453
            'success', ('ok',))
 
2454
        client.add_expected_call(
 
2455
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2456
            'success', ('ok',))
 
2457
        self.checkInsertEmptyStream(repo, client)
 
2458
 
 
2459
    def test_locked_repo_with_no_lock_token(self):
 
2460
        transport_path = 'quack'
 
2461
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2462
        client.add_expected_call(
 
2463
            'Repository.lock_write', ('quack/', ''),
 
2464
            'success', ('ok', ''))
 
2465
        client.add_expected_call(
 
2466
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2467
            'success', ('ok',))
 
2468
        client.add_expected_call(
 
2469
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2470
            'success', ('ok',))
 
2471
        repo.lock_write()
 
2472
        self.checkInsertEmptyStream(repo, client)
 
2473
 
 
2474
    def test_locked_repo_with_lock_token(self):
 
2475
        transport_path = 'quack'
 
2476
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2477
        client.add_expected_call(
 
2478
            'Repository.lock_write', ('quack/', ''),
 
2479
            'success', ('ok', 'a token'))
 
2480
        client.add_expected_call(
 
2481
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2482
            'success', ('ok',))
 
2483
        client.add_expected_call(
 
2484
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2485
            'success', ('ok',))
 
2486
        repo.lock_write()
 
2487
        self.checkInsertEmptyStream(repo, client)
 
2488
 
 
2489
 
 
2490
class TestRepositoryTarball(TestRemoteRepository):
 
2491
 
 
2492
    # This is a canned tarball reponse we can validate against
 
2493
    tarball_content = (
 
2494
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
 
2495
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
 
2496
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
 
2497
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
 
2498
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
 
2499
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
 
2500
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
 
2501
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
 
2502
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
 
2503
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
 
2504
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
 
2505
        'nWQ7QH/F3JFOFCQ0aSPfA='
 
2506
        ).decode('base64')
 
2507
 
 
2508
    def test_repository_tarball(self):
 
2509
        # Test that Repository.tarball generates the right operations
 
2510
        transport_path = 'repo'
 
2511
        expected_calls = [('call_expecting_body', 'Repository.tarball',
 
2512
                           ('repo/', 'bz2',),),
 
2513
            ]
 
2514
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2515
        client.add_success_response_with_body(self.tarball_content, 'ok')
 
2516
        # Now actually ask for the tarball
 
2517
        tarball_file = repo._get_tarball('bz2')
 
2518
        try:
 
2519
            self.assertEqual(expected_calls, client._calls)
 
2520
            self.assertEqual(self.tarball_content, tarball_file.read())
 
2521
        finally:
 
2522
            tarball_file.close()
 
2523
 
 
2524
 
 
2525
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
 
2526
    """RemoteRepository.copy_content_into optimizations"""
 
2527
 
 
2528
    def test_copy_content_remote_to_local(self):
 
2529
        self.transport_server = server.SmartTCPServer_for_testing
 
2530
        src_repo = self.make_repository('repo1')
 
2531
        src_repo = repository.Repository.open(self.get_url('repo1'))
 
2532
        # At the moment the tarball-based copy_content_into can't write back
 
2533
        # into a smart server.  It would be good if it could upload the
 
2534
        # tarball; once that works we'd have to create repositories of
 
2535
        # different formats. -- mbp 20070410
 
2536
        dest_url = self.get_vfs_only_url('repo2')
 
2537
        dest_bzrdir = BzrDir.create(dest_url)
 
2538
        dest_repo = dest_bzrdir.create_repository()
 
2539
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
 
2540
        self.assertTrue(isinstance(src_repo, RemoteRepository))
 
2541
        src_repo.copy_content_into(dest_repo)
 
2542
 
 
2543
 
 
2544
class _StubRealPackRepository(object):
 
2545
 
 
2546
    def __init__(self, calls):
 
2547
        self.calls = calls
 
2548
        self._pack_collection = _StubPackCollection(calls)
 
2549
 
 
2550
    def is_in_write_group(self):
 
2551
        return False
 
2552
 
 
2553
    def refresh_data(self):
 
2554
        self.calls.append(('pack collection reload_pack_names',))
 
2555
 
 
2556
 
 
2557
class _StubPackCollection(object):
 
2558
 
 
2559
    def __init__(self, calls):
 
2560
        self.calls = calls
 
2561
 
 
2562
    def autopack(self):
 
2563
        self.calls.append(('pack collection autopack',))
 
2564
 
 
2565
 
 
2566
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
 
2567
    """Tests for RemoteRepository.autopack implementation."""
 
2568
 
 
2569
    def test_ok(self):
 
2570
        """When the server returns 'ok' and there's no _real_repository, then
 
2571
        nothing else happens: the autopack method is done.
 
2572
        """
 
2573
        transport_path = 'quack'
 
2574
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2575
        client.add_expected_call(
 
2576
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
 
2577
        repo.autopack()
 
2578
        self.assertFinished(client)
 
2579
 
 
2580
    def test_ok_with_real_repo(self):
 
2581
        """When the server returns 'ok' and there is a _real_repository, then
 
2582
        the _real_repository's reload_pack_name's method will be called.
 
2583
        """
 
2584
        transport_path = 'quack'
 
2585
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2586
        client.add_expected_call(
 
2587
            'PackRepository.autopack', ('quack/',),
 
2588
            'success', ('ok',))
 
2589
        repo._real_repository = _StubRealPackRepository(client._calls)
 
2590
        repo.autopack()
 
2591
        self.assertEqual(
 
2592
            [('call', 'PackRepository.autopack', ('quack/',)),
 
2593
             ('pack collection reload_pack_names',)],
 
2594
            client._calls)
 
2595
 
 
2596
    def test_backwards_compatibility(self):
 
2597
        """If the server does not recognise the PackRepository.autopack verb,
 
2598
        fallback to the real_repository's implementation.
 
2599
        """
 
2600
        transport_path = 'quack'
 
2601
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2602
        client.add_unknown_method_response('PackRepository.autopack')
 
2603
        def stub_ensure_real():
 
2604
            client._calls.append(('_ensure_real',))
 
2605
            repo._real_repository = _StubRealPackRepository(client._calls)
 
2606
        repo._ensure_real = stub_ensure_real
 
2607
        repo.autopack()
 
2608
        self.assertEqual(
 
2609
            [('call', 'PackRepository.autopack', ('quack/',)),
 
2610
             ('_ensure_real',),
 
2611
             ('pack collection autopack',)],
 
2612
            client._calls)
 
2613
 
 
2614
 
 
2615
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
 
2616
    """Base class for unit tests for bzrlib.remote._translate_error."""
 
2617
 
 
2618
    def translateTuple(self, error_tuple, **context):
 
2619
        """Call _translate_error with an ErrorFromSmartServer built from the
 
2620
        given error_tuple.
 
2621
 
 
2622
        :param error_tuple: A tuple of a smart server response, as would be
 
2623
            passed to an ErrorFromSmartServer.
 
2624
        :kwargs context: context items to call _translate_error with.
 
2625
 
 
2626
        :returns: The error raised by _translate_error.
 
2627
        """
 
2628
        # Raise the ErrorFromSmartServer before passing it as an argument,
 
2629
        # because _translate_error may need to re-raise it with a bare 'raise'
 
2630
        # statement.
 
2631
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2632
        translated_error = self.translateErrorFromSmartServer(
 
2633
            server_error, **context)
 
2634
        return translated_error
 
2635
 
 
2636
    def translateErrorFromSmartServer(self, error_object, **context):
 
2637
        """Like translateTuple, but takes an already constructed
 
2638
        ErrorFromSmartServer rather than a tuple.
 
2639
        """
 
2640
        try:
 
2641
            raise error_object
 
2642
        except errors.ErrorFromSmartServer, server_error:
 
2643
            translated_error = self.assertRaises(
 
2644
                errors.BzrError, remote._translate_error, server_error,
 
2645
                **context)
 
2646
        return translated_error
 
2647
 
 
2648
 
 
2649
class TestErrorTranslationSuccess(TestErrorTranslationBase):
 
2650
    """Unit tests for bzrlib.remote._translate_error.
 
2651
 
 
2652
    Given an ErrorFromSmartServer (which has an error tuple from a smart
 
2653
    server) and some context, _translate_error raises more specific errors from
 
2654
    bzrlib.errors.
 
2655
 
 
2656
    This test case covers the cases where _translate_error succeeds in
 
2657
    translating an ErrorFromSmartServer to something better.  See
 
2658
    TestErrorTranslationRobustness for other cases.
 
2659
    """
 
2660
 
 
2661
    def test_NoSuchRevision(self):
 
2662
        branch = self.make_branch('')
 
2663
        revid = 'revid'
 
2664
        translated_error = self.translateTuple(
 
2665
            ('NoSuchRevision', revid), branch=branch)
 
2666
        expected_error = errors.NoSuchRevision(branch, revid)
 
2667
        self.assertEqual(expected_error, translated_error)
 
2668
 
 
2669
    def test_nosuchrevision(self):
 
2670
        repository = self.make_repository('')
 
2671
        revid = 'revid'
 
2672
        translated_error = self.translateTuple(
 
2673
            ('nosuchrevision', revid), repository=repository)
 
2674
        expected_error = errors.NoSuchRevision(repository, revid)
 
2675
        self.assertEqual(expected_error, translated_error)
 
2676
 
 
2677
    def test_nobranch(self):
 
2678
        bzrdir = self.make_bzrdir('')
 
2679
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
 
2680
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
 
2681
        self.assertEqual(expected_error, translated_error)
 
2682
 
 
2683
    def test_LockContention(self):
 
2684
        translated_error = self.translateTuple(('LockContention',))
 
2685
        expected_error = errors.LockContention('(remote lock)')
 
2686
        self.assertEqual(expected_error, translated_error)
 
2687
 
 
2688
    def test_UnlockableTransport(self):
 
2689
        bzrdir = self.make_bzrdir('')
 
2690
        translated_error = self.translateTuple(
 
2691
            ('UnlockableTransport',), bzrdir=bzrdir)
 
2692
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
 
2693
        self.assertEqual(expected_error, translated_error)
 
2694
 
 
2695
    def test_LockFailed(self):
 
2696
        lock = 'str() of a server lock'
 
2697
        why = 'str() of why'
 
2698
        translated_error = self.translateTuple(('LockFailed', lock, why))
 
2699
        expected_error = errors.LockFailed(lock, why)
 
2700
        self.assertEqual(expected_error, translated_error)
 
2701
 
 
2702
    def test_TokenMismatch(self):
 
2703
        token = 'a lock token'
 
2704
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
 
2705
        expected_error = errors.TokenMismatch(token, '(remote token)')
 
2706
        self.assertEqual(expected_error, translated_error)
 
2707
 
 
2708
    def test_Diverged(self):
 
2709
        branch = self.make_branch('a')
 
2710
        other_branch = self.make_branch('b')
 
2711
        translated_error = self.translateTuple(
 
2712
            ('Diverged',), branch=branch, other_branch=other_branch)
 
2713
        expected_error = errors.DivergedBranches(branch, other_branch)
 
2714
        self.assertEqual(expected_error, translated_error)
 
2715
 
 
2716
    def test_ReadError_no_args(self):
 
2717
        path = 'a path'
 
2718
        translated_error = self.translateTuple(('ReadError',), path=path)
 
2719
        expected_error = errors.ReadError(path)
 
2720
        self.assertEqual(expected_error, translated_error)
 
2721
 
 
2722
    def test_ReadError(self):
 
2723
        path = 'a path'
 
2724
        translated_error = self.translateTuple(('ReadError', path))
 
2725
        expected_error = errors.ReadError(path)
 
2726
        self.assertEqual(expected_error, translated_error)
 
2727
 
 
2728
    def test_IncompatibleRepositories(self):
 
2729
        translated_error = self.translateTuple(('IncompatibleRepositories',
 
2730
            "repo1", "repo2", "details here"))
 
2731
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
 
2732
            "details here")
 
2733
        self.assertEqual(expected_error, translated_error)
 
2734
 
 
2735
    def test_PermissionDenied_no_args(self):
 
2736
        path = 'a path'
 
2737
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
 
2738
        expected_error = errors.PermissionDenied(path)
 
2739
        self.assertEqual(expected_error, translated_error)
 
2740
 
 
2741
    def test_PermissionDenied_one_arg(self):
 
2742
        path = 'a path'
 
2743
        translated_error = self.translateTuple(('PermissionDenied', path))
 
2744
        expected_error = errors.PermissionDenied(path)
 
2745
        self.assertEqual(expected_error, translated_error)
 
2746
 
 
2747
    def test_PermissionDenied_one_arg_and_context(self):
 
2748
        """Given a choice between a path from the local context and a path on
 
2749
        the wire, _translate_error prefers the path from the local context.
 
2750
        """
 
2751
        local_path = 'local path'
 
2752
        remote_path = 'remote path'
 
2753
        translated_error = self.translateTuple(
 
2754
            ('PermissionDenied', remote_path), path=local_path)
 
2755
        expected_error = errors.PermissionDenied(local_path)
 
2756
        self.assertEqual(expected_error, translated_error)
 
2757
 
 
2758
    def test_PermissionDenied_two_args(self):
 
2759
        path = 'a path'
 
2760
        extra = 'a string with extra info'
 
2761
        translated_error = self.translateTuple(
 
2762
            ('PermissionDenied', path, extra))
 
2763
        expected_error = errors.PermissionDenied(path, extra)
 
2764
        self.assertEqual(expected_error, translated_error)
 
2765
 
 
2766
 
 
2767
class TestErrorTranslationRobustness(TestErrorTranslationBase):
 
2768
    """Unit tests for bzrlib.remote._translate_error's robustness.
 
2769
 
 
2770
    TestErrorTranslationSuccess is for cases where _translate_error can
 
2771
    translate successfully.  This class about how _translate_err behaves when
 
2772
    it fails to translate: it re-raises the original error.
 
2773
    """
 
2774
 
 
2775
    def test_unrecognised_server_error(self):
 
2776
        """If the error code from the server is not recognised, the original
 
2777
        ErrorFromSmartServer is propagated unmodified.
 
2778
        """
 
2779
        error_tuple = ('An unknown error tuple',)
 
2780
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2781
        translated_error = self.translateErrorFromSmartServer(server_error)
 
2782
        expected_error = errors.UnknownErrorFromSmartServer(server_error)
 
2783
        self.assertEqual(expected_error, translated_error)
 
2784
 
 
2785
    def test_context_missing_a_key(self):
 
2786
        """In case of a bug in the client, or perhaps an unexpected response
 
2787
        from a server, _translate_error returns the original error tuple from
 
2788
        the server and mutters a warning.
 
2789
        """
 
2790
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
 
2791
        # in the context dict.  So let's give it an empty context dict instead
 
2792
        # to exercise its error recovery.
 
2793
        empty_context = {}
 
2794
        error_tuple = ('NoSuchRevision', 'revid')
 
2795
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2796
        translated_error = self.translateErrorFromSmartServer(server_error)
 
2797
        self.assertEqual(server_error, translated_error)
 
2798
        # In addition to re-raising ErrorFromSmartServer, some debug info has
 
2799
        # been muttered to the log file for developer to look at.
 
2800
        self.assertContainsRe(
 
2801
            self._get_log(keep_log_file=True),
 
2802
            "Missing key 'branch' in context")
 
2803
 
 
2804
    def test_path_missing(self):
 
2805
        """Some translations (PermissionDenied, ReadError) can determine the
 
2806
        'path' variable from either the wire or the local context.  If neither
 
2807
        has it, then an error is raised.
 
2808
        """
 
2809
        error_tuple = ('ReadError',)
 
2810
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2811
        translated_error = self.translateErrorFromSmartServer(server_error)
 
2812
        self.assertEqual(server_error, translated_error)
 
2813
        # In addition to re-raising ErrorFromSmartServer, some debug info has
 
2814
        # been muttered to the log file for developer to look at.
 
2815
        self.assertContainsRe(
 
2816
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
 
2817
 
 
2818
 
 
2819
class TestStacking(tests.TestCaseWithTransport):
 
2820
    """Tests for operations on stacked remote repositories.
 
2821
 
 
2822
    The underlying format type must support stacking.
 
2823
    """
 
2824
 
 
2825
    def test_access_stacked_remote(self):
 
2826
        # based on <http://launchpad.net/bugs/261315>
 
2827
        # make a branch stacked on another repository containing an empty
 
2828
        # revision, then open it over hpss - we should be able to see that
 
2829
        # revision.
 
2830
        base_transport = self.get_transport()
 
2831
        base_builder = self.make_branch_builder('base', format='1.9')
 
2832
        base_builder.start_series()
 
2833
        base_revid = base_builder.build_snapshot('rev-id', None,
 
2834
            [('add', ('', None, 'directory', None))],
 
2835
            'message')
 
2836
        base_builder.finish_series()
 
2837
        stacked_branch = self.make_branch('stacked', format='1.9')
 
2838
        stacked_branch.set_stacked_on_url('../base')
 
2839
        # start a server looking at this
 
2840
        smart_server = server.SmartTCPServer_for_testing()
 
2841
        self.start_server(smart_server)
 
2842
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
 
2843
        # can get its branch and repository
 
2844
        remote_branch = remote_bzrdir.open_branch()
 
2845
        remote_repo = remote_branch.repository
 
2846
        remote_repo.lock_read()
 
2847
        try:
 
2848
            # it should have an appropriate fallback repository, which should also
 
2849
            # be a RemoteRepository
 
2850
            self.assertLength(1, remote_repo._fallback_repositories)
 
2851
            self.assertIsInstance(remote_repo._fallback_repositories[0],
 
2852
                RemoteRepository)
 
2853
            # and it has the revision committed to the underlying repository;
 
2854
            # these have varying implementations so we try several of them
 
2855
            self.assertTrue(remote_repo.has_revisions([base_revid]))
 
2856
            self.assertTrue(remote_repo.has_revision(base_revid))
 
2857
            self.assertEqual(remote_repo.get_revision(base_revid).message,
 
2858
                'message')
 
2859
        finally:
 
2860
            remote_repo.unlock()
 
2861
 
 
2862
    def prepare_stacked_remote_branch(self):
 
2863
        """Get stacked_upon and stacked branches with content in each."""
 
2864
        self.setup_smart_server_with_call_log()
 
2865
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
 
2866
        tree1.commit('rev1', rev_id='rev1')
 
2867
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
 
2868
            ).open_workingtree()
 
2869
        local_tree = tree2.branch.create_checkout('local')
 
2870
        local_tree.commit('local changes make me feel good.')
 
2871
        branch2 = Branch.open(self.get_url('tree2'))
 
2872
        branch2.lock_read()
 
2873
        self.addCleanup(branch2.unlock)
 
2874
        return tree1.branch, branch2
 
2875
 
 
2876
    def test_stacked_get_parent_map(self):
 
2877
        # the public implementation of get_parent_map obeys stacking
 
2878
        _, branch = self.prepare_stacked_remote_branch()
 
2879
        repo = branch.repository
 
2880
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
 
2881
 
 
2882
    def test_unstacked_get_parent_map(self):
 
2883
        # _unstacked_provider.get_parent_map ignores stacking
 
2884
        _, branch = self.prepare_stacked_remote_branch()
 
2885
        provider = branch.repository._unstacked_provider
 
2886
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
 
2887
 
 
2888
    def fetch_stream_to_rev_order(self, stream):
 
2889
        result = []
 
2890
        for kind, substream in stream:
 
2891
            if not kind == 'revisions':
 
2892
                list(substream)
 
2893
            else:
 
2894
                for content in substream:
 
2895
                    result.append(content.key[-1])
 
2896
        return result
 
2897
 
 
2898
    def get_ordered_revs(self, format, order, branch_factory=None):
 
2899
        """Get a list of the revisions in a stream to format format.
 
2900
 
 
2901
        :param format: The format of the target.
 
2902
        :param order: the order that target should have requested.
 
2903
        :param branch_factory: A callable to create a trunk and stacked branch
 
2904
            to fetch from. If none, self.prepare_stacked_remote_branch is used.
 
2905
        :result: The revision ids in the stream, in the order seen,
 
2906
            the topological order of revisions in the source.
 
2907
        """
 
2908
        unordered_format = bzrdir.format_registry.get(format)()
 
2909
        target_repository_format = unordered_format.repository_format
 
2910
        # Cross check
 
2911
        self.assertEqual(order, target_repository_format._fetch_order)
 
2912
        if branch_factory is None:
 
2913
            branch_factory = self.prepare_stacked_remote_branch
 
2914
        _, stacked = branch_factory()
 
2915
        source = stacked.repository._get_source(target_repository_format)
 
2916
        tip = stacked.last_revision()
 
2917
        revs = stacked.repository.get_ancestry(tip)
 
2918
        search = graph.PendingAncestryResult([tip], stacked.repository)
 
2919
        self.reset_smart_call_log()
 
2920
        stream = source.get_stream(search)
 
2921
        if None in revs:
 
2922
            revs.remove(None)
 
2923
        # We trust that if a revision is in the stream the rest of the new
 
2924
        # content for it is too, as per our main fetch tests; here we are
 
2925
        # checking that the revisions are actually included at all, and their
 
2926
        # order.
 
2927
        return self.fetch_stream_to_rev_order(stream), revs
 
2928
 
 
2929
    def test_stacked_get_stream_unordered(self):
 
2930
        # Repository._get_source.get_stream() from a stacked repository with
 
2931
        # unordered yields the full data from both stacked and stacked upon
 
2932
        # sources.
 
2933
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered')
 
2934
        self.assertEqual(set(expected_revs), set(rev_ord))
 
2935
        # Getting unordered results should have made a streaming data request
 
2936
        # from the server, then one from the backing branch.
 
2937
        self.assertLength(2, self.hpss_calls)
 
2938
 
 
2939
    def test_stacked_on_stacked_get_stream_unordered(self):
 
2940
        # Repository._get_source.get_stream() from a stacked repository which
 
2941
        # is itself stacked yields the full data from all three sources.
 
2942
        def make_stacked_stacked():
 
2943
            _, stacked = self.prepare_stacked_remote_branch()
 
2944
            tree = stacked.bzrdir.sprout('tree3', stacked=True
 
2945
                ).open_workingtree()
 
2946
            local_tree = tree.branch.create_checkout('local-tree3')
 
2947
            local_tree.commit('more local changes are better')
 
2948
            branch = Branch.open(self.get_url('tree3'))
 
2949
            branch.lock_read()
 
2950
            return None, branch
 
2951
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
 
2952
            branch_factory=make_stacked_stacked)
 
2953
        self.assertEqual(set(expected_revs), set(rev_ord))
 
2954
        # Getting unordered results should have made a streaming data request
 
2955
        # from the server, and one from each backing repo
 
2956
        self.assertLength(3, self.hpss_calls)
 
2957
 
 
2958
    def test_stacked_get_stream_topological(self):
 
2959
        # Repository._get_source.get_stream() from a stacked repository with
 
2960
        # topological sorting yields the full data from both stacked and
 
2961
        # stacked upon sources in topological order.
 
2962
        rev_ord, expected_revs = self.get_ordered_revs('knit', 'topological')
 
2963
        self.assertEqual(expected_revs, rev_ord)
 
2964
        # Getting topological sort requires VFS calls still - one of which is
 
2965
        # pushing up from the bound branch.
 
2966
        self.assertLength(13, self.hpss_calls)
 
2967
 
 
2968
    def test_stacked_get_stream_groupcompress(self):
 
2969
        # Repository._get_source.get_stream() from a stacked repository with
 
2970
        # groupcompress sorting yields the full data from both stacked and
 
2971
        # stacked upon sources in groupcompress order.
 
2972
        raise tests.TestSkipped('No groupcompress ordered format available')
 
2973
        rev_ord, expected_revs = self.get_ordered_revs('dev5', 'groupcompress')
 
2974
        self.assertEqual(expected_revs, reversed(rev_ord))
 
2975
        # Getting unordered results should have made a streaming data request
 
2976
        # from the backing branch, and one from the stacked on branch.
 
2977
        self.assertLength(2, self.hpss_calls)
 
2978
 
 
2979
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
 
2980
        # When pulling some fixed amount of content that is more than the
 
2981
        # source has (because some is coming from a fallback branch, no error
 
2982
        # should be received. This was reported as bug 360791.
 
2983
        # Need three branches: a trunk, a stacked branch, and a preexisting
 
2984
        # branch pulling content from stacked and trunk.
 
2985
        self.setup_smart_server_with_call_log()
 
2986
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
 
2987
        r1 = trunk.commit('start')
 
2988
        stacked_branch = trunk.branch.create_clone_on_transport(
 
2989
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
 
2990
        local = self.make_branch('local', format='1.9-rich-root')
 
2991
        local.repository.fetch(stacked_branch.repository,
 
2992
            stacked_branch.last_revision())
 
2993
 
 
2994
 
 
2995
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
 
2996
 
 
2997
    def setUp(self):
 
2998
        super(TestRemoteBranchEffort, self).setUp()
 
2999
        # Create a smart server that publishes whatever the backing VFS server
 
3000
        # does.
 
3001
        self.smart_server = server.SmartTCPServer_for_testing()
 
3002
        self.start_server(self.smart_server, self.get_server())
 
3003
        # Log all HPSS calls into self.hpss_calls.
 
3004
        _SmartClient.hooks.install_named_hook(
 
3005
            'call', self.capture_hpss_call, None)
 
3006
        self.hpss_calls = []
 
3007
 
 
3008
    def capture_hpss_call(self, params):
 
3009
        self.hpss_calls.append(params.method)
 
3010
 
 
3011
    def test_copy_content_into_avoids_revision_history(self):
 
3012
        local = self.make_branch('local')
 
3013
        remote_backing_tree = self.make_branch_and_tree('remote')
 
3014
        remote_backing_tree.commit("Commit.")
 
3015
        remote_branch_url = self.smart_server.get_url() + 'remote'
 
3016
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
 
3017
        local.repository.fetch(remote_branch.repository)
 
3018
        self.hpss_calls = []
 
3019
        remote_branch.copy_content_into(local)
 
3020
        self.assertFalse('Branch.revision_history' in self.hpss_calls)