/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Andrew Bennetts
  • Date: 2009-09-17 03:16:05 UTC
  • mto: This revision was merged to the branch mainline in revision 4702.
  • Revision ID: andrew.bennetts@canonical.com-20090917031605-xilizo5jfq4scbw0
Update documentation.

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
        smart_server.setUp()
 
2003
        self.addCleanup(smart_server.tearDown)
 
2004
        self.make_branch('branch')
 
2005
        branch = Branch.open(smart_server.get_url() + '/branch')
 
2006
        tree = branch.create_checkout('tree', lightweight=True)
 
2007
        tree.lock_write()
 
2008
        self.addCleanup(tree.unlock)
 
2009
        graph = tree.branch.repository.get_graph()
 
2010
        # This provides an opportunity for the missing rev-id to be cached.
 
2011
        self.assertEqual({}, graph.get_parent_map(['rev1']))
 
2012
        tree.commit('message', rev_id='rev1')
 
2013
        graph = tree.branch.repository.get_graph()
 
2014
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
 
2015
 
 
2016
 
 
2017
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
 
2018
 
 
2019
    def test_null_revision(self):
 
2020
        # a null revision has the predictable result {}, we should have no wire
 
2021
        # traffic when calling it with this argument
 
2022
        transport_path = 'empty'
 
2023
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2024
        client.add_success_response('notused')
 
2025
        # actual RemoteRepository.get_revision_graph is gone, but there's an
 
2026
        # equivalent private method for testing
 
2027
        result = repo._get_revision_graph(NULL_REVISION)
 
2028
        self.assertEqual([], client._calls)
 
2029
        self.assertEqual({}, result)
 
2030
 
 
2031
    def test_none_revision(self):
 
2032
        # with none we want the entire graph
 
2033
        r1 = u'\u0e33'.encode('utf8')
 
2034
        r2 = u'\u0dab'.encode('utf8')
 
2035
        lines = [' '.join([r2, r1]), r1]
 
2036
        encoded_body = '\n'.join(lines)
 
2037
 
 
2038
        transport_path = 'sinhala'
 
2039
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2040
        client.add_success_response_with_body(encoded_body, 'ok')
 
2041
        # actual RemoteRepository.get_revision_graph is gone, but there's an
 
2042
        # equivalent private method for testing
 
2043
        result = repo._get_revision_graph(None)
 
2044
        self.assertEqual(
 
2045
            [('call_expecting_body', 'Repository.get_revision_graph',
 
2046
             ('sinhala/', ''))],
 
2047
            client._calls)
 
2048
        self.assertEqual({r1: (), r2: (r1, )}, result)
 
2049
 
 
2050
    def test_specific_revision(self):
 
2051
        # with a specific revision we want the graph for that
 
2052
        # with none we want the entire graph
 
2053
        r11 = u'\u0e33'.encode('utf8')
 
2054
        r12 = u'\xc9'.encode('utf8')
 
2055
        r2 = u'\u0dab'.encode('utf8')
 
2056
        lines = [' '.join([r2, r11, r12]), r11, r12]
 
2057
        encoded_body = '\n'.join(lines)
 
2058
 
 
2059
        transport_path = 'sinhala'
 
2060
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2061
        client.add_success_response_with_body(encoded_body, 'ok')
 
2062
        result = repo._get_revision_graph(r2)
 
2063
        self.assertEqual(
 
2064
            [('call_expecting_body', 'Repository.get_revision_graph',
 
2065
             ('sinhala/', r2))],
 
2066
            client._calls)
 
2067
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
 
2068
 
 
2069
    def test_no_such_revision(self):
 
2070
        revid = '123'
 
2071
        transport_path = 'sinhala'
 
2072
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2073
        client.add_error_response('nosuchrevision', revid)
 
2074
        # also check that the right revision is reported in the error
 
2075
        self.assertRaises(errors.NoSuchRevision,
 
2076
            repo._get_revision_graph, revid)
 
2077
        self.assertEqual(
 
2078
            [('call_expecting_body', 'Repository.get_revision_graph',
 
2079
             ('sinhala/', revid))],
 
2080
            client._calls)
 
2081
 
 
2082
    def test_unexpected_error(self):
 
2083
        revid = '123'
 
2084
        transport_path = 'sinhala'
 
2085
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2086
        client.add_error_response('AnUnexpectedError')
 
2087
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
 
2088
            repo._get_revision_graph, revid)
 
2089
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
 
2090
 
 
2091
 
 
2092
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
 
2093
 
 
2094
    def test_ok(self):
 
2095
        repo, client = self.setup_fake_client_and_repository('quack')
 
2096
        client.add_expected_call(
 
2097
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2098
            'success', ('ok', 'rev-five'))
 
2099
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
 
2100
        self.assertEqual((True, 'rev-five'), result)
 
2101
        self.assertFinished(client)
 
2102
 
 
2103
    def test_history_incomplete(self):
 
2104
        repo, client = self.setup_fake_client_and_repository('quack')
 
2105
        client.add_expected_call(
 
2106
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2107
            'success', ('history-incomplete', 10, 'rev-ten'))
 
2108
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
 
2109
        self.assertEqual((False, (10, 'rev-ten')), result)
 
2110
        self.assertFinished(client)
 
2111
 
 
2112
    def test_history_incomplete_with_fallback(self):
 
2113
        """A 'history-incomplete' response causes the fallback repository to be
 
2114
        queried too, if one is set.
 
2115
        """
 
2116
        # Make a repo with a fallback repo, both using a FakeClient.
 
2117
        format = remote.response_tuple_to_repo_format(
 
2118
            ('yes', 'no', 'yes', 'fake-network-name'))
 
2119
        repo, client = self.setup_fake_client_and_repository('quack')
 
2120
        repo._format = format
 
2121
        fallback_repo, ignored = self.setup_fake_client_and_repository(
 
2122
            'fallback')
 
2123
        fallback_repo._client = client
 
2124
        repo.add_fallback_repository(fallback_repo)
 
