/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: John Arbash Meinel
  • Date: 2008-10-14 21:35:27 UTC
  • mto: This revision was merged to the branch mainline in revision 3805.
  • Revision ID: john@arbash-meinel.com-20081014213527-4j9uc93aq1qmn43b
Add in a shortcut when we haven't cached much yet.

Document the current algorithm more completely, including the proper
justification for the various steps.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""Tests for remote bzrdir/branch/repo/etc
18
18
 
19
19
These are proxy objects which act on remote objects by sending messages
20
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.
 
21
the object given a transport that supports smartserver rpc operations. 
22
22
 
23
23
These tests correspond to tests.test_smart, which exercises the server side.
24
24
"""
27
27
from cStringIO import StringIO
28
28
 
29
29
from bzrlib import (
30
 
    branch,
31
 
    bzrdir,
32
 
    config,
33
30
    errors,
34
31
    graph,
35
 
    inventory,
36
 
    inventory_delta,
37
32
    pack,
38
33
    remote,
39
34
    repository,
40
35
    tests,
41
 
    treebuilder,
42
36
    urlutils,
43
 
    versionedfile,
44
37
    )
45
38
from bzrlib.branch import Branch
46
39
from bzrlib.bzrdir import BzrDir, BzrDirFormat
47
40
from bzrlib.remote import (
48
41
    RemoteBranch,
49
 
    RemoteBranchFormat,
50
42
    RemoteBzrDir,
51
43
    RemoteBzrDirFormat,
52
44
    RemoteRepository,
53
 
    RemoteRepositoryFormat,
54
45
    )
55
 
from bzrlib.repofmt import groupcompress_repo, pack_repo
56
46
from bzrlib.revision import NULL_REVISION
57
 
from bzrlib.smart import medium
 
47
from bzrlib.smart import server, medium
58
48
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
 
    test_server,
65
 
    )
66
 
from bzrlib.transport import get_transport
 
49
from bzrlib.symbol_versioning import one_four
 
50
from bzrlib.transport import get_transport, http
67
51
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': test_server.SmartTCPServer_for_testing_v2_only}),
80
 
        ('HPSS-v3',
81
 
         {'transport_server': test_server.SmartTCPServer_for_testing})]
82
 
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
 
52
from bzrlib.transport.remote import RemoteTransport, RemoteTCPTransport
83
53
 
84
54
 
85
55
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
86
56
 
87
57
    def setUp(self):
 
58
        self.transport_server = server.SmartTCPServer_for_testing
88
59
        super(BasicRemoteObjectTests, self).setUp()
89
60
        self.transport = self.get_transport()
90
61
        # make a branch that can be opened over the smart transport
95
66
        tests.TestCaseWithTransport.tearDown(self)
96
67
 
97
68
    def test_create_remote_bzrdir(self):
98
 
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
69
        b = remote.RemoteBzrDir(self.transport)
99
70
        self.assertIsInstance(b, BzrDir)
100
71
 
101
72
    def test_open_remote_branch(self):
102
73
        # open a standalone branch in the working directory
103
 
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
74
        b = remote.RemoteBzrDir(self.transport)
104
75
        branch = b.open_branch()
105
76
        self.assertIsInstance(branch, Branch)
106
77
 
135
106
        b = BzrDir.open_from_transport(self.transport).open_branch()
136
107
        self.assertStartsWith(str(b), 'RemoteBranch(')
137
108
 
138
 
    def test_remote_bzrdir_repr(self):
139
 
        b = BzrDir.open_from_transport(self.transport)
140
 
        self.assertStartsWith(str(b), 'RemoteBzrDir(')
141
 
 
142
 
    def test_remote_branch_format_supports_stacking(self):
143
 
        t = self.transport
144
 
        self.make_branch('unstackable', format='pack-0.92')
145
 
        b = BzrDir.open_from_transport(t.clone('unstackable')).open_branch()
146
 
        self.assertFalse(b._format.supports_stacking())
147
 
        self.make_branch('stackable', format='1.9')
148
 
        b = BzrDir.open_from_transport(t.clone('stackable')).open_branch()
149
 
        self.assertTrue(b._format.supports_stacking())
150
 
 
151
 
    def test_remote_repo_format_supports_external_references(self):
152
 
        t = self.transport
153
 
        bd = self.make_bzrdir('unstackable', format='pack-0.92')
154
 
        r = bd.create_repository()
155
 
        self.assertFalse(r._format.supports_external_lookups)
156
 
        r = BzrDir.open_from_transport(t.clone('unstackable')).open_repository()
157
 
        self.assertFalse(r._format.supports_external_lookups)
158
 
        bd = self.make_bzrdir('stackable', format='1.9')
159
 
        r = bd.create_repository()
160
 
        self.assertTrue(r._format.supports_external_lookups)
161
 
        r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
162
 
        self.assertTrue(r._format.supports_external_lookups)
163
 
 
164
 
    def test_remote_branch_set_append_revisions_only(self):
165
 
        # Make a format 1.9 branch, which supports append_revisions_only
166
 
        branch = self.make_branch('branch', format='1.9')
167
 
        config = branch.get_config()
168
 
        branch.set_append_revisions_only(True)
169
 
        self.assertEqual(
170
 
            'True', config.get_user_option('append_revisions_only'))
171
 
        branch.set_append_revisions_only(False)
172
 
        self.assertEqual(
173
 
            'False', config.get_user_option('append_revisions_only'))
174
 
 
175
 
    def test_remote_branch_set_append_revisions_only_upgrade_reqd(self):
176
 
        branch = self.make_branch('branch', format='knit')
177
 
        config = branch.get_config()
178
 
        self.assertRaises(
179
 
            errors.UpgradeRequired, branch.set_append_revisions_only, True)
 
109
 
 
110
class FakeRemoteTransport(object):
 
111
    """This class provides the minimum support for use in place of a RemoteTransport.
 
112
    
 
113
    It doesn't actually transmit requests, but rather expects them to be
 
114
    handled by a FakeClient which holds canned responses.  It does not allow
 
115
    any vfs access, therefore is not suitable for testing any operation that
 
116
    will fallback to vfs access.  Backing the test by an instance of this
 
117
    class guarantees that it's - done using non-vfs operations.
 
118
    """
 
119
 
 
120
    _default_url = 'fakeremotetransport://host/path/'
 
121
 
 
122
    def __init__(self, url=None):
 
123
        if url is None:
 
124
            url = self._default_url
 
125
        self.base = url
 
126
 
 
127
    def __repr__(self):
 
128
        return "%r(%r)" % (self.__class__.__name__,
 
129
            self.base)
 
130
 
 
131
    def clone(self, relpath):
 
132
        return FakeRemoteTransport(urlutils.join(self.base, relpath))
 
133
 
 
134
    def get(self, relpath):
 
135
        # only get is specifically stubbed out, because it's usually the first
 
136
        # thing we do.  anything else will fail with an AttributeError.
 
137
        raise AssertionError("%r doesn't support file access to %r"
 
138
            % (self, relpath))
 
139
 
180
140
 
181
141
 
182
142
class FakeProtocol(object):
204
164
 
205
165
class FakeClient(_SmartClient):
206
166
    """Lookalike for _SmartClient allowing testing."""
207
 
 
 
167
    
208
168
    def __init__(self, fake_medium_base='fake base'):
209
 
        """Create a FakeClient."""
 
169
        """Create a FakeClient.
 
170
 
 
171
        :param responses: A list of response-tuple, body-data pairs to be sent
 
172
            back to callers.  A special case is if the response-tuple is
 
173
            'unknown verb', then a UnknownSmartMethod will be raised for that
 
174
            call, using the second element of the tuple as the verb in the
 
175
            exception.
 
176
        """
210
177
        self.responses = []
211
178
        self._calls = []
212
179
        self.expecting_body = False
213
180
        # if non-None, this is the list of expected calls, with only the
214
181
        # method name and arguments included.  the body might be hard to
215
 
        # compute so is not included. If a call is None, that call can
216
 
        # be anything.
 
182
        # compute so is not included
217
183
        self._expected_calls = None
218
184
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
219
185
 
229
195
 
230
196
    def add_success_response_with_body(self, body, *args):
231
197
        self.responses.append(('success', args, body))
232
 
        if self._expected_calls is not None:
233
 
            self._expected_calls.append(None)
234
198
 
235
199
    def add_error_response(self, *args):
236
200
        self.responses.append(('error', args))
265
229
            raise AssertionError("%r didn't expect any more calls "
266
230
                "but got %r%r"
267
231
                % (self, method, args,))
268
 
        if next_call is None:
269
 
            return
270
232
        if method != next_call[0] or args != next_call[1]:
271
233
            raise AssertionError("%r expected %r%r "
272
234
                "but got %r%r"
284
246
        self.expecting_body = True
285
247
        return result[1], FakeProtocol(result[2], self)
286
248
 
287
 
    def call_with_body_bytes(self, method, args, body):
288
 
        self._check_call(method, args)
289
 
        self._calls.append(('call_with_body_bytes', method, args, body))
290
 
        result = self._get_next_response()
291
 
        return result[1], FakeProtocol(result[2], self)
292
 
 
293
249
    def call_with_body_bytes_expecting_body(self, method, args, body):
294
250
        self._check_call(method, args)
295
251
        self._calls.append(('call_with_body_bytes_expecting_body', method,
298
254
        self.expecting_body = True
299
255
        return result[1], FakeProtocol(result[2], self)
300
256
 
301
 
    def call_with_body_stream(self, args, stream):
302
 
        # Explicitly consume the stream before checking for an error, because
303
 
        # that's what happens a real medium.
304
 
        stream = list(stream)
305
 
        self._check_call(args[0], args[1:])
306
 
        self._calls.append(('call_with_body_stream', args[0], args[1:], stream))
307
 
        result = self._get_next_response()
308
 
        # The second value returned from call_with_body_stream is supposed to
309
 
        # be a response_handler object, but so far no tests depend on that.
310
 
        response_handler = None 
311
 
        return result[1], response_handler
312
 
 
313
257
 
314
258
class FakeMedium(medium.SmartClientMedium):
315
259
 
335
279
        self.assertTrue(result)
336
280
 
337
281
 
338
 
class TestRemote(tests.TestCaseWithMemoryTransport):
339
 
 
340
 
    def get_branch_format(self):
341
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
342
 
        return reference_bzrdir_format.get_branch_format()
343
 
 
344
 
    def get_repo_format(self):
345
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
346
 
        return reference_bzrdir_format.repository_format
347
 
 
348
 
    def assertFinished(self, fake_client):
349
 
        """Assert that all of a FakeClient's expected calls have occurred."""
350
 
        fake_client.finished_test()
351
 
 
352
 
 
353
282
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
354
283
    """Tests for the behaviour of client_medium.remote_path_from_transport."""
355
284
 
382
311
        cloned_transport = base_transport.clone(relpath)
383
312
        result = client_medium.remote_path_from_transport(cloned_transport)
384
313
        self.assertEqual(expected, result)
385
 
 
 
314
        
386
315
    def test_remote_path_from_transport_http(self):
387
316
        """Remote paths for HTTP transports are calculated differently to other
388
317
        transports.  They are just relative to the client base, not the root
404
333
        """
405
334
        client_medium = medium.SmartClientMedium('dummy base')
406
335
        self.assertFalse(client_medium._is_remote_before((99, 99)))
407
 
 
 
336
    
408
337
    def test__remember_remote_is_before(self):
