/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Andrew Bennetts
  • Date: 2010-01-12 03:53:21 UTC
  • mfrom: (4948 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4964.
  • Revision ID: andrew.bennetts@canonical.com-20100112035321-hofpz5p10224ryj3
Merge lp:bzr, resolving conflicts.

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