~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Andrew Bennetts
  • Date: 2010-03-11 04:33:41 UTC
  • mfrom: (4797.33.4 2.1)
  • mto: This revision was merged to the branch mainline in revision 5082.
  • Revision ID: andrew.bennetts@canonical.com-20100311043341-rzdik83fnactjsxs
Merge lp:bzr/2.1, including fixes for #496813, #526211, #526353.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2006-2010 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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,
30
31
    bzrdir,
31
32
    config,
32
33
    errors,
33
34
    graph,
 
35
    inventory,
 
36
    inventory_delta,
34
37
    pack,
35
38
    remote,
36
39
    repository,
37
40
    tests,
 
41
    treebuilder,
38
42
    urlutils,
 
43
    versionedfile,
39
44
    )
40
45
from bzrlib.branch import Branch
41
46
from bzrlib.bzrdir import BzrDir, BzrDirFormat
42
47
from bzrlib.remote import (
43
48
    RemoteBranch,
 
49
    RemoteBranchFormat,
44
50
    RemoteBzrDir,
45
51
    RemoteBzrDirFormat,
46
52
    RemoteRepository,
 
53
    RemoteRepositoryFormat,
47
54
    )
 
55
from bzrlib.repofmt import groupcompress_repo, pack_repo
48
56
from bzrlib.revision import NULL_REVISION
49
 
from bzrlib.smart import server, medium
 
57
from bzrlib.smart import medium
50
58
from bzrlib.smart.client import _SmartClient
51
 
from bzrlib.symbol_versioning import one_four
52
 
from bzrlib.transport import get_transport, http
 
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
53
67
from bzrlib.transport.memory import MemoryTransport
54
68
from bzrlib.transport.remote import (
55
69
    RemoteTransport,
57
71
    RemoteTCPTransport,
58
72
)
59
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)
 
83
 
60
84
 
61
85
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
62
86
 
63
87
    def setUp(self):
64
 
        self.transport_server = server.SmartTCPServer_for_testing
65
88
        super(BasicRemoteObjectTests, self).setUp()
66
89
        self.transport = self.get_transport()
67
90
        # make a branch that can be opened over the smart transport
72
95
        tests.TestCaseWithTransport.tearDown(self)
73
96
 
74
97
    def test_create_remote_bzrdir(self):
75
 
        b = remote.RemoteBzrDir(self.transport)
 
98
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
76
99
        self.assertIsInstance(b, BzrDir)
77
100
 
78
101
    def test_open_remote_branch(self):
79
102
        # open a standalone branch in the working directory
80
 
        b = remote.RemoteBzrDir(self.transport)
 
103
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
81
104
        branch = b.open_branch()
82
105
        self.assertIsInstance(branch, Branch)
83
106
 
112
135
        b = BzrDir.open_from_transport(self.transport).open_branch()
113
136
        self.assertStartsWith(str(b), 'RemoteBranch(')
114
137
 
115
 
 
116
 
class FakeRemoteTransport(object):
117
 
    """This class provides the minimum support for use in place of a RemoteTransport.
118
 
    
119
 
    It doesn't actually transmit requests, but rather expects them to be
120
 
    handled by a FakeClient which holds canned responses.  It does not allow
121
 
    any vfs access, therefore is not suitable for testing any operation that
122
 
    will fallback to vfs access.  Backing the test by an instance of this
123
 
    class guarantees that it's - done using non-vfs operations.
124
 
    """
125
 
 
126
 
    _default_url = 'fakeremotetransport://host/path/'
127
 
 
128
 
    def __init__(self, url=None):
129
 
        if url is None:
130
 
            url = self._default_url
131
 
        self.base = url
132
 
 
133
 
    def __repr__(self):
134
 
        return "%r(%r)" % (self.__class__.__name__,
135
 
            self.base)
136
 
 
137
 
    def clone(self, relpath):
138
 
        return FakeRemoteTransport(urlutils.join(self.base, relpath))
139
 
 
140
 
    def get(self, relpath):
141
 
        # only get is specifically stubbed out, because it's usually the first
142
 
        # thing we do.  anything else will fail with an AttributeError.
143
 
        raise AssertionError("%r doesn't support file access to %r"
144
 
            % (self, relpath))
145
 
 
 
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)
146
180
 
147
181
 
148
182
class FakeProtocol(object):
170
204
 
171
205
class FakeClient(_SmartClient):
172
206
    """Lookalike for _SmartClient allowing testing."""
173
 
    
 
207
 
174
208
    def __init__(self, fake_medium_base='fake base'):
175
209
        """Create a FakeClient."""
176
210
        self.responses = []
178
212
        self.expecting_body = False
179
213
        # if non-None, this is the list of expected calls, with only the
180
214
        # method name and arguments included.  the body might be hard to
181
 
        # compute so is not included
 
215
        # compute so is not included. If a call is None, that call can
 
216
        # be anything.
182
217
        self._expected_calls = None
183
218
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
184
219
 
194
229
 
195
230
    def add_success_response_with_body(self, body, *args):
196
231
        self.responses.append(('success', args, body))
 
232
        if self._expected_calls is not None:
 
233
            self._expected_calls.append(None)
197
234
 
198
235
    def add_error_response(self, *args):
199
236
        self.responses.append(('error', args))
228
265
            raise AssertionError("%r didn't expect any more calls "
229
266
                "but got %r%r"
230
267
                % (self, method, args,))
 
268
        if next_call is None:
 
269
            return
231
270
        if method != next_call[0] or args != next_call[1]:
232
271
            raise AssertionError("%r expected %r%r "
233
272
                "but got %r%r"
245
284
        self.expecting_body = True
246
285
        return result[1], FakeProtocol(result[2], self)
247
286
 
 
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
 
248
293
    def call_with_body_bytes_expecting_body(self, method, args, body):
249
294
        self._check_call(method, args)
250
295
        self._calls.append(('call_with_body_bytes_expecting_body', method,
259
304
        stream = list(stream)
260
305
        self._check_call(args[0], args[1:])
261
306
        self._calls.append(('call_with_body_stream', args[0], args[1:], stream))
262
 
        return self._get_next_response()[1]
 
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
263
312
 
264
313
 
265
314
class FakeMedium(medium.SmartClientMedium):
286
335
        self.assertTrue(result)
287
336
 
288
337
 
 
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
 
289
353
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
290
354
    """Tests for the behaviour of client_medium.remote_path_from_transport."""
291
355
 
318
382
        cloned_transport = base_transport.clone(relpath)
319
383
        result = client_medium.remote_path_from_transport(cloned_transport)
320
384
        self.assertEqual(expected, result)
321
 
        
 
385
 
322
386
    def test_remote_path_from_transport_http(self):
323
387
        """Remote paths for HTTP transports are calculated differently to other
324
388
        transports.  They are just relative to the client base, not the root
340
404
        """
341
405
        client_medium = medium.SmartClientMedium('dummy base')
342
406
        self.assertFalse(client_medium._is_remote_before((99, 99)))
343
 
    
 
407
 
344
408
    def test__remember_remote_is_before(self):
345
409
        """Calling _remember_remote_is_before ratchets down the known remote
346
410
        version.
359
423
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
360
424
 
361
425
 
362
 
class TestBzrDirOpenBranch(tests.TestCase):
 
426
class TestBzrDirCloningMetaDir(TestRemote):
 
427
 
 
428
    def test_backwards_compat(self):
 
429
        self.setup_smart_server_with_call_log()
 
430
        a_dir = self.make_bzrdir('.')
 
431
        self.reset_smart_call_log()
 
432
        verb = 'BzrDir.cloning_metadir'
 
433
        self.disable_verb(verb)
 
434
        format = a_dir.cloning_metadir()
 
435
        call_count = len([call for call in self.hpss_calls if
 
436
            call.call.method == verb])
 
437
        self.assertEqual(1, call_count)
 
438
 
 
439
    def test_branch_reference(self):
 
440
        transport = self.get_transport('quack')
 
441
        referenced = self.make_branch('referenced')
 
442
        expected = referenced.bzrdir.cloning_metadir()
 
443
        client = FakeClient(transport.base)
 
444
        client.add_expected_call(
 
445
            'BzrDir.cloning_metadir', ('quack/', 'False'),
 
446
            'error', ('BranchReference',)),
 
447
        client.add_expected_call(
 
448
            'BzrDir.open_branchV3', ('quack/',),
 
449
            'success', ('ref', self.get_url('referenced'))),
 
450
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
451
            _client=client)
 
452
        result = a_bzrdir.cloning_metadir()
 
453
        # We should have got a control dir matching the referenced branch.
 
454
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
 
455
        self.assertEqual(expected._repository_format, result._repository_format)
 
456
        self.assertEqual(expected._branch_format, result._branch_format)
 
457
        self.assertFinished(client)
 
458
 
 
459
    def test_current_server(self):
 
460
        transport = self.get_transport('.')
 
461
        transport = transport.clone('quack')
 
462
        self.make_bzrdir('quack')
 
463
        client = FakeClient(transport.base)
 
464
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
465
        control_name = reference_bzrdir_format.network_name()
 
466
        client.add_expected_call(
 
467
            'BzrDir.cloning_metadir', ('quack/', 'False'),
 
468
            'success', (control_name, '', ('branch', ''))),
 
469
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
470
            _client=client)
 
471
        result = a_bzrdir.cloning_metadir()
 
472
        # We should have got a reference control dir with default branch and
 
473
        # repository formats.
 
474
        # This pokes a little, just to be sure.
 
475
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
 
476
        self.assertEqual(None, result._repository_format)
 
477
        self.assertEqual(None, result._branch_format)
 
478
        self.assertFinished(client)
 
479
 
 
480
 
 
481
class TestBzrDirOpen(TestRemote):
 
482
 
 
483
    def make_fake_client_and_transport(self, path='quack'):
 
484
        transport = MemoryTransport()
 
485
        transport.mkdir(path)
 
486
        transport = transport.clone(path)
 
487
        client = FakeClient(transport.base)
 
488
        return client, transport
 
489
 
 
490
    def test_absent(self):
 
491
        client, transport = self.make_fake_client_and_transport()
 
492
        client.add_expected_call(
 
493
            'BzrDir.open_2.1', ('quack/',), 'success', ('no',))
 
494
        self.assertRaises(errors.NotBranchError, RemoteBzrDir, transport,
 
495
                remote.RemoteBzrDirFormat(), _client=client, _force_probe=True)
 
496
        self.assertFinished(client)
 
497
 
 
498
    def test_present_without_workingtree(self):
 
499
        client, transport = self.make_fake_client_and_transport()
 
500
        client.add_expected_call(
 
501
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'no'))
 
502
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
503
            _client=client, _force_probe=True)
 
504
        self.assertIsInstance(bd, RemoteBzrDir)
 
505
        self.assertFalse(bd.has_workingtree())
 
506
        self.assertRaises(errors.NoWorkingTree, bd.open_workingtree)
 
507
        self.assertFinished(client)
 
508
 
 
509
    def test_present_with_workingtree(self):
 
510
        client, transport = self.make_fake_client_and_transport()
 
511
        client.add_expected_call(
 
512
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'yes'))
 
513
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
514
            _client=client, _force_probe=True)
 
515
        self.assertIsInstance(bd, RemoteBzrDir)
 
516
        self.assertTrue(bd.has_workingtree())
 
517
        self.assertRaises(errors.NotLocalUrl, bd.open_workingtree)
 
518
        self.assertFinished(client)
 
519
 
 
520
    def test_backwards_compat(self):
 
521
        client, transport = self.make_fake_client_and_transport()
 
522
        client.add_expected_call(
 
523
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
 
524
        client.add_expected_call(
 
525
            'BzrDir.open', ('quack/',), 'success', ('yes',))
 
526
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
527
            _client=client, _force_probe=True)
 
528
        self.assertIsInstance(bd, RemoteBzrDir)
 
529
        self.assertFinished(client)
 
530
 
 
531
 
 
532
class TestBzrDirOpenBranch(TestRemote):
 
533
 
 
534
    def test_backwards_compat(self):
 
535
        self.setup_smart_server_with_call_log()
 
536
        self.make_branch('.')
 
537
        a_dir = BzrDir.open(self.get_url('.'))
 
538
        self.reset_smart_call_log()
 
539
        verb = 'BzrDir.open_branchV3'
 
540
        self.disable_verb(verb)
 
541
        format = a_dir.open_branch()
 
542
        call_count = len([call for call in self.hpss_calls if
 
543
            call.call.method == verb])
 
544
        self.assertEqual(1, call_count)
363
545
 
364
546
    def test_branch_present(self):
 
547
        reference_format = self.get_repo_format()
 
548
        network_name = reference_format.network_name()
 
549
        branch_network_name = self.get_branch_format().network_name()
365
550
        transport = MemoryTransport()
366
551
        transport.mkdir('quack')
367
552
        transport = transport.clone('quack')
368
553
        client = FakeClient(transport.base)
369
554
        client.add_expected_call(
370
 
            'BzrDir.open_branch', ('quack/',),
371
 
            'success', ('ok', ''))
 
555
            'BzrDir.open_branchV3', ('quack/',),
 
556
            'success', ('branch', branch_network_name))
372
557
        client.add_expected_call(
373
 
            'BzrDir.find_repositoryV2', ('quack/',),
374
 
            'success', ('ok', '', 'no', 'no', 'no'))
 
558
            'BzrDir.find_repositoryV3', ('quack/',),
 
559
            'success', ('ok', '', 'no', 'no', 'no', network_name))
375
560
        client.add_expected_call(
376
561
            'Branch.get_stacked_on_url', ('quack/',),
377
562
            'error', ('NotStacked',))
378
 
        bzrdir = RemoteBzrDir(transport, _client=client)
 
563
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
564
            _client=client)
379
565
        result = bzrdir.open_branch()
380
566
        self.assertIsInstance(result, RemoteBranch)
381
567
        self.assertEqual(bzrdir, result.bzrdir)
382
 
        client.finished_test()
 
568
        self.assertFinished(client)
383
569
 
384
570
    def test_branch_missing(self):
385
571
        transport = MemoryTransport()
387
573
        transport = transport.clone('quack')
388
574
        client = FakeClient(transport.base)
389
575
        client.add_error_response('nobranch')
390
 
        bzrdir = RemoteBzrDir(transport, _client=client)
 
576
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
577
            _client=client)
391
578
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
392
579
        self.assertEqual(
393
 
            [('call', 'BzrDir.open_branch', ('quack/',))],
 
580
            [('call', 'BzrDir.open_branchV3', ('quack/',))],
394
581
            client._calls)
395
582
 
396
583
    def test__get_tree_branch(self):
403
590
        transport = MemoryTransport()
404
591
        # no requests on the network - catches other api calls being made.
405
592
        client = FakeClient(transport.base)
406
 
        bzrdir = RemoteBzrDir(transport, _client=client)
 
593
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
594
            _client=client)
407
595
        # patch the open_branch call to record that it was called.
408
596
        bzrdir.open_branch = open_branch
409
597
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
415
603
        # transmitted as "~", not "%7E".
416
604
        transport = RemoteTCPTransport('bzr://localhost/~hello/')
417
605
        client = FakeClient(transport.base)
418
 
        client.add_expected_call(
419
 
            'BzrDir.open_branch', ('~hello/',),
420
 
            'success', ('ok', ''))
421
 
        client.add_expected_call(
422
 
            'BzrDir.find_repositoryV2', ('~hello/',),
423
 
            'success', ('ok', '', 'no', 'no', 'no'))
 
606
        reference_format = self.get_repo_format()
 
607
        network_name = reference_format.network_name()
 
608
        branch_network_name = self.get_branch_format().network_name()
 
609
        client.add_expected_call(
 
610
            'BzrDir.open_branchV3', ('~hello/',),
 
611
            'success', ('branch', branch_network_name))
 
612
        client.add_expected_call(
 
613
            'BzrDir.find_repositoryV3', ('~hello/',),
 
614
            'success', ('ok', '', 'no', 'no', 'no', network_name))
424
615
        client.add_expected_call(
425
616
            'Branch.get_stacked_on_url', ('~hello/',),
426
617
            'error', ('NotStacked',))
427
 
        bzrdir = RemoteBzrDir(transport, _client=client)
 
618
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
619
            _client=client)
428
620
        result = bzrdir.open_branch()
429
 
        client.finished_test()
 
621
        self.assertFinished(client)
430
622
 
431
623
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
 
624
        reference_format = self.get_repo_format()
 
625
        network_name = reference_format.network_name()
432
626
        transport = MemoryTransport()
433
627
        transport.mkdir('quack')
434
628
        transport = transport.clone('quack')
442
636
            subtree_response = 'no'
443
637
        client = FakeClient(transport.base)
444
638
        client.add_success_response(
445
 
            'ok', '', rich_response, subtree_response, external_lookup)
446
 
        bzrdir = RemoteBzrDir(transport, _client=client)
 
639
            'ok', '', rich_response, subtree_response, external_lookup,
 
640
            network_name)
 
641
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
642
            _client=client)
447
643
        result = bzrdir.open_repository()
448
644
        self.assertEqual(
449
 
            [('call', 'BzrDir.find_repositoryV2', ('quack/',))],
 
645
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
450
646
            client._calls)
451
647
        self.assertIsInstance(result, RemoteRepository)
452
648
        self.assertEqual(bzrdir, result.bzrdir)
468
664
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
469
665
 
470
666
 
471
 
class TestBzrDirOpenRepository(tests.TestCase):
472
 
 
473
 
    def test_backwards_compat_1_2(self):
474
 
        transport = MemoryTransport()
475
 
        transport.mkdir('quack')
476
 
        transport = transport.clone('quack')
477
 
        client = FakeClient(transport.base)
478
 
        client.add_unknown_method_response('RemoteRepository.find_repositoryV2')
 
667
class TestBzrDirCreateBranch(TestRemote):
 
668
 
 
669
    def test_backwards_compat(self):
 
670
        self.setup_smart_server_with_call_log()
 
671
        repo = self.make_repository('.')
 
672
        self.reset_smart_call_log()
 
673
        self.disable_verb('BzrDir.create_branch')
 
674
        branch = repo.bzrdir.create_branch()
 
675
        create_branch_call_count = len([call for call in self.hpss_calls if
 
676
            call.call.method == 'BzrDir.create_branch'])
 
677
        self.assertEqual(1, create_branch_call_count)
 
678
 
 
679
    def test_current_server(self):
 
680
        transport = self.get_transport('.')
 
681
        transport = transport.clone('quack')
 
682
        self.make_repository('quack')
 
683
        client = FakeClient(transport.base)
 
684
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
685
        reference_format = reference_bzrdir_format.get_branch_format()
 
686
        network_name = reference_format.network_name()
 
687
        reference_repo_fmt = reference_bzrdir_format.repository_format
 
688
        reference_repo_name = reference_repo_fmt.network_name()
 
689
        client.add_expected_call(
 
690
            'BzrDir.create_branch', ('quack/', network_name),
 
691
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
 
692
            reference_repo_name))
 
693
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
694
            _client=client)
 
695
        branch = a_bzrdir.create_branch()
 
696
        # We should have got a remote branch
 
697
        self.assertIsInstance(branch, remote.RemoteBranch)
 
698
        # its format should have the settings from the response
 
699
        format = branch._format
 
700
        self.assertEqual(network_name, format.network_name())
 
701
 
 
702
 
 
703
class TestBzrDirCreateRepository(TestRemote):
 
704
 
 
705
    def test_backwards_compat(self):
 
706
        self.setup_smart_server_with_call_log()
 
707
        bzrdir = self.make_bzrdir('.')
 
708
        self.reset_smart_call_log()
 
709
        self.disable_verb('BzrDir.create_repository')
 
710
        repo = bzrdir.create_repository()
 
711
        create_repo_call_count = len([call for call in self.hpss_calls if
 
712
            call.call.method == 'BzrDir.create_repository'])
 
713
        self.assertEqual(1, create_repo_call_count)
 
714
 
 
715
    def test_current_server(self):
 
716
        transport = self.get_transport('.')
 
717
        transport = transport.clone('quack')
 
718
        self.make_bzrdir('quack')
 
719
        client = FakeClient(transport.base)
 
720
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
721
        reference_format = reference_bzrdir_format.repository_format
 
722
        network_name = reference_format.network_name()
 
723
        client.add_expected_call(
 
724
            'BzrDir.create_repository', ('quack/',
 
725
                'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
 
726
                'False'),
 
727
            'success', ('ok', 'yes', 'yes', 'yes', network_name))
 
728
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
729
            _client=client)
 
730
        repo = a_bzrdir.create_repository()
 
731
        # We should have got a remote repository
 
732
        self.assertIsInstance(repo, remote.RemoteRepository)
 
733
        # its format should have the settings from the response
 
734
        format = repo._format
 
735
        self.assertTrue(format.rich_root_data)
 
736
        self.assertTrue(format.supports_tree_reference)
 
737
        self.assertTrue(format.supports_external_lookups)
 
738
        self.assertEqual(network_name, format.network_name())
 
739
 
 
740
 
 
741
class TestBzrDirOpenRepository(TestRemote):
 
742
 
 
743
    def test_backwards_compat_1_2_3(self):
 
744
        # fallback all the way to the first version.
 
745
        reference_format = self.get_repo_format()
 
746
        network_name = reference_format.network_name()
 
747
        server_url = 'bzr://example.com/'
 
748
        self.permit_url(server_url)
 
749
        client = FakeClient(server_url)
 
750
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
 
751
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
479
752
        client.add_success_response('ok', '', 'no', 'no')
480
 
        bzrdir = RemoteBzrDir(transport, _client=client)
481
 
        repo = bzrdir.open_repository()
482
 
        self.assertEqual(
483
 
            [('call', 'BzrDir.find_repositoryV2', ('quack/',)),
484
 
             ('call', 'BzrDir.find_repository', ('quack/',))],
485
 
            client._calls)
 
753
        # A real repository instance will be created to determine the network
 
754
        # name.
 
755
        client.add_success_response_with_body(
 
756
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
757
        client.add_success_response_with_body(
 
758
            reference_format.get_format_string(), 'ok')
 
759
        # PackRepository wants to do a stat
 
760
        client.add_success_response('stat', '0', '65535')
 
761
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
 
762
            _client=client)
 
763
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
764
            _client=client)
 
765
        repo = bzrdir.open_repository()
 
766
        self.assertEqual(
 
767
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
 
768
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
 
769
             ('call', 'BzrDir.find_repository', ('quack/',)),
 
770
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
771
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
 
772
             ('call', 'stat', ('/quack/.bzr/repository',)),
 
773
             ],
 
774
            client._calls)
 
775
        self.assertEqual(network_name, repo._format.network_name())
 
776
 
 
777
    def test_backwards_compat_2(self):
 
778
        # fallback to find_repositoryV2
 
779
        reference_format = self.get_repo_format()
 
780
        network_name = reference_format.network_name()
 
781
        server_url = 'bzr://example.com/'
 
782
        self.permit_url(server_url)
 
783
        client = FakeClient(server_url)
 
784
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
 
785
        client.add_success_response('ok', '', 'no', 'no', 'no')
 
786
        # A real repository instance will be created to determine the network
 
787
        # name.
 
788
        client.add_success_response_with_body(
 
789
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
790
        client.add_success_response_with_body(
 
791
            reference_format.get_format_string(), 'ok')
 
792
        # PackRepository wants to do a stat
 
793
        client.add_success_response('stat', '0', '65535')
 
794
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
 
795
            _client=client)
 
796
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
797
            _client=client)
 
798
        repo = bzrdir.open_repository()
 
799
        self.assertEqual(
 
800
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
 
801
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
 
802
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
803
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
 
804
             ('call', 'stat', ('/quack/.bzr/repository',)),
 
805
             ],
 
806
            client._calls)
 
807
        self.assertEqual(network_name, repo._format.network_name())
 
808
 
 
809
    def test_current_server(self):
 
810
        reference_format = self.get_repo_format()
 
811
        network_name = reference_format.network_name()
 
812
        transport = MemoryTransport()
 
813
        transport.mkdir('quack')
 
814
        transport = transport.clone('quack')
 
815
        client = FakeClient(transport.base)
 
816
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
 
817
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
818
            _client=client)
 
819
        repo = bzrdir.open_repository()
 
820
        self.assertEqual(
 
821
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
 
822
            client._calls)
 
823
        self.assertEqual(network_name, repo._format.network_name())
 
824
 
 
825
 
 
826
class TestBzrDirFormatInitializeEx(TestRemote):
 
827
 
 
828
    def test_success(self):
 
829
        """Simple test for typical successful call."""
 
830
        fmt = bzrdir.RemoteBzrDirFormat()
 
831
        default_format_name = BzrDirFormat.get_default_format().network_name()
 
832
        transport = self.get_transport()
 
833
        client = FakeClient(transport.base)
 
834
        client.add_expected_call(
 
835
            'BzrDirFormat.initialize_ex_1.16',
 
836
                (default_format_name, 'path', 'False', 'False', 'False', '',
 
837
                 '', '', '', 'False'),
 
838
            'success',
 
839
                ('.', 'no', 'no', 'yes', 'repo fmt', 'repo bzrdir fmt',
 
840
                 'bzrdir fmt', 'False', '', '', 'repo lock token'))
 
841
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
 
842
        # it's currently hard to test that without supplying a real remote
 
843
        # transport connected to a real server.
 
844
        result = fmt._initialize_on_transport_ex_rpc(client, 'path',
 
845
            transport, False, False, False, None, None, None, None, False)
 
846
        self.assertFinished(client)
 
847
 
 
848
    def test_error(self):
 
849
        """Error responses are translated, e.g. 'PermissionDenied' raises the
 
850
        corresponding error from the client.
 
851
        """
 
852
        fmt = bzrdir.RemoteBzrDirFormat()
 
853
        default_format_name = BzrDirFormat.get_default_format().network_name()
 
854
        transport = self.get_transport()
 
855
        client = FakeClient(transport.base)
 
856
        client.add_expected_call(
 
857
            'BzrDirFormat.initialize_ex_1.16',
 
858
                (default_format_name, 'path', 'False', 'False', 'False', '',
 
859
                 '', '', '', 'False'),
 
860
            'error',
 
861
                ('PermissionDenied', 'path', 'extra info'))
 
862
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
 
863
        # it's currently hard to test that without supplying a real remote
 
864
        # transport connected to a real server.
 
865
        err = self.assertRaises(errors.PermissionDenied,
 
866
            fmt._initialize_on_transport_ex_rpc, client, 'path', transport,
 
867
            False, False, False, None, None, None, None, False)
 
868
        self.assertEqual('path', err.path)
 
869
        self.assertEqual(': extra info', err.extra)
 
870
        self.assertFinished(client)
 
871
 
 
872
    def test_error_from_real_server(self):
 
873
        """Integration test for error translation."""
 
874
        transport = self.make_smart_server('foo')
 
875
        transport = transport.clone('no-such-path')
 
876
        fmt = bzrdir.RemoteBzrDirFormat()
 
877
        err = self.assertRaises(errors.NoSuchFile,
 
878
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
486
879
 
487
880
 
488
881
class OldSmartClient(object):
513
906
        return OldSmartClient()
514
907
 
515
908
 
516
 
class RemoteBranchTestCase(tests.TestCase):
 
909
class RemoteBzrDirTestCase(TestRemote):
 
910
 
 
911
    def make_remote_bzrdir(self, transport, client):
 
912
        """Make a RemotebzrDir using 'client' as the _client."""
 
913
        return RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
914
            _client=client)
 
915
 
 
916
 
 
917
class RemoteBranchTestCase(RemoteBzrDirTestCase):
 
918
 
 
919
    def lock_remote_branch(self, branch):
 
920
        """Trick a RemoteBranch into thinking it is locked."""
 
921
        branch._lock_mode = 'w'
 
922
        branch._lock_count = 2
 
923
        branch._lock_token = 'branch token'
 
924
        branch._repo_lock_token = 'repo token'
 
925
        branch.repository._lock_mode = 'w'
 
926
        branch.repository._lock_count = 2
 
927
        branch.repository._lock_token = 'repo token'
517
928
 
518
929
    def make_remote_branch(self, transport, client):
519
930
        """Make a RemoteBranch using 'client' as its _SmartClient.
520
 
        
 
931
 
521
932
        A RemoteBzrDir and RemoteRepository will also be created to fill out
522
933
        the RemoteBranch, albeit with stub values for some of their attributes.
523
934
        """
524
935
        # we do not want bzrdir to make any remote calls, so use False as its
525
936
        # _client.  If it tries to make a remote call, this will fail
526
937
        # immediately.
527
 
        bzrdir = RemoteBzrDir(transport, _client=False)
 
938
        bzrdir = self.make_remote_bzrdir(transport, False)
528
939
        repo = RemoteRepository(bzrdir, None, _client=client)
529
 
        return RemoteBranch(bzrdir, repo, _client=client)
 
940
        branch_format = self.get_branch_format()
 
941
        format = RemoteBranchFormat(network_name=branch_format.network_name())
 
942
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
 
943
 
 
944
 
 
945
class TestBranchGetParent(RemoteBranchTestCase):
 
946
 
 
947
    def test_no_parent(self):
 
948
        # in an empty branch we decode the response properly
 
949
        transport = MemoryTransport()
 
950
        client = FakeClient(transport.base)
 
951
        client.add_expected_call(
 
952
            'Branch.get_stacked_on_url', ('quack/',),
 
953
            'error', ('NotStacked',))
 
954
        client.add_expected_call(
 
955
            'Branch.get_parent', ('quack/',),
 
956
            'success', ('',))
 
957
        transport.mkdir('quack')
 
958
        transport = transport.clone('quack')
 
959
        branch = self.make_remote_branch(transport, client)
 
960
        result = branch.get_parent()
 
961
        self.assertFinished(client)
 
962
        self.assertEqual(None, result)
 
963
 
 
964
    def test_parent_relative(self):
 
965
        transport = MemoryTransport()
 
966
        client = FakeClient(transport.base)
 
967
        client.add_expected_call(
 
968
            'Branch.get_stacked_on_url', ('kwaak/',),
 
969
            'error', ('NotStacked',))
 
970
        client.add_expected_call(
 
971
            'Branch.get_parent', ('kwaak/',),
 
972
            'success', ('../foo/',))
 
973
        transport.mkdir('kwaak')
 
974
        transport = transport.clone('kwaak')
 
975
        branch = self.make_remote_branch(transport, client)
 
976
        result = branch.get_parent()
 
977
        self.assertEqual(transport.clone('../foo').base, result)
 
978
 
 
979
    def test_parent_absolute(self):
 
980
        transport = MemoryTransport()
 
981
        client = FakeClient(transport.base)
 
982
        client.add_expected_call(
 
983
            'Branch.get_stacked_on_url', ('kwaak/',),
 
984
            'error', ('NotStacked',))
 
985
        client.add_expected_call(
 
986
            'Branch.get_parent', ('kwaak/',),
 
987
            'success', ('http://foo/',))
 
988
        transport.mkdir('kwaak')
 
989
        transport = transport.clone('kwaak')
 
990
        branch = self.make_remote_branch(transport, client)
 
991
        result = branch.get_parent()
 
992
        self.assertEqual('http://foo/', result)
 
993
        self.assertFinished(client)
 
994
 
 
995
 
 
996
class TestBranchSetParentLocation(RemoteBranchTestCase):
 
997
 
 
998
    def test_no_parent(self):
 
999
        # We call the verb when setting parent to None
 
1000
        transport = MemoryTransport()
 
1001
        client = FakeClient(transport.base)
 
1002
        client.add_expected_call(
 
1003
            'Branch.get_stacked_on_url', ('quack/',),
 
1004
            'error', ('NotStacked',))
 
1005
        client.add_expected_call(
 
1006
            'Branch.set_parent_location', ('quack/', 'b', 'r', ''),
 
1007
            'success', ())
 
1008
        transport.mkdir('quack')
 
1009
        transport = transport.clone('quack')
 
1010
        branch = self.make_remote_branch(transport, client)
 
1011
        branch._lock_token = 'b'
 
1012
        branch._repo_lock_token = 'r'
 
1013
        branch._set_parent_location(None)
 
1014
        self.assertFinished(client)
 
1015
 
 
1016
    def test_parent(self):
 
1017
        transport = MemoryTransport()
 
1018
        client = FakeClient(transport.base)
 
1019
        client.add_expected_call(
 
1020
            'Branch.get_stacked_on_url', ('kwaak/',),
 
1021
            'error', ('NotStacked',))
 
1022
        client.add_expected_call(
 
1023
            'Branch.set_parent_location', ('kwaak/', 'b', 'r', 'foo'),
 
1024
            'success', ())
 
1025
        transport.mkdir('kwaak')
 
1026
        transport = transport.clone('kwaak')
 
1027
        branch = self.make_remote_branch(transport, client)
 
1028
        branch._lock_token = 'b'
 
1029
        branch._repo_lock_token = 'r'
 
1030
        branch._set_parent_location('foo')
 
1031
        self.assertFinished(client)
 
1032
 
 
1033
    def test_backwards_compat(self):
 
1034
        self.setup_smart_server_with_call_log()
 
1035
        branch = self.make_branch('.')
 
1036
        self.reset_smart_call_log()
 
1037
        verb = 'Branch.set_parent_location'
 
1038
        self.disable_verb(verb)
 
1039
        branch.set_parent('http://foo/')
 
1040
        self.assertLength(12, self.hpss_calls)
 
1041
 
 
1042
 
 
1043
class TestBranchGetTagsBytes(RemoteBranchTestCase):
 
1044
 
 
1045
    def test_backwards_compat(self):
 
1046
        self.setup_smart_server_with_call_log()
 
1047
        branch = self.make_branch('.')
 
1048
        self.reset_smart_call_log()
 
1049
        verb = 'Branch.get_tags_bytes'
 
1050
        self.disable_verb(verb)
 
1051
        branch.tags.get_tag_dict()
 
1052
        call_count = len([call for call in self.hpss_calls if
 
1053
            call.call.method == verb])
 
1054
        self.assertEqual(1, call_count)
 
1055
 
 
1056
    def test_trivial(self):
 
1057
        transport = MemoryTransport()
 
1058
        client = FakeClient(transport.base)
 
1059
        client.add_expected_call(
 
1060
            'Branch.get_stacked_on_url', ('quack/',),
 
1061
            'error', ('NotStacked',))
 
1062
        client.add_expected_call(
 
1063
            'Branch.get_tags_bytes', ('quack/',),
 
1064
            'success', ('',))
 
1065
        transport.mkdir('quack')
 
1066
        transport = transport.clone('quack')
 
1067
        branch = self.make_remote_branch(transport, client)
 
1068
        result = branch.tags.get_tag_dict()
 
1069
        self.assertFinished(client)
 
1070
        self.assertEqual({}, result)
 
1071
 
 
1072
 
 
1073
class TestBranchSetTagsBytes(RemoteBranchTestCase):
 
1074
 
 
1075
    def test_trivial(self):
 
1076
        transport = MemoryTransport()
 
1077
        client = FakeClient(transport.base)
 
1078
        client.add_expected_call(
 
1079
            'Branch.get_stacked_on_url', ('quack/',),
 
1080
            'error', ('NotStacked',))
 
1081
        client.add_expected_call(
 
1082
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
 
1083
            'success', ('',))
 
1084
        transport.mkdir('quack')
 
1085
        transport = transport.clone('quack')
 
1086
        branch = self.make_remote_branch(transport, client)
 
1087
        self.lock_remote_branch(branch)
 
1088
        branch._set_tags_bytes('tags bytes')
 
1089
        self.assertFinished(client)
 
1090
        self.assertEqual('tags bytes', client._calls[-1][-1])
 
1091
 
 
1092
    def test_backwards_compatible(self):
 
1093
        transport = MemoryTransport()
 
1094
        client = FakeClient(transport.base)
 
1095
        client.add_expected_call(
 
1096
            'Branch.get_stacked_on_url', ('quack/',),
 
1097
            'error', ('NotStacked',))
 
1098
        client.add_expected_call(
 
1099
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
 
1100
            'unknown', ('Branch.set_tags_bytes',))
 
1101
        transport.mkdir('quack')
 
1102
        transport = transport.clone('quack')
 
1103
        branch = self.make_remote_branch(transport, client)
 
1104
        self.lock_remote_branch(branch)
 
1105
        class StubRealBranch(object):
 
1106
            def __init__(self):
 
1107
                self.calls = []
 
1108
            def _set_tags_bytes(self, bytes):
 
1109
                self.calls.append(('set_tags_bytes', bytes))
 
1110
        real_branch = StubRealBranch()
 
1111
        branch._real_branch = real_branch
 
1112
        branch._set_tags_bytes('tags bytes')
 
1113
        # Call a second time, to exercise the 'remote version already inferred'
 
1114
        # code path.
 
1115
        branch._set_tags_bytes('tags bytes')
 
1116
        self.assertFinished(client)
 
1117
        self.assertEqual(
 
1118
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
530
1119
 
531
1120
 
532
1121
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
545
1134
        transport = transport.clone('quack')
546
1135
        branch = self.make_remote_branch(transport, client)
547
1136
        result = branch.last_revision_info()
548
 
        client.finished_test()
 
1137
        self.assertFinished(client)
549
1138
        self.assertEqual((0, NULL_REVISION), result)
550
1139
 
551
1140
    def test_non_empty_branch(self):
566
1155
        self.assertEqual((2, revid), result)
567
1156
 
568
1157
 
569
 
class TestBranch_get_stacked_on_url(tests.TestCaseWithMemoryTransport):
 
1158
class TestBranch_get_stacked_on_url(TestRemote):
570
1159
    """Test Branch._get_stacked_on_url rpc"""
571
1160
 
572
1161
    def test_get_stacked_on_invalid_url(self):
573
 
        raise tests.KnownFailure('opening a branch requires the server to open the fallback repository')
574
 
        transport = FakeRemoteTransport('fakeremotetransport:///')
 
1162
        # test that asking for a stacked on url the server can't access works.
 
1163
        # This isn't perfect, but then as we're in the same process there
 
1164
        # really isn't anything we can do to be 100% sure that the server
 
1165
        # doesn't just open in - this test probably needs to be rewritten using
 
1166
        # a spawn()ed server.
 
1167
        stacked_branch = self.make_branch('stacked', format='1.9')
 
1168
        memory_branch = self.make_branch('base', format='1.9')
 
1169
        vfs_url = self.get_vfs_only_url('base')
 
1170
        stacked_branch.set_stacked_on_url(vfs_url)
 
1171
        transport = stacked_branch.bzrdir.root_transport
575
1172
        client = FakeClient(transport.base)
576
1173
        client.add_expected_call(
577
 
            'Branch.get_stacked_on_url', ('.',),
578
 
            'success', ('ok', 'file:///stacked/on'))
579
 
        bzrdir = RemoteBzrDir(transport, _client=client)
580
 
        branch = RemoteBranch(bzrdir, None, _client=client)
 
1174
            'Branch.get_stacked_on_url', ('stacked/',),
 
1175
            'success', ('ok', vfs_url))
 
1176
        # XXX: Multiple calls are bad, this second call documents what is
 
1177
        # today.
 
1178
        client.add_expected_call(
 
1179
            'Branch.get_stacked_on_url', ('stacked/',),
 
1180
            'success', ('ok', vfs_url))
 
1181
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1182
            _client=client)
 
1183
        repo_fmt = remote.RemoteRepositoryFormat()
 
1184
        repo_fmt._custom_format = stacked_branch.repository._format
 
1185
        branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, repo_fmt),
 
1186
            _client=client)
581
1187
        result = branch.get_stacked_on_url()
582
 
        self.assertEqual(
583
 
            'file:///stacked/on', result)
 
1188
        self.assertEqual(vfs_url, result)
584
1189
 
585
1190
    def test_backwards_compatible(self):
586
1191
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
588
1193
        stacked_branch = self.make_branch('stacked', format='1.6')
589
1194
        stacked_branch.set_stacked_on_url('../base')
590
1195
        client = FakeClient(self.get_url())
591
 
        client.add_expected_call(
592
 
            'BzrDir.open_branch', ('stacked/',),
593
 
            'success', ('ok', ''))
594
 
        client.add_expected_call(
595
 
            'BzrDir.find_repositoryV2', ('stacked/',),
596
 
            'success', ('ok', '', 'no', 'no', 'no'))
 
1196
        branch_network_name = self.get_branch_format().network_name()
 
1197
        client.add_expected_call(
 
1198
            'BzrDir.open_branchV3', ('stacked/',),
 
1199
            'success', ('branch', branch_network_name))
 
1200
        client.add_expected_call(
 
1201
            'BzrDir.find_repositoryV3', ('stacked/',),
 
1202
            'success', ('ok', '', 'no', 'no', 'yes',
 
1203
                stacked_branch.repository._format.network_name()))
597
1204
        # called twice, once from constructor and then again by us
598
1205
        client.add_expected_call(
599
1206
            'Branch.get_stacked_on_url', ('stacked/',),
603
1210
            'unknown', ('Branch.get_stacked_on_url',))
604
1211
        # this will also do vfs access, but that goes direct to the transport
605
1212
        # and isn't seen by the FakeClient.
606
 
        bzrdir = RemoteBzrDir(self.get_transport('stacked'), _client=client)
 
1213
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
 
1214
            remote.RemoteBzrDirFormat(), _client=client)
607
1215
        branch = bzrdir.open_branch()
608
1216
        result = branch.get_stacked_on_url()
609
1217
        self.assertEqual('../base', result)
610
 
        client.finished_test()
 
1218
        self.assertFinished(client)
611
1219
        # it's in the fallback list both for the RemoteRepository and its vfs
612
1220
        # repository
613
1221
        self.assertEqual(1, len(branch.repository._fallback_repositories))
618
1226
        base_branch = self.make_branch('base', format='1.6')
619
1227
        stacked_branch = self.make_branch('stacked', format='1.6')
620
1228
        stacked_branch.set_stacked_on_url('../base')
 
1229
        reference_format = self.get_repo_format()
 
1230
        network_name = reference_format.network_name()
621
1231
        client = FakeClient(self.get_url())
622
 
        client.add_expected_call(
623
 
            'BzrDir.open_branch', ('stacked/',),
624
 
            'success', ('ok', ''))
625
 
        client.add_expected_call(
626
 
            'BzrDir.find_repositoryV2', ('stacked/',),
627
 
            'success', ('ok', '', 'no', 'no', 'no'))
 
1232
        branch_network_name = self.get_branch_format().network_name()
 
1233
        client.add_expected_call(
 
1234
            'BzrDir.open_branchV3', ('stacked/',),
 
1235
            'success', ('branch', branch_network_name))
 
1236
        client.add_expected_call(
 
1237
            'BzrDir.find_repositoryV3', ('stacked/',),
 
1238
            'success', ('ok', '', 'no', 'no', 'yes', network_name))
628
1239
        # called twice, once from constructor and then again by us
629
1240
        client.add_expected_call(
630
1241
            'Branch.get_stacked_on_url', ('stacked/',),
632
1243
        client.add_expected_call(
633
1244
            'Branch.get_stacked_on_url', ('stacked/',),
634
1245
            'success', ('ok', '../base'))
635
 
        bzrdir = RemoteBzrDir(self.get_transport('stacked'), _client=client)
 
1246
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
 
1247
            remote.RemoteBzrDirFormat(), _client=client)
636
1248
        branch = bzrdir.open_branch()
637
1249
        result = branch.get_stacked_on_url()
638
1250
        self.assertEqual('../base', result)
639
 
        client.finished_test()
640
 
        # it's in the fallback list both for the RemoteRepository and its vfs
641
 
        # repository
 
1251
        self.assertFinished(client)
 
1252
        # it's in the fallback list both for the RemoteRepository.
642
1253
        self.assertEqual(1, len(branch.repository._fallback_repositories))
643
 
        self.assertEqual(1,
644
 
            len(branch.repository._real_repository._fallback_repositories))
 
1254
        # And we haven't had to construct a real repository.
 
1255
        self.assertEqual(None, branch.repository._real_repository)
645
1256
 
646
1257
 
647
1258
class TestBranchSetLastRevision(RemoteBranchTestCase):
661
1272
            'Branch.lock_write', ('branch/', '', ''),
662
1273
            'success', ('ok', 'branch token', 'repo token'))
663
1274
        client.add_expected_call(
 
1275
            'Branch.last_revision_info',
 
1276
            ('branch/',),
 
1277
            'success', ('ok', '0', 'null:'))
 
1278
        client.add_expected_call(
664
1279
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
665
1280
            'success', ('ok',))
666
1281
        client.add_expected_call(
674
1289
        result = branch.set_revision_history([])
675
1290
        branch.unlock()
676
1291
        self.assertEqual(None, result)
677
 
        client.finished_test()
 
1292
        self.assertFinished(client)
678
1293
 
679
1294
    def test_set_nonempty(self):
680
1295
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
691
1306
            'Branch.lock_write', ('branch/', '', ''),
692
1307
            'success', ('ok', 'branch token', 'repo token'))
693
1308
        client.add_expected_call(
 
1309
            'Branch.last_revision_info',
 
1310
            ('branch/',),
 
1311
            'success', ('ok', '0', 'null:'))
 
1312
        lines = ['rev-id2']
 
1313
        encoded_body = bz2.compress('\n'.join(lines))
 
1314
        client.add_success_response_with_body(encoded_body, 'ok')
 
1315
        client.add_expected_call(
694
1316
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
695
1317
            'success', ('ok',))
696
1318
        client.add_expected_call(
705
1327
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
706
1328
        branch.unlock()
707
1329
        self.assertEqual(None, result)
708
 
        client.finished_test()
 
1330
        self.assertFinished(client)
709
1331
 
710
1332
    def test_no_such_revision(self):
711
1333
        transport = MemoryTransport()
720
1342
            'Branch.lock_write', ('branch/', '', ''),
721
1343
            'success', ('ok', 'branch token', 'repo token'))
722
1344
        client.add_expected_call(
 
1345
            'Branch.last_revision_info',
 
1346
            ('branch/',),
 
1347
            'success', ('ok', '0', 'null:'))
 
1348
        # get_graph calls to construct the revision history, for the set_rh
 
1349
        # hook
 
1350
        lines = ['rev-id']
 
1351
        encoded_body = bz2.compress('\n'.join(lines))
 
1352
        client.add_success_response_with_body(encoded_body, 'ok')
 
1353
        client.add_expected_call(
723
1354
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
724
1355
            'error', ('NoSuchRevision', 'rev-id'))
725
1356
        client.add_expected_call(
731
1362
        self.assertRaises(
732
1363
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
733
1364
        branch.unlock()
734
 
        client.finished_test()
 
1365
        self.assertFinished(client)
735
1366
 
736
1367
    def test_tip_change_rejected(self):
737
1368
        """TipChangeRejected responses cause a TipChangeRejected exception to
750
1381
            'Branch.lock_write', ('branch/', '', ''),
751
1382
            'success', ('ok', 'branch token', 'repo token'))
752
1383
        client.add_expected_call(
 
1384
            'Branch.last_revision_info',
 
1385
            ('branch/',),
 
1386
            'success', ('ok', '0', 'null:'))
 
1387
        lines = ['rev-id']
 
1388
        encoded_body = bz2.compress('\n'.join(lines))
 
1389
        client.add_success_response_with_body(encoded_body, 'ok')
 
1390
        client.add_expected_call(
753
1391
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
754
1392
            'error', ('TipChangeRejected', rejection_msg_utf8))
755
1393
        client.add_expected_call(
758
1396
        branch = self.make_remote_branch(transport, client)
759
1397
        branch._ensure_real = lambda: None
760
1398
        branch.lock_write()
761
 
        self.addCleanup(branch.unlock)
762
1399
        # The 'TipChangeRejected' error response triggered by calling
763
1400
        # set_revision_history causes a TipChangeRejected exception.
764
1401
        err = self.assertRaises(
768
1405
        self.assertIsInstance(err.msg, unicode)
769
1406
        self.assertEqual(rejection_msg_unicode, err.msg)
770
1407
        branch.unlock()
771
 
        client.finished_test()
 
1408
        self.assertFinished(client)
772
1409
 
773
1410
 
774
1411
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
784
1421
        client.add_error_response('NotStacked')
785
1422
        # lock_write
786
1423
        client.add_success_response('ok', 'branch token', 'repo token')
 
1424
        # query the current revision
 
1425
        client.add_success_response('ok', '0', 'null:')
787
1426
        # set_last_revision
788
1427
        client.add_success_response('ok')
789
1428
        # unlock
795
1434
        client._calls = []
796
1435
        result = branch.set_last_revision_info(1234, 'a-revision-id')
797
1436
        self.assertEqual(
798
 
            [('call', 'Branch.set_last_revision_info',
 
1437
            [('call', 'Branch.last_revision_info', ('branch/',)),
 
1438
             ('call', 'Branch.set_last_revision_info',
799
1439
                ('branch/', 'branch token', 'repo token',
800
1440
                 '1234', 'a-revision-id'))],
801
1441
            client._calls)
825
1465
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
826
1466
        branch.unlock()
827
1467
 
828
 
    def lock_remote_branch(self, branch):
829
 
        """Trick a RemoteBranch into thinking it is locked."""
830
 
        branch._lock_mode = 'w'
831
 
        branch._lock_count = 2
832
 
        branch._lock_token = 'branch token'
833
 
        branch._repo_lock_token = 'repo token'
834
 
        branch.repository._lock_mode = 'w'
835
 
        branch.repository._lock_count = 2
836
 
        branch.repository._lock_token = 'repo token'
837
 
 
838
1468
    def test_backwards_compatibility(self):
839
1469
        """If the server does not support the Branch.set_last_revision_info
840
1470
        verb (which is new in 1.4), then the client falls back to VFS methods.
855
1485
            'Branch.get_stacked_on_url', ('branch/',),
856
1486
            'error', ('NotStacked',))
857
1487
        client.add_expected_call(
 
1488
            'Branch.last_revision_info',
 
1489
            ('branch/',),
 
1490
            'success', ('ok', '0', 'null:'))
 
1491
        client.add_expected_call(
858
1492
            'Branch.set_last_revision_info',
859
1493
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
860
1494
            'unknown', 'Branch.set_last_revision_info')
877
1511
        self.assertEqual(
878
1512
            [('set_last_revision_info', 1234, 'a-revision-id')],
879
1513
            real_branch.calls)
880
 
        client.finished_test()
 
1514
        self.assertFinished(client)
881
1515
 
882
1516
    def test_unexpected_error(self):
883
1517
        # If the server sends an error the client doesn't understand, it gets
938
1572
        self.assertEqual('rejection message', err.msg)
939
1573
 
940
1574
 
941
 
class TestBranchControlGetBranchConf(tests.TestCaseWithMemoryTransport):
942
 
    """Getting the branch configuration should use an abstract method not vfs.
943
 
    """
 
1575
class TestBranchGetSetConfig(RemoteBranchTestCase):
944
1576
 
945
1577
    def test_get_branch_conf(self):
946
 
        raise tests.KnownFailure('branch.conf is not retrieved by get_config_file')
947
 
        ## # We should see that branch.get_config() does a single rpc to get the
948
 
        ## # remote configuration file, abstracting away where that is stored on
949
 
        ## # the server.  However at the moment it always falls back to using the
950
 
        ## # vfs, and this would need some changes in config.py.
951
 
 
952
 
        ## # in an empty branch we decode the response properly
953
 
        ## client = FakeClient([(('ok', ), '# config file body')], self.get_url())
954
 
        ## # we need to make a real branch because the remote_branch.control_files
955
 
        ## # will trigger _ensure_real.
956
 
        ## branch = self.make_branch('quack')
957
 
        ## transport = branch.bzrdir.root_transport
958
 
        ## # we do not want bzrdir to make any remote calls
959
 
        ## bzrdir = RemoteBzrDir(transport, _client=False)
960
 
        ## branch = RemoteBranch(bzrdir, None, _client=client)
961
 
        ## config = branch.get_config()
962
 
        ## self.assertEqual(
963
 
        ##     [('call_expecting_body', 'Branch.get_config_file', ('quack/',))],
964
 
        ##     client._calls)
 
1578
        # in an empty branch we decode the response properly
 
1579
        client = FakeClient()
 
1580
        client.add_expected_call(
 
1581
            'Branch.get_stacked_on_url', ('memory:///',),
 
1582
            'error', ('NotStacked',),)
 
1583
        client.add_success_response_with_body('# config file body', 'ok')
 
1584
        transport = MemoryTransport()
 
1585
        branch = self.make_remote_branch(transport, client)
 
1586
        config = branch.get_config()
 
1587
        config.has_explicit_nickname()
 
1588
        self.assertEqual(
 
1589
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
 
1590
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
 
1591
            client._calls)
 
1592
 
 
1593
    def test_get_multi_line_branch_conf(self):
 
1594
        # Make sure that multiple-line branch.conf files are supported
 
1595
        #
 
1596
        # https://bugs.edge.launchpad.net/bzr/+bug/354075
 
1597
        client = FakeClient()
 
1598
        client.add_expected_call(
 
1599
            'Branch.get_stacked_on_url', ('memory:///',),
 
1600
            'error', ('NotStacked',),)
 
1601
        client.add_success_response_with_body('a = 1\nb = 2\nc = 3\n', 'ok')
 
1602
        transport = MemoryTransport()
 
1603
        branch = self.make_remote_branch(transport, client)
 
1604
        config = branch.get_config()
 
1605
        self.assertEqual(u'2', config.get_user_option('b'))
 
1606
 
 
1607
    def test_set_option(self):
 
1608
        client = FakeClient()
 
1609
        client.add_expected_call(
 
1610
            'Branch.get_stacked_on_url', ('memory:///',),
 
1611
            'error', ('NotStacked',),)
 
1612
        client.add_expected_call(
 
1613
            'Branch.lock_write', ('memory:///', '', ''),
 
1614
            'success', ('ok', 'branch token', 'repo token'))
 
1615
        client.add_expected_call(
 
1616
            'Branch.set_config_option', ('memory:///', 'branch token',
 
1617
            'repo token', 'foo', 'bar', ''),
 
1618
            'success', ())
 
1619
        client.add_expected_call(
 
1620
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
 
1621
            'success', ('ok',))
 
1622
        transport = MemoryTransport()
 
1623
        branch = self.make_remote_branch(transport, client)
 
1624
        branch.lock_write()
 
1625
        config = branch._get_config()
 
1626
        config.set_option('foo', 'bar')
 
1627
        branch.unlock()
 
1628
        self.assertFinished(client)
 
1629
 
 
1630
    def test_backwards_compat_set_option(self):
 
1631
        self.setup_smart_server_with_call_log()
 
1632
        branch = self.make_branch('.')
 
1633
        verb = 'Branch.set_config_option'
 
1634
        self.disable_verb(verb)
 
1635
        branch.lock_write()
 
1636
        self.addCleanup(branch.unlock)
 
1637
        self.reset_smart_call_log()
 
1638
        branch._get_config().set_option('value', 'name')
 
1639
        self.assertLength(10, self.hpss_calls)
 
1640
        self.assertEqual('value', branch._get_config().get_option('name'))
965
1641
 
966
1642
 
967
1643
class TestBranchLockWrite(RemoteBranchTestCase):
979
1655
        transport = transport.clone('quack')
980
1656
        branch = self.make_remote_branch(transport, client)
981
1657
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
982
 
        client.finished_test()
 
1658
        self.assertFinished(client)
 
1659
 
 
1660
 
 
1661
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
 
1662
 
 
1663
    def test__get_config(self):
 
1664
        client = FakeClient()
 
1665
        client.add_success_response_with_body('default_stack_on = /\n', 'ok')
 
1666
        transport = MemoryTransport()
 
1667
        bzrdir = self.make_remote_bzrdir(transport, client)
 
1668
        config = bzrdir.get_config()
 
1669
        self.assertEqual('/', config.get_default_stack_on())
 
1670
        self.assertEqual(
 
1671
            [('call_expecting_body', 'BzrDir.get_config_file', ('memory:///',))],
 
1672
            client._calls)
 
1673
 
 
1674
    def test_set_option_uses_vfs(self):
 
1675
        self.setup_smart_server_with_call_log()
 
1676
        bzrdir = self.make_bzrdir('.')
 
1677
        self.reset_smart_call_log()
 
1678
        config = bzrdir.get_config()
 
1679
        config.set_default_stack_on('/')
 
1680
        self.assertLength(3, self.hpss_calls)
 
1681
 
 
1682
    def test_backwards_compat_get_option(self):
 
1683
        self.setup_smart_server_with_call_log()
 
1684
        bzrdir = self.make_bzrdir('.')
 
1685
        verb = 'BzrDir.get_config_file'
 
1686
        self.disable_verb(verb)
 
1687
        self.reset_smart_call_log()
 
1688
        self.assertEqual(None,
 
1689
            bzrdir._get_config().get_option('default_stack_on'))
 
1690
        self.assertLength(3, self.hpss_calls)
983
1691
 
984
1692
 
985
1693
class TestTransportIsReadonly(tests.TestCase):
1006
1714
 
1007
1715
    def test_error_from_old_server(self):
1008
1716
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
1009
 
        
 
1717
 
1010
1718
        Clients should treat it as a "no" response, because is_readonly is only
1011
1719
        advisory anyway (a transport could be read-write, but then the
1012
1720
        underlying filesystem could be readonly anyway).
1050
1758
        self.assertEqual('bar', t._get_credentials()[0])
1051
1759
 
1052
1760
 
1053
 
class TestRemoteRepository(tests.TestCase):
 
1761
class TestRemoteRepository(TestRemote):
1054
1762
    """Base for testing RemoteRepository protocol usage.
1055
 
    
1056
 
    These tests contain frozen requests and responses.  We want any changes to 
 
1763
 
 
1764
    These tests contain frozen requests and responses.  We want any changes to
1057
1765
    what is sent or expected to be require a thoughtful update to these tests
1058
1766
    because they might break compatibility with different-versioned servers.
1059
1767
    """
1060
1768
 
1061
1769
    def setup_fake_client_and_repository(self, transport_path):
1062
1770
        """Create the fake client and repository for testing with.
1063
 
        
 
1771
 
1064
1772
        There's no real server here; we just have canned responses sent
1065
1773
        back one by one.
1066
 
        
 
1774
 
1067
1775
        :param transport_path: Path below the root of the MemoryTransport
1068
1776
            where the repository will be created.
1069
1777
        """
1072
1780
        client = FakeClient(transport.base)
1073
1781
        transport = transport.clone(transport_path)
1074
1782
        # we do not want bzrdir to make any remote calls
1075
 
        bzrdir = RemoteBzrDir(transport, _client=False)
 
1783
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1784
            _client=False)
1076
1785
        repo = RemoteRepository(bzrdir, None, _client=client)
1077
1786
        return repo, client
1078
1787
 
1079
1788
 
 
1789
def remoted_description(format):
 
1790
    return 'Remote: ' + format.get_format_description()
 
1791
 
 
1792
 
 
1793
class TestBranchFormat(tests.TestCase):
 
1794
 
 
1795
    def test_get_format_description(self):
 
1796
        remote_format = RemoteBranchFormat()
 
1797
        real_format = branch.BranchFormat.get_default_format()
 
1798
        remote_format._network_name = real_format.network_name()
 
1799
        self.assertEqual(remoted_description(real_format),
 
1800
            remote_format.get_format_description())
 
1801
 
 
1802
 
 
1803
class TestRepositoryFormat(TestRemoteRepository):
 
1804
 
 
1805
    def test_fast_delta(self):
 
1806
        true_name = groupcompress_repo.RepositoryFormatCHK1().network_name()
 
1807
        true_format = RemoteRepositoryFormat()
 
1808
        true_format._network_name = true_name
 
1809
        self.assertEqual(True, true_format.fast_deltas)
 
1810
        false_name = pack_repo.RepositoryFormatKnitPack1().network_name()
 
1811
        false_format = RemoteRepositoryFormat()
 
1812
        false_format._network_name = false_name
 
1813
        self.assertEqual(False, false_format.fast_deltas)
 
1814
 
 
1815
    def test_get_format_description(self):
 
1816
        remote_repo_format = RemoteRepositoryFormat()
 
1817
        real_format = repository.RepositoryFormat.get_default_format()
 
1818
        remote_repo_format._network_name = real_format.network_name()
 
1819
        self.assertEqual(remoted_description(real_format),
 
1820
            remote_repo_format.get_format_description())
 
1821
 
 
1822
 
1080
1823
class TestRepositoryGatherStats(TestRemoteRepository):
1081
1824
 
1082
1825
    def test_revid_none(self):
1170
1913
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
1171
1914
        self.assertEqual(
1172
1915
            [('call_with_body_bytes_expecting_body',
1173
 
              'Repository.get_parent_map', ('quack/', r2), '\n\n0')],
 
1916
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
 
1917
              '\n\n0')],
1174
1918
            client._calls)
1175
1919
        repo.unlock()
1176
1920
        # now we call again, and it should use the second response.
1180
1924
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
1181
1925
        self.assertEqual(
1182
1926
            [('call_with_body_bytes_expecting_body',
1183
 
              'Repository.get_parent_map', ('quack/', r2), '\n\n0'),
 
1927
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
 
1928
              '\n\n0'),
1184
1929
             ('call_with_body_bytes_expecting_body',
1185
 
              'Repository.get_parent_map', ('quack/', r1), '\n\n0'),
 
1930
              'Repository.get_parent_map', ('quack/', 'include-missing:', r1),
 
1931
              '\n\n0'),
1186
1932
            ],
1187
1933
            client._calls)
1188
1934
        repo.unlock()
1189
1935
 
1190
1936
    def test_get_parent_map_reconnects_if_unknown_method(self):
1191
1937
        transport_path = 'quack'
 
1938
        rev_id = 'revision-id'
1192
1939
        repo, client = self.setup_fake_client_and_repository(transport_path)
1193
 
        client.add_unknown_method_response('Repository,get_parent_map')
1194
 
        client.add_success_response_with_body('', 'ok')
 
1940
        client.add_unknown_method_response('Repository.get_parent_map')
 
1941
        client.add_success_response_with_body(rev_id, 'ok')
1195
1942
        self.assertFalse(client._medium._is_remote_before((1, 2)))
1196
 
        rev_id = 'revision-id'
1197
 
        expected_deprecations = [
1198
 
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1199
 
            'in version 1.4.']
1200
 
        parents = self.callDeprecated(
1201
 
            expected_deprecations, repo.get_parent_map, [rev_id])
 
1943
        parents = repo.get_parent_map([rev_id])
1202
1944
        self.assertEqual(
1203
1945
            [('call_with_body_bytes_expecting_body',
1204
 
              'Repository.get_parent_map', ('quack/', rev_id), '\n\n0'),
 
1946
              'Repository.get_parent_map', ('quack/', 'include-missing:',
 
1947
              rev_id), '\n\n0'),
1205
1948
             ('disconnect medium',),
1206
1949
             ('call_expecting_body', 'Repository.get_revision_graph',
1207
1950
              ('quack/', ''))],
1208
1951
            client._calls)
1209
1952
        # The medium is now marked as being connected to an older server
1210
1953
        self.assertTrue(client._medium._is_remote_before((1, 2)))
 
1954
        self.assertEqual({rev_id: ('null:',)}, parents)
1211
1955
 
1212
1956
    def test_get_parent_map_fallback_parentless_node(self):
1213
1957
        """get_parent_map falls back to get_revision_graph on old servers.  The
1225
1969
        repo, client = self.setup_fake_client_and_repository(transport_path)
1226
1970
        client.add_success_response_with_body(rev_id, 'ok')
1227
1971
        client._medium._remember_remote_is_before((1, 2))
1228
 
        expected_deprecations = [
1229
 
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1230
 
            'in version 1.4.']
1231
 
        parents = self.callDeprecated(
1232
 
            expected_deprecations, repo.get_parent_map, [rev_id])
 
1972
        parents = repo.get_parent_map([rev_id])
1233
1973
        self.assertEqual(
1234
1974
            [('call_expecting_body', 'Repository.get_revision_graph',
1235
1975
             ('quack/', ''))],
1243
1983
            errors.UnexpectedSmartServerResponse,
1244
1984
            repo.get_parent_map, ['a-revision-id'])
1245
1985
 
 
1986
    def test_get_parent_map_negative_caches_missing_keys(self):
 
1987
        self.setup_smart_server_with_call_log()
 
1988
        repo = self.make_repository('foo')
 
1989
        self.assertIsInstance(repo, RemoteRepository)
 
1990
        repo.lock_read()
 
1991
        self.addCleanup(repo.unlock)
 
1992
        self.reset_smart_call_log()
 
1993
        graph = repo.get_graph()
 
1994
        self.assertEqual({},
 
1995
            graph.get_parent_map(['some-missing', 'other-missing']))
 
1996
        self.assertLength(1, self.hpss_calls)
 
1997
        # No call if we repeat this
 
1998
        self.reset_smart_call_log()
 
1999
        graph = repo.get_graph()
 
2000
        self.assertEqual({},
 
2001
            graph.get_parent_map(['some-missing', 'other-missing']))
 
2002
        self.assertLength(0, self.hpss_calls)
 
2003
        # Asking for more unknown keys makes a request.
 
2004
        self.reset_smart_call_log()
 
2005
        graph = repo.get_graph()
 
2006
        self.assertEqual({},
 
2007
            graph.get_parent_map(['some-missing', 'other-missing',
 
2008
                'more-missing']))
 
2009
        self.assertLength(1, self.hpss_calls)
 
2010
 
 
2011
    def disableExtraResults(self):
 
2012
        self.overrideAttr(SmartServerRepositoryGetParentMap,
 
2013
                          'no_extra_results', True)
 
2014
 
 
2015
    def test_null_cached_missing_and_stop_key(self):
 
2016
        self.setup_smart_server_with_call_log()
 
2017
        # Make a branch with a single revision.
 
2018
        builder = self.make_branch_builder('foo')
 
2019
        builder.start_series()
 
2020
        builder.build_snapshot('first', None, [
 
2021
            ('add', ('', 'root-id', 'directory', ''))])
 
2022
        builder.finish_series()
 
2023
        branch = builder.get_branch()
 
2024
        repo = branch.repository
 
2025
        self.assertIsInstance(repo, RemoteRepository)
 
2026
        # Stop the server from sending extra results.
 
2027
        self.disableExtraResults()
 
2028
        repo.lock_read()
 
2029
        self.addCleanup(repo.unlock)
 
2030
        self.reset_smart_call_log()
 
2031
        graph = repo.get_graph()
 
2032
        # Query for 'first' and 'null:'.  Because 'null:' is a parent of
 
2033
        # 'first' it will be a candidate for the stop_keys of subsequent
 
2034
        # requests, and because 'null:' was queried but not returned it will be
 
2035
        # cached as missing.
 
2036
        self.assertEqual({'first': ('null:',)},
 
2037
            graph.get_parent_map(['first', 'null:']))
 
2038
        # Now query for another key.  This request will pass along a recipe of
 
2039
        # start and stop keys describing the already cached results, and this
 
2040
        # recipe's revision count must be correct (or else it will trigger an
 
2041
        # error from the server).
 
2042
        self.assertEqual({}, graph.get_parent_map(['another-key']))
 
2043
        # This assertion guards against disableExtraResults silently failing to
 
2044
        # work, thus invalidating the test.
 
2045
        self.assertLength(2, self.hpss_calls)
 
2046
 
 
2047
    def test_get_parent_map_gets_ghosts_from_result(self):
 
2048
        # asking for a revision should negatively cache close ghosts in its
 
2049
        # ancestry.
 
2050
        self.setup_smart_server_with_call_log()
 
2051
        tree = self.make_branch_and_memory_tree('foo')
 
2052
        tree.lock_write()
 
2053
        try:
 
2054
            builder = treebuilder.TreeBuilder()
 
2055
            builder.start_tree(tree)
 
2056
            builder.build([])
 
2057
            builder.finish_tree()
 
2058
            tree.set_parent_ids(['non-existant'], allow_leftmost_as_ghost=True)
 
2059
            rev_id = tree.commit('')
 
2060
        finally:
 
2061
            tree.unlock()
 
2062
        tree.lock_read()
 
2063
        self.addCleanup(tree.unlock)
 
2064
        repo = tree.branch.repository
 
2065
        self.assertIsInstance(repo, RemoteRepository)
 
2066
        # ask for rev_id
 
2067
        repo.get_parent_map([rev_id])
 
2068
        self.reset_smart_call_log()
 
2069
        # Now asking for rev_id's ghost parent should not make calls
 
2070
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
 
2071
        self.assertLength(0, self.hpss_calls)
 
2072
 
1246
2073
 
1247
2074
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
1248
2075
 
1249
2076
    def test_allows_new_revisions(self):
1250
2077
        """get_parent_map's results can be updated by commit."""
1251
 
        smart_server = server.SmartTCPServer_for_testing()
1252
 
        smart_server.setUp()
1253
 
        self.addCleanup(smart_server.tearDown)
 
2078
        smart_server = test_server.SmartTCPServer_for_testing()
 
2079
        self.start_server(smart_server)
1254
2080
        self.make_branch('branch')
1255
2081
        branch = Branch.open(smart_server.get_url() + '/branch')
1256
2082
        tree = branch.create_checkout('tree', lightweight=True)
1265
2091
 
1266
2092
 
1267
2093
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
1268
 
    
 
2094
 
1269
2095
    def test_null_revision(self):
1270
2096
        # a null revision has the predictable result {}, we should have no wire
1271
2097
        # traffic when calling it with this argument
1272
2098
        transport_path = 'empty'
1273
2099
        repo, client = self.setup_fake_client_and_repository(transport_path)
1274
2100
        client.add_success_response('notused')
1275
 
        result = self.applyDeprecated(one_four, repo.get_revision_graph,
1276
 
            NULL_REVISION)
 
2101
        # actual RemoteRepository.get_revision_graph is gone, but there's an
 
2102
        # equivalent private method for testing
 
2103
        result = repo._get_revision_graph(NULL_REVISION)
1277
2104
        self.assertEqual([], client._calls)
1278
2105
        self.assertEqual({}, result)
1279
2106
 
1287
2114
        transport_path = 'sinhala'
1288
2115
        repo, client = self.setup_fake_client_and_repository(transport_path)
1289
2116
        client.add_success_response_with_body(encoded_body, 'ok')
1290
 
        result = self.applyDeprecated(one_four, repo.get_revision_graph)
 
2117
        # actual RemoteRepository.get_revision_graph is gone, but there's an
 
2118
        # equivalent private method for testing
 
2119
        result = repo._get_revision_graph(None)
1291
2120
        self.assertEqual(
1292
2121
            [('call_expecting_body', 'Repository.get_revision_graph',
1293
2122
             ('sinhala/', ''))],
1306
2135
        transport_path = 'sinhala'
1307
2136
        repo, client = self.setup_fake_client_and_repository(transport_path)
1308
2137
        client.add_success_response_with_body(encoded_body, 'ok')
1309
 
        result = self.applyDeprecated(one_four, repo.get_revision_graph, r2)
 
2138
        result = repo._get_revision_graph(r2)
1310
2139
        self.assertEqual(
1311
2140
            [('call_expecting_body', 'Repository.get_revision_graph',
1312
2141
             ('sinhala/', r2))],
1320
2149
        client.add_error_response('nosuchrevision', revid)
1321
2150
        # also check that the right revision is reported in the error
1322
2151
        self.assertRaises(errors.NoSuchRevision,
1323
 
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
 
2152
            repo._get_revision_graph, revid)
1324
2153
        self.assertEqual(
1325
2154
            [('call_expecting_body', 'Repository.get_revision_graph',
1326
2155
             ('sinhala/', revid))],
1332
2161
        repo, client = self.setup_fake_client_and_repository(transport_path)
1333
2162
        client.add_error_response('AnUnexpectedError')
1334
2163
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
1335
 
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
 
2164
            repo._get_revision_graph, revid)
1336
2165
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
1337
2166
 
1338
 
        
 
2167
 
 
2168
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
 
2169
 
 
2170
    def test_ok(self):
 
2171
        repo, client = self.setup_fake_client_and_repository('quack')
 
2172
        client.add_expected_call(
 
2173
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2174
            'success', ('ok', 'rev-five'))
 
2175
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
 
2176
        self.assertEqual((True, 'rev-five'), result)
 
2177
        self.assertFinished(client)
 
2178
 
 
2179
    def test_history_incomplete(self):
 
2180
        repo, client = self.setup_fake_client_and_repository('quack')
 
2181
        client.add_expected_call(
 
2182
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2183
            'success', ('history-incomplete', 10, 'rev-ten'))
 
2184
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
 
2185
        self.assertEqual((False, (10, 'rev-ten')), result)
 
2186
        self.assertFinished(client)
 
2187
 
 
2188
    def test_history_incomplete_with_fallback(self):
 
2189
        """A 'history-incomplete' response causes the fallback repository to be
 
2190
        queried too, if one is set.
 
2191
        """
 
2192
        # Make a repo with a fallback repo, both using a FakeClient.
 
2193
        format = remote.response_tuple_to_repo_format(
 
2194
            ('yes', 'no', 'yes', 'fake-network-name'))
 
2195
        repo, client = self.setup_fake_client_and_repository('quack')
 
2196
        repo._format = format
 
2197
        fallback_repo, ignored = self.setup_fake_client_and_repository(
 
2198
            'fallback')
 
2199
        fallback_repo._client = client
 
2200
        repo.add_fallback_repository(fallback_repo)
 
2201
        # First the client should ask the primary repo
 
2202
        client.add_expected_call(
 
2203
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
 
2204
            'success', ('history-incomplete', 2, 'rev-two'))
 
2205
        # Then it should ask the fallback, using revno/revid from the
 
2206
        # history-incomplete response as the known revno/revid.
 
2207
        client.add_expected_call(
 
2208
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
 
2209
            'success', ('ok', 'rev-one'))
 
2210
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
 
2211
        self.assertEqual((True, 'rev-one'), result)
 
2212
        self.assertFinished(client)
 
2213
 
 
2214
    def test_nosuchrevision(self):
 
2215
        # 'nosuchrevision' is returned when the known-revid is not found in the
 
2216
        # remote repo.  The client translates that response to NoSuchRevision.
 
2217
        repo, client = self.setup_fake_client_and_repository('quack')
 
2218
        client.add_expected_call(
 
2219
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
 
2220
            'error', ('nosuchrevision', 'rev-foo'))
 
2221
        self.assertRaises(
 
2222
            errors.NoSuchRevision,
 
2223
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
 
2224
        self.assertFinished(client)
 
2225
 
 
2226
    def test_branch_fallback_locking(self):
 
2227
        """RemoteBranch.get_rev_id takes a read lock, and tries to call the
 
2228
        get_rev_id_for_revno verb.  If the verb is unknown the VFS fallback
 
2229
        will be invoked, which will fail if the repo is unlocked.
 
2230
        """
 
2231
        self.setup_smart_server_with_call_log()
 
2232
        tree = self.make_branch_and_memory_tree('.')
 
2233
        tree.lock_write()
 
2234
        rev1 = tree.commit('First')
 
2235
        rev2 = tree.commit('Second')
 
2236
        tree.unlock()
 
2237
        branch = tree.branch
 
2238
        self.assertFalse(branch.is_locked())
 
2239
        self.reset_smart_call_log()
 
2240
        verb = 'Repository.get_rev_id_for_revno'
 
2241
        self.disable_verb(verb)
 
2242
        self.assertEqual(rev1, branch.get_rev_id(1))
 
2243
        self.assertLength(1, [call for call in self.hpss_calls if
 
2244
                              call.call.method == verb])
 
2245
 
 
2246
 
1339
2247
class TestRepositoryIsShared(TestRemoteRepository):
1340
2248
 
1341
2249
    def test_is_shared(self):
1392
2300
            client._calls)
1393
2301
 
1394
2302
 
 
2303
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
 
2304
 
 
2305
    def test_backwards_compat(self):
 
2306
        self.setup_smart_server_with_call_log()
 
2307
        repo = self.make_repository('.')
 
2308
        self.reset_smart_call_log()
 
2309
        verb = 'Repository.set_make_working_trees'
 
2310
        self.disable_verb(verb)
 
2311
        repo.set_make_working_trees(True)
 
2312
        call_count = len([call for call in self.hpss_calls if
 
2313
            call.call.method == verb])
 
2314
        self.assertEqual(1, call_count)
 
2315
 
 
2316
    def test_current(self):
 
2317
        transport_path = 'quack'
 
2318
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2319
        client.add_expected_call(
 
2320
            'Repository.set_make_working_trees', ('quack/', 'True'),
 
2321
            'success', ('ok',))
 
2322
        client.add_expected_call(
 
2323
            'Repository.set_make_working_trees', ('quack/', 'False'),
 
2324
            'success', ('ok',))
 
2325
        repo.set_make_working_trees(True)
 
2326
        repo.set_make_working_trees(False)
 
2327
 
 
2328
 
1395
2329
class TestRepositoryUnlock(TestRemoteRepository):
1396
2330
 
1397
2331
    def test_unlock(self):
1430
2364
        self.assertEqual([], client._calls)
1431
2365
 
1432
2366
 
 
2367
class TestRepositoryInsertStreamBase(TestRemoteRepository):
 
2368
    """Base class for Repository.insert_stream and .insert_stream_1.19
 
2369
    tests.
 
2370
    """
 
2371
    
 
2372
    def checkInsertEmptyStream(self, repo, client):
 
2373
        """Insert an empty stream, checking the result.
 
2374
 
 
2375
        This checks that there are no resume_tokens or missing_keys, and that
 
2376
        the client is finished.
 
2377
        """
 
2378
        sink = repo._get_sink()
 
2379
        fmt = repository.RepositoryFormat.get_default_format()
 
2380
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
 
2381
        self.assertEqual([], resume_tokens)
 
2382
        self.assertEqual(set(), missing_keys)
 
2383
        self.assertFinished(client)
 
2384
 
 
2385
 
 
2386
class TestRepositoryInsertStream(TestRepositoryInsertStreamBase):
 
2387
    """Tests for using Repository.insert_stream verb when the _1.19 variant is
 
2388
    not available.
 
2389
 
 
2390
    This test case is very similar to TestRepositoryInsertStream_1_19.
 
2391
    """
 
2392
 
 
2393
    def setUp(self):
 
2394
        TestRemoteRepository.setUp(self)
 
2395
        self.disable_verb('Repository.insert_stream_1.19')
 
2396
 
 
2397
    def test_unlocked_repo(self):
 
2398
        transport_path = 'quack'
 
2399
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2400
        client.add_expected_call(
 
2401
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2402
            'unknown', ('Repository.insert_stream_1.19',))
 
2403
        client.add_expected_call(
 
2404
            'Repository.insert_stream', ('quack/', ''),
 
2405
            'success', ('ok',))
 
2406
        client.add_expected_call(
 
2407
            'Repository.insert_stream', ('quack/', ''),
 
2408
            'success', ('ok',))
 
2409
        self.checkInsertEmptyStream(repo, client)
 
2410
 
 
2411
    def test_locked_repo_with_no_lock_token(self):
 
2412
        transport_path = 'quack'
 
2413
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2414
        client.add_expected_call(
 
2415
            'Repository.lock_write', ('quack/', ''),
 
2416
            'success', ('ok', ''))
 
2417
        client.add_expected_call(
 
2418
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2419
            'unknown', ('Repository.insert_stream_1.19',))
 
2420
        client.add_expected_call(
 
2421
            'Repository.insert_stream', ('quack/', ''),
 
2422
            'success', ('ok',))
 
2423
        client.add_expected_call(
 
2424
            'Repository.insert_stream', ('quack/', ''),
 
2425
            'success', ('ok',))
 
2426
        repo.lock_write()
 
2427
        self.checkInsertEmptyStream(repo, client)
 
2428
 
 
2429
    def test_locked_repo_with_lock_token(self):
 
2430
        transport_path = 'quack'
 
2431
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2432
        client.add_expected_call(
 
2433
            'Repository.lock_write', ('quack/', ''),
 
2434
            'success', ('ok', 'a token'))
 
2435
        client.add_expected_call(
 
2436
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2437
            'unknown', ('Repository.insert_stream_1.19',))
 
2438
        client.add_expected_call(
 
2439
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2440
            'success', ('ok',))
 
2441
        client.add_expected_call(
 
2442
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2443
            'success', ('ok',))
 
2444
        repo.lock_write()
 
2445
        self.checkInsertEmptyStream(repo, client)
 
2446
 
 
2447
    def test_stream_with_inventory_deltas(self):
 
2448
        """'inventory-deltas' substreams cannot be sent to the
 
2449
        Repository.insert_stream verb, because not all servers that implement
 
2450
        that verb will accept them.  So when one is encountered the RemoteSink
 
2451
        immediately stops using that verb and falls back to VFS insert_stream.
 
2452
        """
 
2453
        transport_path = 'quack'
 
2454
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2455
        client.add_expected_call(
 
2456
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2457
            'unknown', ('Repository.insert_stream_1.19',))
 
2458
        client.add_expected_call(
 
2459
            'Repository.insert_stream', ('quack/', ''),
 
2460
            'success', ('ok',))
 
2461
        client.add_expected_call(
 
2462
            'Repository.insert_stream', ('quack/', ''),
 
2463
            'success', ('ok',))
 
2464
        # Create a fake real repository for insert_stream to fall back on, so
 
2465
        # that we can directly see the records the RemoteSink passes to the
 
2466
        # real sink.
 
2467
        class FakeRealSink:
 
2468
            def __init__(self):
 
2469
                self.records = []
 
2470
            def insert_stream(self, stream, src_format, resume_tokens):
 
2471
                for substream_kind, substream in stream:
 
2472
                    self.records.append(
 
2473
                        (substream_kind, [record.key for record in substream]))
 
2474
                return ['fake tokens'], ['fake missing keys']
 
2475
        fake_real_sink = FakeRealSink()
 
2476
        class FakeRealRepository:
 
2477
            def _get_sink(self):
 
2478
                return fake_real_sink
 
2479
            def is_in_write_group(self):
 
2480
                return False
 
2481
            def refresh_data(self):
 
2482
                return True
 
2483
        repo._real_repository = FakeRealRepository()
 
2484
        sink = repo._get_sink()
 
2485
        fmt = repository.RepositoryFormat.get_default_format()
 
2486
        stream = self.make_stream_with_inv_deltas(fmt)
 
2487
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
 
2488
        # Every record from the first inventory delta should have been sent to
 
2489
        # the VFS sink.
 
2490
        expected_records = [
 
2491
            ('inventory-deltas', [('rev2',), ('rev3',)]),
 
2492
            ('texts', [('some-rev', 'some-file')])]
 
2493
        self.assertEqual(expected_records, fake_real_sink.records)
 
2494
        # The return values from the real sink's insert_stream are propagated
 
2495
        # back to the original caller.
 
2496
        self.assertEqual(['fake tokens'], resume_tokens)
 
2497
        self.assertEqual(['fake missing keys'], missing_keys)
 
2498
        self.assertFinished(client)
 
2499
 
 
2500
    def make_stream_with_inv_deltas(self, fmt):
 
2501
        """Make a simple stream with an inventory delta followed by more
 
2502
        records and more substreams to test that all records and substreams
 
2503
        from that point on are used.
 
2504
 
 
2505
        This sends, in order:
 
2506
           * inventories substream: rev1, rev2, rev3.  rev2 and rev3 are
 
2507
             inventory-deltas.
 
2508
           * texts substream: (some-rev, some-file)
 
2509
        """
 
2510
        # Define a stream using generators so that it isn't rewindable.
 
2511
        inv = inventory.Inventory(revision_id='rev1')
 
2512
        inv.root.revision = 'rev1'
 
2513
        def stream_with_inv_delta():
 
2514
            yield ('inventories', inventories_substream())
 
2515
            yield ('inventory-deltas', inventory_delta_substream())
 
2516
            yield ('texts', [
 
2517
                versionedfile.FulltextContentFactory(
 
2518
                    ('some-rev', 'some-file'), (), None, 'content')])
 
2519
        def inventories_substream():
 
2520
            # An empty inventory fulltext.  This will be streamed normally.
 
2521
            text = fmt._serializer.write_inventory_to_string(inv)
 
2522
            yield versionedfile.FulltextContentFactory(
 
2523
                ('rev1',), (), None, text)
 
2524
        def inventory_delta_substream():
 
2525
            # An inventory delta.  This can't be streamed via this verb, so it
 
2526
            # will trigger a fallback to VFS insert_stream.
 
2527
            entry = inv.make_entry(
 
2528
                'directory', 'newdir', inv.root.file_id, 'newdir-id')
 
2529
            entry.revision = 'ghost'
 
2530
            delta = [(None, 'newdir', 'newdir-id', entry)]
 
2531
            serializer = inventory_delta.InventoryDeltaSerializer(
 
2532
                versioned_root=True, tree_references=False)
 
2533
            lines = serializer.delta_to_lines('rev1', 'rev2', delta)
 
2534
            yield versionedfile.ChunkedContentFactory(
 
2535
                ('rev2',), (('rev1',)), None, lines)
 
2536
            # Another delta.
 
2537
            lines = serializer.delta_to_lines('rev1', 'rev3', delta)
 
2538
            yield versionedfile.ChunkedContentFactory(
 
2539
                ('rev3',), (('rev1',)), None, lines)
 
2540
        return stream_with_inv_delta()
 
2541
 
 
2542
 
 
2543
class TestRepositoryInsertStream_1_19(TestRepositoryInsertStreamBase):
 
2544
 
 
2545
    def test_unlocked_repo(self):
 
2546
        transport_path = 'quack'
 
2547
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2548
        client.add_expected_call(
 
2549
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2550
            'success', ('ok',))
 
2551
        client.add_expected_call(
 
2552
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2553
            'success', ('ok',))
 
2554
        self.checkInsertEmptyStream(repo, client)
 
2555
 
 
2556
    def test_locked_repo_with_no_lock_token(self):
 
2557
        transport_path = 'quack'
 
2558
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2559
        client.add_expected_call(
 
2560
            'Repository.lock_write', ('quack/', ''),
 
2561
            'success', ('ok', ''))
 
2562
        client.add_expected_call(
 
2563
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2564
            'success', ('ok',))
 
2565
        client.add_expected_call(
 
2566
            'Repository.insert_stream_1.19', ('quack/', ''),
 
2567
            'success', ('ok',))
 
2568
        repo.lock_write()
 
2569
        self.checkInsertEmptyStream(repo, client)
 
2570
 
 
2571
    def test_locked_repo_with_lock_token(self):
 
2572
        transport_path = 'quack'
 
2573
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2574
        client.add_expected_call(
 
2575
            'Repository.lock_write', ('quack/', ''),
 
2576
            'success', ('ok', 'a token'))
 
2577
        client.add_expected_call(
 
2578
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2579
            'success', ('ok',))
 
2580
        client.add_expected_call(
 
2581
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
 
2582
            'success', ('ok',))
 
2583
        repo.lock_write()
 
2584
        self.checkInsertEmptyStream(repo, client)
 
2585
 
 
2586
 
1433
2587
class TestRepositoryTarball(TestRemoteRepository):
1434
2588
 
1435
2589
    # This is a canned tarball reponse we can validate against
1469
2623
    """RemoteRepository.copy_content_into optimizations"""
1470
2624
 
1471
2625
    def test_copy_content_remote_to_local(self):
1472
 
        self.transport_server = server.SmartTCPServer_for_testing
 
2626
        self.transport_server = test_server.SmartTCPServer_for_testing
1473
2627
        src_repo = self.make_repository('repo1')
1474
2628
        src_repo = repository.Repository.open(self.get_url('repo1'))
1475
2629
        # At the moment the tarball-based copy_content_into can't write back
1487
2641
class _StubRealPackRepository(object):
1488
2642
 
1489
2643
    def __init__(self, calls):
 
2644
        self.calls = calls
1490
2645
        self._pack_collection = _StubPackCollection(calls)
1491
2646
 
 
2647
    def is_in_write_group(self):
 
2648
        return False
 
2649
 
 
2650
    def refresh_data(self):
 
2651
        self.calls.append(('pack collection reload_pack_names',))
 
2652
 
1492
2653
 
1493
2654
class _StubPackCollection(object):
1494
2655
 
1498
2659
    def autopack(self):
1499
2660
        self.calls.append(('pack collection autopack',))
1500
2661
 
1501
 
    def reload_pack_names(self):
1502
 
        self.calls.append(('pack collection reload_pack_names',))
1503
2662
 
1504
 
    
1505
2663
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
1506
2664
    """Tests for RemoteRepository.autopack implementation."""
1507
2665
 
1514
2672
        client.add_expected_call(
1515
2673
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
1516
2674
        repo.autopack()
1517
 
        client.finished_test()
 
2675
        self.assertFinished(client)
1518
2676
 
1519
2677
    def test_ok_with_real_repo(self):
1520
2678
        """When the server returns 'ok' and there is a _real_repository, then
1531
2689
            [('call', 'PackRepository.autopack', ('quack/',)),
1532
2690
             ('pack collection reload_pack_names',)],
1533
2691
            client._calls)
1534
 
        
 
2692
 
1535
2693
    def test_backwards_compatibility(self):
1536
2694
        """If the server does not recognise the PackRepository.autopack verb,
1537
2695
        fallback to the real_repository's implementation.
1587
2745
 
1588
2746
class TestErrorTranslationSuccess(TestErrorTranslationBase):
1589
2747
    """Unit tests for bzrlib.remote._translate_error.
1590
 
    
 
2748
 
1591
2749
    Given an ErrorFromSmartServer (which has an error tuple from a smart
1592
2750
    server) and some context, _translate_error raises more specific errors from
1593
2751
    bzrlib.errors.
1619
2777
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
1620
2778
        self.assertEqual(expected_error, translated_error)
1621
2779
 
 
2780
    def test_nobranch_one_arg(self):
 
2781
        bzrdir = self.make_bzrdir('')
 
2782
        translated_error = self.translateTuple(
 
2783
            ('nobranch', 'extra detail'), bzrdir=bzrdir)
 
2784
        expected_error = errors.NotBranchError(
 
2785
            path=bzrdir.root_transport.base,
 
2786
            detail='extra detail')
 
2787
        self.assertEqual(expected_error, translated_error)
 
2788
 
1622
2789
    def test_LockContention(self):
1623
2790
        translated_error = self.translateTuple(('LockContention',))
1624
2791
        expected_error = errors.LockContention('(remote lock)')
1664
2831
        expected_error = errors.ReadError(path)
1665
2832
        self.assertEqual(expected_error, translated_error)
1666
2833
 
 
2834
    def test_IncompatibleRepositories(self):
 
2835
        translated_error = self.translateTuple(('IncompatibleRepositories',
 
2836
            "repo1", "repo2", "details here"))
 
2837
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
 
2838
            "details here")
 
2839
        self.assertEqual(expected_error, translated_error)
 
2840
 
1667
2841
    def test_PermissionDenied_no_args(self):
1668
2842
        path = 'a path'
1669
2843
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
1698
2872
 
1699
2873
class TestErrorTranslationRobustness(TestErrorTranslationBase):
1700
2874
    """Unit tests for bzrlib.remote._translate_error's robustness.
1701
 
    
 
2875
 
1702
2876
    TestErrorTranslationSuccess is for cases where _translate_error can
1703
2877
    translate successfully.  This class about how _translate_err behaves when
1704
2878
    it fails to translate: it re-raises the original error.
1730
2904
        # In addition to re-raising ErrorFromSmartServer, some debug info has
1731
2905
        # been muttered to the log file for developer to look at.
1732
2906
        self.assertContainsRe(
1733
 
            self._get_log(keep_log_file=True),
 
2907
            self.get_log(),
1734
2908
            "Missing key 'branch' in context")
1735
 
        
 
2909
 
1736
2910
    def test_path_missing(self):
1737
2911
        """Some translations (PermissionDenied, ReadError) can determine the
1738
2912
        'path' variable from either the wire or the local context.  If neither
1744
2918
        self.assertEqual(server_error, translated_error)
1745
2919
        # In addition to re-raising ErrorFromSmartServer, some debug info has
1746
2920
        # been muttered to the log file for developer to look at.
1747
 
        self.assertContainsRe(
1748
 
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
 
2921
        self.assertContainsRe(self.get_log(), "Missing key 'path' in context")
1749
2922
 
1750
2923
 
1751
2924
class TestStacking(tests.TestCaseWithTransport):
1752
2925
    """Tests for operations on stacked remote repositories.
1753
 
    
 
2926
 
1754
2927
    The underlying format type must support stacking.
1755
2928
    """
1756
2929
 
1760
2933
        # revision, then open it over hpss - we should be able to see that
1761
2934
        # revision.
1762
2935
        base_transport = self.get_transport()
1763
 
        base_builder = self.make_branch_builder('base', format='1.6')
 
2936
        base_builder = self.make_branch_builder('base', format='1.9')
1764
2937
        base_builder.start_series()
1765
2938
        base_revid = base_builder.build_snapshot('rev-id', None,
1766
2939
            [('add', ('', None, 'directory', None))],
1767
2940
            'message')
1768
2941
        base_builder.finish_series()
1769
 
        stacked_branch = self.make_branch('stacked', format='1.6')
 
2942
        stacked_branch = self.make_branch('stacked', format='1.9')
1770
2943
        stacked_branch.set_stacked_on_url('../base')
1771
2944
        # start a server looking at this
1772
 
        smart_server = server.SmartTCPServer_for_testing()
1773
 
        smart_server.setUp()
1774
 
        self.addCleanup(smart_server.tearDown)
 
2945
        smart_server = test_server.SmartTCPServer_for_testing()
 
2946
        self.start_server(smart_server)
1775
2947
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
1776
2948
        # can get its branch and repository
1777
2949
        remote_branch = remote_bzrdir.open_branch()
1780
2952
        try:
1781
2953
            # it should have an appropriate fallback repository, which should also
1782
2954
            # be a RemoteRepository
1783
 
            self.assertEquals(len(remote_repo._fallback_repositories), 1)
 
2955
            self.assertLength(1, remote_repo._fallback_repositories)
1784
2956
            self.assertIsInstance(remote_repo._fallback_repositories[0],
1785
2957
                RemoteRepository)
1786
2958
            # and it has the revision committed to the underlying repository;
1793
2965
            remote_repo.unlock()
1794
2966
 
1795
2967
    def prepare_stacked_remote_branch(self):
1796
 
        smart_server = server.SmartTCPServer_for_testing()
1797
 
        smart_server.setUp()
1798
 
        self.addCleanup(smart_server.tearDown)
1799
 
        tree1 = self.make_branch_and_tree('tree1')
 
2968
        """Get stacked_upon and stacked branches with content in each."""
 
2969
        self.setup_smart_server_with_call_log()
 
2970
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
1800
2971
        tree1.commit('rev1', rev_id='rev1')
1801
 
        tree2 = self.make_branch_and_tree('tree2', format='1.6')
1802
 
        tree2.branch.set_stacked_on_url(tree1.branch.base)
1803
 
        branch2 = Branch.open(smart_server.get_url() + '/tree2')
 
2972
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
 
2973
            ).open_workingtree()
 
2974
        local_tree = tree2.branch.create_checkout('local')
 
2975
        local_tree.commit('local changes make me feel good.')
 
2976
        branch2 = Branch.open(self.get_url('tree2'))
1804
2977
        branch2.lock_read()
1805
2978
        self.addCleanup(branch2.unlock)
1806
 
        return branch2
 
2979
        return tree1.branch, branch2
1807
2980
 
1808
2981
    def test_stacked_get_parent_map(self):
1809
2982
        # the public implementation of get_parent_map obeys stacking
1810
 
        branch = self.prepare_stacked_remote_branch()
 
2983
        _, branch = self.prepare_stacked_remote_branch()
1811
2984
        repo = branch.repository
1812
2985
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
1813
2986
 
1814
2987
    def test_unstacked_get_parent_map(self):
1815
2988
        # _unstacked_provider.get_parent_map ignores stacking
1816
 
        branch = self.prepare_stacked_remote_branch()
 
2989
        _, branch = self.prepare_stacked_remote_branch()
1817
2990
        provider = branch.repository._unstacked_provider
1818
2991
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
1819
2992
 
 
2993
    def fetch_stream_to_rev_order(self, stream):
 
2994
        result = []
 
2995
        for kind, substream in stream:
 
2996
            if not kind == 'revisions':
 
2997
                list(substream)
 
2998
            else:
 
2999
                for content in substream:
 
3000
                    result.append(content.key[-1])
 
3001
        return result
 
3002
 
 
3003
    def get_ordered_revs(self, format, order, branch_factory=None):
 
3004
        """Get a list of the revisions in a stream to format format.
 
3005
 
 
3006
        :param format: The format of the target.
 
3007
        :param order: the order that target should have requested.
 
3008
        :param branch_factory: A callable to create a trunk and stacked branch
 
3009
            to fetch from. If none, self.prepare_stacked_remote_branch is used.
 
3010
        :result: The revision ids in the stream, in the order seen,
 
3011
            the topological order of revisions in the source.
 
3012
        """
 
3013
        unordered_format = bzrdir.format_registry.get(format)()
 
3014
        target_repository_format = unordered_format.repository_format
 
3015
        # Cross check
 
3016
        self.assertEqual(order, target_repository_format._fetch_order)
 
3017
        if branch_factory is None:
 
3018
            branch_factory = self.prepare_stacked_remote_branch
 
3019
        _, stacked = branch_factory()
 
3020
        source = stacked.repository._get_source(target_repository_format)
 
3021
        tip = stacked.last_revision()
 
3022
        revs = stacked.repository.get_ancestry(tip)
 
3023
        search = graph.PendingAncestryResult([tip], stacked.repository)
 
3024
        self.reset_smart_call_log()
 
3025
        stream = source.get_stream(search)
 
3026
        if None in revs:
 
3027
            revs.remove(None)
 
3028
        # We trust that if a revision is in the stream the rest of the new
 
3029
        # content for it is too, as per our main fetch tests; here we are
 
3030
        # checking that the revisions are actually included at all, and their
 
3031
        # order.
 
3032
        return self.fetch_stream_to_rev_order(stream), revs
 
3033
 
 
3034
    def test_stacked_get_stream_unordered(self):
 
3035
        # Repository._get_source.get_stream() from a stacked repository with
 
3036
        # unordered yields the full data from both stacked and stacked upon
 
3037
        # sources.
 
3038
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered')
 
3039
        self.assertEqual(set(expected_revs), set(rev_ord))
 
3040
        # Getting unordered results should have made a streaming data request
 
3041
        # from the server, then one from the backing branch.
 
3042
        self.assertLength(2, self.hpss_calls)
 
3043
 
 
3044
    def test_stacked_on_stacked_get_stream_unordered(self):
 
3045
        # Repository._get_source.get_stream() from a stacked repository which
 
3046
        # is itself stacked yields the full data from all three sources.
 
3047
        def make_stacked_stacked():
 
3048
            _, stacked = self.prepare_stacked_remote_branch()
 
3049
            tree = stacked.bzrdir.sprout('tree3', stacked=True
 
3050
                ).open_workingtree()
 
3051
            local_tree = tree.branch.create_checkout('local-tree3')
 
3052
            local_tree.commit('more local changes are better')
 
3053
            branch = Branch.open(self.get_url('tree3'))
 
3054
            branch.lock_read()
 
3055
            self.addCleanup(branch.unlock)
 
3056
            return None, branch
 
3057
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
 
3058
            branch_factory=make_stacked_stacked)
 
3059
        self.assertEqual(set(expected_revs), set(rev_ord))
 
3060
        # Getting unordered results should have made a streaming data request
 
3061
        # from the server, and one from each backing repo
 
3062
        self.assertLength(3, self.hpss_calls)
 
3063
 
 
3064
    def test_stacked_get_stream_topological(self):
 
3065
        # Repository._get_source.get_stream() from a stacked repository with
 
3066
        # topological sorting yields the full data from both stacked and
 
3067
        # stacked upon sources in topological order.
 
3068
        rev_ord, expected_revs = self.get_ordered_revs('knit', 'topological')
 
3069
        self.assertEqual(expected_revs, rev_ord)
 
3070
        # Getting topological sort requires VFS calls still - one of which is
 
3071
        # pushing up from the bound branch.
 
3072
        self.assertLength(13, self.hpss_calls)
 
3073
 
 
3074
    def test_stacked_get_stream_groupcompress(self):
 
3075
        # Repository._get_source.get_stream() from a stacked repository with
 
3076
        # groupcompress sorting yields the full data from both stacked and
 
3077
        # stacked upon sources in groupcompress order.
 
3078
        raise tests.TestSkipped('No groupcompress ordered format available')
 
3079
        rev_ord, expected_revs = self.get_ordered_revs('dev5', 'groupcompress')
 
3080
        self.assertEqual(expected_revs, reversed(rev_ord))
 
3081
        # Getting unordered results should have made a streaming data request
 
3082
        # from the backing branch, and one from the stacked on branch.
 
3083
        self.assertLength(2, self.hpss_calls)
 
3084
 
 
3085
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
 
3086
        # When pulling some fixed amount of content that is more than the
 
3087
        # source has (because some is coming from a fallback branch, no error
 
3088
        # should be received. This was reported as bug 360791.
 
3089
        # Need three branches: a trunk, a stacked branch, and a preexisting
 
3090
        # branch pulling content from stacked and trunk.
 
3091
        self.setup_smart_server_with_call_log()
 
3092
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
 
3093
        r1 = trunk.commit('start')
 
3094
        stacked_branch = trunk.branch.create_clone_on_transport(
 
3095
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
 
3096
        local = self.make_branch('local', format='1.9-rich-root')
 
3097
        local.repository.fetch(stacked_branch.repository,
 
3098
            stacked_branch.last_revision())
 
3099
 
1820
3100
 
1821
3101
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
1822
3102
 
1824
3104
        super(TestRemoteBranchEffort, self).setUp()
1825
3105
        # Create a smart server that publishes whatever the backing VFS server
1826
3106
        # does.
1827
 
        self.smart_server = server.SmartTCPServer_for_testing()
1828
 
        self.smart_server.setUp(self.get_server())
1829
 
        self.addCleanup(self.smart_server.tearDown)
 
3107
        self.smart_server = test_server.SmartTCPServer_for_testing()
 
3108
        self.start_server(self.smart_server, self.get_server())
1830
3109
        # Log all HPSS calls into self.hpss_calls.
1831
3110
        _SmartClient.hooks.install_named_hook(
1832
3111
            'call', self.capture_hpss_call, None)