409
338
        """Calling _remember_remote_is_before ratchets down the known remote
410
339
        version.
418
347
        # Calling _remember_remote_is_before again with a lower value works.
419
348
        client_medium._remember_remote_is_before((1, 5))
420
349
        self.assertTrue(client_medium._is_remote_before((1, 5)))
421
 
        # If you call _remember_remote_is_before with a higher value it logs a
422
 
        # warning, and continues to remember the lower value.
423
 
        self.assertNotContainsRe(self.get_log(), '_remember_remote_is_before')
424
 
        client_medium._remember_remote_is_before((1, 9))
425
 
        self.assertContainsRe(self.get_log(), '_remember_remote_is_before')
426
 
        self.assertTrue(client_medium._is_remote_before((1, 5)))
427
 
 
428
 
 
429
 
class TestBzrDirCloningMetaDir(TestRemote):
430
 
 
431
 
    def test_backwards_compat(self):
432
 
        self.setup_smart_server_with_call_log()
433
 
        a_dir = self.make_bzrdir('.')
434
 
        self.reset_smart_call_log()
435
 
        verb = 'BzrDir.cloning_metadir'
436
 
        self.disable_verb(verb)
437
 
        format = a_dir.cloning_metadir()
438
 
        call_count = len([call for call in self.hpss_calls if
439
 
            call.call.method == verb])
440
 
        self.assertEqual(1, call_count)
441
 
 
442
 
    def test_branch_reference(self):
443
 
        transport = self.get_transport('quack')
444
 
        referenced = self.make_branch('referenced')
445
 
        expected = referenced.bzrdir.cloning_metadir()
446
 
        client = FakeClient(transport.base)
447
 
        client.add_expected_call(
448
 
            'BzrDir.cloning_metadir', ('quack/', 'False'),
449
 
            'error', ('BranchReference',)),
450
 
        client.add_expected_call(
451
 
            'BzrDir.open_branchV3', ('quack/',),
452
 
            'success', ('ref', self.get_url('referenced'))),
453
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
454
 
            _client=client)
455
 
        result = a_bzrdir.cloning_metadir()
456
 
        # We should have got a control dir matching the referenced branch.
457
 
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
458
 
        self.assertEqual(expected._repository_format, result._repository_format)
459
 
        self.assertEqual(expected._branch_format, result._branch_format)
460
 
        self.assertFinished(client)
461
 
 
462
 
    def test_current_server(self):
463
 
        transport = self.get_transport('.')
464
 
        transport = transport.clone('quack')
465
 
        self.make_bzrdir('quack')
466
 
        client = FakeClient(transport.base)
467
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
468
 
        control_name = reference_bzrdir_format.network_name()
469
 
        client.add_expected_call(
470
 
            'BzrDir.cloning_metadir', ('quack/', 'False'),
471
 
            'success', (control_name, '', ('branch', ''))),
472
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
473
 
            _client=client)
474
 
        result = a_bzrdir.cloning_metadir()
475
 
        # We should have got a reference control dir with default branch and
476
 
        # repository formats.
477
 
        # This pokes a little, just to be sure.
478
 
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
479
 
        self.assertEqual(None, result._repository_format)
480
 
        self.assertEqual(None, result._branch_format)
481
 
        self.assertFinished(client)
482
 
 
483
 
 
484
 
class TestBzrDirOpen(TestRemote):
485
 
 
486
 
    def make_fake_client_and_transport(self, path='quack'):
487
 
        transport = MemoryTransport()
488
 
        transport.mkdir(path)
489
 
        transport = transport.clone(path)
490
 
        client = FakeClient(transport.base)
491
 
        return client, transport
492
 
 
493
 
    def test_absent(self):
494
 
        client, transport = self.make_fake_client_and_transport()
495
 
        client.add_expected_call(
496
 
            'BzrDir.open_2.1', ('quack/',), 'success', ('no',))
497
 
        self.assertRaises(errors.NotBranchError, RemoteBzrDir, transport,
498
 
                remote.RemoteBzrDirFormat(), _client=client, _force_probe=True)
499
 
        self.assertFinished(client)
500
 
 
501
 
    def test_present_without_workingtree(self):
502
 
        client, transport = self.make_fake_client_and_transport()
503
 
        client.add_expected_call(
504
 
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'no'))
505
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
506
 
            _client=client, _force_probe=True)
507
 
        self.assertIsInstance(bd, RemoteBzrDir)
508
 
        self.assertFalse(bd.has_workingtree())
509
 
        self.assertRaises(errors.NoWorkingTree, bd.open_workingtree)
510
 
        self.assertFinished(client)
511
 
 
512
 
    def test_present_with_workingtree(self):
513
 
        client, transport = self.make_fake_client_and_transport()
514
 
        client.add_expected_call(
515
 
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'yes'))
516
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
517
 
            _client=client, _force_probe=True)
518
 
        self.assertIsInstance(bd, RemoteBzrDir)
519
 
        self.assertTrue(bd.has_workingtree())
520
 
        self.assertRaises(errors.NotLocalUrl, bd.open_workingtree)
521
 
        self.assertFinished(client)
522
 
 
523
 
    def test_backwards_compat(self):
524
 
        client, transport = self.make_fake_client_and_transport()
525
 
        client.add_expected_call(
526
 
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
527
 
        client.add_expected_call(
528
 
            'BzrDir.open', ('quack/',), 'success', ('yes',))
529
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
530
 
            _client=client, _force_probe=True)
531
 
        self.assertIsInstance(bd, RemoteBzrDir)
532
 
        self.assertFinished(client)
533
 
 
534
 
    def test_backwards_compat_hpss_v2(self):
535
 
        client, transport = self.make_fake_client_and_transport()
536
 
        # Monkey-patch fake client to simulate real-world behaviour with v2
537
 
        # server: upon first RPC call detect the protocol version, and because
538
 
        # the version is 2 also do _remember_remote_is_before((1, 6)) before
539
 
        # continuing with the RPC.
540
 
        orig_check_call = client._check_call
541
 
        def check_call(method, args):
542
 
            client._medium._protocol_version = 2
543
 
            client._medium._remember_remote_is_before((1, 6))
544
 
            client._check_call = orig_check_call
545
 
            client._check_call(method, args)
546
 
        client._check_call = check_call
547
 
        client.add_expected_call(
548
 
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
549
 
        client.add_expected_call(
550
 
            'BzrDir.open', ('quack/',), 'success', ('yes',))
551
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
552
 
            _client=client, _force_probe=True)
553
 
        self.assertIsInstance(bd, RemoteBzrDir)
554
 
        self.assertFinished(client)
555
 
 
556
 
 
557
 
class TestBzrDirOpenBranch(TestRemote):
558
 
 
559
 
    def test_backwards_compat(self):
560
 
        self.setup_smart_server_with_call_log()
561
 
        self.make_branch('.')
562
 
        a_dir = BzrDir.open(self.get_url('.'))
563
 
        self.reset_smart_call_log()
564
 
        verb = 'BzrDir.open_branchV3'
565
 
        self.disable_verb(verb)
566
 
        format = a_dir.open_branch()
567
 
        call_count = len([call for call in self.hpss_calls if
568
 
            call.call.method == verb])
569
 
        self.assertEqual(1, call_count)
 
350
        # You cannot call _remember_remote_is_before with a larger value.
 
351
        self.assertRaises(
 
352
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
 
353
 
 
354
 
 
355
class TestBzrDirOpenBranch(tests.TestCase):
570
356
 
571
357
    def test_branch_present(self):
572
 
        reference_format = self.get_repo_format()
573
 
        network_name = reference_format.network_name()
574
 
        branch_network_name = self.get_branch_format().network_name()
575
358
        transport = MemoryTransport()
576
359
        transport.mkdir('quack')
577
360
        transport = transport.clone('quack')
578
361
        client = FakeClient(transport.base)
579
362
        client.add_expected_call(
580
 
            'BzrDir.open_branchV3', ('quack/',),
581
 
            'success', ('branch', branch_network_name))
 
363
            'BzrDir.open_branch', ('quack/',),
 
364
            'success', ('ok', ''))
582
365
        client.add_expected_call(
583
 
            'BzrDir.find_repositoryV3', ('quack/',),
584
 
            'success', ('ok', '', 'no', 'no', 'no', network_name))
 
366
            'BzrDir.find_repositoryV2', ('quack/',),
 
367
            'success', ('ok', '', 'no', 'no', 'no'))
585
368
        client.add_expected_call(
586
369
            'Branch.get_stacked_on_url', ('quack/',),
587
370
            'error', ('NotStacked',))
588
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
589
 
            _client=client)
 
371
        bzrdir = RemoteBzrDir(transport, _client=client)
590
372
        result = bzrdir.open_branch()
591
373
        self.assertIsInstance(result, RemoteBranch)
592
374
        self.assertEqual(bzrdir, result.bzrdir)
593
 
        self.assertFinished(client)
 
375
        client.finished_test()
594
376
 
595
377
    def test_branch_missing(self):
596
378
        transport = MemoryTransport()
598
380
        transport = transport.clone('quack')
599
381
        client = FakeClient(transport.base)
600
382
        client.add_error_response('nobranch')
601
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
602
 
            _client=client)
 
383
        bzrdir = RemoteBzrDir(transport, _client=client)
603
384
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
604
385
        self.assertEqual(
605
 
            [('call', 'BzrDir.open_branchV3', ('quack/',))],
 
386
            [('call', 'BzrDir.open_branch', ('quack/',))],
606
387
            client._calls)
607
388
 
608
389
    def test__get_tree_branch(self):
615
396
        transport = MemoryTransport()
616
397
        # no requests on the network - catches other api calls being made.
617
398
        client = FakeClient(transport.base)
618
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
619
 
            _client=client)
 
399
        bzrdir = RemoteBzrDir(transport, _client=client)
620
400
        # patch the open_branch call to record that it was called.
621
401
        bzrdir.open_branch = open_branch
622
402
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
628
408
        # transmitted as "~", not "%7E".
629
409
        transport = RemoteTCPTransport('bzr://localhost/~hello/')
630
410
        client = FakeClient(transport.base)
631
 
        reference_format = self.get_repo_format()
632
 
        network_name = reference_format.network_name()
633
 
        branch_network_name = self.get_branch_format().network_name()
634
 
        client.add_expected_call(
635
 
            'BzrDir.open_branchV3', ('~hello/',),
636
 
            'success', ('branch', branch_network_name))
637
 
        client.add_expected_call(
638
 
            'BzrDir.find_repositoryV3', ('~hello/',),
639
 
            'success', ('ok', '', 'no', 'no', 'no', network_name))
 
411
        client.add_expected_call(
 
412
            'BzrDir.open_branch', ('~hello/',),
 
413
            'success', ('ok', ''))
 
414
        client.add_expected_call(
 
415
            'BzrDir.find_repositoryV2', ('~hello/',),
 
416
            'success', ('ok', '', 'no', 'no', 'no'))
640
417
        client.add_expected_call(
641
418
            'Branch.get_stacked_on_url', ('~hello/',),
642
419
            'error', ('NotStacked',))
643
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
644
 
            _client=client)
 
420
        bzrdir = RemoteBzrDir(transport, _client=client)
645
421
        result = bzrdir.open_branch()
646
 
        self.assertFinished(client)
 
422
        client.finished_test()
647
423
 
648
424
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
649
 
        reference_format = self.get_repo_format()
650
 
        network_name = reference_format.network_name()
651
425
        transport = MemoryTransport()
652
426
        transport.mkdir('quack')
653
427
        transport = transport.clone('quack')
661
435
            subtree_response = 'no'
662
436
        client = FakeClient(transport.base)
663
437
        client.add_success_response(
664
 
            'ok', '', rich_response, subtree_response, external_lookup,
665
 
            network_name)
666
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
667
 
            _client=client)
 
438
            'ok', '', rich_response, subtree_response, external_lookup)
 
439
        bzrdir = RemoteBzrDir(transport, _client=client)
668
440
        result = bzrdir.open_repository()
669
441
        self.assertEqual(
670
 
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
 
442
            [('call', 'BzrDir.find_repositoryV2', ('quack/',))],
671
443
            client._calls)
672
444
        self.assertIsInstance(result, RemoteRepository)
673
445
        self.assertEqual(bzrdir, result.bzrdir)
689
461
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
690
462
 
691
463
 
692
 
class TestBzrDirCreateBranch(TestRemote):
693
 
 
694
 
    def test_backwards_compat(self):
695
 
        self.setup_smart_server_with_call_log()
696
 
        repo = self.make_repository('.')
697
 
        self.reset_smart_call_log()
698
 
        self.disable_verb('BzrDir.create_branch')
699
 
        branch = repo.bzrdir.create_branch()
700
 
        create_branch_call_count = len([call for call in self.hpss_calls if
701
 
            call.call.method == 'BzrDir.create_branch'])
702
 
        self.assertEqual(1, create_branch_call_count)
703
 
 
704
 
    def test_current_server(self):
705
 
        transport = self.get_transport('.')
706
 
        transport = transport.clone('quack')
707
 
        self.make_repository('quack')
708
 
        client = FakeClient(transport.base)
709
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
710
 
        reference_format = reference_bzrdir_format.get_branch_format()
711
 
        network_name = reference_format.network_name()
712
 
        reference_repo_fmt = reference_bzrdir_format.repository_format
713
 
        reference_repo_name = reference_repo_fmt.network_name()
714
 
        client.add_expected_call(
715
 
            'BzrDir.create_branch', ('quack/', network_name),
716
 
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
717
 
            reference_repo_name))
718
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
719
 
            _client=client)
720
 
        branch = a_bzrdir.create_branch()
721
 
        # We should have got a remote branch
722
 
        self.assertIsInstance(branch, remote.RemoteBranch)
723
 
        # its format should have the settings from the response
724
 
        format = branch._format
725
 
        self.assertEqual(network_name, format.network_name())
726
 
 
727
 
 
728
 
class TestBzrDirCreateRepository(TestRemote):
729
 
 
730
 
    def test_backwards_compat(self):
731
 
        self.setup_smart_server_with_call_log()
732
 
        bzrdir = self.make_bzrdir('.')
733
 
        self.reset_smart_call_log()
734
 
        self.disable_verb('BzrDir.create_repository')
735
 
        repo = bzrdir.create_repository()
736
 
        create_repo_call_count = len([call for call in self.hpss_calls if
737
 
            call.call.method == 'BzrDir.create_repository'])
738
 
        self.assertEqual(1, create_repo_call_count)
739
 
 
740
 
    def test_current_server(self):
741
 
        transport = self.get_transport('.')
742
 
        transport = transport.clone('quack')
743
 
        self.make_bzrdir('quack')
744
 
        client = FakeClient(transport.base)
745
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
746
 
        reference_format = reference_bzrdir_format.repository_format
747
 
        network_name = reference_format.network_name()
748
 
        client.add_expected_call(
749
 
            'BzrDir.create_repository', ('quack/',
750
 
                'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
751
 
                'False'),
752
 
            'success', ('ok', 'yes', 'yes', 'yes', network_name))
753
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
754
 
            _client=client)
755
 
        repo = a_bzrdir.create_repository()
756
 
        # We should have got a remote repository
757
 
        self.assertIsInstance(repo, remote.RemoteRepository)
758
 
        # its format should have the settings from the response
759
 
        format = repo._format
760
 
        self.assertTrue(format.rich_root_data)
761
 
        self.assertTrue(format.supports_tree_reference)
762
 
        self.assertTrue(format.supports_external_lookups)
763
 
        self.assertEqual(network_name, format.network_name())
764
 
 
765
 
 
766
 
class TestBzrDirOpenRepository(TestRemote):
767
 
 
768
 
    def test_backwards_compat_1_2_3(self):
769
 
        # fallback all the way to the first version.
770
 
        reference_format = self.get_repo_format()
771
 
        network_name = reference_format.network_name()
772
 
        server_url = 'bzr://example.com/'
773
 
        self.permit_url(server_url)
774
 
        client = FakeClient(server_url)
775
 
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
776
 
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
 
464
class TestBzrDirOpenRepository(tests.TestCase):
 
465
 
 
466
    def test_backwards_compat_1_2(self):
 
467
        transport = MemoryTransport()
 
468
        transport.mkdir('quack')
 
469
        transport = transport.clone('quack')
 
470
        client = FakeClient(transport.base)
 
471
        client.add_unknown_method_response('RemoteRepository.find_repositoryV2')
777
472
        client.add_success_response('ok', '', 'no', 'no')
778
 
        # A real repository instance will be created to determine the network
779
 
        # name.
780
 
        client.add_success_response_with_body(
781
 
            "Bazaar-NG meta directory, format 1\n", 'ok')
782
 
        client.add_success_response_with_body(
783
 
            reference_format.get_format_string(), 'ok')
784
 
        # PackRepository wants to do a stat
785
 
        client.add_success_response('stat', '0', '65535')
786
 
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
787
 
            _client=client)
788
 
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
789
 
            _client=client)
790
 
        repo = bzrdir.open_repository()
791
 
        self.assertEqual(
792
 
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
793
 
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
794
 
             ('call', 'BzrDir.find_repository', ('quack/',)),
795
 
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
796
 
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
797
 
             ('call', 'stat', ('/quack/.bzr/repository',)),
798
 
             ],
799
 
            client._calls)
800
 
        self.assertEqual(network_name, repo._format.network_name())
801
 
 
802
 
    def test_backwards_compat_2(self):
803
 
        # fallback to find_repositoryV2
804
 
        reference_format = self.get_repo_format()
805
 
        network_name = reference_format.network_name()
806
 
        server_url = 'bzr://example.com/'
807
 
        self.permit_url(server_url)
808
 
        client = FakeClient(server_url)
809
 
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
810
 
        client.add_success_response('ok', '', 'no', 'no', 'no')
811
 
        # A real repository instance will be created to determine the network
812
 
        # name.
813
 
        client.add_success_response_with_body(
814
 
            "Bazaar-NG meta directory, format 1\n", 'ok')
815
 
        client.add_success_response_with_body(
816
 
            reference_format.get_format_string(), 'ok')
817
 
        # PackRepository wants to do a stat
818
 
        client.add_success_response('stat', '0', '65535')
819
 
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
820
 
            _client=client)
821
 
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
822
 
            _client=client)
823
 
        repo = bzrdir.open_repository()
824
 
        self.assertEqual(
825
 
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
826
 
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
827
 
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
828
 
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
829
 
             ('call', 'stat', ('/quack/.bzr/repository',)),
830
 
             ],
831
 
            client._calls)
832
 
        self.assertEqual(network_name, repo._format.network_name())
833
 
 
834
 
    def test_current_server(self):
835
 
        reference_format = self.get_repo_format()
836
 
        network_name = reference_format.network_name()
837
 
        transport = MemoryTransport()
838
 
        transport.mkdir('quack')
839
 
        transport = transport.clone('quack')
840
 
        client = FakeClient(transport.base)
841
 
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
842
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
843
 
            _client=client)
844
 
        repo = bzrdir.open_repository()
845
 
        self.assertEqual(
846
 
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
847
 
            client._calls)
848
 
        self.assertEqual(network_name, repo._format.network_name())
849
 
 
850
 
 
851
 
class TestBzrDirFormatInitializeEx(TestRemote):
852
 
 
853
 
    def test_success(self):
854
 
        """Simple test for typical successful call."""
855
 
        fmt = bzrdir.RemoteBzrDirFormat()
856
 
        default_format_name = BzrDirFormat.get_default_format().network_name()
857
 
        transport = self.get_transport()
858
 
        client = FakeClient(transport.base)
859
 
        client.add_expected_call(
860
 
            'BzrDirFormat.initialize_ex_1.16',
861
 
                (default_format_name, 'path', 'False', 'False', 'False', '',
862
 
                 '', '', '', 'False'),
863
 
            'success',
864
 
                ('.', 'no', 'no', 'yes', 'repo fmt', 'repo bzrdir fmt',
865
 
                 'bzrdir fmt', 'False', '', '', 'repo lock token'))
866
 
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
867
 
        # it's currently hard to test that without supplying a real remote
868
 
        # transport connected to a real server.
869
 
        result = fmt._initialize_on_transport_ex_rpc(client, 'path',
870
 
            transport, False, False, False, None, None, None, None, False)
871
 
        self.assertFinished(client)
872
 
 
873
 
    def test_error(self):
874
 
        """Error responses are translated, e.g. 'PermissionDenied' raises the
