~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Robert Collins
  • Date: 2010-01-28 18:05:44 UTC
  • mto: (4797.2.5 2.1)
  • mto: This revision was merged to the branch mainline in revision 4989.
  • Revision ID: robertc@robertcollins.net-20100128180544-6l8x7o7obaq7b51x
Tweak ConfigurableFileMerger to use class variables rather than requiring __init__ wrapping as future proofing for helper functions.

Show diffs side-by-side

added added

removed removed

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