2125
        # First the client should ask the primary repo
 
2126
        client.add_expected_call(
 
2127
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
 
2128
            'success', ('history-incomplete', 2, 'rev-two'))
 
2129
        # Then it should ask the fallback, using revno/revid from the
 
2130
        # history-incomplete response as the known revno/revid.
 
2131
        client.add_expected_call(
 
2132
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
 
2133
            'success', ('ok', 'rev-one'))
 
2134
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
 
2135
        self.assertEqual((True, 'rev-one'), result)
 
2136
        self.assertFinished(client)
 
2137
 
 
2138
    def test_nosuchrevision(self):
 
2139
        # 'nosuchrevision' is returned when the known-revid is not found in the
 
2140
        # remote repo.  The client translates that response to NoSuchRevision.
 
2141
        repo, client = self.setup_fake_client_and_repository('quack')
 
2142
        client.add_expected_call(
 
2143
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2144
            'error', ('nosuchrevision', 'rev-foo'))
 
2145
        self.assertRaises(
 
2146
            errors.NoSuchRevision,
 
2147
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
 
2148
        self.assertFinished(client)
 
2149
 
 
2150
 
 
2151
class TestRepositoryIsShared(TestRemoteRepository):
 
2152
 
 
2153
    def test_is_shared(self):
 
2154
        # ('yes', ) for Repository.is_shared -> 'True'.
 
2155
        transport_path = 'quack'
 
2156
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2157
        client.add_success_response('yes')
 
2158
        result = repo.is_shared()
 
2159
        self.assertEqual(
 
2160
            [('call', 'Repository.is_shared', ('quack/',))],
 
2161
            client._calls)
 
2162
        self.assertEqual(True, result)
 
2163
 
 
2164
    def test_is_not_shared(self):
 
2165
        # ('no', ) for Repository.is_shared -> 'False'.
 
2166
        transport_path = 'qwack'
 
2167
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2168
        client.add_success_response('no')
 
2169
        result = repo.is_shared()
 
2170
        self.assertEqual(
 
2171
            [('call', 'Repository.is_shared', ('qwack/',))],
 
2172
            client._calls)
 
2173
        self.assertEqual(False, result)
 
2174
 
 
2175
 
 
2176
class TestRepositoryLockWrite(TestRemoteRepository):
 
2177
 
 
2178
    def test_lock_write(self):
 
2179
        transport_path = 'quack'
 
2180
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2181
        client.add_success_response('ok', 'a token')
 
2182
        result = repo.lock_write()
 
2183
        self.assertEqual(
 
2184
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
2185
            client._calls)
 
2186
        self.assertEqual('a token', result)
 
2187
 
 
2188
    def test_lock_write_already_locked(self):
 
2189
        transport_path = 'quack'
 
2190
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2191
        client.add_error_response('LockContention')
 
2192
        self.assertRaises(errors.LockContention, repo.lock_write)
 
2193
        self.assertEqual(
 
2194
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
2195
            client._calls)
 
2196
 
 
2197
    def test_lock_write_unlockable(self):
 
2198
        transport_path = 'quack'
 
2199
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2200
        client.add_error_response('UnlockableTransport')
 
2201
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
 
2202
        self.assertEqual(
 
2203
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
2204
            client._calls)
 
2205
 
 
2206
 
 
2207
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
 
2208
 
 
2209
    def test_backwards_compat(self):
 
2210
        self.setup_smart_server_with_call_log()
 
2211
        repo = self.make_repository('.')
 
2212
        self.reset_smart_call_log()
 
2213
        verb = 'Repository.set_make_working_trees'
 
2214
        self.disable_verb(verb)
 
2215
        repo.set_make_working_trees(True)
 
2216
        call_count = len([call for call in self.hpss_calls if
 
2217
            call.call.method == verb])
 
2218
        self.assertEqual(1, call_count)
 
2219
 
 
2220
    def test_current(self):
 
2221
        transport_path = 'quack'
 
2222
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2223
        client.add_expected_call(
 
2224
            'Repository.set_make_working_trees', ('quack/', 'True'),
 
2225
            'success', ('ok',))
 
2226
        client.add_expected_call(
 
2227
            'Repository.set_make_working_trees', ('quack/', 'False'),
 
2228
            'success', ('ok',))
 
2229
        repo.set_make_working_trees(True)
 
2230
        repo.set_make_working_trees(False)
 
2231
 
 
2232
 
 
2233
class TestRepositoryUnlock(TestRemoteRepository):
 
2234
 
 
2235
    def test_unlock(self):
 
2236
        transport_path = 'quack'
 
2237
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2238
        client.add_success_response('ok', 'a token')
 
2239
        client.add_success_response('ok')
 
2240
        repo.lock_write()
 
2241
        repo.unlock()
 
2242
        self.assertEqual(
 
2243
            [('call', 'Repository.lock_write', ('quack/', '')),
 
2244
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
 
2245
            client._calls)
 
2246
 
 
2247
    def test_unlock_wrong_token(self):
 
2248
        # If somehow the token is wrong, unlock will raise TokenMismatch.
 
2249
        transport_path = 'quack'
 
2250
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2251
        client.add_success_response('ok', 'a token')
 
2252
        client.add_error_response('TokenMismatch')
 
2253
        repo.lock_write()
 
2254
        self.assertRaises(errors.TokenMismatch, repo.unlock)
 
2255
 
 
2256
 
 
2257
class TestRepositoryHasRevision(TestRemoteRepository):
 
2258
 
 
2259
    def test_none(self):
 
2260
        # repo.has_revision(None) should not cause any traffic.
 
2261
        transport_path = 'quack'
 
2262
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2263
 
 
2264
        # The null revision is always there, so has_revision(None) == True.
 
2265
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
 
2266
 
 
2267
        # The remote repo shouldn't be accessed.
 
2268
        self.assertEqual([], client._calls)
 
2269
 
 
2270
 
 
2271
class TestRepositoryInsertStreamBase(TestRemoteRepository):
 
2272
    """Base class for Repository.insert_stream and .insert_stream_1.19
 
2273
    tests.
 
2274
    """
 
2275
    
 
2276
    def checkInsertEmptyStream(self, repo, client):
 
2277
        """Insert an empty stream, checking the result.
 
2278
 
 
2279
        This checks that there are no resume_tokens or missing_keys, and that
 
2280
        the client is finished.
 
2281
        """
 
2282
        sink = repo._get_sink()
 
2283
        fmt = repository.RepositoryFormat.get_default_format()
 
2284
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
 
2285
        self.assertEqual([], resume_tokens)
 
2286
        self.assertEqual(set(), missing_keys)
 
2287
        self.assertFinished(client)
 
2288
 
 
2289
 
 
2290
class TestRepositoryInsertStream(TestRepositoryInsertStreamBase):
 
2291
    """Tests for using Repository.insert_stream verb when the _1.19 variant is
 
2292
    not available.
 
2293
 
 
2294
    This test case is very similar to TestRepositoryInsertStream_1_19.
 
2295
    """
 
2296
 
 
2297
    def setUp(self):
 
2298
        TestRemoteRepository.setUp(self)
 
2299
        self.disable_verb('Repository.insert_stream_1.19')
 
2300
 
 
2301
    def test_unlocked_repo(self):
 
2302
        transport_path = 'quack'
 
2303
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2304
        client.add_expected_call(
 
2305
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2306
            'unknown', ('Repository.insert_stream_1.19',))
 
2307
        client.add_expected_call(
 
2308
            'Repository.insert_stream', ('quack/', ''),
 
2309
            'success', ('ok',))
 
2310
        client.add_expected_call(
 
2311
            'Repository.insert_stream', ('quack/', ''),
 
2312
            'success', ('ok',))
 
2313
        self.checkInsertEmptyStream(repo, client)
 
2314
 
 
2315
    def test_locked_repo_with_no_lock_token(self):
 
2316
        transport_path = 'quack'
 
2317
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2318
        client.add_expected_call(
 
2319
            'Repository.lock_write', ('quack/', ''),
 
2320
            'success', ('ok', ''))
 
2321
        client.add_expected_call(
 
2322
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2323
            'unknown', ('Repository.insert_stream_1.19',))
 
2324
        client.add_expected_call(
 
2325
            'Repository.insert_stream', ('quack/', ''),
 
2326
            'success', ('ok',))
 
2327
        client.add_expected_call(
 
2328
            'Repository.insert_stream', ('quack/', ''),
 
2329
            'success', ('ok',))
 
2330
        repo.lock_write()
 
2331
        self.checkInsertEmptyStream(repo, client)
 
2332
 
 
2333
    def test_locked_repo_with_lock_token(self):
 
2334
        transport_path = 'quack'
 
2335
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2336
        client.add_expected_call(
 
2337
            'Repository.lock_write', ('quack/', ''),
 
2338
            'success', ('ok', 'a token'))
 
2339
        client.add_expected_call(
 
2340
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2341
            'unknown', ('Repository.insert_stream_1.19',))
 
2342
        client.add_expected_call(
 
2343
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2344
            'success', ('ok',))
 
2345
        client.add_expected_call(
 
2346
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2347
            'success', ('ok',))
 
2348
        repo.lock_write()
 
2349
        self.checkInsertEmptyStream(repo, client)
 
2350
 
 
2351
    def test_stream_with_inventory_deltas(self):
 
2352
        """'inventory-deltas' substreams cannot be sent to the
 
2353
        Repository.insert_stream verb, because not all servers that implement
 
2354
        that verb will accept them.  So when one is encountered the RemoteSink
 
2355
        immediately stops using that verb and falls back to VFS insert_stream.
 
2356
        """
 
2357
        transport_path = 'quack'
 
2358
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2359
        client.add_expected_call(
 
2360
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2361
            'unknown', ('Repository.insert_stream_1.19',))
 
2362
        client.add_expected_call(
 
2363
            'Repository.insert_stream', ('quack/', ''),
 
2364
            'success', ('ok',))
 
2365
        client.add_expected_call(
 
2366
            'Repository.insert_stream', ('quack/', ''),
 
2367
            'success', ('ok',))
 
2368
        # Create a fake real repository for insert_stream to fall back on, so
 
2369
        # that we can directly see the records the RemoteSink passes to the
 
2370
        # real sink.
 
2371
        class FakeRealSink:
 
2372
            def __init__(self):
 
2373
                self.records = []
 
2374
            def insert_stream(self, stream, src_format, resume_tokens):
 
2375
                for substream_kind, substream in stream:
 
2376
                    self.records.append(
 
2377
                        (substream_kind, [record.key for record in substream]))
 
2378
                return ['fake tokens'], ['fake missing keys']
 
2379
        fake_real_sink = FakeRealSink()
 
2380
        class FakeRealRepository:
 
2381
            def _get_sink(self):
 
2382
                return fake_real_sink
 
2383
            def is_in_write_group(self):
 
2384
                return False
 
2385
            def refresh_data(self):
 
2386
                return True
 
2387
        repo._real_repository = FakeRealRepository()
 
2388
        sink = repo._get_sink()
 
2389
        fmt = repository.RepositoryFormat.get_default_format()
 
2390
        stream = self.make_stream_with_inv_deltas(fmt)
 
2391
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
 
2392
        # Every record from the first inventory delta should have been sent to
 
2393
        # the VFS sink.
 
2394
        expected_records = [
 
2395
            ('inventory-deltas', [('rev2',), ('rev3',)]),
 
2396
            ('texts', [('some-rev', 'some-file')])]
 
2397
        self.assertEqual(expected_records, fake_real_sink.records)
 
2398
        # The return values from the real sink's insert_stream are propagated
 
2399
        # back to the original caller.
 
2400
        self.assertEqual(['fake tokens'], resume_tokens)
 
2401
        self.assertEqual(['fake missing keys'], missing_keys)
 
2402
        self.assertFinished(client)
 
2403
 
 
2404
    def make_stream_with_inv_deltas(self, fmt):
 
2405
        """Make a simple stream with an inventory delta followed by more
 
2406
        records and more substreams to test that all records and substreams
 
2407
        from that point on are used.
 
2408
 
 
2409
        This sends, in order:
 
2410
           * inventories substream: rev1, rev2, rev3.  rev2 and rev3 are
 
2411
             inventory-deltas.
 
2412
           * texts substream: (some-rev, some-file)
 
2413
        """
 
2414
        # Define a stream using generators so that it isn't rewindable.
 
2415
        inv = inventory.Inventory(revision_id='rev1')
 
2416
        inv.root.revision = 'rev1'
 
2417
        def stream_with_inv_delta():
 
2418
            yield ('inventories', inventories_substream())
 
2419
            yield ('inventory-deltas', inventory_delta_substream())
 
2420
            yield ('texts', [
 
2421
                versionedfile.FulltextContentFactory(
 
2422
                    ('some-rev', 'some-file'), (), None, 'content')])
 
2423
        def inventories_substream():
 
2424
            # An empty inventory fulltext.  This will be streamed normally.
 
2425
            text = fmt._serializer.write_inventory_to_string(inv)
 
2426
            yield versionedfile.FulltextContentFactory(
 
2427
                ('rev1',), (), None, text)
 
2428
        def inventory_delta_substream():
 
2429
            # An inventory delta.  This can't be streamed via this verb, so it
 
2430
            # will trigger a fallback to VFS insert_stream.
 
2431
            entry = inv.make_entry(
 
2432
                'directory', 'newdir', inv.root.file_id, 'newdir-id')
 
2433
            entry.revision = 'ghost'
 
2434
            delta = [(None, 'newdir', 'newdir-id', entry)]
 
2435
            serializer = inventory_delta.InventoryDeltaSerializer(
 
2436
                versioned_root=True, tree_references=False)
 
2437
            lines = serializer.delta_to_lines('rev1', 'rev2', delta)
 
2438
            yield versionedfile.ChunkedContentFactory(
 
2439
                ('rev2',), (('rev1',)), None, lines)
 
2440
            # Another delta.
 
2441
            lines = serializer.delta_to_lines('rev1', 'rev3', delta)
 
2442
            yield versionedfile.ChunkedContentFactory(
 
2443
                ('rev3',), (('rev1',)), None, lines)
 
2444
        return stream_with_inv_delta()
 
2445
 
 
2446
 
 
2447
class TestRepositoryInsertStream_1_19(TestRepositoryInsertStreamBase):
 
2448
 
 
2449
    def test_unlocked_repo(self):
 
2450
        transport_path = 'quack'
 
2451
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2452
        client.add_expected_call(
 
2453
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2454
            'success', ('ok',))
 
2455
        client.add_expected_call(
 
2456
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2457
            'success', ('ok',))
 
2458
        self.checkInsertEmptyStream(repo, client)
 
2459
 
 
2460
    def test_locked_repo_with_no_lock_token(self):
 
2461
        transport_path = 'quack'
 
2462
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2463
        client.add_expected_call(
 
2464
            'Repository.lock_write', ('quack/', ''),
 
2465
            'success', ('ok', ''))
 
2466
        client.add_expected_call(
 
2467
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2468
            'success', ('ok',))
 
2469
        client.add_expected_call(
 
2470
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2471
            'success', ('ok',))
 
2472
        repo.lock_write()
 
2473
        self.checkInsertEmptyStream(repo, client)
 
2474
 
 
2475
    def test_locked_repo_with_lock_token(self):
 
2476
        transport_path = 'quack'
 
2477
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2478
        client.add_expected_call(
 
2479
            'Repository.lock_write', ('quack/', ''),
 
2480
            'success', ('ok', 'a token'))
 
2481
        client.add_expected_call(
 
2482
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2483
            'success', ('ok',))
 
2484
        client.add_expected_call(
 
2485
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2486
            'success', ('ok',))
 
2487
        repo.lock_write()
 
2488
        self.checkInsertEmptyStream(repo, client)
 
2489
 
 
2490
 
 
2491
class TestRepositoryTarball(TestRemoteRepository):
 
2492
 
 
2493
    # This is a canned tarball reponse we can validate against
 
2494
    tarball_content = (
 
2495
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
 
2496
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
 
2497
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
 
2498
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
 
2499
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
 
2500
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
 
2501
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
 
2502
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
 
2503
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
 
2504
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
 
2505
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
 
2506
        'nWQ7QH/F3JFOFCQ0aSPfA='
 
2507
        ).decode('base64')
 
2508
 
 
2509
    def test_repository_tarball(self):
 
2510
        # Test that Repository.tarball generates the right operations
 
2511
        transport_path = 'repo'
 
2512
        expected_calls = [('call_expecting_body', 'Repository.tarball',
 
2513
                           ('repo/', 'bz2',),),
 
2514
            ]
 
2515
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2516
        client.add_success_response_with_body(self.tarball_content, 'ok')
 
2517
        # Now actually ask for the tarball
 
2518
        tarball_file = repo._get_tarball('bz2')
 
2519
        try:
 
2520
            self.assertEqual(expected_calls, client._calls)
 
2521
            self.assertEqual(self.tarball_content, tarball_file.read())
 
2522
        finally:
 
2523
            tarball_file.close()
 
2524
 
 
2525
 
 
2526
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
 
2527
    """RemoteRepository.copy_content_into optimizations"""
 
2528
 
 
2529
    def test_copy_content_remote_to_local(self):
 
2530
        self.transport_server = server.SmartTCPServer_for_testing
 
2531
        src_repo = self.make_repository('repo1')
 
2532
        src_repo = repository.Repository.open(self.get_url('repo1'))
 
2533
        # At the moment the tarball-based copy_content_into can't write back
 
2534
        # into a smart server.  It would be good if it could upload the
 
2535
        # tarball; once that works we'd have to create repositories of
 
2536
        # different formats. -- mbp 20070410
 
2537
        dest_url = self.get_vfs_only_url('repo2')
 
2538
        dest_bzrdir = BzrDir.create(dest_url)
 
2539
        dest_repo = dest_bzrdir.create_repository()
 
2540
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
 
2541
        self.assertTrue(isinstance(src_repo, RemoteRepository))
 
2542
        src_repo.copy_content_into(dest_repo)
 
2543
 
 
2544
 
 
2545
class _StubRealPackRepository(object):
 
2546
 
 
2547
    def __init__(self, calls):
 
2548
        self.calls = calls
 
2549
        self._pack_collection = _StubPackCollection(calls)
 
2550
 
 
2551
    def is_in_write_group(self):
 
2552
        return False
 
2553
 
 
2554
    def refresh_data(self):
 
2555
        self.calls.append(('pack collection reload_pack_names',))
 
2556
 
 
2557
 
 
2558
class _StubPackCollection(object):
 
2559
 
 
2560
    def __init__(self, calls):
 
2561
        self.calls = calls
 
2562
 
 
2563
    def autopack(self):
 
2564
        self.calls.append(('pack collection autopack',))
 
2565
 
 
2566
 
 
2567
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
 
2568
    """Tests for RemoteRepository.autopack implementation."""
 
2569
 
 
2570
    def test_ok(self):
 
2571
        """When the server returns 'ok' and there's no _real_repository, then
 
2572
        nothing else happens: the autopack method is done.
 
2573
        """
 
2574
        transport_path = 'quack'
 
2575
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2576
        client.add_expected_call(
 
2577
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
 
2578
        repo.autopack()
 
2579
        self.assertFinished(client)
 
2580
 
 
2581
    def test_ok_with_real_repo(self):
 
2582
        """When the server returns 'ok' and there is a _real_repository, then
 
2583
        the _real_repository's reload_pack_name's method will be called.
 
2584
        """
 
2585
        transport_path = 'quack'
 
2586
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2587
        client.add_expected_call(
 
2588
            'PackRepository.autopack', ('quack/',),
 
2589
            'success', ('ok',))
 
2590
        repo._real_repository = _StubRealPackRepository(client._calls)
 
2591
        repo.autopack()
 
2592
        self.assertEqual(
 
2593
            [('call', 'PackRepository.autopack', ('quack/',)),
 
2594
             ('pack collection reload_pack_names',)],
 
2595
            client._calls)
 
2596
 
 
2597
    def test_backwards_compatibility(self):
 
2598
        """If the server does not recognise the PackRepository.autopack verb,
 
2599
        fallback to the real_repository's implementation.
 
2600
        """
 
2601
        transport_path = 'quack'
 
2602
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2603
        client.add_unknown_method_response('PackRepository.autopack')
 
2604
        def stub_ensure_real():
 
2605
            client._calls.append(('_ensure_real',))
 
2606
            repo._real_repository = _StubRealPackRepository(client._calls)
 
2607
        repo._ensure_real = stub_ensure_real
 
2608
        repo.autopack()
 
2609
        self.assertEqual(
 
2610
            [('call', 'PackRepository.autopack', ('quack/',)),
 
2611
             ('_ensure_real',),
 
2612
             ('pack collection autopack',)],
 
2613
            client._calls)
 
2614
 
 
2615
 
 
2616
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
 
2617
    """Base class for unit tests for bzrlib.remote._translate_error."""
 
2618
 
 
2619
    def translateTuple(self, error_tuple, **context):
 
2620
        """Call _translate_error with an ErrorFromSmartServer built from the
 
2621
        given error_tuple.
 
2622
 
 
2623
        :param error_tuple: A tuple of a smart server response, as would be
 
2624
            passed to an ErrorFromSmartServer.
 
2625
        :kwargs context: context items to call _translate_error with.
 
2626
 
 
2627
        :returns: The error raised by _translate_error.
 
2628
        """
 
2629
        # Raise the ErrorFromSmartServer before passing it as an argument,
 
2630
        # because _translate_error may need to re-raise it with a bare 'raise'
 
2631
        # statement.
 
2632
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2633
        translated_error = self.translateErrorFromSmartServer(
 
2634
            server_error, **context)
 
2635
        return translated_error
 
2636
 
 
2637
    def translateErrorFromSmartServer(self, error_object, **context):
 
2638
        """Like translateTuple, but takes an already constructed
 
2639
        ErrorFromSmartServer rather than a tuple.
 
2640
        """
 
2641
        try:
 
2642
            raise error_object
 
2643
        except errors.ErrorFromSmartServer, server_error:
 
2644
            translated_error = self.assertRaises(
 
2645
                errors.BzrError, remote._translate_error, server_error,
 
2646
                **context)
 
2647
        return translated_error
 
2648
 
 
2649
 
 
2650
class TestErrorTranslationSuccess(TestErrorTranslationBase):
 
2651
    """Unit tests for bzrlib.remote._translate_error.
 
2652
 
 
2653
    Given an ErrorFromSmartServer (which has an error tuple from a smart
 
2654
    server) and some context, _translate_error raises more specific errors from
 
2655
    bzrlib.errors.
 
2656
 
 
2657
    This test case covers the cases where _translate_error succeeds in
 
2658
    translating an ErrorFromSmartServer to something better.  See
 
2659
    TestErrorTranslationRobustness for other cases.
 
2660
    """
 
2661
 
 
2662
    def test_NoSuchRevision(self):
 
2663
        branch = self.make_branch('')
 
2664
        revid = 'revid'
 
2665
        translated_error = self.translateTuple(
 
2666
            ('NoSuchRevision', revid), branch=branch)
 
2667
        expected_error = errors.NoSuchRevision(branch, revid)
 
2668
        self.assertEqual(expected_error, translated_error)
 
2669
 
 
2670
    def test_nosuchrevision(self):
 
2671
        repository = self.make_repository('')
 
2672
        revid = 'revid'
 
2673
        translated_error = self.translateTuple(
 
2674
            ('nosuchrevision', revid), repository=repository)
 
2675
        expected_error = errors.NoSuchRevision(repository, revid)
 
2676
        self.assertEqual(expected_error, translated_error)
 
2677
 
 
2678
    def test_nobranch(self):
 
2679
        bzrdir = self.make_bzrdir('')
 
2680
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
 
2681
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
 
2682
        self.assertEqual(expected_error, translated_error)
 
2683
 
 
2684
    def test_LockContention(self):
 
2685
        translated_error = self.translateTuple(('LockContention',))
 
2686
        expected_error = errors.LockContention('(remote lock)')
 
2687
        self.assertEqual(expected_error, translated_error)
 
2688
 
 
2689
    def test_UnlockableTransport(self):
 
2690
        bzrdir = self.make_bzrdir('')
 
2691
        translated_error = self.translateTuple(
 
2692
            ('UnlockableTransport',), bzrdir=bzrdir)
 
2693
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
 
2694
        self.assertEqual(expected_error, translated_error)
 
2695
 
 
2696
    def test_LockFailed(self):
 
2697
        lock = 'str() of a server lock'
 
2698
        why = 'str() of why'
 
2699
        translated_error = self.translateTuple(('LockFailed', lock, why))
 
2700
        expected_error = errors.LockFailed(lock, why)
 
2701
        self.assertEqual(expected_error, translated_error)
 
2702
 
 
2703
    def test_TokenMismatch(self):
 
2704
        token = 'a lock token'
 
2705
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
 
2706
        expected_error = errors.TokenMismatch(token, '(remote token)')
 
2707
        self.assertEqual(expected_error, translated_error)
 
2708
 
 
2709
    def test_Diverged(self):
 
2710
        branch = self.make_branch('a')
 
2711
        other_branch = self.make_branch('b')
 
2712
        translated_error = self.translateTuple(
 
2713
            ('Diverged',), branch=branch, other_branch=other_branch)
 
2714
        expected_error = errors.DivergedBranches(branch, other_branch)
 
2715
        self.assertEqual(expected_error, translated_error)
 
2716
 
 
2717
    def test_ReadError_no_args(self):
 
2718
        path = 'a path'
 
2719
        translated_error = self.translateTuple(('ReadError',), path=path)
 
2720
        expected_error = errors.ReadError(path)
 
2721
        self.assertEqual(expected_error, translated_error)
 
2722
 
 
2723
    def test_ReadError(self):
 
2724
        path = 'a path'
 
2725
        translated_error = self.translateTuple(('ReadError', path))
 
2726
        expected_error = errors.ReadError(path)
 
2727
        self.assertEqual(expected_error, translated_error)
 
2728
 
 
2729
    def test_IncompatibleRepositories(self):
 
2730
        translated_error = self.translateTuple(('IncompatibleRepositories',
 
2731
            "repo1", "repo2", "details here"))
 
2732
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
 
2733
            "details here")
 
2734
        self.assertEqual(expected_error, translated_error)
 
2735
 
 
2736
    def test_PermissionDenied_no_args(self):
 
2737
        path = 'a path'
 
2738
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
 
2739
        expected_error = errors.PermissionDenied(path)
 
2740
        self.assertEqual(expected_error, translated_error)
 
2741
 
 
2742
    def test_PermissionDenied_one_arg(self):
 
2743
        path = 'a path'
 
2744
        translated_error = self.translateTuple(('PermissionDenied', path))
 
2745
        expected_error = errors.PermissionDenied(path)
 
2746
        self.assertEqual(expected_error, translated_error)
 
2747
 
 
2748
    def test_PermissionDenied_one_arg_and_context(self):
 
2749
        """Given a choice between a path from the local context and a path on
 
2750
        the wire, _translate_error prefers the path from the local context.
 
2751
        """
 
2752
        local_path = 'local path'
 
2753
        remote_path = 'remote path'
 
2754
        translated_error = self.translateTuple(
 
2755
            ('PermissionDenied', remote_path), path=local_path)
 
2756
        expected_error = errors.PermissionDenied(local_path)
 
2757
        self.assertEqual(expected_error, translated_error)
 
2758
 
 
2759
    def test_PermissionDenied_two_args(self):
 
2760
        path = 'a path'
 
2761
        extra = 'a string with extra info'
 
2762
        translated_error = self.translateTuple(
 
2763
            ('PermissionDenied', path, extra))
 
2764
        expected_error = errors.PermissionDenied(path, extra)
 
2765
        self.assertEqual(expected_error, translated_error)
 
2766
 
 
2767
 
 
2768
class TestErrorTranslationRobustness(TestErrorTranslationBase):
 
2769
    """Unit tests for bzrlib.remote._translate_error's robustness.
 
2770
 
 
2771
    TestErrorTranslationSuccess is for cases where _translate_error can
 
2772
    translate successfully.  This class about how _translate_err behaves when
 
2773
    it fails to translate: it re-raises the original error.
 
2774
    """
 
2775
 
 
2776
    def test_unrecognised_server_error(self):
 
2777
        """If the error code from the server is not recognised, the original
 
2778
        ErrorFromSmartServer is propagated unmodified.
 
2779
        """
 
2780
        error_tuple = ('An unknown error tuple',)
 
2781
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2782
        translated_error = self.translateErrorFromSmartServer(server_error)
 
2783
        expected_error = errors.UnknownErrorFromSmartServer(server_error)
 
2784
        self.assertEqual(expected_error, translated_error)
 
2785
 
 
2786
    def test_context_missing_a_key(self):
 
2787
        """In case of a bug in the client, or perhaps an unexpected response
 
2788
        from a server, _translate_error returns the original error tuple from
 
2789
        the server and mutters a warning.
 
2790
        """
 
2791
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
 
2792
        # in the context dict.  So let's give it an empty context dict instead
 
2793
        # to exercise its error recovery.
 
2794
        empty_context = {}
 
2795
        error_tuple = ('NoSuchRevision', 'revid')
 
2796
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2797
        translated_error = self.translateErrorFromSmartServer(server_error)
 
2798
        self.assertEqual(server_error, translated_error)
 
2799
        # In addition to re-raising ErrorFromSmartServer, some debug info has
 
2800
        # been muttered to the log file for developer to look at.
 
2801
        self.assertContainsRe(
 
2802
            self._get_log(keep_log_file=True),
 
2803
            "Missing key 'branch' in context")
 
2804
 
 
2805
    def test_path_missing(self):
 
2806
        """Some translations (PermissionDenied, ReadError) can determine the
 
2807
        'path' variable from either the wire or the local context.  If neither
 
2808
        has it, then an error is raised.
 
2809
        """
 
2810
        error_tuple = ('ReadError',)
 
2811
        server_error = errors.ErrorFromSmartServer(error_tuple)
 
2812
        translated_error = self.translateErrorFromSmartServer(server_error)
 
2813
        self.assertEqual(server_error, translated_error)
 
2814
        # In addition to re-raising ErrorFromSmartServer, some debug info has
 
2815
        # been muttered to the log file for developer to look at.
 
2816
        self.assertContainsRe(
 
2817
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
 
2818
 
 
2819
 
 
2820
class TestStacking(tests.TestCaseWithTransport):
 
2821
    """Tests for operations on stacked remote repositories.
 
2822
 
 
2823
    The underlying format type must support stacking.
 
2824
    """
 
2825
 
 
2826
    def test_access_stacked_remote(self):
 
2827
        # based on <http://launchpad.net/bugs/261315>
 
2828
        # make a branch stacked on another repository containing an empty
 
2829
        # revision, then open it over hpss - we should be able to see that
 
2830
        # revision.
 
2831
        base_transport = self.get_transport()
 
2832
        base_builder = self.make_branch_builder('base', format='1.9')
 
2833
        base_builder.start_series()
 
2834
        base_revid = base_builder.build_snapshot('rev-id', None,
 
2835
            [('add', ('', None, 'directory', None))],
 
2836
            'message')
 
2837
        base_builder.finish_series()
 
2838
        stacked_branch = self.make_branch('stacked', format='1.9')
 
2839
        stacked_branch.set_stacked_on_url('../base')
 
2840
        # start a server looking at this
 
2841
        smart_server = server.SmartTCPServer_for_testing()
 
2842
        smart_server.setUp()
 
2843
        self.addCleanup(smart_server.tearDown)
 
2844
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
 
2845
        # can get its branch and repository
 
2846
        remote_branch = remote_bzrdir.open_branch()
 
2847
        remote_repo = remote_branch.repository
 
2848
        remote_repo.lock_read()
 
2849
        try:
 
2850
            # it should have an appropriate fallback repository, which should also
 
2851
            # be a RemoteRepository
 
2852
            self.assertLength(1, remote_repo._fallback_repositories)
 
2853
            self.assertIsInstance(remote_repo._fallback_repositories[0],
 
2854
                RemoteRepository)
 
2855
            # and it has the revision committed to the underlying repository;
 
2856
            # these have varying implementations so we try several of them
 
2857
            self.assertTrue(remote_repo.has_revisions([base_revid]))
 
2858
            self.assertTrue(remote_repo.has_revision(base_revid))
 
2859
            self.assertEqual(remote_repo.get_revision(base_revid).message,
 
2860
                'message')
 
2861
        finally:
 
2862
            remote_repo.unlock()
 
2863
 
 
2864
    def prepare_stacked_remote_branch(self):
 
2865
        """Get stacked_upon and stacked branches with content in each."""
 
2866
        self.setup_smart_server_with_call_log()
 
2867
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
 
2868
        tree1.commit('rev1', rev_id='rev1')
 
2869
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
 
2870
            ).open_workingtree()
 
2871
        local_tree = tree2.branch.create_checkout('local')
 
2872
        local_tree.commit('local changes make me feel good.')
 
2873
        branch2 = Branch.open(self.get_url('tree2'))
 
2874
        branch2.lock_read()
 
2875
        self.addCleanup(branch2.unlock)
 
2876
        return tree1.branch, branch2
 
2877
 
 
2878
    def test_stacked_get_parent_map(self):
 
2879
        # the public implementation of get_parent_map obeys stacking
 
2880
        _, branch = self.prepare_stacked_remote_branch()
 
2881
        repo = branch.repository
 
2882
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
 
2883
 
 
2884
    def test_unstacked_get_parent_map(self):
 
2885
        # _unstacked_provider.get_parent_map ignores stacking
 
2886
        _, branch = self.prepare_stacked_remote_branch()
 
2887
        provider = branch.repository._unstacked_provider
 
2888
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
 
2889
 
 
2890
    def fetch_stream_to_rev_order(self, stream):
 
2891
        result = []
 
2892
        for kind, substream in stream:
 
2893
            if not kind == 'revisions':
 
2894
                list(substream)
 
2895
            else:
 
2896
                for content in substream:
 
2897
                    result.append(content.key[-1])
 
2898
        return result
 
2899
 
 
2900
    def get_ordered_revs(self, format, order, branch_factory=None):
 
2901
        """Get a list of the revisions in a stream to format format.
 
2902
 
 
2903
        :param format: The format of the target.
 
2904
        :param order: the order that target should have requested.
 
2905
        :param branch_factory: A callable to create a trunk and stacked branch
 
2906
            to fetch from. If none, self.prepare_stacked_remote_branch is used.
 
2907
        :result: The revision ids in the stream, in the order seen,
 
2908
            the topological order of revisions in the source.
 
2909
        """
 
2910
        unordered_format = bzrdir.format_registry.get(format)()
 
2911
        target_repository_format = unordered_format.repository_format
 
2912
        # Cross check
 
2913
        self.assertEqual(order, target_repository_format._fetch_order)
 
2914
        if branch_factory is None:
 
2915
            branch_factory = self.prepare_stacked_remote_branch
 
2916
        _, stacked = branch_factory()
 
2917
        source = stacked.repository._get_source(target_repository_format)
 
2918
        tip = stacked.last_revision()
 
2919
        revs = stacked.repository.get_ancestry(tip)
 
2920
        search = graph.PendingAncestryResult([tip], stacked.repository)
 
2921
        self.reset_smart_call_log()
 
2922
        stream = source.get_stream(search)
 
2923
        if None in revs:
 
2924
            revs.remove(None)
 
2925
        # We trust that if a revision is in the stream the rest of the new
 
2926
        # content for it is too, as per our main fetch tests; here we are
 
2927
        # checking that the revisions are actually included at all, and their
 
2928
        # order.
 
2929
        return self.fetch_stream_to_rev_order(stream), revs
 
2930
 
 
2931
    def test_stacked_get_stream_unordered(self):
 
2932
        # Repository._get_source.get_stream() from a stacked repository with
 
2933
        # unordered yields the full data from both stacked and stacked upon
 
2934
        # sources.
 
2935
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered')
 
2936
        self.assertEqual(set(expected_revs), set(rev_ord))
 
2937
        # Getting unordered results should have made a streaming data request
 
2938
        # from the server, then one from the backing branch.
 
2939
        self.assertLength(2, self.hpss_calls)
 
2940
 
 
2941
    def test_stacked_on_stacked_get_stream_unordered(self):
 
2942
        # Repository._get_source.get_stream() from a stacked repository which
 
2943
        # is itself stacked yields the full data from all three sources.
 
2944
        def make_stacked_stacked():
 
2945
            _, stacked = self.prepare_stacked_remote_branch()
 
2946
            tree = stacked.bzrdir.sprout('tree3', stacked=True
 
2947
                ).open_workingtree()
 
2948
            local_tree = tree.branch.create_checkout('local-tree3')
 
2949
            local_tree.commit('more local changes are better')
 
2950
            branch = Branch.open(self.get_url('tree3'))
 
2951
            branch.lock_read()
 
2952
            return None, branch
 
2953
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
 
2954
            branch_factory=make_stacked_stacked)
 
2955
        self.assertEqual(set(expected_revs), set(rev_ord))
 
2956
        # Getting unordered results should have made a streaming data request
 
2957
        # from the server, and one from each backing repo
 
2958
        self.assertLength(3, self.hpss_calls)
 
2959
 
 
2960
    def test_stacked_get_stream_topological(self):
 
2961
        # Repository._get_source.get_stream() from a stacked repository with
 
2962
        # topological sorting yields the full data from both stacked and
 
2963
        # stacked upon sources in topological order.
 
2964
        rev_ord, expected_revs = self.get_ordered_revs('knit', 'topological')
 
2965
        self.assertEqual(expected_revs, rev_ord)
 
2966
        # Getting topological sort requires VFS calls still - one of which is
 
2967
        # pushing up from the bound branch.
 
2968
        self.assertLength(13, self.hpss_calls)
 
2969
 
 
2970
    def test_stacked_get_stream_groupcompress(self):
 
2971
        # Repository._get_source.get_stream() from a stacked repository with
 
2972
        # groupcompress sorting yields the full data from both stacked and
 
2973
        # stacked upon sources in groupcompress order.
 
2974
        raise tests.TestSkipped('No groupcompress ordered format available')
 
2975
        rev_ord, expected_revs = self.get_ordered_revs('dev5', 'groupcompress')
 
2976
        self.assertEqual(expected_revs, reversed(rev_ord))
 
2977
        # Getting unordered results should have made a streaming data request
 
2978
        # from the backing branch, and one from the stacked on branch.
 
2979
        self.assertLength(2, self.hpss_calls)
 
2980
 
 
2981
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
 
2982
        # When pulling some fixed amount of content that is more than the
 
2983
        # source has (because some is coming from a fallback branch, no error
 
2984
        # should be received. This was reported as bug 360791.
 
2985
        # Need three branches: a trunk, a stacked branch, and a preexisting
 
2986
        # branch pulling content from stacked and trunk.
 
2987
        self.setup_smart_server_with_call_log()
 
2988
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
 
2989
        r1 = trunk.commit('start')
 
2990
        stacked_branch = trunk.branch.create_clone_on_transport(
 
2991
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
 
2992
        local = self.make_branch('local', format='1.9-rich-root')
 
2993
        local.repository.fetch(stacked_branch.repository,
 
2994
            stacked_branch.last_revision())
 
2995
 
 
2996
 
 
2997
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
 
2998
 
 
2999
    def setUp(self):
 
3000
        super(TestRemoteBranchEffort, self).setUp()
 
3001
        # Create a smart server that publishes whatever the backing VFS server
 
3002
        # does.
 
3003
        self.smart_server = server.SmartTCPServer_for_testing()
 
3004
        self.smart_server.setUp(self.get_server())
 
3005
        self.addCleanup(self.smart_server.tearDown)
 
3006
        # Log all HPSS calls into self.hpss_calls.
 
3007
        _SmartClient.hooks.install_named_hook(
 
3008
            'call', self.capture_hpss_call, None)
 
3009
        self.hpss_calls = []
 
3010
 
 
3011
    def capture_hpss_call(self, params):
 
3012
        self.hpss_calls.append(params.method)
 
3013
 
 
3014
    def test_copy_content_into_avoids_revision_history(self):
 
3015
        local = self.make_branch('local')
 
3016
        remote_backing_tree = self.make_branch_and_tree('remote')
 
3017
        remote_backing_tree.commit("Commit.")
 
3018
        remote_branch_url = self.smart_server.get_url() + 'remote'
 
3019
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
 
3020
        local.repository.fetch(remote_branch.repository)
 
3021
        self.hpss_calls = []
 
3022
        remote_branch.copy_content_into(local)
 
3023
        self.assertFalse('Branch.revision_history' in self.hpss_calls)