875
 
        corresponding error from the client.
876
 
        """
877
 
        fmt = bzrdir.RemoteBzrDirFormat()
878
 
        default_format_name = BzrDirFormat.get_default_format().network_name()
879
 
        transport = self.get_transport()
880
 
        client = FakeClient(transport.base)
881
 
        client.add_expected_call(
882
 
            'BzrDirFormat.initialize_ex_1.16',
883
 
                (default_format_name, 'path', 'False', 'False', 'False', '',
884
 
                 '', '', '', 'False'),
885
 
            'error',
886
 
                ('PermissionDenied', 'path', 'extra info'))
887
 
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
888
 
        # it's currently hard to test that without supplying a real remote
889
 
        # transport connected to a real server.
890
 
        err = self.assertRaises(errors.PermissionDenied,
891
 
            fmt._initialize_on_transport_ex_rpc, client, 'path', transport,
892
 
            False, False, False, None, None, None, None, False)
893
 
        self.assertEqual('path', err.path)
894
 
        self.assertEqual(': extra info', err.extra)
895
 
        self.assertFinished(client)
896
 
 
897
 
    def test_error_from_real_server(self):
898
 
        """Integration test for error translation."""
899
 
        transport = self.make_smart_server('foo')
900
 
        transport = transport.clone('no-such-path')
901
 
        fmt = bzrdir.RemoteBzrDirFormat()
902
 
        err = self.assertRaises(errors.NoSuchFile,
903
 
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
 
473
        bzrdir = RemoteBzrDir(transport, _client=client)
 
474
        repo = bzrdir.open_repository()
 
475
        self.assertEqual(
 
476
            [('call', 'BzrDir.find_repositoryV2', ('quack/',)),
 
477
             ('call', 'BzrDir.find_repository', ('quack/',))],
 
478
            client._calls)
904
479
 
905
480
 
906
481
class OldSmartClient(object):
931
506
        return OldSmartClient()
932
507
 
933
508
 
934
 
class RemoteBzrDirTestCase(TestRemote):
935
 
 
936
 
    def make_remote_bzrdir(self, transport, client):
937
 
        """Make a RemotebzrDir using 'client' as the _client."""
938
 
        return RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
939
 
            _client=client)
940
 
 
941
 
 
942
 
class RemoteBranchTestCase(RemoteBzrDirTestCase):
943
 
 
944
 
    def lock_remote_branch(self, branch):
945
 
        """Trick a RemoteBranch into thinking it is locked."""
946
 
        branch._lock_mode = 'w'
947
 
        branch._lock_count = 2
948
 
        branch._lock_token = 'branch token'
949
 
        branch._repo_lock_token = 'repo token'
950
 
        branch.repository._lock_mode = 'w'
951
 
        branch.repository._lock_count = 2
952
 
        branch.repository._lock_token = 'repo token'
 
509
class RemoteBranchTestCase(tests.TestCase):
953
510
 
954
511
    def make_remote_branch(self, transport, client):
955
512
        """Make a RemoteBranch using 'client' as its _SmartClient.
956
 
 
 
513
        
957
514
        A RemoteBzrDir and RemoteRepository will also be created to fill out
958
515
        the RemoteBranch, albeit with stub values for some of their attributes.
959
516
        """
960
517
        # we do not want bzrdir to make any remote calls, so use False as its
961
518
        # _client.  If it tries to make a remote call, this will fail
962
519
        # immediately.
963
 
        bzrdir = self.make_remote_bzrdir(transport, False)
 
520
        bzrdir = RemoteBzrDir(transport, _client=False)
964
521
        repo = RemoteRepository(bzrdir, None, _client=client)
965
 
        branch_format = self.get_branch_format()
966
 
        format = RemoteBranchFormat(network_name=branch_format.network_name())
967
 
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
968
 
 
969
 
 
970
 
class TestBranchGetParent(RemoteBranchTestCase):
971
 
 
972
 
    def test_no_parent(self):
973
 
        # in an empty branch we decode the response properly
974
 
        transport = MemoryTransport()
975
 
        client = FakeClient(transport.base)
976
 
        client.add_expected_call(
977
 
            'Branch.get_stacked_on_url', ('quack/',),
978
 
            'error', ('NotStacked',))
979
 
        client.add_expected_call(
980
 
            'Branch.get_parent', ('quack/',),
981
 
            'success', ('',))
982
 
        transport.mkdir('quack')
983
 
        transport = transport.clone('quack')
984
 
        branch = self.make_remote_branch(transport, client)
985
 
        result = branch.get_parent()
986
 
        self.assertFinished(client)
987
 
        self.assertEqual(None, result)
988
 
 
989
 
    def test_parent_relative(self):
990
 
        transport = MemoryTransport()
991
 
        client = FakeClient(transport.base)
992
 
        client.add_expected_call(
993
 
            'Branch.get_stacked_on_url', ('kwaak/',),
994
 
            'error', ('NotStacked',))
995
 
        client.add_expected_call(
996
 
            'Branch.get_parent', ('kwaak/',),
997
 
            'success', ('../foo/',))
998
 
        transport.mkdir('kwaak')
999
 
        transport = transport.clone('kwaak')
1000
 
        branch = self.make_remote_branch(transport, client)
1001
 
        result = branch.get_parent()
1002
 
        self.assertEqual(transport.clone('../foo').base, result)
1003
 
 
1004
 
    def test_parent_absolute(self):
1005
 
        transport = MemoryTransport()
1006
 
        client = FakeClient(transport.base)
1007
 
        client.add_expected_call(
1008
 
            'Branch.get_stacked_on_url', ('kwaak/',),
1009
 
            'error', ('NotStacked',))
1010
 
        client.add_expected_call(
1011
 
            'Branch.get_parent', ('kwaak/',),
1012
 
            'success', ('http://foo/',))
1013
 
        transport.mkdir('kwaak')
1014
 
        transport = transport.clone('kwaak')
1015
 
        branch = self.make_remote_branch(transport, client)
1016
 
        result = branch.get_parent()
1017
 
        self.assertEqual('http://foo/', result)
1018
 
        self.assertFinished(client)
1019
 
 
1020
 
 
1021
 
class TestBranchSetParentLocation(RemoteBranchTestCase):
1022
 
 
1023
 
    def test_no_parent(self):
1024
 
        # We call the verb when setting parent to None
1025
 
        transport = MemoryTransport()
1026
 
        client = FakeClient(transport.base)
1027
 
        client.add_expected_call(
1028
 
            'Branch.get_stacked_on_url', ('quack/',),
1029
 
            'error', ('NotStacked',))
1030
 
        client.add_expected_call(
1031
 
            'Branch.set_parent_location', ('quack/', 'b', 'r', ''),
1032
 
            'success', ())
1033
 
        transport.mkdir('quack')
1034
 
        transport = transport.clone('quack')
1035
 
        branch = self.make_remote_branch(transport, client)
1036
 
        branch._lock_token = 'b'
1037
 
        branch._repo_lock_token = 'r'
1038
 
        branch._set_parent_location(None)
1039
 
        self.assertFinished(client)
1040
 
 
1041
 
    def test_parent(self):
1042
 
        transport = MemoryTransport()
1043
 
        client = FakeClient(transport.base)
1044
 
        client.add_expected_call(
1045
 
            'Branch.get_stacked_on_url', ('kwaak/',),
1046
 
            'error', ('NotStacked',))
1047
 
        client.add_expected_call(
1048
 
            'Branch.set_parent_location', ('kwaak/', 'b', 'r', 'foo'),
1049
 
            'success', ())
1050
 
        transport.mkdir('kwaak')
1051
 
        transport = transport.clone('kwaak')
1052
 
        branch = self.make_remote_branch(transport, client)
1053
 
        branch._lock_token = 'b'
1054
 
        branch._repo_lock_token = 'r'
1055
 
        branch._set_parent_location('foo')
1056
 
        self.assertFinished(client)
1057
 
 
1058
 
    def test_backwards_compat(self):
1059
 
        self.setup_smart_server_with_call_log()
1060
 
        branch = self.make_branch('.')
1061
 
        self.reset_smart_call_log()
1062
 
        verb = 'Branch.set_parent_location'
1063
 
        self.disable_verb(verb)
1064
 
        branch.set_parent('http://foo/')
1065
 
        self.assertLength(12, self.hpss_calls)
1066
 
 
1067
 
 
1068
 
class TestBranchGetTagsBytes(RemoteBranchTestCase):
1069
 
 
1070
 
    def test_backwards_compat(self):
1071
 
        self.setup_smart_server_with_call_log()
1072
 
        branch = self.make_branch('.')
1073
 
        self.reset_smart_call_log()
1074
 
        verb = 'Branch.get_tags_bytes'
1075
 
        self.disable_verb(verb)
1076
 
        branch.tags.get_tag_dict()
1077
 
        call_count = len([call for call in self.hpss_calls if
1078
 
            call.call.method == verb])
1079
 
        self.assertEqual(1, call_count)
1080
 
 
1081
 
    def test_trivial(self):
1082
 
        transport = MemoryTransport()
1083
 
        client = FakeClient(transport.base)
1084
 
        client.add_expected_call(
1085
 
            'Branch.get_stacked_on_url', ('quack/',),
1086
 
            'error', ('NotStacked',))
1087
 
        client.add_expected_call(
1088
 
            'Branch.get_tags_bytes', ('quack/',),
1089
 
            'success', ('',))
1090
 
        transport.mkdir('quack')
1091
 
        transport = transport.clone('quack')
1092
 
        branch = self.make_remote_branch(transport, client)
1093
 
        result = branch.tags.get_tag_dict()
1094
 
        self.assertFinished(client)
1095
 
        self.assertEqual({}, result)
1096
 
 
1097
 
 
1098
 
class TestBranchSetTagsBytes(RemoteBranchTestCase):
1099
 
 
1100
 
    def test_trivial(self):
1101
 
        transport = MemoryTransport()
1102
 
        client = FakeClient(transport.base)
1103
 
        client.add_expected_call(
1104
 
            'Branch.get_stacked_on_url', ('quack/',),
1105
 
            'error', ('NotStacked',))
1106
 
        client.add_expected_call(
1107
 
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1108
 
            'success', ('',))
1109
 
        transport.mkdir('quack')
1110
 
        transport = transport.clone('quack')
1111
 
        branch = self.make_remote_branch(transport, client)
1112
 
        self.lock_remote_branch(branch)
1113
 
        branch._set_tags_bytes('tags bytes')
1114
 
        self.assertFinished(client)
1115
 
        self.assertEqual('tags bytes', client._calls[-1][-1])
1116
 
 
1117
 
    def test_backwards_compatible(self):
1118
 
        transport = MemoryTransport()
1119
 
        client = FakeClient(transport.base)
1120
 
        client.add_expected_call(
1121
 
            'Branch.get_stacked_on_url', ('quack/',),
1122
 
            'error', ('NotStacked',))
1123
 
        client.add_expected_call(
1124
 
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1125
 
            'unknown', ('Branch.set_tags_bytes',))
1126
 
        transport.mkdir('quack')
1127
 
        transport = transport.clone('quack')
1128
 
        branch = self.make_remote_branch(transport, client)
1129
 
        self.lock_remote_branch(branch)
1130
 
        class StubRealBranch(object):
1131
 
            def __init__(self):
1132
 
                self.calls = []
1133
 
            def _set_tags_bytes(self, bytes):
1134
 
                self.calls.append(('set_tags_bytes', bytes))
1135
 
        real_branch = StubRealBranch()
1136
 
        branch._real_branch = real_branch
1137
 
        branch._set_tags_bytes('tags bytes')
1138
 
        # Call a second time, to exercise the 'remote version already inferred'
1139
 
        # code path.
1140
 
        branch._set_tags_bytes('tags bytes')
1141
 
        self.assertFinished(client)
1142
 
        self.assertEqual(
1143
 
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
 
522
        return RemoteBranch(bzrdir, repo, _client=client)
1144
523
 
1145
524
 
1146
525
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
1159
538
        transport = transport.clone('quack')
1160
539
        branch = self.make_remote_branch(transport, client)
1161
540
        result = branch.last_revision_info()
1162
 
        self.assertFinished(client)
 
541
        client.finished_test()
1163
542
        self.assertEqual((0, NULL_REVISION), result)
1164
543
 
1165
544
    def test_non_empty_branch(self):
1180
559
        self.assertEqual((2, revid), result)
1181
560
 
1182
561
 
1183
 
class TestBranch_get_stacked_on_url(TestRemote):
 
562
class TestBranch_get_stacked_on_url(tests.TestCaseWithMemoryTransport):
1184
563
    """Test Branch._get_stacked_on_url rpc"""
1185
564
 
1186
565
    def test_get_stacked_on_invalid_url(self):
1187
 
        # test that asking for a stacked on url the server can't access works.
1188
 
        # This isn't perfect, but then as we're in the same process there
1189
 
        # really isn't anything we can do to be 100% sure that the server
1190
 
        # doesn't just open in - this test probably needs to be rewritten using
1191
 
        # a spawn()ed server.
1192
 
        stacked_branch = self.make_branch('stacked', format='1.9')
1193
 
        memory_branch = self.make_branch('base', format='1.9')
1194
 
        vfs_url = self.get_vfs_only_url('base')
1195
 
        stacked_branch.set_stacked_on_url(vfs_url)
1196
 
        transport = stacked_branch.bzrdir.root_transport
 
566
        raise tests.KnownFailure('opening a branch requires the server to open the fallback repository')
 
567
        transport = FakeRemoteTransport('fakeremotetransport:///')
1197
568
        client = FakeClient(transport.base)
1198
569
        client.add_expected_call(
1199
 
            'Branch.get_stacked_on_url', ('stacked/',),
1200
 
            'success', ('ok', vfs_url))
1201
 
        # XXX: Multiple calls are bad, this second call documents what is
1202
 
        # today.
1203
 
        client.add_expected_call(
1204
 
            'Branch.get_stacked_on_url', ('stacked/',),
1205
 
            'success', ('ok', vfs_url))
1206
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
1207
 
            _client=client)
1208
 
        repo_fmt = remote.RemoteRepositoryFormat()
1209
 
        repo_fmt._custom_format = stacked_branch.repository._format
1210
 
        branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, repo_fmt),
1211
 
            _client=client)
 
570
            'Branch.get_stacked_on_url', ('.',),
 
571
            'success', ('ok', 'file:///stacked/on'))
 
572
        bzrdir = RemoteBzrDir(transport, _client=client)
 
573
        branch = RemoteBranch(bzrdir, None, _client=client)
1212
574
        result = branch.get_stacked_on_url()
1213
 
        self.assertEqual(vfs_url, result)
 
575
        self.assertEqual(
 
576
            'file:///stacked/on', result)
1214
577
 
1215
578
    def test_backwards_compatible(self):
1216
579
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
1218
581
        stacked_branch = self.make_branch('stacked', format='1.6')
1219
582
        stacked_branch.set_stacked_on_url('../base')
1220
583
        client = FakeClient(self.get_url())
1221
 
        branch_network_name = self.get_branch_format().network_name()
1222
 
        client.add_expected_call(
1223
 
            'BzrDir.open_branchV3', ('stacked/',),
1224
 
            'success', ('branch', branch_network_name))
1225
 
        client.add_expected_call(
1226
 
            'BzrDir.find_repositoryV3', ('stacked/',),
1227
 
            'success', ('ok', '', 'no', 'no', 'yes',
1228
 
                stacked_branch.repository._format.network_name()))
 
584
        client.add_expected_call(
 
585
            'BzrDir.open_branch', ('stacked/',),
 
586
            'success', ('ok', ''))
 
587
        client.add_expected_call(
 
588
            'BzrDir.find_repositoryV2', ('stacked/',),
 
589
            'success', ('ok', '', 'no', 'no', 'no'))
1229
590
        # called twice, once from constructor and then again by us
1230
591
        client.add_expected_call(
1231
592
            'Branch.get_stacked_on_url', ('stacked/',),
1235
596
            'unknown', ('Branch.get_stacked_on_url',))
1236
597
        # this will also do vfs access, but that goes direct to the transport
1237
598
        # and isn't seen by the FakeClient.
1238
 
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1239
 
            remote.RemoteBzrDirFormat(), _client=client)
 
599
        bzrdir = RemoteBzrDir(self.get_transport('stacked'), _client=client)
1240
600
        branch = bzrdir.open_branch()
1241
601
        result = branch.get_stacked_on_url()
1242
602
        self.assertEqual('../base', result)
1243
 
        self.assertFinished(client)
 
603
        client.finished_test()
1244
604
        # it's in the fallback list both for the RemoteRepository and its vfs
1245
605
        # repository
1246
606
        self.assertEqual(1, len(branch.repository._fallback_repositories))
1248
608
            len(branch.repository._real_repository._fallback_repositories))
1249
609
 
1250
610
    def test_get_stacked_on_real_branch(self):
1251
 
        base_branch = self.make_branch('base')
1252
 
        stacked_branch = self.make_branch('stacked')
 
611
        base_branch = self.make_branch('base', format='1.6')
 
612
        stacked_branch = self.make_branch('stacked', format='1.6')
1253
613
        stacked_branch.set_stacked_on_url('../base')
1254
 
        reference_format = self.get_repo_format()
1255
 
        network_name = reference_format.network_name()
1256
614
        client = FakeClient(self.get_url())
1257
 
        branch_network_name = self.get_branch_format().network_name()
1258
 
        client.add_expected_call(
1259
 
            'BzrDir.open_branchV3', ('stacked/',),
1260
 
            'success', ('branch', branch_network_name))
1261
 
        client.add_expected_call(
1262
 
            'BzrDir.find_repositoryV3', ('stacked/',),
1263
 
            'success', ('ok', '', 'yes', 'no', 'yes', network_name))
 
615
        client.add_expected_call(
 
616
            'BzrDir.open_branch', ('stacked/',),
 
617
            'success', ('ok', ''))
 
618
        client.add_expected_call(
 
619
            'BzrDir.find_repositoryV2', ('stacked/',),
 
620
            'success', ('ok', '', 'no', 'no', 'no'))
1264
621
        # called twice, once from constructor and then again by us
1265
622
        client.add_expected_call(
1266
623
            'Branch.get_stacked_on_url', ('stacked/',),
1268
625
        client.add_expected_call(
1269
626
            'Branch.get_stacked_on_url', ('stacked/',),
1270
627
            'success', ('ok', '../base'))
1271
 
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1272
 
            remote.RemoteBzrDirFormat(), _client=client)
 
628
        bzrdir = RemoteBzrDir(self.get_transport('stacked'), _client=client)
1273
629
        branch = bzrdir.open_branch()
1274
630
        result = branch.get_stacked_on_url()
1275
631
        self.assertEqual('../base', result)
1276
 
        self.assertFinished(client)
1277
 
        # it's in the fallback list both for the RemoteRepository.
 
632
        client.finished_test()
 
633
        # it's in the fallback list both for the RemoteRepository and its vfs
 
634
        # repository
1278
635
        self.assertEqual(1, len(branch.repository._fallback_repositories))
1279
 
        # And we haven't had to construct a real repository.
1280
 
        self.assertEqual(None, branch.repository._real_repository)
 
636
        self.assertEqual(1,
 
637
            len(branch.repository._real_repository._fallback_repositories))
1281
638
 
1282
639
 
1283
640
class TestBranchSetLastRevision(RemoteBranchTestCase):
1297
654
            'Branch.lock_write', ('branch/', '', ''),
1298
655
            'success', ('ok', 'branch token', 'repo token'))
1299
656
        client.add_expected_call(
1300
 
            'Branch.last_revision_info',
1301
 
            ('branch/',),
1302
 
            'success', ('ok', '0', 'null:'))
1303
 
        client.add_expected_call(
1304
657
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
1305
658
            'success', ('ok',))
1306
659
        client.add_expected_call(
1314
667
        result = branch.set_revision_history([])
1315
668
        branch.unlock()
1316
669
        self.assertEqual(None, result)
1317
 
        self.assertFinished(client)
 
670
        client.finished_test()
1318
671
 
1319
672
    def test_set_nonempty(self):
1320
673
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
1331
684
            'Branch.lock_write', ('branch/', '', ''),
1332
685
            'success', ('ok', 'branch token', 'repo token'))
1333
686
        client.add_expected_call(
1334
 
            'Branch.last_revision_info',
1335
 
            ('branch/',),
1336
 
            'success', ('ok', '0', 'null:'))
1337
 
        lines = ['rev-id2']
1338
 
        encoded_body = bz2.compress('\n'.join(lines))
1339
 
        client.add_success_response_with_body(encoded_body, 'ok')
1340
 
        client.add_expected_call(
1341
687
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
1342
688
            'success', ('ok',))
1343
689
        client.add_expected_call(
1352
698
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
1353
699
        branch.unlock()
1354
700
        self.assertEqual(None, result)
1355
 
        self.assertFinished(client)
 
701
        client.finished_test()
1356
702
 
1357
703
    def test_no_such_revision(self):
1358
704
        transport = MemoryTransport()
1367
713
            'Branch.lock_write', ('branch/', '', ''),
1368
714
            'success', ('ok', 'branch token', 'repo token'))
1369
715
        client.add_expected_call(
1370
 
            'Branch.last_revision_info',
1371
 
            ('branch/',),
1372
 
            'success', ('ok', '0', 'null:'))
1373
 
        # get_graph calls to construct the revision history, for the set_rh
1374
 
        # hook
1375
 
        lines = ['rev-id']
1376
 
        encoded_body = bz2.compress('\n'.join(lines))
1377
 
        client.add_success_response_with_body(encoded_body, 'ok')
1378
 
        client.add_expected_call(
1379
716
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1380
717
            'error', ('NoSuchRevision', 'rev-id'))
1381
718
        client.add_expected_call(
1387
724
        self.assertRaises(
1388
725
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
1389
726
        branch.unlock()
1390
 
        self.assertFinished(client)
 
727
        client.finished_test()
1391
728
 
1392
729
    def test_tip_change_rejected(self):
1393
730
        """TipChangeRejected responses cause a TipChangeRejected exception to
1406
743
            'Branch.lock_write', ('branch/', '', ''),
1407
744
            'success', ('ok', 'branch token', 'repo token'))
1408
745
        client.add_expected_call(
1409
 
            'Branch.last_revision_info',
1410
 
            ('branch/',),
1411
 
            'success', ('ok', '0', 'null:'))
1412
 
        lines = ['rev-id']
1413
 
        encoded_body = bz2.compress('\n'.join(lines))
1414
 
        client.add_success_response_with_body(encoded_body, 'ok')
1415
 
        client.add_expected_call(
1416
746
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1417
747
            'error', ('TipChangeRejected', rejection_msg_utf8))
1418
748
        client.add_expected_call(
1421
751
        branch = self.make_remote_branch(transport, client)
1422
752
        branch._ensure_real = lambda: None
1423
753
        branch.lock_write()
 
754
        self.addCleanup(branch.unlock)
1424
755
        # The 'TipChangeRejected' error response triggered by calling
1425
756
        # set_revision_history causes a TipChangeRejected exception.
1426
757
        err = self.assertRaises(
1430
761
        self.assertIsInstance(err.msg, unicode)
1431
762
        self.assertEqual(rejection_msg_unicode, err.msg)
1432
763
        branch.unlock()
1433
 
        self.assertFinished(client)
 
764
        client.finished_test()
1434
765
 
1435
766
 
1436
767
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
1446
777
        client.add_error_response('NotStacked')
1447
778
        # lock_write
1448
779
        client.add_success_response('ok', 'branch token', 'repo token')
1449
 
        # query the current revision
1450
 
        client.add_success_response('ok', '0', 'null:')
1451
780
        # set_last_revision
1452
781
        client.add_success_response('ok')
1453
782
        # unlock
1459
788
        client._calls = []
1460
789
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1461
790
        self.assertEqual(
1462
 
            [('call', 'Branch.last_revision_info', ('branch/',)),
1463
 
             ('call', 'Branch.set_last_revision_info',
 
791
            [('call', 'Branch.set_last_revision_info',
1464
792
                ('branch/', 'branch token', 'repo token',
1465
793
                 '1234', 'a-revision-id'))],
1466
794
            client._calls)
1490
818
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1491
819
        branch.unlock()
1492
820
 
 
821
    def lock_remote_branch(self, branch):
 
822
        """Trick a RemoteBranch into thinking it is locked."""
 
823
        branch._lock_mode = 'w'
 
824
        branch._lock_count = 2
 
825
        branch._lock_token = 'branch token'
 
826
        branch._repo_lock_token = 'repo token'
 
827
        branch.repository._lock_mode = 'w'
 
828
        branch.repository._lock_count = 2
 
829
        branch.repository._lock_token = 'repo token'
 
830
 
1493
831
    def test_backwards_compatibility(self):
1494
832
        """If the server does not support the Branch.set_last_revision_info
1495
833
        verb (which is new in 1.4), then the client falls back to VFS methods.
1510
848
            'Branch.get_stacked_on_url', ('branch/',),
1511
849
            'error', ('NotStacked',))
1512
850
        client.add_expected_call(
1513
 
            'Branch.last_revision_info',
1514
 
            ('branch/',),
1515
 
            'success', ('ok', '0', 'null:'))
1516
 
        client.add_expected_call(
1517
851
            'Branch.set_last_revision_info',
1518
852
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
1519
853
            'unknown', 'Branch.set_last_revision_info')
1536
870
        self.assertEqual(
1537
871
            [('set_last_revision_info', 1234, 'a-revision-id')],
1538
872
            real_branch.calls)
1539
 
        self.assertFinished(client)
 
873
        client.finished_test()
1540
874
 
1541
875
    def test_unexpected_error(self):
1542
876
        # If the server sends an error the client doesn't understand, it gets
1597
931
        self.assertEqual('rejection message', err.msg)
1598
932
 
1599
933
 
1600
 
class TestBranchGetSetConfig(RemoteBranchTestCase):
 
934
class TestBranchControlGetBranchConf(tests.TestCaseWithMemoryTransport):
 
935
    """Getting the branch configuration should use an abstract method not vfs.
 
936
    """
1601
937
 
1602
938
    def test_get_branch_conf(self):
1603
 
        # in an empty branch we decode the response properly
1604
 
        client = FakeClient()
1605
 
        client.add_expected_call(
1606
 
            'Branch.get_stacked_on_url', ('memory:///',),
1607
 
            'error', ('NotStacked',),)
1608
 
        client.add_success_response_with_body('# config file body', 'ok')
1609
 
        transport = MemoryTransport()
1610
 
        branch = self.make_remote_branch(transport, client)
1611
 
        config = branch.get_config()
1612
 
        config.has_explicit_nickname()
1613
 
        self.assertEqual(
1614
 
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
1615
 
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
1616
 
            client._calls)
1617
 
 
1618
 
    def test_get_multi_line_branch_conf(self):
1619
 
        # Make sure that multiple-line branch.conf files are supported
1620
 
        #
1621
 
        # https://bugs.edge.launchpad.net/bzr/+bug/354075
1622
 
        client = FakeClient()
1623
 
        client.add_expected_call(
1624
 
            'Branch.get_stacked_on_url', ('memory:///',),
1625
 
            'error', ('NotStacked',),)
1626
 
        client.add_success_response_with_body('a = 1\nb = 2\nc = 3\n', 'ok')
1627
 
        transport = MemoryTransport()
1628
 
        branch = self.make_remote_branch(transport, client)
1629
 
        config = branch.get_config()
1630
 
        self.assertEqual(u'2', config.get_user_option('b'))
1631
 
 
1632
 
    def test_set_option(self):
1633
 
        client = FakeClient()
1634
 
        client.add_expected_call(
1635
 
            'Branch.get_stacked_on_url', ('memory:///',),
1636
 
            'error', ('NotStacked',),)
1637
 
        client.add_expected_call(
1638
 
            'Branch.lock_write', ('memory:///', '', ''),
1639
 
            'success', ('ok', 'branch token', 'repo token'))
1640
 
        client.add_expected_call(
1641
 
            'Branch.set_config_option', ('memory:///', 'branch token',
1642
 
            'repo token', 'foo', 'bar', ''),
1643
 
            'success', ())
1644
 
        client.add_expected_call(
1645
 
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1646
 
            'success', ('ok',))
1647
 
        transport = MemoryTransport()
1648
 
        branch = self.make_remote_branch(transport, client)
1649
 
        branch.lock_write()
1650
 
        config = branch._get_config()
1651
 
        config.set_option('foo', 'bar')
1652
 
        branch.unlock()
1653
 
        self.assertFinished(client)
1654
 
 
1655
 
    def test_backwards_compat_set_option(self):
1656
 
        self.setup_smart_server_with_call_log()
1657
 
        branch = self.make_branch('.')
1658
 
        verb = 'Branch.set_config_option'
1659
 
        self.disable_verb(verb)
1660
 
        branch.lock_write()
1661
 
        self.addCleanup(branch.unlock)
1662
 
        self.reset_smart_call_log()
1663
 
        branch._get_config().set_option('value', 'name')
1664
 
        self.assertLength(10, self.hpss_calls)
1665
 
        self.assertEqual('value', branch._get_config().get_option('name'))
 
939
        raise tests.KnownFailure('branch.conf is not retrieved by get_config_file')
 
940
        ## # We should see that branch.get_config() does a single rpc to get the
 
941
        ## # remote configuration file, abstracting away where that is stored on
 
942
        ## # the server.  However at the moment it always falls back to using the
 
943
        ## # vfs, and this would need some changes in config.py.
 
944
 
 
945
        ## # in an empty branch we decode the response properly
 
946
        ## client = FakeClient([(('ok', ), '# config file body')], self.get_url())
 
947
        ## # we need to make a real branch because the remote_branch.control_files
 
948
        ## # will trigger _ensure_real.
 
949
        ## branch = self.make_branch('quack')
 
950
        ## transport = branch.bzrdir.root_transport
 
951
        ## # we do not want bzrdir to make any remote calls
 
952
        ## bzrdir = RemoteBzrDir(transport, _client=False)
 
953
        ## branch = RemoteBranch(bzrdir, None, _client=client)
 
954
        ## config = branch.get_config()
 
955
        ## self.assertEqual(
 
956
        ##     [('call_expecting_body', 'Branch.get_config_file', ('quack/',))],
 
957
        ##     client._calls)
1666
958
 
1667
959
 
1668
960
class TestBranchLockWrite(RemoteBranchTestCase):
1680
972
        transport = transport.clone('quack')
1681
973
        branch = self.make_remote_branch(transport, client)
1682
974
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
1683
 
        self.assertFinished(client)
1684
 
 
1685
 
 
1686
 
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
1687
 
 
1688
 
    def test__get_config(self):
1689
 
        client = FakeClient()
1690
 
        client.add_success_response_with_body('default_stack_on = /\n', 'ok')
1691
 
        transport = MemoryTransport()
1692
 
        bzrdir = self.make_remote_bzrdir(transport, client)
1693
 
        config = bzrdir.get_config()
1694
 
        self.assertEqual('/', config.get_default_stack_on())
1695
 
        self.assertEqual(
1696
 
            [('call_expecting_body', 'BzrDir.get_config_file', ('memory:///',))],
1697
 
            client._calls)
1698
 
 
1699
 
    def test_set_option_uses_vfs(self):
1700
 
        self.setup_smart_server_with_call_log()
1701
 
        bzrdir = self.make_bzrdir('.')
1702
 
        self.reset_smart_call_log()
1703
 
        config = bzrdir.get_config()
1704
 
        config.set_default_stack_on('/')
1705
 
        self.assertLength(3, self.hpss_calls)
1706
 
 
1707
 
    def test_backwards_compat_get_option(self):
1708
 
        self.setup_smart_server_with_call_log()
1709
 
        bzrdir = self.make_bzrdir('.')
1710
 
        verb = 'BzrDir.get_config_file'
1711
 
        self.disable_verb(verb)
1712
 
        self.reset_smart_call_log()
1713
 
        self.assertEqual(None,
1714
 
            bzrdir._get_config().get_option('default_stack_on'))
1715
 
        self.assertLength(3, self.hpss_calls)
 
975
        client.finished_test()
1716
976
 
1717
977
 
1718
978
class TestTransportIsReadonly(tests.TestCase):
1739
999
 
1740
1000
    def test_error_from_old_server(self):
1741
1001
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
1742
 
 
 
1002
        
1743
1003
        Clients should treat it as a "no" response, because is_readonly is only
1744
1004
        advisory anyway (a transport could be read-write, but then the
1745
1005
        underlying filesystem could be readonly anyway).
1754
1014
            client._calls)
1755
1015
 
1756
1016
 
1757
 
class TestTransportMkdir(tests.TestCase):
1758
 
 
1759
 
    def test_permissiondenied(self):
1760
 
        client = FakeClient()
1761
 
        client.add_error_response('PermissionDenied', 'remote path', 'extra')
1762
 
        transport = RemoteTransport('bzr://example.com/', medium=False,
1763
 
                                    _client=client)
1764
 
        exc = self.assertRaises(
1765
 
            errors.PermissionDenied, transport.mkdir, 'client path')
1766
 
        expected_error = errors.PermissionDenied('/client path', 'extra')
1767
 
        self.assertEqual(expected_error, exc)
1768
 
 
1769
 
 
1770
 
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
1771
 
 
1772
 
    def test_defaults_to_none(self):
1773
 
        t = RemoteSSHTransport('bzr+ssh://example.com')
1774
 
        self.assertIs(None, t._get_credentials()[0])
1775
 
 
1776
 
    def test_uses_authentication_config(self):
1777
 
        conf = config.AuthenticationConfig()
1778
 
        conf._get_config().update(
1779
 
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
1780
 
            'example.com'}})
1781
 
        conf._save()
1782
 
        t = RemoteSSHTransport('bzr+ssh://example.com')
1783
 
        self.assertEqual('bar', t._get_credentials()[0])
1784
 
 
1785
 
 
1786
 
class TestRemoteRepository(TestRemote):
 
1017
class TestRemoteRepository(tests.TestCase):
1787
1018
    """Base for testing RemoteRepository protocol usage.
1788
 
 
1789
 
    These tests contain frozen requests and responses.  We want any changes to
 
1019
    
 
1020
    These tests contain frozen requests and responses.  We want any changes to 
1790
1021
    what is sent or expected to be require a thoughtful update to these tests
1791
1022
    because they might break compatibility with different-versioned servers.
1792
1023
    """
1793
1024
 
1794
1025
    def setup_fake_client_and_repository(self, transport_path):
1795
1026
        """Create the fake client and repository for testing with.
1796
 
 
 
1027
        
1797
1028
        There's no real server here; we just have canned responses sent
1798
1029
        back one by one.
1799
 
 
 
1030
        
1800
1031
        :param transport_path: Path below the root of the MemoryTransport
1801
1032
            where the repository will be created.
1802
1033
        """
1805
1036
        client = FakeClient(transport.base)
1806
1037
        transport = transport.clone(transport_path)
1807
1038
        # we do not want bzrdir to make any remote calls
1808
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
1809
 
            _client=False)
 
1039
        bzrdir = RemoteBzrDir(transport, _client=False)
1810
1040
        repo = RemoteRepository(bzrdir, None, _client=client)
1811
1041
        return repo, client
1812
1042
 
1813
1043
 
1814
 
def remoted_description(format):
1815
 
    return 'Remote: ' + format.get_format_description()
1816
 
 
1817
 
 
1818
 
class TestBranchFormat(tests.TestCase):
1819
 
 
1820
 
    def test_get_format_description(self):
1821
 
        remote_format = RemoteBranchFormat()
1822
 
        real_format = branch.BranchFormat.get_default_format()
1823
 
        remote_format._network_name = real_format.network_name()
1824
 
        self.assertEqual(remoted_description(real_format),
1825
 
            remote_format.get_format_description())
1826
 
 
1827
 
 
1828
 
class TestRepositoryFormat(TestRemoteRepository):
1829
 
 
1830
 
    def test_fast_delta(self):
1831
 
        true_name = groupcompress_repo.RepositoryFormatCHK1().network_name()
1832
 
        true_format = RemoteRepositoryFormat()
1833
 
        true_format._network_name = true_name
1834
 
        self.assertEqual(True, true_format.fast_deltas)
1835
 
        false_name = pack_repo.RepositoryFormatKnitPack1().network_name()
1836
 
        false_format = RemoteRepositoryFormat()
1837
 
        false_format._network_name = false_name
1838
 
        self.assertEqual(False, false_format.fast_deltas)
1839
 
 
1840
 
    def test_get_format_description(self):
1841
 
        remote_repo_format = RemoteRepositoryFormat()
1842
 
        real_format = repository.RepositoryFormat.get_default_format()
1843
 
        remote_repo_format._network_name = real_format.network_name()
1844
 
        self.assertEqual(remoted_description(real_format),
1845
 
            remote_repo_format.get_format_description())
1846
 
 
1847
 
 
1848
1044
class TestRepositoryGatherStats(TestRemoteRepository):
1849
1045
 
1850
1046
    def test_revid_none(self):
1906
1102
class TestRepositoryGetGraph(TestRemoteRepository):
1907
1103
 
1908
1104
    def test_get_graph(self):
1909
 
        # get_graph returns a graph with a custom parents provider.
 
1105
        # get_graph returns a graph with the repository as the
 
1106
        # parents_provider.
1910
1107
        transport_path = 'quack'
1911
1108
        repo, client = self.setup_fake_client_and_repository(transport_path)
1912
1109
        graph = repo.get_graph()
1913
 
        self.assertNotEqual(graph._parents_provider, repo)
 
1110
        self.assertEqual(graph._parents_provider, repo)
1914
1111
 
1915
1112
 
1916
1113
class TestRepositoryGetParentMap(TestRemoteRepository):
1938
1135
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
1939
1136
        self.assertEqual(
1940
1137
            [('call_with_body_bytes_expecting_body',
1941
 
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
1942
 
              '\n\n0')],
 
1138
              'Repository.get_parent_map', ('quack/', r2), '\n\n0')],
1943
1139
            client._calls)
1944
1140
        repo.unlock()
1945
1141
        # now we call again, and it should use the second response.
1949
1145
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
1950
1146
        self.assertEqual(
1951
1147
            [('call_with_body_bytes_expecting_body',
1952
 
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
1953
 
              '\n\n0'),
 
1148
              'Repository.get_parent_map', ('quack/', r2), '\n\n0'),
1954
1149
             ('call_with_body_bytes_expecting_body',
1955
 
              'Repository.get_parent_map', ('quack/', 'include-missing:', r1),
1956
 
              '\n\n0'),
 
1150
              'Repository.get_parent_map', ('quack/', r1), '\n\n0'),
1957
1151
            ],
1958
1152
            client._calls)
1959
1153
        repo.unlock()
1960
1154
 
1961
1155
    def test_get_parent_map_reconnects_if_unknown_method(self):
1962
1156
        transport_path = 'quack'
1963
 
        rev_id = 'revision-id'
1964
1157
        repo, client = self.setup_fake_client_and_repository(transport_path)
1965
 
        client.add_unknown_method_response('Repository.get_parent_map')
1966
 
        client.add_success_response_with_body(rev_id, 'ok')
 
1158
        client.add_unknown_method_response('Repository,get_parent_map')
 
1159
        client.add_success_response_with_body('', 'ok')
1967
1160
        self.assertFalse(client._medium._is_remote_before((1, 2)))
1968
 
        parents = repo.get_parent_map([rev_id])
 
1161
        rev_id = 'revision-id'
 
1162
        expected_deprecations = [
 
1163
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
 
1164
            'in version 1.4.']
 
1165
        parents = self.callDeprecated(
 
1166
            expected_deprecations, repo.get_parent_map, [rev_id])
1969
1167
        self.assertEqual(
1970
1168
            [('call_with_body_bytes_expecting_body',
1971
 
              'Repository.get_parent_map', ('quack/', 'include-missing:',
1972
 
              rev_id), '\n\n0'),
 
1169
              'Repository.get_parent_map', ('quack/', rev_id), '\n\n0'),
1973
1170
             ('disconnect medium',),
1974
1171
             ('call_expecting_body', 'Repository.get_revision_graph',
1975
1172
              ('quack/', ''))],
1976
1173
            client._calls)
1977
1174
        # The medium is now marked as being connected to an older server
1978
1175
        self.assertTrue(client._medium._is_remote_before((1, 2)))
1979
 
        self.assertEqual({rev_id: ('null:',)}, parents)
1980
1176
 
1981
1177
    def test_get_parent_map_fallback_parentless_node(self):
1982
1178
        """get_parent_map falls back to get_revision_graph on old servers.  The
1994
1190
        repo, client = self.setup_fake_client_and_repository(transport_path)
1995
1191
        client.add_success_response_with_body(rev_id, 'ok')
1996
1192
        client._medium._remember_remote_is_before((1, 2))
1997
 
        parents = repo.get_parent_map([rev_id])
 
1193
        expected_deprecations = [
 
1194
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
 
1195
            'in version 1.4.']
 
1196
        parents = self.callDeprecated(
 
1197
            expected_deprecations, repo.get_parent_map, [rev_id])
1998
1198
        self.assertEqual(
1999
1199
            [('call_expecting_body', 'Repository.get_revision_graph',
2000
1200
             ('quack/', ''))],
2008
1208
            errors.UnexpectedSmartServerResponse,
2009
1209
            repo.get_parent_map, ['a-revision-id'])
2010
1210
 
2011
 
    def test_get_parent_map_negative_caches_missing_keys(self):
2012
 
        self.setup_smart_server_with_call_log()
2013
 
        repo = self.make_repository('foo')
2014
 
        self.assertIsInstance(repo, RemoteRepository)
2015
 
        repo.lock_read()
2016
 
        self.addCleanup(repo.unlock)
2017
 
        self.reset_smart_call_log()
2018
 
        graph = repo.get_graph()
2019
 
        self.assertEqual({},
2020
 
            graph.get_parent_map(['some-missing', 'other-missing']))
2021
 
        self.assertLength(1, self.hpss_calls)
2022
 
        # No call if we repeat this
2023
 
        self.reset_smart_call_log()
2024
 
        graph = repo.get_graph()
2025
 
        self.assertEqual({},
2026
 
            graph.get_parent_map(['some-missing', 'other-missing']))
2027
 
        self.assertLength(0, self.hpss_calls)
2028
 
        # Asking for more unknown keys makes a request.
2029
 
        self.reset_smart_call_log()
2030
 
        graph = repo.get_graph()
2031
 
        self.assertEqual({},
2032
 
            graph.get_parent_map(['some-missing', 'other-missing',
2033
 
                'more-missing']))
2034
 
        self.assertLength(1, self.hpss_calls)
2035
 
 
2036
 
    def disableExtraResults(self):
2037
 
        self.overrideAttr(SmartServerRepositoryGetParentMap,
2038
 
                          'no_extra_results', True)
2039
 
 
2040
 
    def test_null_cached_missing_and_stop_key(self):
2041
 
        self.setup_smart_server_with_call_log()
2042
 
        # Make a branch with a single revision.
2043
 
        builder = self.make_branch_builder('foo')
2044
 
        builder.start_series()
2045
 
        builder.build_snapshot('first', None, [
2046
 
            ('add', ('', 'root-id', 'directory', ''))])
2047
 
        builder.finish_series()
2048
 
        branch = builder.get_branch()
2049
 
        repo = branch.repository
2050
 
        self.assertIsInstance(repo, RemoteRepository)
2051
 
        # Stop the server from sending extra results.
2052
 
        self.disableExtraResults()
2053
 
        repo.lock_read()
2054
 
        self.addCleanup(repo.unlock)
2055
 
        self.reset_smart_call_log()
2056
 
        graph = repo.get_graph()
2057
 
        # Query for 'first' and 'null:'.  Because 'null:' is a parent of
2058
 
        # 'first' it will be a candidate for the stop_keys of subsequent
2059
 
        # requests, and because 'null:' was queried but not returned it will be
2060
 
        # cached as missing.
2061
 
        self.assertEqual({'first': ('null:',)},
2062
 
            graph.get_parent_map(['first', 'null:']))
2063
 
        # Now query for another key.  This request will pass along a recipe of
2064
 
        # start and stop keys describing the already cached results, and this
2065
 
        # recipe's revision count must be correct (or else it will trigger an
2066
 
        # error from the server).
2067
 
        self.assertEqual({}, graph.get_parent_map(['another-key']))
2068
 
        # This assertion guards against disableExtraResults silently failing to
2069
 
        # work, thus invalidating the test.
2070
 
        self.assertLength(2, self.hpss_calls)
2071
 
 
2072
 
    def test_get_parent_map_gets_ghosts_from_result(self):
2073
 
        # asking for a revision should negatively cache close ghosts in its
2074
 
        # ancestry.
2075
 
        self.setup_smart_server_with_call_log()
2076
 
        tree = self.make_branch_and_memory_tree('foo')
2077
 
        tree.lock_write()
2078
 
        try:
2079
 
            builder = treebuilder.TreeBuilder()
2080
 
            builder.start_tree(tree)
2081
 
            builder.build([])
2082
 
            builder.finish_tree()
2083
 
            tree.set_parent_ids(['non-existant'], allow_leftmost_as_ghost=True)
2084
 
            rev_id = tree.commit('')
2085
 
        finally:
2086
 
            tree.unlock()
2087
 
        tree.lock_read()
2088
 
        self.addCleanup(tree.unlock)
2089
 
        repo = tree.branch.repository
2090
 
        self.assertIsInstance(repo, RemoteRepository)
2091
 
        # ask for rev_id
2092
 
        repo.get_parent_map([rev_id])
2093
 
        self.reset_smart_call_log()
2094
 
        # Now asking for rev_id's ghost parent should not make calls
2095
 
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
2096
 
        self.assertLength(0, self.hpss_calls)
2097
 
 
2098
 
 
2099
 
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
2100
 
 
2101
 
    def test_allows_new_revisions(self):
2102
 
        """get_parent_map's results can be updated by commit."""
2103
 
        smart_server = test_server.SmartTCPServer_for_testing()
2104
 
        self.start_server(smart_server)
2105
 
        self.make_branch('branch')
2106
 
        branch = Branch.open(smart_server.get_url() + '/branch')
2107
 
        tree = branch.create_checkout('tree', lightweight=True)
2108
 
        tree.lock_write()
2109
 
        self.addCleanup(tree.unlock)
2110
 
        graph = tree.branch.repository.get_graph()
2111
 
        # This provides an opportunity for the missing rev-id to be cached.
2112
 
        self.assertEqual({}, graph.get_parent_map(['rev1']))
2113
 
        tree.commit('message', rev_id='rev1')
2114
 
        graph = tree.branch.repository.get_graph()
2115
 
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
2116
 
 
2117
1211
 
2118
1212
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
2119
 
 
 
1213
    
2120
1214
    def test_null_revision(self):
2121
1215
        # a null revision has the predictable result {}, we should have no wire
2122
1216
        # traffic when calling it with this argument
2123
1217
        transport_path = 'empty'
2124
1218
        repo, client = self.setup_fake_client_and_repository(transport_path)
2125
1219
        client.add_success_response('notused')
2126
 
        # actual RemoteRepository.get_revision_graph is gone, but there's an
2127
 
        # equivalent private method for testing
2128
 
        result = repo._get_revision_graph(NULL_REVISION)
 
1220
        result = self.applyDeprecated(one_four, repo.get_revision_graph,
 
1221
            NULL_REVISION)
2129
1222
        self.assertEqual([], client._calls)
2130
1223
        self.assertEqual({}, result)
2131
1224
 
2139
1232
        transport_path = 'sinhala'
2140
1233
        repo, client = self.setup_fake_client_and_repository(transport_path)
2141
1234
        client.add_success_response_with_body(encoded_body, 'ok')
2142
 
        # actual RemoteRepository.get_revision_graph is gone, but there's an
2143
 
        # equivalent private method for testing
2144
 
        result = repo._get_revision_graph(None)
 
1235
        result = self.applyDeprecated(one_four, repo.get_revision_graph)
2145
1236
        self.assertEqual(
2146
1237
            [('call_expecting_body', 'Repository.get_revision_graph',
2147
1238
             ('sinhala/', ''))],
2160
1251
        transport_path = 'sinhala'
2161
1252
        repo, client = self.setup_fake_client_and_repository(transport_path)
2162
1253
        client.add_success_response_with_body(encoded_body, 'ok')
2163
 
        result = repo._get_revision_graph(r2)
 
1254
        result = self.applyDeprecated(one_four, repo.get_revision_graph, r2)
2164
1255
        self.assertEqual(
2165
1256
            [('call_expecting_body', 'Repository.get_revision_graph',
2166
1257
             ('sinhala/', r2))],
2174
1265
        client.add_error_response('nosuchrevision', revid)
2175
1266
        # also check that the right revision is reported in the error
2176
1267
        self.assertRaises(errors.NoSuchRevision,
2177
 
            repo._get_revision_graph, revid)
 
1268
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
2178
1269
        self.assertEqual(
2179
1270
            [('call_expecting_body', 'Repository.get_revision_graph',
2180
1271
             ('sinhala/', revid))],
2186
1277
        repo, client = self.setup_fake_client_and_repository(transport_path)
2187
1278
        client.add_error_response('AnUnexpectedError')
2188
1279
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
2189
 
            repo._get_revision_graph, revid)
 
1280
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
2190
1281
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
2191
1282
 
2192
 
 
2193
 
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
2194
 
 
2195
 
    def test_ok(self):
2196
 
        repo, client = self.setup_fake_client_and_repository('quack')
2197
 
        client.add_expected_call(
2198
 
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2199
 
            'success', ('ok', 'rev-five'))
2200
 
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2201
 
        self.assertEqual((True, 'rev-five'), result)
2202
 
        self.assertFinished(client)
2203
 
 
2204
 
    def test_history_incomplete(self):
2205
 
        repo, client = self.setup_fake_client_and_repository('quack')
2206
 
        client.add_expected_call(
2207
 
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2208
 
            'success', ('history-incomplete', 10, 'rev-ten'))
2209
 
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2210
 
        self.assertEqual((False, (10, 'rev-ten')), result)
2211
 
        self.assertFinished(client)
2212
 
 
2213
 
    def test_history_incomplete_with_fallback(self):
2214
 
        """A 'history-incomplete' response causes the fallback repository to be
2215
 
        queried too, if one is set.
2216
 
        """
2217
 
        # Make a repo with a fallback repo, both using a FakeClient.
2218
 
        format = remote.response_tuple_to_repo_format(
2219
 
            ('yes', 'no', 'yes', self.get_repo_format().network_name()))
2220
 
        repo, client = self.setup_fake_client_and_repository('quack')
2221
 
        repo._format = format
2222
 
        fallback_repo, ignored = self.setup_fake_client_and_repository(
2223
 
            'fallback')
2224
 
        fallback_repo._client = client
2225
 
        fallback_repo._format = format
2226
 
        repo.add_fallback_repository(fallback_repo)
2227
 
        # First the client should ask the primary repo
2228
 
        client.add_expected_call(
2229
 
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
2230
 
            'success', ('history-incomplete', 2, 'rev-two'))
2231
 
        # Then it should ask the fallback, using revno/revid from the
2232
 
        # history-incomplete response as the known revno/revid.
2233
 
        client.add_expected_call(
2234
 
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
2235
 
            'success', ('ok', 'rev-one'))
2236
 
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
2237
 
        self.assertEqual((True, 'rev-one'), result)
2238
 
        self.assertFinished(client)
2239
 
 
2240
 
    def test_nosuchrevision(self):
2241
 
        # 'nosuchrevision' is returned when the known-revid is not found in the
2242
 
        # remote repo.  The client translates that response to NoSuchRevision.
2243
 
        repo, client = self.setup_fake_client_and_repository('quack')
2244
 
        client.add_expected_call(
2245
 
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2246
 
            'error', ('nosuchrevision', 'rev-foo'))
2247
 
        self.assertRaises(
2248
 
            errors.NoSuchRevision,
2249
 
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
2250
 
        self.assertFinished(client)
2251
 
 
2252
 
    def test_branch_fallback_locking(self):
2253
 
        """RemoteBranch.get_rev_id takes a read lock, and tries to call the
2254
 
        get_rev_id_for_revno verb.  If the verb is unknown the VFS fallback
2255
 
        will be invoked, which will fail if the repo is unlocked.
2256
 
        """
2257
 
        self.setup_smart_server_with_call_log()
2258
 
        tree = self.make_branch_and_memory_tree('.')
2259
 
        tree.lock_write()
2260
 
        rev1 = tree.commit('First')
2261
 
        rev2 = tree.commit('Second')
2262
 
        tree.unlock()
2263
 
        branch = tree.branch
2264
 
        self.assertFalse(branch.is_locked())
2265
 
        self.reset_smart_call_log()
2266
 
        verb = 'Repository.get_rev_id_for_revno'
2267
 
        self.disable_verb(verb)
2268
 
        self.assertEqual(rev1, branch.get_rev_id(1))
2269
 
        self.assertLength(1, [call for call in self.hpss_calls if
2270
 
                              call.call.method == verb])
2271
 
 
2272
 
 
 
1283
        
2273
1284
class TestRepositoryIsShared(TestRemoteRepository):
2274
1285
 
2275
1286
    def test_is_shared(self):
2326
1337
            client._calls)
2327
1338
 
2328
1339
 
2329
 
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
2330
 
 
2331
 
    def test_backwards_compat(self):
2332
 
        self.setup_smart_server_with_call_log()
2333
 
        repo = self.make_repository('.')
2334
 
        self.reset_smart_call_log()
2335
 
        verb = 'Repository.set_make_working_trees'
2336
 
        self.disable_verb(verb)
2337
 
        repo.set_make_working_trees(True)
2338
 
        call_count = len([call for call in self.hpss_calls if
2339
 
            call.call.method == verb])
2340
 
        self.assertEqual(1, call_count)
2341
 
 
2342
 
    def test_current(self):
2343
 
        transport_path = 'quack'
2344
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2345
 
        client.add_expected_call(
2346
 
            'Repository.set_make_working_trees', ('quack/', 'True'),
2347
 
            'success', ('ok',))
2348
 
        client.add_expected_call(
2349
 
            'Repository.set_make_working_trees', ('quack/', 'False'),
2350
 
            'success', ('ok',))
2351
 
        repo.set_make_working_trees(True)
2352
 
        repo.set_make_working_trees(False)
2353
 
 
2354
 
 
2355
1340
class TestRepositoryUnlock(TestRemoteRepository):
2356
1341
 
2357
1342
    def test_unlock(self):
2390
1375
        self.assertEqual([], client._calls)
2391
1376
 
2392
1377
 
2393
 
class TestRepositoryInsertStreamBase(TestRemoteRepository):
2394
 
    """Base class for Repository.insert_stream and .insert_stream_1.19
2395
 
    tests.
2396
 
    """
2397
 
    
2398
 
    def checkInsertEmptyStream(self, repo, client):
2399
 
        """Insert an empty stream, checking the result.
2400
 
 
2401
 
        This checks that there are no resume_tokens or missing_keys, and that
2402
 
        the client is finished.
2403
 
        """
2404
 
        sink = repo._get_sink()
2405
 
        fmt = repository.RepositoryFormat.get_default_format()
2406
 
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2407
 
        self.assertEqual([], resume_tokens)
2408
 
        self.assertEqual(set(), missing_keys)
2409
 
        self.assertFinished(client)
2410
 
 
2411
 
 
2412
 
class TestRepositoryInsertStream(TestRepositoryInsertStreamBase):
2413
 
    """Tests for using Repository.insert_stream verb when the _1.19 variant is
2414
 
    not available.
2415
 
 
2416
 
    This test case is very similar to TestRepositoryInsertStream_1_19.
2417
 
    """
2418
 
 
2419
 
    def setUp(self):
2420
 
        TestRemoteRepository.setUp(self)
2421
 
        self.disable_verb('Repository.insert_stream_1.19')
2422
 
 
2423
 
    def test_unlocked_repo(self):
2424
 
        transport_path = 'quack'
2425
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2426
 
        client.add_expected_call(
2427
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2428
 
            'unknown', ('Repository.insert_stream_1.19',))
2429
 
        client.add_expected_call(
2430
 
            'Repository.insert_stream', ('quack/', ''),
2431
 
            'success', ('ok',))
2432
 
        client.add_expected_call(
2433
 
            'Repository.insert_stream', ('quack/', ''),
2434
 
            'success', ('ok',))
2435
 
        self.checkInsertEmptyStream(repo, client)
2436
 
 
2437
 
    def test_locked_repo_with_no_lock_token(self):
2438
 
        transport_path = 'quack'
2439
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2440
 
        client.add_expected_call(
2441
 
            'Repository.lock_write', ('quack/', ''),
2442
 
            'success', ('ok', ''))
2443
 
        client.add_expected_call(
2444
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2445
 
            'unknown', ('Repository.insert_stream_1.19',))
2446
 
        client.add_expected_call(
2447
 
            'Repository.insert_stream', ('quack/', ''),
2448
 
            'success', ('ok',))
2449
 
        client.add_expected_call(
2450
 
            'Repository.insert_stream', ('quack/', ''),
2451
 
            'success', ('ok',))
2452
 
        repo.lock_write()
2453
 
        self.checkInsertEmptyStream(repo, client)
2454
 
 
2455
 
    def test_locked_repo_with_lock_token(self):
2456
 
        transport_path = 'quack'
2457
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2458
 
        client.add_expected_call(
2459
 
            'Repository.lock_write', ('quack/', ''),
2460
 
            'success', ('ok', 'a token'))
2461
 
        client.add_expected_call(
2462
 
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2463
 
            'unknown', ('Repository.insert_stream_1.19',))
2464
 
        client.add_expected_call(
2465
 
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2466
 
            'success', ('ok',))
2467
 
        client.add_expected_call(
2468
 
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2469
 
            'success', ('ok',))
2470
 
        repo.lock_write()
2471
 
        self.checkInsertEmptyStream(repo, client)
2472
 
 
2473
 
    def test_stream_with_inventory_deltas(self):
2474
 
        """'inventory-deltas' substreams cannot be sent to the
2475
 
        Repository.insert_stream verb, because not all servers that implement
2476
 
        that verb will accept them.  So when one is encountered the RemoteSink
2477
 
        immediately stops using that verb and falls back to VFS insert_stream.
2478
 
        """
2479
 
        transport_path = 'quack'
2480
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2481
 
        client.add_expected_call(
2482
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2483
 
            'unknown', ('Repository.insert_stream_1.19',))
2484
 
        client.add_expected_call(
2485
 
            'Repository.insert_stream', ('quack/', ''),
2486
 
            'success', ('ok',))
2487
 
        client.add_expected_call(
2488
 
            'Repository.insert_stream', ('quack/', ''),
2489
 
            'success', ('ok',))
2490
 
        # Create a fake real repository for insert_stream to fall back on, so
2491
 
        # that we can directly see the records the RemoteSink passes to the
2492
 
        # real sink.
2493
 
        class FakeRealSink:
2494
 
            def __init__(self):
2495
 
                self.records = []
2496
 
            def insert_stream(self, stream, src_format, resume_tokens):
2497
 
                for substream_kind, substream in stream:
2498
 
                    self.records.append(
2499
 
                        (substream_kind, [record.key for record in substream]))
2500
 
                return ['fake tokens'], ['fake missing keys']
2501
 
        fake_real_sink = FakeRealSink()
2502
 
        class FakeRealRepository:
2503
 
            def _get_sink(self):
2504
 
                return fake_real_sink
2505
 
            def is_in_write_group(self):
2506
 
                return False
2507
 
            def refresh_data(self):
2508
 
                return True
2509
 
        repo._real_repository = FakeRealRepository()
2510
 
        sink = repo._get_sink()
2511
 
        fmt = repository.RepositoryFormat.get_default_format()
2512
 
        stream = self.make_stream_with_inv_deltas(fmt)
2513
 
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
2514
 
        # Every record from the first inventory delta should have been sent to
2515
 
        # the VFS sink.
2516
 
        expected_records = [
2517
 
            ('inventory-deltas', [('rev2',), ('rev3',)]),
2518
 
            ('texts', [('some-rev', 'some-file')])]
2519
 
        self.assertEqual(expected_records, fake_real_sink.records)
2520
 
        # The return values from the real sink's insert_stream are propagated
2521
 
        # back to the original caller.
2522
 
        self.assertEqual(['fake tokens'], resume_tokens)
2523
 
        self.assertEqual(['fake missing keys'], missing_keys)
2524
 
        self.assertFinished(client)
2525
 
 
2526
 
    def make_stream_with_inv_deltas(self, fmt):
2527
 
        """Make a simple stream with an inventory delta followed by more
2528
 
        records and more substreams to test that all records and substreams
2529
 
        from that point on are used.
2530
 
 
2531
 
        This sends, in order:
2532
 
           * inventories substream: rev1, rev2, rev3.  rev2 and rev3 are
2533
 
             inventory-deltas.
2534
 
           * texts substream: (some-rev, some-file)
2535
 
        """
2536
 
        # Define a stream using generators so that it isn't rewindable.
2537
 
        inv = inventory.Inventory(revision_id='rev1')
2538
 
        inv.root.revision = 'rev1'
2539
 
        def stream_with_inv_delta():
2540
 
            yield ('inventories', inventories_substream())
2541
 
            yield ('inventory-deltas', inventory_delta_substream())
2542
 
            yield ('texts', [
2543
 
                versionedfile.FulltextContentFactory(
2544
 
                    ('some-rev', 'some-file'), (), None, 'content')])
2545
 
        def inventories_substream():
2546
 
            # An empty inventory fulltext.  This will be streamed normally.
2547
 
            text = fmt._serializer.write_inventory_to_string(inv)
2548
 
            yield versionedfile.FulltextContentFactory(
2549
 
                ('rev1',), (), None, text)
2550
 
        def inventory_delta_substream():
2551
 
            # An inventory delta.  This can't be streamed via this verb, so it
2552
 
            # will trigger a fallback to VFS insert_stream.
2553
 
            entry = inv.make_entry(
2554
 
                'directory', 'newdir', inv.root.file_id, 'newdir-id')
2555
 
            entry.revision = 'ghost'
2556
 
            delta = [(None, 'newdir', 'newdir-id', entry)]
2557
 
            serializer = inventory_delta.InventoryDeltaSerializer(
2558
 
                versioned_root=True, tree_references=False)
2559
 
            lines = serializer.delta_to_lines('rev1', 'rev2', delta)
2560
 
            yield versionedfile.ChunkedContentFactory(
2561
 
                ('rev2',), (('rev1',)), None, lines)
2562
 
            # Another delta.
2563
 
            lines = serializer.delta_to_lines('rev1', 'rev3', delta)
2564
 
            yield versionedfile.ChunkedContentFactory(
2565
 
                ('rev3',), (('rev1',)), None, lines)
2566
 
        return stream_with_inv_delta()
2567
 
 
2568
 
 
2569
 
class TestRepositoryInsertStream_1_19(TestRepositoryInsertStreamBase):
2570
 
 
2571
 
    def test_unlocked_repo(self):
2572
 
        transport_path = 'quack'
2573
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2574
 
        client.add_expected_call(
2575
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2576
 
            'success', ('ok',))
2577
 
        client.add_expected_call(
2578
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2579
 
            'success', ('ok',))
2580
 
        self.checkInsertEmptyStream(repo, client)
2581
 
 
2582
 
    def test_locked_repo_with_no_lock_token(self):
2583
 
        transport_path = 'quack'
2584
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2585
 
        client.add_expected_call(
2586
 
            'Repository.lock_write', ('quack/', ''),
2587
 
            'success', ('ok', ''))
2588
 
        client.add_expected_call(
2589
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2590
 
            'success', ('ok',))
2591
 
        client.add_expected_call(
2592
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2593
 
            'success', ('ok',))
2594
 
        repo.lock_write()
2595
 
        self.checkInsertEmptyStream(repo, client)
2596
 
 
2597
 
    def test_locked_repo_with_lock_token(self):
2598
 
        transport_path = 'quack'
2599
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2600
 
        client.add_expected_call(
2601
 
            'Repository.lock_write', ('quack/', ''),
2602
 
            'success', ('ok', 'a token'))
2603
 
        client.add_expected_call(
2604
 
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2605
 
            'success', ('ok',))
2606
 
        client.add_expected_call(
2607
 
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2608
 
            'success', ('ok',))
2609
 
        repo.lock_write()
2610
 
        self.checkInsertEmptyStream(repo, client)
2611
 
 
2612
 
 
2613
1378
class TestRepositoryTarball(TestRemoteRepository):
2614
1379
 
2615
1380
    # This is a canned tarball reponse we can validate against
2649
1414
    """RemoteRepository.copy_content_into optimizations"""
2650
1415
 
2651
1416
    def test_copy_content_remote_to_local(self):
2652
 
        self.transport_server = test_server.SmartTCPServer_for_testing
 
1417
        self.transport_server = server.SmartTCPServer_for_testing
2653
1418
        src_repo = self.make_repository('repo1')
2654
1419
        src_repo = repository.Repository.open(self.get_url('repo1'))
2655
1420
        # At the moment the tarball-based copy_content_into can't write back
2664
1429
        src_repo.copy_content_into(dest_repo)
2665
1430
 
2666
1431
 
2667
 
class _StubRealPackRepository(object):
2668
 
 
2669
 
    def __init__(self, calls):
2670
 
        self.calls = calls
2671
 
        self._pack_collection = _StubPackCollection(calls)
2672
 
 
2673
 
    def is_in_write_group(self):
2674
 
        return False
2675
 
 
2676
 
    def refresh_data(self):
2677
 
        self.calls.append(('pack collection reload_pack_names',))
2678
 
 
2679
 
 
2680
 
class _StubPackCollection(object):
2681
 
 
2682
 
    def __init__(self, calls):
2683
 
        self.calls = calls
2684
 
 
2685
 
    def autopack(self):
2686
 
        self.calls.append(('pack collection autopack',))
2687
 
 
2688
 
 
2689
 
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
2690
 
    """Tests for RemoteRepository.autopack implementation."""
2691
 
 
2692
 
    def test_ok(self):
2693
 
        """When the server returns 'ok' and there's no _real_repository, then
2694
 
        nothing else happens: the autopack method is done.
2695
 
        """
2696
 
        transport_path = 'quack'
2697
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2698
 
        client.add_expected_call(
2699
 
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
2700
 
        repo.autopack()
2701
 
        self.assertFinished(client)
2702
 
 
2703
 
    def test_ok_with_real_repo(self):
2704
 
        """When the server returns 'ok' and there is a _real_repository, then
2705
 
        the _real_repository's reload_pack_name's method will be called.
2706
 
        """
2707
 
        transport_path = 'quack'
2708
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2709
 
        client.add_expected_call(
2710
 
            'PackRepository.autopack', ('quack/',),
2711
 
            'success', ('ok',))
2712
 
        repo._real_repository = _StubRealPackRepository(client._calls)
2713
 
        repo.autopack()
2714
 
        self.assertEqual(
2715
 
            [('call', 'PackRepository.autopack', ('quack/',)),
2716
 
             ('pack collection reload_pack_names',)],
2717
 
            client._calls)
2718
 
 
2719
 
    def test_backwards_compatibility(self):
2720
 
        """If the server does not recognise the PackRepository.autopack verb,
2721
 
        fallback to the real_repository's implementation.
2722
 
        """
2723
 
        transport_path = 'quack'
2724
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2725
 
        client.add_unknown_method_response('PackRepository.autopack')
2726
 
        def stub_ensure_real():
2727
 
            client._calls.append(('_ensure_real',))
2728
 
            repo._real_repository = _StubRealPackRepository(client._calls)
2729
 
        repo._ensure_real = stub_ensure_real
2730
 
        repo.autopack()
2731
 
        self.assertEqual(
2732
 
            [('call', 'PackRepository.autopack', ('quack/',)),
2733
 
             ('_ensure_real',),
2734
 
             ('pack collection autopack',)],
2735
 
            client._calls)
2736
 
 
2737
 
 
2738
1432
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
2739
1433
    """Base class for unit tests for bzrlib.remote._translate_error."""
2740
1434
 
2768
1462
                **context)
2769
1463
        return translated_error
2770
1464
 
2771
 
 
 
1465
    
2772
1466
class TestErrorTranslationSuccess(TestErrorTranslationBase):
2773
1467
    """Unit tests for bzrlib.remote._translate_error.
2774
 
 
 
1468
    
2775
1469
    Given an ErrorFromSmartServer (which has an error tuple from a smart
2776
1470
    server) and some context, _translate_error raises more specific errors from
2777
1471
    bzrlib.errors.
2803
1497
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
2804
1498
        self.assertEqual(expected_error, translated_error)
2805
1499
 
2806
 
    def test_nobranch_one_arg(self):
2807
 
        bzrdir = self.make_bzrdir('')
2808
 
        translated_error = self.translateTuple(
2809
 
            ('nobranch', 'extra detail'), bzrdir=bzrdir)
2810
 
        expected_error = errors.NotBranchError(
2811
 
            path=bzrdir.root_transport.base,
2812
 
            detail='extra detail')
2813
 
        self.assertEqual(expected_error, translated_error)
2814
 
 
2815
1500
    def test_LockContention(self):
2816
1501
        translated_error = self.translateTuple(('LockContention',))
2817
1502
        expected_error = errors.LockContention('(remote lock)')
2845
1530
        expected_error = errors.DivergedBranches(branch, other_branch)
2846
1531
        self.assertEqual(expected_error, translated_error)
2847
1532
 
2848
 
    def test_ReadError_no_args(self):
2849
 
        path = 'a path'
2850
 
        translated_error = self.translateTuple(('ReadError',), path=path)
2851
 
        expected_error = errors.ReadError(path)
2852
 
        self.assertEqual(expected_error, translated_error)
2853
 
 
2854
 
    def test_ReadError(self):
2855
 
        path = 'a path'
2856
 
        translated_error = self.translateTuple(('ReadError', path))
2857
 
        expected_error = errors.ReadError(path)
2858
 
        self.assertEqual(expected_error, translated_error)
2859
 
 
2860
 
    def test_IncompatibleRepositories(self):
2861
 
        translated_error = self.translateTuple(('IncompatibleRepositories',
2862
 
            "repo1", "repo2", "details here"))
2863
 
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
2864
 
            "details here")
2865
 
        self.assertEqual(expected_error, translated_error)
2866
 
 
2867
 
    def test_PermissionDenied_no_args(self):
2868
 
        path = 'a path'
2869
 
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
2870
 
        expected_error = errors.PermissionDenied(path)
2871
 
        self.assertEqual(expected_error, translated_error)
2872
 
 
2873
 
    def test_PermissionDenied_one_arg(self):
2874
 
        path = 'a path'
2875
 
        translated_error = self.translateTuple(('PermissionDenied', path))
2876
 
        expected_error = errors.PermissionDenied(path)
2877
 
        self.assertEqual(expected_error, translated_error)
2878
 
 
2879
 
    def test_PermissionDenied_one_arg_and_context(self):
2880
 
        """Given a choice between a path from the local context and a path on
2881
 
        the wire, _translate_error prefers the path from the local context.
2882
 
        """
2883
 
        local_path = 'local path'
2884
 
        remote_path = 'remote path'
2885
 
        translated_error = self.translateTuple(
2886
 
            ('PermissionDenied', remote_path), path=local_path)
2887
 
        expected_error = errors.PermissionDenied(local_path)
2888
 
        self.assertEqual(expected_error, translated_error)
2889
 
 
2890
 
    def test_PermissionDenied_two_args(self):
2891
 
        path = 'a path'
2892
 
        extra = 'a string with extra info'
2893
 
        translated_error = self.translateTuple(
2894
 
            ('PermissionDenied', path, extra))
2895
 
        expected_error = errors.PermissionDenied(path, extra)
2896
 
        self.assertEqual(expected_error, translated_error)
2897
 
 
2898
1533
 
2899
1534
class TestErrorTranslationRobustness(TestErrorTranslationBase):
2900
1535
    """Unit tests for bzrlib.remote._translate_error's robustness.
2901
 
 
 
1536
    
2902
1537
    TestErrorTranslationSuccess is for cases where _translate_error can
2903
1538
    translate successfully.  This class about how _translate_err behaves when
2904
1539
    it fails to translate: it re-raises the original error.
2930
1565
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2931
1566
        # been muttered to the log file for developer to look at.
2932
1567
        self.assertContainsRe(
2933
 
            self.get_log(),
 
1568
            self._get_log(keep_log_file=True),
2934
1569
            "Missing key 'branch' in context")
2935
 
 
2936
 
    def test_path_missing(self):
2937
 
        """Some translations (PermissionDenied, ReadError) can determine the
2938
 
        'path' variable from either the wire or the local context.  If neither
2939
 
        has it, then an error is raised.
2940
 
        """
2941
 
        error_tuple = ('ReadError',)
2942
 
        server_error = errors.ErrorFromSmartServer(error_tuple)
2943
 
        translated_error = self.translateErrorFromSmartServer(server_error)
2944
 
        self.assertEqual(server_error, translated_error)
2945
 
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2946
 
        # been muttered to the log file for developer to look at.
2947
 
        self.assertContainsRe(self.get_log(), "Missing key 'path' in context")
2948
 
 
 
1570
        
2949
1571
 
2950
1572
class TestStacking(tests.TestCaseWithTransport):
2951
1573
    """Tests for operations on stacked remote repositories.
2952
 
 
 
1574
    
2953
1575
    The underlying format type must support stacking.
2954
1576
    """
2955
1577
 
2959
1581
        # revision, then open it over hpss - we should be able to see that
2960
1582
        # revision.
2961
1583
        base_transport = self.get_transport()
2962
 
        base_builder = self.make_branch_builder('base', format='1.9')
 
1584
        base_builder = self.make_branch_builder('base', format='1.6')
2963
1585
        base_builder.start_series()
2964
1586
        base_revid = base_builder.build_snapshot('rev-id', None,
2965
1587
            [('add', ('', None, 'directory', None))],
2966
1588
            'message')
2967
1589
        base_builder.finish_series()
2968
 
        stacked_branch = self.make_branch('stacked', format='1.9')
 
1590
        stacked_branch = self.make_branch('stacked', format='1.6')
2969
1591
        stacked_branch.set_stacked_on_url('../base')
2970
1592
        # start a server looking at this
2971
 
        smart_server = test_server.SmartTCPServer_for_testing()
2972
 
        self.start_server(smart_server)
 
1593
        smart_server = server.SmartTCPServer_for_testing()
 
1594
        smart_server.setUp()
 
1595
        self.addCleanup(smart_server.tearDown)
2973
1596
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
2974
1597
        # can get its branch and repository
2975
1598
        remote_branch = remote_bzrdir.open_branch()
2978
1601
        try:
2979
1602
            # it should have an appropriate fallback repository, which should also
2980
1603
            # be a RemoteRepository
2981
 
            self.assertLength(1, remote_repo._fallback_repositories)
 
1604
            self.assertEquals(len(remote_repo._fallback_repositories), 1)
2982
1605
            self.assertIsInstance(remote_repo._fallback_repositories[0],
2983
1606
                RemoteRepository)
2984
1607
            # and it has the revision committed to the underlying repository;
2989
1612
                'message')
2990
1613
        finally:
2991
1614
            remote_repo.unlock()
2992
 
 
2993
 
    def prepare_stacked_remote_branch(self):
2994
 
        """Get stacked_upon and stacked branches with content in each."""
2995
 
        self.setup_smart_server_with_call_log()
2996
 
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
2997
 
        tree1.commit('rev1', rev_id='rev1')
2998
 
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
2999
 
            ).open_workingtree()
3000
 
        local_tree = tree2.branch.create_checkout('local')
3001
 
        local_tree.commit('local changes make me feel good.')
3002
 
        branch2 = Branch.open(self.get_url('tree2'))
3003
 
        branch2.lock_read()
3004
 
        self.addCleanup(branch2.unlock)
3005
 
        return tree1.branch, branch2
3006
 
 
3007
 
    def test_stacked_get_parent_map(self):
3008
 
        # the public implementation of get_parent_map obeys stacking
3009
 
        _, branch = self.prepare_stacked_remote_branch()
3010
 
        repo = branch.repository
3011
 
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
3012
 
 
3013
 
    def test_unstacked_get_parent_map(self):
3014
 
        # _unstacked_provider.get_parent_map ignores stacking
3015
 
        _, branch = self.prepare_stacked_remote_branch()
3016
 
        provider = branch.repository._unstacked_provider
3017
 
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
3018
 
 
3019
 
    def fetch_stream_to_rev_order(self, stream):
3020
 
        result = []
3021
 
        for kind, substream in stream:
3022
 
            if not kind == 'revisions':
3023
 
                list(substream)
3024
 
            else:
3025
 
                for content in substream:
3026
 
                    result.append(content.key[-1])
3027
 
        return result
3028
 
 
3029
 
    def get_ordered_revs(self, format, order, branch_factory=None):
3030
 
        """Get a list of the revisions in a stream to format format.
3031
 
 
3032
 
        :param format: The format of the target.
3033
 
        :param order: the order that target should have requested.
3034
 
        :param branch_factory: A callable to create a trunk and stacked branch
3035
 
            to fetch from. If none, self.prepare_stacked_remote_branch is used.
3036
 
        :result: The revision ids in the stream, in the order seen,
3037
 
            the topological order of revisions in the source.
3038
 
        """
3039
 
        unordered_format = bzrdir.format_registry.get(format)()
3040
 
        target_repository_format = unordered_format.repository_format
3041
 
        # Cross check
3042
 
        self.assertEqual(order, target_repository_format._fetch_order)
3043
 
        if branch_factory is None:
3044
 
            branch_factory = self.prepare_stacked_remote_branch
3045
 
        _, stacked = branch_factory()
3046
 
        source = stacked.repository._get_source(target_repository_format)
3047
 
        tip = stacked.last_revision()
3048
 
        revs = stacked.repository.get_ancestry(tip)
3049
 
        search = graph.PendingAncestryResult([tip], stacked.repository)
3050
 
        self.reset_smart_call_log()
3051
 
        stream = source.get_stream(search)
3052
 
        if None in revs:
3053
 
            revs.remove(None)
3054
 
        # We trust that if a revision is in the stream the rest of the new
3055
 
        # content for it is too, as per our main fetch tests; here we are
3056
 
        # checking that the revisions are actually included at all, and their
3057
 
        # order.
3058
 
        return self.fetch_stream_to_rev_order(stream), revs
3059
 
 
3060
 
    def test_stacked_get_stream_unordered(self):
3061
 
        # Repository._get_source.get_stream() from a stacked repository with
3062
 
        # unordered yields the full data from both stacked and stacked upon
3063
 
        # sources.
3064
 
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered')
3065
 
        self.assertEqual(set(expected_revs), set(rev_ord))
3066
 
        # Getting unordered results should have made a streaming data request
3067
 
        # from the server, then one from the backing branch.
3068
 
        self.assertLength(2, self.hpss_calls)
3069
 
 
3070
 
    def test_stacked_on_stacked_get_stream_unordered(self):
3071
 
        # Repository._get_source.get_stream() from a stacked repository which
3072
 
        # is itself stacked yields the full data from all three sources.
3073
 
        def make_stacked_stacked():
3074
 
            _, stacked = self.prepare_stacked_remote_branch()
3075
 
            tree = stacked.bzrdir.sprout('tree3', stacked=True
3076
 
                ).open_workingtree()
3077
 
            local_tree = tree.branch.create_checkout('local-tree3')
3078
 
            local_tree.commit('more local changes are better')
3079
 
            branch = Branch.open(self.get_url('tree3'))
3080
 
            branch.lock_read()
3081
 
            self.addCleanup(branch.unlock)
3082
 
            return None, branch
3083
 
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
3084
 
            branch_factory=make_stacked_stacked)
3085
 
        self.assertEqual(set(expected_revs), set(rev_ord))
3086
 
        # Getting unordered results should have made a streaming data request
3087
 
        # from the server, and one from each backing repo
3088
 
        self.assertLength(3, self.hpss_calls)
3089
 
 
3090
 
    def test_stacked_get_stream_topological(self):
3091
 
        # Repository._get_source.get_stream() from a stacked repository with
3092
 
        # topological sorting yields the full data from both stacked and
3093
 
        # stacked upon sources in topological order.
3094
 
        rev_ord, expected_revs = self.get_ordered_revs('knit', 'topological')
3095
 
        self.assertEqual(expected_revs, rev_ord)
3096
 
        # Getting topological sort requires VFS calls still - one of which is
3097
 
        # pushing up from the bound branch.
3098
 
        self.assertLength(13, self.hpss_calls)
3099
 
 
3100
 
    def test_stacked_get_stream_groupcompress(self):
3101
 
        # Repository._get_source.get_stream() from a stacked repository with
3102
 
        # groupcompress sorting yields the full data from both stacked and
3103
 
        # stacked upon sources in groupcompress order.
3104
 
        raise tests.TestSkipped('No groupcompress ordered format available')
3105
 
        rev_ord, expected_revs = self.get_ordered_revs('dev5', 'groupcompress')
3106
 
        self.assertEqual(expected_revs, reversed(rev_ord))
3107
 
        # Getting unordered results should have made a streaming data request
3108
 
        # from the backing branch, and one from the stacked on branch.
3109
 
        self.assertLength(2, self.hpss_calls)
3110
 
 
3111
 
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
3112
 
        # When pulling some fixed amount of content that is more than the
3113
 
        # source has (because some is coming from a fallback branch, no error
3114
 
        # should be received. This was reported as bug 360791.
3115
 
        # Need three branches: a trunk, a stacked branch, and a preexisting
3116
 
        # branch pulling content from stacked and trunk.
3117
 
        self.setup_smart_server_with_call_log()
3118
 
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
3119
 
        r1 = trunk.commit('start')
3120
 
        stacked_branch = trunk.branch.create_clone_on_transport(
3121
 
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
3122
 
        local = self.make_branch('local', format='1.9-rich-root')
3123
 
        local.repository.fetch(stacked_branch.repository,
3124
 
            stacked_branch.last_revision())
3125
 
 
3126
 
 
3127
 
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
3128
 
 
3129
 
    def setUp(self):
3130
 
        super(TestRemoteBranchEffort, self).setUp()
3131
 
        # Create a smart server that publishes whatever the backing VFS server
3132
 
        # does.
3133
 
        self.smart_server = test_server.SmartTCPServer_for_testing()
3134
 
        self.start_server(self.smart_server, self.get_server())
3135
 
        # Log all HPSS calls into self.hpss_calls.
3136
 
        _SmartClient.hooks.install_named_hook(
3137
 
            'call', self.capture_hpss_call, None)
3138
 
        self.hpss_calls = []
3139
 
 
3140
 
    def capture_hpss_call(self, params):
3141
 
        self.hpss_calls.append(params.method)
3142
 
 
3143
 
    def test_copy_content_into_avoids_revision_history(self):
3144
 
        local = self.make_branch('local')
3145
 
        remote_backing_tree = self.make_branch_and_tree('remote')
3146
 
        remote_backing_tree.commit("Commit.")
3147
 
        remote_branch_url = self.smart_server.get_url() + 'remote'
3148
 
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3149
 
        local.repository.fetch(remote_branch.repository)
3150
 
        self.hpss_calls = []
3151
 
        remote_branch.copy_content_into(local)
3152
 
        self.assertFalse('Branch.revision_history' in self.hpss_calls)