~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Tarmac
  • Author(s): Vincent Ladeuil
  • Date: 2017-01-30 14:42:05 UTC
  • mfrom: (6620.1.1 trunk)
  • Revision ID: tarmac-20170130144205-r8fh2xpmiuxyozpv
Merge  2.7 into trunk including fix for bug #1657238 [r=vila]

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2006-2013, 2016 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
25
25
 
26
26
import bz2
27
27
from cStringIO import StringIO
 
28
import zlib
28
29
 
29
30
from bzrlib import (
 
31
    bencode,
 
32
    branch,
30
33
    bzrdir,
31
34
    config,
 
35
    controldir,
32
36
    errors,
33
 
    graph,
34
37
    inventory,
35
38
    inventory_delta,
36
 
    pack,
37
39
    remote,
38
40
    repository,
39
 
    smart,
40
41
    tests,
 
42
    transport,
41
43
    treebuilder,
42
 
    urlutils,
43
44
    versionedfile,
 
45
    vf_search,
44
46
    )
45
47
from bzrlib.branch import Branch
46
 
from bzrlib.bzrdir import BzrDir, BzrDirFormat
 
48
from bzrlib.bzrdir import (
 
49
    BzrDir,
 
50
    BzrDirFormat,
 
51
    RemoteBzrProber,
 
52
    )
 
53
from bzrlib.chk_serializer import chk_bencode_serializer
47
54
from bzrlib.remote import (
48
55
    RemoteBranch,
49
56
    RemoteBranchFormat,
52
59
    RemoteRepository,
53
60
    RemoteRepositoryFormat,
54
61
    )
55
 
from bzrlib.repofmt import groupcompress_repo, pack_repo
56
 
from bzrlib.revision import NULL_REVISION
57
 
from bzrlib.smart import server, medium
 
62
from bzrlib.repofmt import groupcompress_repo, knitpack_repo
 
63
from bzrlib.revision import (
 
64
    NULL_REVISION,
 
65
    Revision,
 
66
    )
 
67
from bzrlib.smart import medium, request
58
68
from bzrlib.smart.client import _SmartClient
59
 
from bzrlib.smart.repository import SmartServerRepositoryGetParentMap
 
69
from bzrlib.smart.repository import (
 
70
    SmartServerRepositoryGetParentMap,
 
71
    SmartServerRepositoryGetStream_1_19,
 
72
    _stream_to_byte_stream,
 
73
    )
 
74
from bzrlib.symbol_versioning import deprecated_in
60
75
from bzrlib.tests import (
61
 
    condition_isinstance,
62
 
    split_suite_by_condition,
63
 
    multiply_tests,
64
 
    KnownFailure,
 
76
    test_server,
65
77
    )
66
 
from bzrlib.transport import get_transport, http
 
78
from bzrlib.tests.scenarios import load_tests_apply_scenarios
67
79
from bzrlib.transport.memory import MemoryTransport
68
80
from bzrlib.transport.remote import (
69
81
    RemoteTransport,
70
82
    RemoteSSHTransport,
71
83
    RemoteTCPTransport,
72
 
)
73
 
 
74
 
def load_tests(standard_tests, module, loader):
75
 
    to_adapt, result = split_suite_by_condition(
76
 
        standard_tests, condition_isinstance(BasicRemoteObjectTests))
77
 
    smart_server_version_scenarios = [
 
84
    )
 
85
 
 
86
 
 
87
load_tests = load_tests_apply_scenarios
 
88
 
 
89
 
 
90
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
 
91
 
 
92
    scenarios = [
78
93
        ('HPSS-v2',
79
 
            {'transport_server': server.SmartTCPServer_for_testing_v2_only}),
 
94
            {'transport_server': test_server.SmartTCPServer_for_testing_v2_only}),
80
95
        ('HPSS-v3',
81
 
            {'transport_server': server.SmartTCPServer_for_testing})]
82
 
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
83
 
 
84
 
 
85
 
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
 
96
            {'transport_server': test_server.SmartTCPServer_for_testing})]
 
97
 
86
98
 
87
99
    def setUp(self):
88
100
        super(BasicRemoteObjectTests, self).setUp()
89
101
        self.transport = self.get_transport()
90
102
        # make a branch that can be opened over the smart transport
91
103
        self.local_wt = BzrDir.create_standalone_workingtree('.')
92
 
 
93
 
    def tearDown(self):
94
 
        self.transport.disconnect()
95
 
        tests.TestCaseWithTransport.tearDown(self)
 
104
        self.addCleanup(self.transport.disconnect)
96
105
 
97
106
    def test_create_remote_bzrdir(self):
98
 
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
107
        b = remote.RemoteBzrDir(self.transport, RemoteBzrDirFormat())
99
108
        self.assertIsInstance(b, BzrDir)
100
109
 
101
110
    def test_open_remote_branch(self):
102
111
        # open a standalone branch in the working directory
103
 
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
112
        b = remote.RemoteBzrDir(self.transport, RemoteBzrDirFormat())
104
113
        branch = b.open_branch()
105
114
        self.assertIsInstance(branch, Branch)
106
115
 
112
121
        self.local_wt.commit(message='test commit', rev_id=revid)
113
122
        self.assertTrue(repo.has_revision(revid))
114
123
 
115
 
    def test_remote_branch_revision_history(self):
116
 
        b = BzrDir.open_from_transport(self.transport).open_branch()
117
 
        self.assertEqual([], b.revision_history())
118
 
        r1 = self.local_wt.commit('1st commit')
119
 
        r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
120
 
        self.assertEqual([r1, r2], b.revision_history())
121
 
 
122
124
    def test_find_correct_format(self):
123
125
        """Should open a RemoteBzrDir over a RemoteTransport"""
124
126
        fmt = BzrDirFormat.find_format(self.transport)
125
 
        self.assertTrue(RemoteBzrDirFormat
126
 
                        in BzrDirFormat._control_server_formats)
127
 
        self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
 
127
        self.assertTrue(bzrdir.RemoteBzrProber
 
128
                        in controldir.ControlDirFormat._server_probers)
 
129
        self.assertIsInstance(fmt, RemoteBzrDirFormat)
128
130
 
129
131
    def test_open_detected_smart_format(self):
130
132
        fmt = BzrDirFormat.find_format(self.transport)
135
137
        b = BzrDir.open_from_transport(self.transport).open_branch()
136
138
        self.assertStartsWith(str(b), 'RemoteBranch(')
137
139
 
 
140
    def test_remote_bzrdir_repr(self):
 
141
        b = BzrDir.open_from_transport(self.transport)
 
142
        self.assertStartsWith(str(b), 'RemoteBzrDir(')
 
143
 
138
144
    def test_remote_branch_format_supports_stacking(self):
139
145
        t = self.transport
140
146
        self.make_branch('unstackable', format='pack-0.92')
160
166
    def test_remote_branch_set_append_revisions_only(self):
161
167
        # Make a format 1.9 branch, which supports append_revisions_only
162
168
        branch = self.make_branch('branch', format='1.9')
163
 
        config = branch.get_config()
164
169
        branch.set_append_revisions_only(True)
 
170
        config = branch.get_config_stack()
165
171
        self.assertEqual(
166
 
            'True', config.get_user_option('append_revisions_only'))
 
172
            True, config.get('append_revisions_only'))
167
173
        branch.set_append_revisions_only(False)
 
174
        config = branch.get_config_stack()
168
175
        self.assertEqual(
169
 
            'False', config.get_user_option('append_revisions_only'))
 
176
            False, config.get('append_revisions_only'))
170
177
 
171
178
    def test_remote_branch_set_append_revisions_only_upgrade_reqd(self):
172
179
        branch = self.make_branch('branch', format='knit')
173
 
        config = branch.get_config()
174
180
        self.assertRaises(
175
181
            errors.UpgradeRequired, branch.set_append_revisions_only, True)
176
182
 
280
286
        self.expecting_body = True
281
287
        return result[1], FakeProtocol(result[2], self)
282
288
 
 
289
    def call_with_body_bytes(self, method, args, body):
 
290
        self._check_call(method, args)
 
291
        self._calls.append(('call_with_body_bytes', method, args, body))
 
292
        result = self._get_next_response()
 
293
        return result[1], FakeProtocol(result[2], self)
 
294
 
283
295
    def call_with_body_bytes_expecting_body(self, method, args, body):
284
296
        self._check_call(method, args)
285
297
        self._calls.append(('call_with_body_bytes_expecting_body', method,
328
340
class TestRemote(tests.TestCaseWithMemoryTransport):
329
341
 
330
342
    def get_branch_format(self):
331
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
343
        reference_bzrdir_format = controldir.format_registry.get('default')()
332
344
        return reference_bzrdir_format.get_branch_format()
333
345
 
334
346
    def get_repo_format(self):
335
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
347
        reference_bzrdir_format = controldir.format_registry.get('default')()
336
348
        return reference_bzrdir_format.repository_format
337
349
 
338
350
    def assertFinished(self, fake_client):
349
361
        a given client_base and transport_base.
350
362
        """
351
363
        client_medium = medium.SmartClientMedium(client_base)
352
 
        transport = get_transport(transport_base)
353
 
        result = client_medium.remote_path_from_transport(transport)
 
364
        t = transport.get_transport(transport_base)
 
365
        result = client_medium.remote_path_from_transport(t)
354
366
        self.assertEqual(expected, result)
355
367
 
356
368
    def test_remote_path_from_transport(self):
367
379
        a given transport_base and relpath of that transport.  (Note that
368
380
        HttpTransportBase is a subclass of SmartClientMedium)
369
381
        """
370
 
        base_transport = get_transport(transport_base)
 
382
        base_transport = transport.get_transport(transport_base)
371
383
        client_medium = base_transport.get_smart_medium()
372
384
        cloned_transport = base_transport.clone(relpath)
373
385
        result = client_medium.remote_path_from_transport(cloned_transport)
408
420
        # Calling _remember_remote_is_before again with a lower value works.
409
421
        client_medium._remember_remote_is_before((1, 5))
410
422
        self.assertTrue(client_medium._is_remote_before((1, 5)))
411
 
        # You cannot call _remember_remote_is_before with a larger value.
412
 
        self.assertRaises(
413
 
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
 
423
        # If you call _remember_remote_is_before with a higher value it logs a
 
424
        # warning, and continues to remember the lower value.
 
425
        self.assertNotContainsRe(self.get_log(), '_remember_remote_is_before')
 
426
        client_medium._remember_remote_is_before((1, 9))
 
427
        self.assertContainsRe(self.get_log(), '_remember_remote_is_before')
 
428
        self.assertTrue(client_medium._is_remote_before((1, 5)))
414
429
 
415
430
 
416
431
class TestBzrDirCloningMetaDir(TestRemote):
435
450
            'BzrDir.cloning_metadir', ('quack/', 'False'),
436
451
            'error', ('BranchReference',)),
437
452
        client.add_expected_call(
438
 
            'BzrDir.open_branchV2', ('quack/',),
 
453
            'BzrDir.open_branchV3', ('quack/',),
439
454
            'success', ('ref', self.get_url('referenced'))),
440
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
455
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
441
456
            _client=client)
442
457
        result = a_bzrdir.cloning_metadir()
443
458
        # We should have got a control dir matching the referenced branch.
451
466
        transport = transport.clone('quack')
452
467
        self.make_bzrdir('quack')
453
468
        client = FakeClient(transport.base)
454
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
469
        reference_bzrdir_format = controldir.format_registry.get('default')()
455
470
        control_name = reference_bzrdir_format.network_name()
456
471
        client.add_expected_call(
457
472
            'BzrDir.cloning_metadir', ('quack/', 'False'),
458
473
            'success', (control_name, '', ('branch', ''))),
459
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
474
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
460
475
            _client=client)
461
476
        result = a_bzrdir.cloning_metadir()
462
477
        # We should have got a reference control dir with default branch and
467
482
        self.assertEqual(None, result._branch_format)
468
483
        self.assertFinished(client)
469
484
 
 
485
    def test_unknown(self):
 
486
        transport = self.get_transport('quack')
 
487
        referenced = self.make_branch('referenced')
 
488
        expected = referenced.bzrdir.cloning_metadir()
 
489
        client = FakeClient(transport.base)
 
490
        client.add_expected_call(
 
491
            'BzrDir.cloning_metadir', ('quack/', 'False'),
 
492
            'success', ('unknown', 'unknown', ('branch', ''))),
 
493
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
494
            _client=client)
 
495
        self.assertRaises(errors.UnknownFormatError, a_bzrdir.cloning_metadir)
 
496
 
 
497
 
 
498
class TestBzrDirCheckoutMetaDir(TestRemote):
 
499
 
 
500
    def test__get_checkout_format(self):
 
501
        transport = MemoryTransport()
 
502
        client = FakeClient(transport.base)
 
503
        reference_bzrdir_format = controldir.format_registry.get('default')()
 
504
        control_name = reference_bzrdir_format.network_name()
 
505
        client.add_expected_call(
 
506
            'BzrDir.checkout_metadir', ('quack/', ),
 
507
            'success', (control_name, '', ''))
 
508
        transport.mkdir('quack')
 
509
        transport = transport.clone('quack')
 
510
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
511
            _client=client)
 
512
        result = a_bzrdir.checkout_metadir()
 
513
        # We should have got a reference control dir with default branch and
 
514
        # repository formats.
 
515
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
 
516
        self.assertEqual(None, result._repository_format)
 
517
        self.assertEqual(None, result._branch_format)
 
518
        self.assertFinished(client)
 
519
 
 
520
    def test_unknown_format(self):
 
521
        transport = MemoryTransport()
 
522
        client = FakeClient(transport.base)
 
523
        client.add_expected_call(
 
524
            'BzrDir.checkout_metadir', ('quack/',),
 
525
            'success', ('dontknow', '', ''))
 
526
        transport.mkdir('quack')
 
527
        transport = transport.clone('quack')
 
528
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
529
            _client=client)
 
530
        self.assertRaises(errors.UnknownFormatError,
 
531
            a_bzrdir.checkout_metadir)
 
532
        self.assertFinished(client)
 
533
 
 
534
 
 
535
class TestBzrDirGetBranches(TestRemote):
 
536
 
 
537
    def test_get_branches(self):
 
538
        transport = MemoryTransport()
 
539
        client = FakeClient(transport.base)
 
540
        reference_bzrdir_format = controldir.format_registry.get('default')()
 
541
        branch_name = reference_bzrdir_format.get_branch_format().network_name()
 
542
        client.add_success_response_with_body(
 
543
            bencode.bencode({
 
544
                "foo": ("branch", branch_name),
 
545
                "": ("branch", branch_name)}), "success")
 
546
        client.add_success_response(
 
547
            'ok', '', 'no', 'no', 'no',
 
548
                reference_bzrdir_format.repository_format.network_name())
 
549
        client.add_error_response('NotStacked')
 
550
        client.add_success_response(
 
551
            'ok', '', 'no', 'no', 'no',
 
552
                reference_bzrdir_format.repository_format.network_name())
 
553
        client.add_error_response('NotStacked')
 
554
        transport.mkdir('quack')
 
555
        transport = transport.clone('quack')
 
556
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
557
            _client=client)
 
558
        result = a_bzrdir.get_branches()
 
559
        self.assertEqual(set(["", "foo"]), set(result.keys()))
 
560
        self.assertEqual(
 
561
            [('call_expecting_body', 'BzrDir.get_branches', ('quack/',)),
 
562
             ('call', 'BzrDir.find_repositoryV3', ('quack/', )),
 
563
             ('call', 'Branch.get_stacked_on_url', ('quack/', )),
 
564
             ('call', 'BzrDir.find_repositoryV3', ('quack/', )),
 
565
             ('call', 'Branch.get_stacked_on_url', ('quack/', ))],
 
566
            client._calls)
 
567
 
 
568
 
 
569
class TestBzrDirDestroyBranch(TestRemote):
 
570
 
 
571
    def test_destroy_default(self):
 
572
        transport = self.get_transport('quack')
 
573
        referenced = self.make_branch('referenced')
 
574
        client = FakeClient(transport.base)
 
575
        client.add_expected_call(
 
576
            'BzrDir.destroy_branch', ('quack/', ),
 
577
            'success', ('ok',)),
 
578
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
579
            _client=client)
 
580
        a_bzrdir.destroy_branch()
 
581
        self.assertFinished(client)
 
582
 
 
583
 
 
584
class TestBzrDirHasWorkingTree(TestRemote):
 
585
 
 
586
    def test_has_workingtree(self):
 
587
        transport = self.get_transport('quack')
 
588
        client = FakeClient(transport.base)
 
589
        client.add_expected_call(
 
590
            'BzrDir.has_workingtree', ('quack/',),
 
591
            'success', ('yes',)),
 
592
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
593
            _client=client)
 
594
        self.assertTrue(a_bzrdir.has_workingtree())
 
595
        self.assertFinished(client)
 
596
 
 
597
    def test_no_workingtree(self):
 
598
        transport = self.get_transport('quack')
 
599
        client = FakeClient(transport.base)
 
600
        client.add_expected_call(
 
601
            'BzrDir.has_workingtree', ('quack/',),
 
602
            'success', ('no',)),
 
603
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
604
            _client=client)
 
605
        self.assertFalse(a_bzrdir.has_workingtree())
 
606
        self.assertFinished(client)
 
607
 
 
608
 
 
609
class TestBzrDirDestroyRepository(TestRemote):
 
610
 
 
611
    def test_destroy_repository(self):
 
612
        transport = self.get_transport('quack')
 
613
        client = FakeClient(transport.base)
 
614
        client.add_expected_call(
 
615
            'BzrDir.destroy_repository', ('quack/',),
 
616
            'success', ('ok',)),
 
617
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
618
            _client=client)
 
619
        a_bzrdir.destroy_repository()
 
620
        self.assertFinished(client)
 
621
 
 
622
 
 
623
class TestBzrDirOpen(TestRemote):
 
624
 
 
625
    def make_fake_client_and_transport(self, path='quack'):
 
626
        transport = MemoryTransport()
 
627
        transport.mkdir(path)
 
628
        transport = transport.clone(path)
 
629
        client = FakeClient(transport.base)
 
630
        return client, transport
 
631
 
 
632
    def test_absent(self):
 
633
        client, transport = self.make_fake_client_and_transport()
 
634
        client.add_expected_call(
 
635
            'BzrDir.open_2.1', ('quack/',), 'success', ('no',))
 
636
        self.assertRaises(errors.NotBranchError, RemoteBzrDir, transport,
 
637
                RemoteBzrDirFormat(), _client=client, _force_probe=True)
 
638
        self.assertFinished(client)
 
639
 
 
640
    def test_present_without_workingtree(self):
 
641
        client, transport = self.make_fake_client_and_transport()
 
642
        client.add_expected_call(
 
643
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'no'))
 
644
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
645
            _client=client, _force_probe=True)
 
646
        self.assertIsInstance(bd, RemoteBzrDir)
 
647
        self.assertFalse(bd.has_workingtree())
 
648
        self.assertRaises(errors.NoWorkingTree, bd.open_workingtree)
 
649
        self.assertFinished(client)
 
650
 
 
651
    def test_present_with_workingtree(self):
 
652
        client, transport = self.make_fake_client_and_transport()
 
653
        client.add_expected_call(
 
654
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'yes'))
 
655
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
656
            _client=client, _force_probe=True)
 
657
        self.assertIsInstance(bd, RemoteBzrDir)
 
658
        self.assertTrue(bd.has_workingtree())
 
659
        self.assertRaises(errors.NotLocalUrl, bd.open_workingtree)
 
660
        self.assertFinished(client)
 
661
 
 
662
    def test_backwards_compat(self):
 
663
        client, transport = self.make_fake_client_and_transport()
 
664
        client.add_expected_call(
 
665
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
 
666
        client.add_expected_call(
 
667
            'BzrDir.open', ('quack/',), 'success', ('yes',))
 
668
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
669
            _client=client, _force_probe=True)
 
670
        self.assertIsInstance(bd, RemoteBzrDir)
 
671
        self.assertFinished(client)
 
672
 
 
673
    def test_backwards_compat_hpss_v2(self):
 
674
        client, transport = self.make_fake_client_and_transport()
 
675
        # Monkey-patch fake client to simulate real-world behaviour with v2
 
676
        # server: upon first RPC call detect the protocol version, and because
 
677
        # the version is 2 also do _remember_remote_is_before((1, 6)) before
 
678
        # continuing with the RPC.
 
679
        orig_check_call = client._check_call
 
680
        def check_call(method, args):
 
681
            client._medium._protocol_version = 2
 
682
            client._medium._remember_remote_is_before((1, 6))
 
683
            client._check_call = orig_check_call
 
684
            client._check_call(method, args)
 
685
        client._check_call = check_call
 
686
        client.add_expected_call(
 
687
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
 
688
        client.add_expected_call(
 
689
            'BzrDir.open', ('quack/',), 'success', ('yes',))
 
690
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
691
            _client=client, _force_probe=True)
 
692
        self.assertIsInstance(bd, RemoteBzrDir)
 
693
        self.assertFinished(client)
 
694
 
470
695
 
471
696
class TestBzrDirOpenBranch(TestRemote):
472
697
 
475
700
        self.make_branch('.')
476
701
        a_dir = BzrDir.open(self.get_url('.'))
477
702
        self.reset_smart_call_log()
478
 
        verb = 'BzrDir.open_branchV2'
 
703
        verb = 'BzrDir.open_branchV3'
479
704
        self.disable_verb(verb)
480
705
        format = a_dir.open_branch()
481
706
        call_count = len([call for call in self.hpss_calls if
491
716
        transport = transport.clone('quack')
492
717
        client = FakeClient(transport.base)
493
718
        client.add_expected_call(
494
 
            'BzrDir.open_branchV2', ('quack/',),
 
719
            'BzrDir.open_branchV3', ('quack/',),
495
720
            'success', ('branch', branch_network_name))
496
721
        client.add_expected_call(
497
722
            'BzrDir.find_repositoryV3', ('quack/',),
499
724
        client.add_expected_call(
500
725
            'Branch.get_stacked_on_url', ('quack/',),
501
726
            'error', ('NotStacked',))
502
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
727
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
503
728
            _client=client)
504
729
        result = bzrdir.open_branch()
505
730
        self.assertIsInstance(result, RemoteBranch)
512
737
        transport = transport.clone('quack')
513
738
        client = FakeClient(transport.base)
514
739
        client.add_error_response('nobranch')
515
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
740
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
516
741
            _client=client)
517
742
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
518
743
        self.assertEqual(
519
 
            [('call', 'BzrDir.open_branchV2', ('quack/',))],
 
744
            [('call', 'BzrDir.open_branchV3', ('quack/',))],
520
745
            client._calls)
521
746
 
522
747
    def test__get_tree_branch(self):
523
748
        # _get_tree_branch is a form of open_branch, but it should only ask for
524
749
        # branch opening, not any other network requests.
525
750
        calls = []
526
 
        def open_branch():
 
751
        def open_branch(name=None, possible_transports=None):
527
752
            calls.append("Called")
528
753
            return "a-branch"
529
754
        transport = MemoryTransport()
530
755
        # no requests on the network - catches other api calls being made.
531
756
        client = FakeClient(transport.base)
532
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
757
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
533
758
            _client=client)
534
759
        # patch the open_branch call to record that it was called.
535
760
        bzrdir.open_branch = open_branch
546
771
        network_name = reference_format.network_name()
547
772
        branch_network_name = self.get_branch_format().network_name()
548
773
        client.add_expected_call(
549
 
            'BzrDir.open_branchV2', ('~hello/',),
 
774
            'BzrDir.open_branchV3', ('~hello/',),
550
775
            'success', ('branch', branch_network_name))
551
776
        client.add_expected_call(
552
777
            'BzrDir.find_repositoryV3', ('~hello/',),
554
779
        client.add_expected_call(
555
780
            'Branch.get_stacked_on_url', ('~hello/',),
556
781
            'error', ('NotStacked',))
557
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
782
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
558
783
            _client=client)
559
784
        result = bzrdir.open_branch()
560
785
        self.assertFinished(client)
577
802
        client.add_success_response(
578
803
            'ok', '', rich_response, subtree_response, external_lookup,
579
804
            network_name)
580
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
805
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
581
806
            _client=client)
582
807
        result = bzrdir.open_repository()
583
808
        self.assertEqual(
600
825
        old.
601
826
        """
602
827
        self.assertRaises(errors.NotBranchError,
603
 
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
 
828
            RemoteBzrProber.probe_transport, OldServerTransport())
604
829
 
605
830
 
606
831
class TestBzrDirCreateBranch(TestRemote):
620
845
        transport = transport.clone('quack')
621
846
        self.make_repository('quack')
622
847
        client = FakeClient(transport.base)
623
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
848
        reference_bzrdir_format = controldir.format_registry.get('default')()
624
849
        reference_format = reference_bzrdir_format.get_branch_format()
625
850
        network_name = reference_format.network_name()
626
851
        reference_repo_fmt = reference_bzrdir_format.repository_format
629
854
            'BzrDir.create_branch', ('quack/', network_name),
630
855
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
631
856
            reference_repo_name))
632
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
857
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
633
858
            _client=client)
634
859
        branch = a_bzrdir.create_branch()
635
860
        # We should have got a remote branch
638
863
        format = branch._format
639
864
        self.assertEqual(network_name, format.network_name())
640
865
 
 
866
    def test_already_open_repo_and_reused_medium(self):
 
867
        """Bug 726584: create_branch(..., repository=repo) should work
 
868
        regardless of what the smart medium's base URL is.
 
869
        """
 
870
        self.transport_server = test_server.SmartTCPServer_for_testing
 
871
        transport = self.get_transport('.')
 
872
        repo = self.make_repository('quack')
 
873
        # Client's medium rooted a transport root (not at the bzrdir)
 
874
        client = FakeClient(transport.base)
 
875
        transport = transport.clone('quack')
 
876
        reference_bzrdir_format = controldir.format_registry.get('default')()
 
877
        reference_format = reference_bzrdir_format.get_branch_format()
 
878
        network_name = reference_format.network_name()
 
879
        reference_repo_fmt = reference_bzrdir_format.repository_format
 
880
        reference_repo_name = reference_repo_fmt.network_name()
 
881
        client.add_expected_call(
 
882
            'BzrDir.create_branch', ('extra/quack/', network_name),
 
883
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
 
884
            reference_repo_name))
 
885
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
886
            _client=client)
 
887
        branch = a_bzrdir.create_branch(repository=repo)
 
888
        # We should have got a remote branch
 
889
        self.assertIsInstance(branch, remote.RemoteBranch)
 
890
        # its format should have the settings from the response
 
891
        format = branch._format
 
892
        self.assertEqual(network_name, format.network_name())
 
893
 
641
894
 
642
895
class TestBzrDirCreateRepository(TestRemote):
643
896
 
656
909
        transport = transport.clone('quack')
657
910
        self.make_bzrdir('quack')
658
911
        client = FakeClient(transport.base)
659
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
912
        reference_bzrdir_format = controldir.format_registry.get('default')()
660
913
        reference_format = reference_bzrdir_format.repository_format
661
914
        network_name = reference_format.network_name()
662
915
        client.add_expected_call(
664
917
                'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
665
918
                'False'),
666
919
            'success', ('ok', 'yes', 'yes', 'yes', network_name))
667
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
920
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
668
921
            _client=client)
669
922
        repo = a_bzrdir.create_repository()
670
923
        # We should have got a remote repository
683
936
        # fallback all the way to the first version.
684
937
        reference_format = self.get_repo_format()
685
938
        network_name = reference_format.network_name()
686
 
        client = FakeClient('bzr://example.com/')
 
939
        server_url = 'bzr://example.com/'
 
940
        self.permit_url(server_url)
 
941
        client = FakeClient(server_url)
687
942
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
688
943
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
689
944
        client.add_success_response('ok', '', 'no', 'no')
691
946
        # name.
692
947
        client.add_success_response_with_body(
693
948
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
949
        client.add_success_response('stat', '0', '65535')
694
950
        client.add_success_response_with_body(
695
951
            reference_format.get_format_string(), 'ok')
696
952
        # PackRepository wants to do a stat
697
953
        client.add_success_response('stat', '0', '65535')
698
 
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
 
954
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
699
955
            _client=client)
700
 
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
956
        bzrdir = RemoteBzrDir(remote_transport, RemoteBzrDirFormat(),
701
957
            _client=client)
702
958
        repo = bzrdir.open_repository()
703
959
        self.assertEqual(
705
961
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
706
962
             ('call', 'BzrDir.find_repository', ('quack/',)),
707
963
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
964
             ('call', 'stat', ('/quack/.bzr',)),
708
965
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
709
966
             ('call', 'stat', ('/quack/.bzr/repository',)),
710
967
             ],
715
972
        # fallback to find_repositoryV2
716
973
        reference_format = self.get_repo_format()
717
974
        network_name = reference_format.network_name()
718
 
        client = FakeClient('bzr://example.com/')
 
975
        server_url = 'bzr://example.com/'
 
976
        self.permit_url(server_url)
 
977
        client = FakeClient(server_url)
719
978
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
720
979
        client.add_success_response('ok', '', 'no', 'no', 'no')
721
980
        # A real repository instance will be created to determine the network
722
981
        # name.
723
982
        client.add_success_response_with_body(
724
983
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
984
        client.add_success_response('stat', '0', '65535')
725
985
        client.add_success_response_with_body(
726
986
            reference_format.get_format_string(), 'ok')
727
987
        # PackRepository wants to do a stat
728
988
        client.add_success_response('stat', '0', '65535')
729
 
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
 
989
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
730
990
            _client=client)
731
 
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
991
        bzrdir = RemoteBzrDir(remote_transport, RemoteBzrDirFormat(),
732
992
            _client=client)
733
993
        repo = bzrdir.open_repository()
734
994
        self.assertEqual(
735
995
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
736
996
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
737
997
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
998
             ('call', 'stat', ('/quack/.bzr',)),
738
999
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
739
1000
             ('call', 'stat', ('/quack/.bzr/repository',)),
740
1001
             ],
749
1010
        transport = transport.clone('quack')
750
1011
        client = FakeClient(transport.base)
751
1012
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
752
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1013
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
753
1014
            _client=client)
754
1015
        repo = bzrdir.open_repository()
755
1016
        self.assertEqual(
762
1023
 
763
1024
    def test_success(self):
764
1025
        """Simple test for typical successful call."""
765
 
        fmt = bzrdir.RemoteBzrDirFormat()
 
1026
        fmt = RemoteBzrDirFormat()
766
1027
        default_format_name = BzrDirFormat.get_default_format().network_name()
767
1028
        transport = self.get_transport()
768
1029
        client = FakeClient(transport.base)
784
1045
        """Error responses are translated, e.g. 'PermissionDenied' raises the
785
1046
        corresponding error from the client.
786
1047
        """
787
 
        fmt = bzrdir.RemoteBzrDirFormat()
 
1048
        fmt = RemoteBzrDirFormat()
788
1049
        default_format_name = BzrDirFormat.get_default_format().network_name()
789
1050
        transport = self.get_transport()
790
1051
        client = FakeClient(transport.base)
808
1069
        """Integration test for error translation."""
809
1070
        transport = self.make_smart_server('foo')
810
1071
        transport = transport.clone('no-such-path')
811
 
        fmt = bzrdir.RemoteBzrDirFormat()
 
1072
        fmt = RemoteBzrDirFormat()
812
1073
        err = self.assertRaises(errors.NoSuchFile,
813
1074
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
814
1075
 
845
1106
 
846
1107
    def make_remote_bzrdir(self, transport, client):
847
1108
        """Make a RemotebzrDir using 'client' as the _client."""
848
 
        return RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1109
        return RemoteBzrDir(transport, RemoteBzrDirFormat(),
849
1110
            _client=client)
850
1111
 
851
1112
 
852
1113
class RemoteBranchTestCase(RemoteBzrDirTestCase):
853
1114
 
 
1115
    def lock_remote_branch(self, branch):
 
1116
        """Trick a RemoteBranch into thinking it is locked."""
 
1117
        branch._lock_mode = 'w'
 
1118
        branch._lock_count = 2
 
1119
        branch._lock_token = 'branch token'
 
1120
        branch._repo_lock_token = 'repo token'
 
1121
        branch.repository._lock_mode = 'w'
 
1122
        branch.repository._lock_count = 2
 
1123
        branch.repository._lock_token = 'repo token'
 
1124
 
854
1125
    def make_remote_branch(self, transport, client):
855
1126
        """Make a RemoteBranch using 'client' as its _SmartClient.
856
1127
 
867
1138
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
868
1139
 
869
1140
 
 
1141
class TestBranchBreakLock(RemoteBranchTestCase):
 
1142
 
 
1143
    def test_break_lock(self):
 
1144
        transport_path = 'quack'
 
1145
        transport = MemoryTransport()
 
1146
        client = FakeClient(transport.base)
 
1147
        client.add_expected_call(
 
1148
            'Branch.get_stacked_on_url', ('quack/',),
 
1149
            'error', ('NotStacked',))
 
1150
        client.add_expected_call(
 
1151
            'Branch.break_lock', ('quack/',),
 
1152
            'success', ('ok',))
 
1153
        transport.mkdir('quack')
 
1154
        transport = transport.clone('quack')
 
1155
        branch = self.make_remote_branch(transport, client)
 
1156
        branch.break_lock()
 
1157
        self.assertFinished(client)
 
1158
 
 
1159
 
 
1160
class TestBranchGetPhysicalLockStatus(RemoteBranchTestCase):
 
1161
 
 
1162
    def test_get_physical_lock_status_yes(self):
 
1163
        transport = MemoryTransport()
 
1164
        client = FakeClient(transport.base)
 
1165
        client.add_expected_call(
 
1166
            'Branch.get_stacked_on_url', ('quack/',),
 
1167
            'error', ('NotStacked',))
 
1168
        client.add_expected_call(
 
1169
            'Branch.get_physical_lock_status', ('quack/',),
 
1170
            'success', ('yes',))
 
1171
        transport.mkdir('quack')
 
1172
        transport = transport.clone('quack')
 
1173
        branch = self.make_remote_branch(transport, client)
 
1174
        result = branch.get_physical_lock_status()
 
1175
        self.assertFinished(client)
 
1176
        self.assertEqual(True, result)
 
1177
 
 
1178
    def test_get_physical_lock_status_no(self):
 
1179
        transport = MemoryTransport()
 
1180
        client = FakeClient(transport.base)
 
1181
        client.add_expected_call(
 
1182
            'Branch.get_stacked_on_url', ('quack/',),
 
1183
            'error', ('NotStacked',))
 
1184
        client.add_expected_call(
 
1185
            'Branch.get_physical_lock_status', ('quack/',),
 
1186
            'success', ('no',))
 
1187
        transport.mkdir('quack')
 
1188
        transport = transport.clone('quack')
 
1189
        branch = self.make_remote_branch(transport, client)
 
1190
        result = branch.get_physical_lock_status()
 
1191
        self.assertFinished(client)
 
1192
        self.assertEqual(False, result)
 
1193
 
 
1194
 
870
1195
class TestBranchGetParent(RemoteBranchTestCase):
871
1196
 
872
1197
    def test_no_parent(self):
962
1287
        verb = 'Branch.set_parent_location'
963
1288
        self.disable_verb(verb)
964
1289
        branch.set_parent('http://foo/')
965
 
        self.assertLength(12, self.hpss_calls)
 
1290
        self.assertLength(14, self.hpss_calls)
966
1291
 
967
1292
 
968
1293
class TestBranchGetTagsBytes(RemoteBranchTestCase):
995
1320
        self.assertEqual({}, result)
996
1321
 
997
1322
 
 
1323
class TestBranchSetTagsBytes(RemoteBranchTestCase):
 
1324
 
 
1325
    def test_trivial(self):
 
1326
        transport = MemoryTransport()
 
1327
        client = FakeClient(transport.base)
 
1328
        client.add_expected_call(
 
1329
            'Branch.get_stacked_on_url', ('quack/',),
 
1330
            'error', ('NotStacked',))
 
1331
        client.add_expected_call(
 
1332
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
 
1333
            'success', ('',))
 
1334
        transport.mkdir('quack')
 
1335
        transport = transport.clone('quack')
 
1336
        branch = self.make_remote_branch(transport, client)
 
1337
        self.lock_remote_branch(branch)
 
1338
        branch._set_tags_bytes('tags bytes')
 
1339
        self.assertFinished(client)
 
1340
        self.assertEqual('tags bytes', client._calls[-1][-1])
 
1341
 
 
1342
    def test_backwards_compatible(self):
 
1343
        transport = MemoryTransport()
 
1344
        client = FakeClient(transport.base)
 
1345
        client.add_expected_call(
 
1346
            'Branch.get_stacked_on_url', ('quack/',),
 
1347
            'error', ('NotStacked',))
 
1348
        client.add_expected_call(
 
1349
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
 
1350
            'unknown', ('Branch.set_tags_bytes',))
 
1351
        transport.mkdir('quack')
 
1352
        transport = transport.clone('quack')
 
1353
        branch = self.make_remote_branch(transport, client)
 
1354
        self.lock_remote_branch(branch)
 
1355
        class StubRealBranch(object):
 
1356
            def __init__(self):
 
1357
                self.calls = []
 
1358
            def _set_tags_bytes(self, bytes):
 
1359
                self.calls.append(('set_tags_bytes', bytes))
 
1360
        real_branch = StubRealBranch()
 
1361
        branch._real_branch = real_branch
 
1362
        branch._set_tags_bytes('tags bytes')
 
1363
        # Call a second time, to exercise the 'remote version already inferred'
 
1364
        # code path.
 
1365
        branch._set_tags_bytes('tags bytes')
 
1366
        self.assertFinished(client)
 
1367
        self.assertEqual(
 
1368
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
 
1369
 
 
1370
 
 
1371
class TestBranchHeadsToFetch(RemoteBranchTestCase):
 
1372
 
 
1373
    def test_uses_last_revision_info_and_tags_by_default(self):
 
1374
        transport = MemoryTransport()
 
1375
        client = FakeClient(transport.base)
 
1376
        client.add_expected_call(
 
1377
            'Branch.get_stacked_on_url', ('quack/',),
 
1378
            'error', ('NotStacked',))
 
1379
        client.add_expected_call(
 
1380
            'Branch.last_revision_info', ('quack/',),
 
1381
            'success', ('ok', '1', 'rev-tip'))
 
1382
        client.add_expected_call(
 
1383
            'Branch.get_config_file', ('quack/',),
 
1384
            'success', ('ok',), '')
 
1385
        transport.mkdir('quack')
 
1386
        transport = transport.clone('quack')
 
1387
        branch = self.make_remote_branch(transport, client)
 
1388
        result = branch.heads_to_fetch()
 
1389
        self.assertFinished(client)
 
1390
        self.assertEqual((set(['rev-tip']), set()), result)
 
1391
 
 
1392
    def test_uses_last_revision_info_and_tags_when_set(self):
 
1393
        transport = MemoryTransport()
 
1394
        client = FakeClient(transport.base)
 
1395
        client.add_expected_call(
 
1396
            'Branch.get_stacked_on_url', ('quack/',),
 
1397
            'error', ('NotStacked',))
 
1398
        client.add_expected_call(
 
1399
            'Branch.last_revision_info', ('quack/',),
 
1400
            'success', ('ok', '1', 'rev-tip'))
 
1401
        client.add_expected_call(
 
1402
            'Branch.get_config_file', ('quack/',),
 
1403
            'success', ('ok',), 'branch.fetch_tags = True')
 
1404
        # XXX: this will break if the default format's serialization of tags
 
1405
        # changes, or if the RPC for fetching tags changes from get_tags_bytes.
 
1406
        client.add_expected_call(
 
1407
            'Branch.get_tags_bytes', ('quack/',),
 
1408
            'success', ('d5:tag-17:rev-foo5:tag-27:rev-bare',))
 
1409
        transport.mkdir('quack')
 
1410
        transport = transport.clone('quack')
 
1411
        branch = self.make_remote_branch(transport, client)
 
1412
        result = branch.heads_to_fetch()
 
1413
        self.assertFinished(client)
 
1414
        self.assertEqual(
 
1415
            (set(['rev-tip']), set(['rev-foo', 'rev-bar'])), result)
 
1416
 
 
1417
    def test_uses_rpc_for_formats_with_non_default_heads_to_fetch(self):
 
1418
        transport = MemoryTransport()
 
1419
        client = FakeClient(transport.base)
 
1420
        client.add_expected_call(
 
1421
            'Branch.get_stacked_on_url', ('quack/',),
 
1422
            'error', ('NotStacked',))
 
1423
        client.add_expected_call(
 
1424
            'Branch.heads_to_fetch', ('quack/',),
 
1425
            'success', (['tip'], ['tagged-1', 'tagged-2']))
 
1426
        transport.mkdir('quack')
 
1427
        transport = transport.clone('quack')
 
1428
        branch = self.make_remote_branch(transport, client)
 
1429
        branch._format._use_default_local_heads_to_fetch = lambda: False
 
1430
        result = branch.heads_to_fetch()
 
1431
        self.assertFinished(client)
 
1432
        self.assertEqual((set(['tip']), set(['tagged-1', 'tagged-2'])), result)
 
1433
 
 
1434
    def make_branch_with_tags(self):
 
1435
        self.setup_smart_server_with_call_log()
 
1436
        # Make a branch with a single revision.
 
1437
        builder = self.make_branch_builder('foo')
 
1438
        builder.start_series()
 
1439
        builder.build_snapshot('tip', None, [
 
1440
            ('add', ('', 'root-id', 'directory', ''))])
 
1441
        builder.finish_series()
 
1442
        branch = builder.get_branch()
 
1443
        # Add two tags to that branch
 
1444
        branch.tags.set_tag('tag-1', 'rev-1')
 
1445
        branch.tags.set_tag('tag-2', 'rev-2')
 
1446
        return branch
 
1447
 
 
1448
    def test_backwards_compatible(self):
 
1449
        br = self.make_branch_with_tags()
 
1450
        br.get_config_stack().set('branch.fetch_tags', True)
 
1451
        self.addCleanup(br.lock_read().unlock)
 
1452
        # Disable the heads_to_fetch verb
 
1453
        verb = 'Branch.heads_to_fetch'
 
1454
        self.disable_verb(verb)
 
1455
        self.reset_smart_call_log()
 
1456
        result = br.heads_to_fetch()
 
1457
        self.assertEqual((set(['tip']), set(['rev-1', 'rev-2'])), result)
 
1458
        self.assertEqual(
 
1459
            ['Branch.last_revision_info', 'Branch.get_tags_bytes'],
 
1460
            [call.call.method for call in self.hpss_calls])
 
1461
 
 
1462
    def test_backwards_compatible_no_tags(self):
 
1463
        br = self.make_branch_with_tags()
 
1464
        br.get_config_stack().set('branch.fetch_tags', False)
 
1465
        self.addCleanup(br.lock_read().unlock)
 
1466
        # Disable the heads_to_fetch verb
 
1467
        verb = 'Branch.heads_to_fetch'
 
1468
        self.disable_verb(verb)
 
1469
        self.reset_smart_call_log()
 
1470
        result = br.heads_to_fetch()
 
1471
        self.assertEqual((set(['tip']), set()), result)
 
1472
        self.assertEqual(
 
1473
            ['Branch.last_revision_info'],
 
1474
            [call.call.method for call in self.hpss_calls])
 
1475
 
 
1476
 
998
1477
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
999
1478
 
1000
1479
    def test_empty_branch(self):
1055
1534
        client.add_expected_call(
1056
1535
            'Branch.get_stacked_on_url', ('stacked/',),
1057
1536
            'success', ('ok', vfs_url))
1058
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1537
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
1059
1538
            _client=client)
1060
1539
        repo_fmt = remote.RemoteRepositoryFormat()
1061
1540
        repo_fmt._custom_format = stacked_branch.repository._format
1072
1551
        client = FakeClient(self.get_url())
1073
1552
        branch_network_name = self.get_branch_format().network_name()
1074
1553
        client.add_expected_call(
1075
 
            'BzrDir.open_branchV2', ('stacked/',),
 
1554
            'BzrDir.open_branchV3', ('stacked/',),
1076
1555
            'success', ('branch', branch_network_name))
1077
1556
        client.add_expected_call(
1078
1557
            'BzrDir.find_repositoryV3', ('stacked/',),
1088
1567
        # this will also do vfs access, but that goes direct to the transport
1089
1568
        # and isn't seen by the FakeClient.
1090
1569
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1091
 
            remote.RemoteBzrDirFormat(), _client=client)
 
1570
            RemoteBzrDirFormat(), _client=client)
1092
1571
        branch = bzrdir.open_branch()
1093
1572
        result = branch.get_stacked_on_url()
1094
1573
        self.assertEqual('../base', result)
1100
1579
            len(branch.repository._real_repository._fallback_repositories))
1101
1580
 
1102
1581
    def test_get_stacked_on_real_branch(self):
1103
 
        base_branch = self.make_branch('base', format='1.6')
1104
 
        stacked_branch = self.make_branch('stacked', format='1.6')
 
1582
        base_branch = self.make_branch('base')
 
1583
        stacked_branch = self.make_branch('stacked')
1105
1584
        stacked_branch.set_stacked_on_url('../base')
1106
1585
        reference_format = self.get_repo_format()
1107
1586
        network_name = reference_format.network_name()
1108
1587
        client = FakeClient(self.get_url())
1109
1588
        branch_network_name = self.get_branch_format().network_name()
1110
1589
        client.add_expected_call(
1111
 
            'BzrDir.open_branchV2', ('stacked/',),
 
1590
            'BzrDir.open_branchV3', ('stacked/',),
1112
1591
            'success', ('branch', branch_network_name))
1113
1592
        client.add_expected_call(
1114
1593
            'BzrDir.find_repositoryV3', ('stacked/',),
1115
 
            'success', ('ok', '', 'no', 'no', 'yes', network_name))
 
1594
            'success', ('ok', '', 'yes', 'no', 'yes', network_name))
1116
1595
        # called twice, once from constructor and then again by us
1117
1596
        client.add_expected_call(
1118
1597
            'Branch.get_stacked_on_url', ('stacked/',),
1121
1600
            'Branch.get_stacked_on_url', ('stacked/',),
1122
1601
            'success', ('ok', '../base'))
1123
1602
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1124
 
            remote.RemoteBzrDirFormat(), _client=client)
 
1603
            RemoteBzrDirFormat(), _client=client)
1125
1604
        branch = bzrdir.open_branch()
1126
1605
        result = branch.get_stacked_on_url()
1127
1606
        self.assertEqual('../base', result)
1135
1614
class TestBranchSetLastRevision(RemoteBranchTestCase):
1136
1615
 
1137
1616
    def test_set_empty(self):
1138
 
        # set_revision_history([]) is translated to calling
 
1617
        # _set_last_revision_info('null:') is translated to calling
1139
1618
        # Branch.set_last_revision(path, '') on the wire.
1140
1619
        transport = MemoryTransport()
1141
1620
        transport.mkdir('branch')
1159
1638
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1160
1639
            'success', ('ok',))
1161
1640
        branch = self.make_remote_branch(transport, client)
1162
 
        # This is a hack to work around the problem that RemoteBranch currently
1163
 
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1164
 
        branch._ensure_real = lambda: None
1165
1641
        branch.lock_write()
1166
 
        result = branch.set_revision_history([])
 
1642
        result = branch._set_last_revision(NULL_REVISION)
1167
1643
        branch.unlock()
1168
1644
        self.assertEqual(None, result)
1169
1645
        self.assertFinished(client)
1170
1646
 
1171
1647
    def test_set_nonempty(self):
1172
 
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
 
1648
        # set_last_revision_info(N, rev-idN) is translated to calling
1173
1649
        # Branch.set_last_revision(path, rev-idN) on the wire.
1174
1650
        transport = MemoryTransport()
1175
1651
        transport.mkdir('branch')
1196
1672
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1197
1673
            'success', ('ok',))
1198
1674
        branch = self.make_remote_branch(transport, client)
1199
 
        # This is a hack to work around the problem that RemoteBranch currently
1200
 
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1201
 
        branch._ensure_real = lambda: None
1202
1675
        # Lock the branch, reset the record of remote calls.
1203
1676
        branch.lock_write()
1204
 
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
 
1677
        result = branch._set_last_revision('rev-id2')
1205
1678
        branch.unlock()
1206
1679
        self.assertEqual(None, result)
1207
1680
        self.assertFinished(client)
1237
1710
        branch = self.make_remote_branch(transport, client)
1238
1711
        branch.lock_write()
1239
1712
        self.assertRaises(
1240
 
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
 
1713
            errors.NoSuchRevision, branch._set_last_revision, 'rev-id')
1241
1714
        branch.unlock()
1242
1715
        self.assertFinished(client)
1243
1716
 
1271
1744
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1272
1745
            'success', ('ok',))
1273
1746
        branch = self.make_remote_branch(transport, client)
1274
 
        branch._ensure_real = lambda: None
1275
1747
        branch.lock_write()
1276
1748
        # The 'TipChangeRejected' error response triggered by calling
1277
 
        # set_revision_history causes a TipChangeRejected exception.
 
1749
        # set_last_revision_info causes a TipChangeRejected exception.
1278
1750
        err = self.assertRaises(
1279
 
            errors.TipChangeRejected, branch.set_revision_history, ['rev-id'])
 
1751
            errors.TipChangeRejected,
 
1752
            branch._set_last_revision, 'rev-id')
1280
1753
        # The UTF-8 message from the response has been decoded into a unicode
1281
1754
        # object.
1282
1755
        self.assertIsInstance(err.msg, unicode)
1342
1815
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1343
1816
        branch.unlock()
1344
1817
 
1345
 
    def lock_remote_branch(self, branch):
1346
 
        """Trick a RemoteBranch into thinking it is locked."""
1347
 
        branch._lock_mode = 'w'
1348
 
        branch._lock_count = 2
1349
 
        branch._lock_token = 'branch token'
1350
 
        branch._repo_lock_token = 'repo token'
1351
 
        branch.repository._lock_mode = 'w'
1352
 
        branch.repository._lock_count = 2
1353
 
        branch.repository._lock_token = 'repo token'
1354
 
 
1355
1818
    def test_backwards_compatibility(self):
1356
1819
        """If the server does not support the Branch.set_last_revision_info
1357
1820
        verb (which is new in 1.4), then the client falls back to VFS methods.
1480
1943
    def test_get_multi_line_branch_conf(self):
1481
1944
        # Make sure that multiple-line branch.conf files are supported
1482
1945
        #
1483
 
        # https://bugs.edge.launchpad.net/bzr/+bug/354075
 
1946
        # https://bugs.launchpad.net/bzr/+bug/354075
1484
1947
        client = FakeClient()
1485
1948
        client.add_expected_call(
1486
1949
            'Branch.get_stacked_on_url', ('memory:///',),
1514
1977
        branch.unlock()
1515
1978
        self.assertFinished(client)
1516
1979
 
 
1980
    def test_set_option_with_dict(self):
 
1981
        client = FakeClient()
 
1982
        client.add_expected_call(
 
1983
            'Branch.get_stacked_on_url', ('memory:///',),
 
1984
            'error', ('NotStacked',),)
 
1985
        client.add_expected_call(
 
1986
            'Branch.lock_write', ('memory:///', '', ''),
 
1987
            'success', ('ok', 'branch token', 'repo token'))
 
1988
        encoded_dict_value = 'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde'
 
1989
        client.add_expected_call(
 
1990
            'Branch.set_config_option_dict', ('memory:///', 'branch token',
 
1991
            'repo token', encoded_dict_value, 'foo', ''),
 
1992
            'success', ())
 
1993
        client.add_expected_call(
 
1994
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
 
1995
            'success', ('ok',))
 
1996
        transport = MemoryTransport()
 
1997
        branch = self.make_remote_branch(transport, client)
 
1998
        branch.lock_write()
 
1999
        config = branch._get_config()
 
2000
        config.set_option(
 
2001
            {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'},
 
2002
            'foo')
 
2003
        branch.unlock()
 
2004
        self.assertFinished(client)
 
2005
 
1517
2006
    def test_backwards_compat_set_option(self):
1518
2007
        self.setup_smart_server_with_call_log()
1519
2008
        branch = self.make_branch('.')
1523
2012
        self.addCleanup(branch.unlock)
1524
2013
        self.reset_smart_call_log()
1525
2014
        branch._get_config().set_option('value', 'name')
1526
 
        self.assertLength(10, self.hpss_calls)
 
2015
        self.assertLength(11, self.hpss_calls)
1527
2016
        self.assertEqual('value', branch._get_config().get_option('name'))
1528
2017
 
 
2018
    def test_backwards_compat_set_option_with_dict(self):
 
2019
        self.setup_smart_server_with_call_log()
 
2020
        branch = self.make_branch('.')
 
2021
        verb = 'Branch.set_config_option_dict'
 
2022
        self.disable_verb(verb)
 
2023
        branch.lock_write()
 
2024
        self.addCleanup(branch.unlock)
 
2025
        self.reset_smart_call_log()
 
2026
        config = branch._get_config()
 
2027
        value_dict = {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
 
2028
        config.set_option(value_dict, 'name')
 
2029
        self.assertLength(11, self.hpss_calls)
 
2030
        self.assertEqual(value_dict, branch._get_config().get_option('name'))
 
2031
 
 
2032
 
 
2033
class TestBranchGetPutConfigStore(RemoteBranchTestCase):
 
2034
 
 
2035
    def test_get_branch_conf(self):
 
2036
        # in an empty branch we decode the response properly
 
2037
        client = FakeClient()
 
2038
        client.add_expected_call(
 
2039
            'Branch.get_stacked_on_url', ('memory:///',),
 
2040
            'error', ('NotStacked',),)
 
2041
        client.add_success_response_with_body('# config file body', 'ok')
 
2042
        transport = MemoryTransport()
 
2043
        branch = self.make_remote_branch(transport, client)
 
2044
        config = branch.get_config_stack()
 
2045
        config.get("email")
 
2046
        config.get("log_format")
 
2047
        self.assertEqual(
 
2048
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
 
2049
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
 
2050
            client._calls)
 
2051
 
 
2052
    def test_set_branch_conf(self):
 
2053
        client = FakeClient()
 
2054
        client.add_expected_call(
 
2055
            'Branch.get_stacked_on_url', ('memory:///',),
 
2056
            'error', ('NotStacked',),)
 
2057
        client.add_expected_call(
 
2058
            'Branch.lock_write', ('memory:///', '', ''),
 
2059
            'success', ('ok', 'branch token', 'repo token'))
 
2060
        client.add_expected_call(
 
2061
            'Branch.get_config_file', ('memory:///', ),
 
2062
            'success', ('ok', ), "# line 1\n")
 
2063
        client.add_expected_call(
 
2064
            'Branch.get_config_file', ('memory:///', ),
 
2065
            'success', ('ok', ), "# line 1\n")
 
2066
        client.add_expected_call(
 
2067
            'Branch.put_config_file', ('memory:///', 'branch token',
 
2068
            'repo token'),
 
2069
            'success', ('ok',))
 
2070
        client.add_expected_call(
 
2071
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
 
2072
            'success', ('ok',))
 
2073
        transport = MemoryTransport()
 
2074
        branch = self.make_remote_branch(transport, client)
 
2075
        branch.lock_write()
 
2076
        config = branch.get_config_stack()
 
2077
        config.set('email', 'The Dude <lebowski@example.com>')
 
2078
        branch.unlock()
 
2079
        self.assertFinished(client)
 
2080
        self.assertEqual(
 
2081
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
 
2082
             ('call', 'Branch.lock_write', ('memory:///', '', '')),
 
2083
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',)),
 
2084
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',)),
 
2085
             ('call_with_body_bytes_expecting_body', 'Branch.put_config_file',
 
2086
                 ('memory:///', 'branch token', 'repo token'),
 
2087
                 '# line 1\nemail = The Dude <lebowski@example.com>\n'),
 
2088
             ('call', 'Branch.unlock', ('memory:///', 'branch token', 'repo token'))],
 
2089
            client._calls)
 
2090
 
1529
2091
 
1530
2092
class TestBranchLockWrite(RemoteBranchTestCase):
1531
2093
 
1545
2107
        self.assertFinished(client)
1546
2108
 
1547
2109
 
 
2110
class TestBranchRevisionIdToRevno(RemoteBranchTestCase):
 
2111
 
 
2112
    def test_simple(self):
 
2113
        transport = MemoryTransport()
 
2114
        client = FakeClient(transport.base)
 
2115
        client.add_expected_call(
 
2116
            'Branch.get_stacked_on_url', ('quack/',),
 
2117
            'error', ('NotStacked',),)
 
2118
        client.add_expected_call(
 
2119
            'Branch.revision_id_to_revno', ('quack/', 'null:'),
 
2120
            'success', ('ok', '0',),)
 
2121
        client.add_expected_call(
 
2122
            'Branch.revision_id_to_revno', ('quack/', 'unknown'),
 
2123
            'error', ('NoSuchRevision', 'unknown',),)
 
2124
        transport.mkdir('quack')
 
2125
        transport = transport.clone('quack')
 
2126
        branch = self.make_remote_branch(transport, client)
 
2127
        self.assertEqual(0, branch.revision_id_to_revno('null:'))
 
2128
        self.assertRaises(errors.NoSuchRevision,
 
2129
            branch.revision_id_to_revno, 'unknown')
 
2130
        self.assertFinished(client)
 
2131
 
 
2132
    def test_dotted(self):
 
2133
        transport = MemoryTransport()
 
2134
        client = FakeClient(transport.base)
 
2135
        client.add_expected_call(
 
2136
            'Branch.get_stacked_on_url', ('quack/',),
 
2137
            'error', ('NotStacked',),)
 
2138
        client.add_expected_call(
 
2139
            'Branch.revision_id_to_revno', ('quack/', 'null:'),
 
2140
            'success', ('ok', '0',),)
 
2141
        client.add_expected_call(
 
2142
            'Branch.revision_id_to_revno', ('quack/', 'unknown'),
 
2143
            'error', ('NoSuchRevision', 'unknown',),)
 
2144
        transport.mkdir('quack')
 
2145
        transport = transport.clone('quack')
 
2146
        branch = self.make_remote_branch(transport, client)
 
2147
        self.assertEqual((0, ), branch.revision_id_to_dotted_revno('null:'))
 
2148
        self.assertRaises(errors.NoSuchRevision,
 
2149
            branch.revision_id_to_dotted_revno, 'unknown')
 
2150
        self.assertFinished(client)
 
2151
 
 
2152
    def test_dotted_no_smart_verb(self):
 
2153
        self.setup_smart_server_with_call_log()
 
2154
        branch = self.make_branch('.')
 
2155
        self.disable_verb('Branch.revision_id_to_revno')
 
2156
        self.reset_smart_call_log()
 
2157
        self.assertEqual((0, ),
 
2158
            branch.revision_id_to_dotted_revno('null:'))
 
2159
        self.assertLength(8, self.hpss_calls)
 
2160
 
 
2161
 
1548
2162
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
1549
2163
 
1550
2164
    def test__get_config(self):
1564
2178
        self.reset_smart_call_log()
1565
2179
        config = bzrdir.get_config()
1566
2180
        config.set_default_stack_on('/')
1567
 
        self.assertLength(3, self.hpss_calls)
 
2181
        self.assertLength(4, self.hpss_calls)
1568
2182
 
1569
2183
    def test_backwards_compat_get_option(self):
1570
2184
        self.setup_smart_server_with_call_log()
1574
2188
        self.reset_smart_call_log()
1575
2189
        self.assertEqual(None,
1576
2190
            bzrdir._get_config().get_option('default_stack_on'))
1577
 
        self.assertLength(3, self.hpss_calls)
 
2191
        self.assertLength(4, self.hpss_calls)
1578
2192
 
1579
2193
 
1580
2194
class TestTransportIsReadonly(tests.TestCase):
1667
2281
        client = FakeClient(transport.base)
1668
2282
        transport = transport.clone(transport_path)
1669
2283
        # we do not want bzrdir to make any remote calls
1670
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
2284
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
1671
2285
            _client=False)
1672
2286
        repo = RemoteRepository(bzrdir, None, _client=client)
1673
2287
        return repo, client
1674
2288
 
1675
2289
 
 
2290
def remoted_description(format):
 
2291
    return 'Remote: ' + format.get_format_description()
 
2292
 
 
2293
 
 
2294
class TestBranchFormat(tests.TestCase):
 
2295
 
 
2296
    def test_get_format_description(self):
 
2297
        remote_format = RemoteBranchFormat()
 
2298
        real_format = branch.format_registry.get_default()
 
2299
        remote_format._network_name = real_format.network_name()
 
2300
        self.assertEqual(remoted_description(real_format),
 
2301
            remote_format.get_format_description())
 
2302
 
 
2303
 
1676
2304
class TestRepositoryFormat(TestRemoteRepository):
1677
2305
 
1678
2306
    def test_fast_delta(self):
1679
 
        true_name = groupcompress_repo.RepositoryFormatCHK1().network_name()
 
2307
        true_name = groupcompress_repo.RepositoryFormat2a().network_name()
1680
2308
        true_format = RemoteRepositoryFormat()
1681
2309
        true_format._network_name = true_name
1682
2310
        self.assertEqual(True, true_format.fast_deltas)
1683
 
        false_name = pack_repo.RepositoryFormatKnitPack1().network_name()
 
2311
        false_name = knitpack_repo.RepositoryFormatKnitPack1().network_name()
1684
2312
        false_format = RemoteRepositoryFormat()
1685
2313
        false_format._network_name = false_name
1686
2314
        self.assertEqual(False, false_format.fast_deltas)
1687
2315
 
 
2316
    def test_get_format_description(self):
 
2317
        remote_repo_format = RemoteRepositoryFormat()
 
2318
        real_format = repository.format_registry.get_default()
 
2319
        remote_repo_format._network_name = real_format.network_name()
 
2320
        self.assertEqual(remoted_description(real_format),
 
2321
            remote_repo_format.get_format_description())
 
2322
 
 
2323
 
 
2324
class TestRepositoryAllRevisionIds(TestRemoteRepository):
 
2325
 
 
2326
    def test_empty(self):
 
2327
        transport_path = 'quack'
 
2328
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2329
        client.add_success_response_with_body('', 'ok')
 
2330
        self.assertEqual([], repo.all_revision_ids())
 
2331
        self.assertEqual(
 
2332
            [('call_expecting_body', 'Repository.all_revision_ids',
 
2333
             ('quack/',))],
 
2334
            client._calls)
 
2335
 
 
2336
    def test_with_some_content(self):
 
2337
        transport_path = 'quack'
 
2338
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2339
        client.add_success_response_with_body(
 
2340
            'rev1\nrev2\nanotherrev\n', 'ok')
 
2341
        self.assertEqual(["rev1", "rev2", "anotherrev"],
 
2342
            repo.all_revision_ids())
 
2343
        self.assertEqual(
 
2344
            [('call_expecting_body', 'Repository.all_revision_ids',
 
2345
             ('quack/',))],
 
2346
            client._calls)
 
2347
 
1688
2348
 
1689
2349
class TestRepositoryGatherStats(TestRemoteRepository):
1690
2350
 
1744
2404
                         result)
1745
2405
 
1746
2406
 
 
2407
class TestRepositoryBreakLock(TestRemoteRepository):
 
2408
 
 
2409
    def test_break_lock(self):
 
2410
        transport_path = 'quack'
 
2411
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2412
        client.add_success_response('ok')
 
2413
        repo.break_lock()
 
2414
        self.assertEqual(
 
2415
            [('call', 'Repository.break_lock', ('quack/',))],
 
2416
            client._calls)
 
2417
 
 
2418
 
 
2419
class TestRepositoryGetSerializerFormat(TestRemoteRepository):
 
2420
 
 
2421
    def test_get_serializer_format(self):
 
2422
        transport_path = 'hill'
 
2423
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2424
        client.add_success_response('ok', '7')
 
2425
        self.assertEqual('7', repo.get_serializer_format())
 
2426
        self.assertEqual(
 
2427
            [('call', 'VersionedFileRepository.get_serializer_format',
 
2428
              ('hill/', ))],
 
2429
            client._calls)
 
2430
 
 
2431
 
 
2432
class TestRepositoryReconcile(TestRemoteRepository):
 
2433
 
 
2434
    def test_reconcile(self):
 
2435
        transport_path = 'hill'
 
2436
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2437
        body = ("garbage_inventories: 2\n"
 
2438
                "inconsistent_parents: 3\n")
 
2439
        client.add_expected_call(
 
2440
            'Repository.lock_write', ('hill/', ''),
 
2441
            'success', ('ok', 'a token'))
 
2442
        client.add_success_response_with_body(body, 'ok')
 
2443
        reconciler = repo.reconcile()
 
2444
        self.assertEqual(
 
2445
            [('call', 'Repository.lock_write', ('hill/', '')),
 
2446
             ('call_expecting_body', 'Repository.reconcile',
 
2447
                ('hill/', 'a token'))],
 
2448
            client._calls)
 
2449
        self.assertEqual(2, reconciler.garbage_inventories)
 
2450
        self.assertEqual(3, reconciler.inconsistent_parents)
 
2451
 
 
2452
 
 
2453
class TestRepositoryGetRevisionSignatureText(TestRemoteRepository):
 
2454
 
 
2455
    def test_text(self):
 
2456
        # ('ok',), body with signature text
 
2457
        transport_path = 'quack'
 
2458
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2459
        client.add_success_response_with_body(
 
2460
            'THETEXT', 'ok')
 
2461
        self.assertEqual("THETEXT", repo.get_signature_text("revid"))
 
2462
        self.assertEqual(
 
2463
            [('call_expecting_body', 'Repository.get_revision_signature_text',
 
2464
             ('quack/', 'revid'))],
 
2465
            client._calls)
 
2466
 
 
2467
    def test_no_signature(self):
 
2468
        transport_path = 'quick'
 
2469
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2470
        client.add_error_response('nosuchrevision', 'unknown')
 
2471
        self.assertRaises(errors.NoSuchRevision, repo.get_signature_text,
 
2472
                "unknown")
 
2473
        self.assertEqual(
 
2474
            [('call_expecting_body', 'Repository.get_revision_signature_text',
 
2475
              ('quick/', 'unknown'))],
 
2476
            client._calls)
 
2477
 
 
2478
 
1747
2479
class TestRepositoryGetGraph(TestRemoteRepository):
1748
2480
 
1749
2481
    def test_get_graph(self):
1754
2486
        self.assertNotEqual(graph._parents_provider, repo)
1755
2487
 
1756
2488
 
 
2489
class TestRepositoryAddSignatureText(TestRemoteRepository):
 
2490
 
 
2491
    def test_add_signature_text(self):
 
2492
        transport_path = 'quack'
 
2493
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2494
        client.add_expected_call(
 
2495
            'Repository.lock_write', ('quack/', ''),
 
2496
            'success', ('ok', 'a token'))
 
2497
        client.add_expected_call(
 
2498
            'Repository.start_write_group', ('quack/', 'a token'),
 
2499
            'success', ('ok', ('token1', )))
 
2500
        client.add_expected_call(
 
2501
            'Repository.add_signature_text', ('quack/', 'a token', 'rev1',
 
2502
                'token1'),
 
2503
            'success', ('ok', ), None)
 
2504
        repo.lock_write()
 
2505
        repo.start_write_group()
 
2506
        self.assertIs(None,
 
2507
            repo.add_signature_text("rev1", "every bloody emperor"))
 
2508
        self.assertEqual(
 
2509
            ('call_with_body_bytes_expecting_body',
 
2510
              'Repository.add_signature_text',
 
2511
                ('quack/', 'a token', 'rev1', 'token1'),
 
2512
              'every bloody emperor'),
 
2513
            client._calls[-1])
 
2514
 
 
2515
 
1757
2516
class TestRepositoryGetParentMap(TestRemoteRepository):
1758
2517
 
1759
2518
    def test_get_parent_map_caching(self):
1809
2568
        parents = repo.get_parent_map([rev_id])
1810
2569
        self.assertEqual(
1811
2570
            [('call_with_body_bytes_expecting_body',
1812
 
              'Repository.get_parent_map', ('quack/', 'include-missing:',
1813
 
              rev_id), '\n\n0'),
 
2571
              'Repository.get_parent_map',
 
2572
              ('quack/', 'include-missing:', rev_id), '\n\n0'),
1814
2573
             ('disconnect medium',),
1815
2574
             ('call_expecting_body', 'Repository.get_revision_graph',
1816
2575
              ('quack/', ''))],
1875
2634
        self.assertLength(1, self.hpss_calls)
1876
2635
 
1877
2636
    def disableExtraResults(self):
1878
 
        old_flag = SmartServerRepositoryGetParentMap.no_extra_results
1879
 
        SmartServerRepositoryGetParentMap.no_extra_results = True
1880
 
        def reset_values():
1881
 
            SmartServerRepositoryGetParentMap.no_extra_results = old_flag
1882
 
        self.addCleanup(reset_values)
 
2637
        self.overrideAttr(SmartServerRepositoryGetParentMap,
 
2638
                          'no_extra_results', True)
1883
2639
 
1884
2640
    def test_null_cached_missing_and_stop_key(self):
1885
2641
        self.setup_smart_server_with_call_log()
1939
2695
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
1940
2696
        self.assertLength(0, self.hpss_calls)
1941
2697
 
 
2698
    def test_exposes_get_cached_parent_map(self):
 
2699
        """RemoteRepository exposes get_cached_parent_map from
 
2700
        _unstacked_provider
 
2701
        """
 
2702
        r1 = u'\u0e33'.encode('utf8')
 
2703
        r2 = u'\u0dab'.encode('utf8')
 
2704
        lines = [' '.join([r2, r1]), r1]
 
2705
        encoded_body = bz2.compress('\n'.join(lines))
 
2706
 
 
2707
        transport_path = 'quack'
 
2708
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2709
        client.add_success_response_with_body(encoded_body, 'ok')
 
2710
        repo.lock_read()
 
2711
        # get_cached_parent_map should *not* trigger an RPC
 
2712
        self.assertEqual({}, repo.get_cached_parent_map([r1]))
 
2713
        self.assertEqual([], client._calls)
 
2714
        self.assertEqual({r2: (r1,)}, repo.get_parent_map([r2]))
 
2715
        self.assertEqual({r1: (NULL_REVISION,)},
 
2716
            repo.get_cached_parent_map([r1]))
 
2717
        self.assertEqual(
 
2718
            [('call_with_body_bytes_expecting_body',
 
2719
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
 
2720
              '\n\n0')],
 
2721
            client._calls)
 
2722
        repo.unlock()
 
2723
 
1942
2724
 
1943
2725
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
1944
2726
 
1945
2727
    def test_allows_new_revisions(self):
1946
2728
        """get_parent_map's results can be updated by commit."""
1947
 
        smart_server = server.SmartTCPServer_for_testing()
1948
 
        smart_server.setUp()
1949
 
        self.addCleanup(smart_server.tearDown)
 
2729
        smart_server = test_server.SmartTCPServer_for_testing()
 
2730
        self.start_server(smart_server)
1950
2731
        self.make_branch('branch')
1951
2732
        branch = Branch.open(smart_server.get_url() + '/branch')
1952
2733
        tree = branch.create_checkout('tree', lightweight=True)
1960
2741
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
1961
2742
 
1962
2743
 
 
2744
class TestRepositoryGetRevisions(TestRemoteRepository):
 
2745
 
 
2746
    def test_hpss_missing_revision(self):
 
2747
        transport_path = 'quack'
 
2748
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2749
        client.add_success_response_with_body(
 
2750
            '', 'ok', '10')
 
2751
        self.assertRaises(errors.NoSuchRevision, repo.get_revisions,
 
2752
            ['somerev1', 'anotherrev2'])
 
2753
        self.assertEqual(
 
2754
            [('call_with_body_bytes_expecting_body', 'Repository.iter_revisions',
 
2755
             ('quack/', ), "somerev1\nanotherrev2")],
 
2756
            client._calls)
 
2757
 
 
2758
    def test_hpss_get_single_revision(self):
 
2759
        transport_path = 'quack'
 
2760
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2761
        somerev1 = Revision("somerev1")
 
2762
        somerev1.committer = "Joe Committer <joe@example.com>"
 
2763
        somerev1.timestamp = 1321828927
 
2764
        somerev1.timezone = -60
 
2765
        somerev1.inventory_sha1 = "691b39be74c67b1212a75fcb19c433aaed903c2b"
 
2766
        somerev1.message = "Message"
 
2767
        body = zlib.compress(chk_bencode_serializer.write_revision_to_string(
 
2768
            somerev1))
 
2769
        # Split up body into two bits to make sure the zlib compression object
 
2770
        # gets data fed twice.
 
2771
        client.add_success_response_with_body(
 
2772
                [body[:10], body[10:]], 'ok', '10')
 
2773
        revs = repo.get_revisions(['somerev1'])
 
2774
        self.assertEqual(revs, [somerev1])
 
2775
        self.assertEqual(
 
2776
            [('call_with_body_bytes_expecting_body', 'Repository.iter_revisions',
 
2777
             ('quack/', ), "somerev1")],
 
2778
            client._calls)
 
2779
 
 
2780
 
1963
2781
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
1964
2782
 
1965
2783
    def test_null_revision(self):
2061
2879
        """
2062
2880
        # Make a repo with a fallback repo, both using a FakeClient.
2063
2881
        format = remote.response_tuple_to_repo_format(
2064
 
            ('yes', 'no', 'yes', 'fake-network-name'))
 
2882
            ('yes', 'no', 'yes', self.get_repo_format().network_name()))
2065
2883
        repo, client = self.setup_fake_client_and_repository('quack')
2066
2884
        repo._format = format
2067
2885
        fallback_repo, ignored = self.setup_fake_client_and_repository(
2068
2886
            'fallback')
2069
2887
        fallback_repo._client = client
 
2888
        fallback_repo._format = format
2070
2889
        repo.add_fallback_repository(fallback_repo)
2071
2890
        # First the client should ask the primary repo
2072
2891
        client.add_expected_call(
2093
2912
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
2094
2913
        self.assertFinished(client)
2095
2914
 
 
2915
    def test_branch_fallback_locking(self):
 
2916
        """RemoteBranch.get_rev_id takes a read lock, and tries to call the
 
2917
        get_rev_id_for_revno verb.  If the verb is unknown the VFS fallback
 
2918
        will be invoked, which will fail if the repo is unlocked.
 
2919
        """
 
2920
        self.setup_smart_server_with_call_log()
 
2921
        tree = self.make_branch_and_memory_tree('.')
 
2922
        tree.lock_write()
 
2923
        tree.add('')
 
2924
        rev1 = tree.commit('First')
 
2925
        rev2 = tree.commit('Second')
 
2926
        tree.unlock()
 
2927
        branch = tree.branch
 
2928
        self.assertFalse(branch.is_locked())
 
2929
        self.reset_smart_call_log()
 
2930
        verb = 'Repository.get_rev_id_for_revno'
 
2931
        self.disable_verb(verb)
 
2932
        self.assertEqual(rev1, branch.get_rev_id(1))
 
2933
        self.assertLength(1, [call for call in self.hpss_calls if
 
2934
                              call.call.method == verb])
 
2935
 
 
2936
 
 
2937
class TestRepositoryHasSignatureForRevisionId(TestRemoteRepository):
 
2938
 
 
2939
    def test_has_signature_for_revision_id(self):
 
2940
        # ('yes', ) for Repository.has_signature_for_revision_id -> 'True'.
 
2941
        transport_path = 'quack'
 
2942
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2943
        client.add_success_response('yes')
 
2944
        result = repo.has_signature_for_revision_id('A')
 
2945
        self.assertEqual(
 
2946
            [('call', 'Repository.has_signature_for_revision_id',
 
2947
              ('quack/', 'A'))],
 
2948
            client._calls)
 
2949
        self.assertEqual(True, result)
 
2950
 
 
2951
    def test_is_not_shared(self):
 
2952
        # ('no', ) for Repository.has_signature_for_revision_id -> 'False'.
 
2953
        transport_path = 'qwack'
 
2954
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2955
        client.add_success_response('no')
 
2956
        result = repo.has_signature_for_revision_id('A')
 
2957
        self.assertEqual(
 
2958
            [('call', 'Repository.has_signature_for_revision_id',
 
2959
              ('qwack/', 'A'))],
 
2960
            client._calls)
 
2961
        self.assertEqual(False, result)
 
2962
 
 
2963
 
 
2964
class TestRepositoryPhysicalLockStatus(TestRemoteRepository):
 
2965
 
 
2966
    def test_get_physical_lock_status_yes(self):
 
2967
        transport_path = 'qwack'
 
2968
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2969
        client.add_success_response('yes')
 
2970
        result = repo.get_physical_lock_status()
 
2971
        self.assertEqual(
 
2972
            [('call', 'Repository.get_physical_lock_status',
 
2973
              ('qwack/', ))],
 
2974
            client._calls)
 
2975
        self.assertEqual(True, result)
 
2976
 
 
2977
    def test_get_physical_lock_status_no(self):
 
2978
        transport_path = 'qwack'
 
2979
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2980
        client.add_success_response('no')
 
2981
        result = repo.get_physical_lock_status()
 
2982
        self.assertEqual(
 
2983
            [('call', 'Repository.get_physical_lock_status',
 
2984
              ('qwack/', ))],
 
2985
            client._calls)
 
2986
        self.assertEqual(False, result)
 
2987
 
2096
2988
 
2097
2989
class TestRepositoryIsShared(TestRemoteRepository):
2098
2990
 
2119
3011
        self.assertEqual(False, result)
2120
3012
 
2121
3013
 
 
3014
class TestRepositoryMakeWorkingTrees(TestRemoteRepository):
 
3015
 
 
3016
    def test_make_working_trees(self):
 
3017
        # ('yes', ) for Repository.make_working_trees -> 'True'.
 
3018
        transport_path = 'quack'
 
3019
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3020
        client.add_success_response('yes')
 
3021
        result = repo.make_working_trees()
 
3022
        self.assertEqual(
 
3023
            [('call', 'Repository.make_working_trees', ('quack/',))],
 
3024
            client._calls)
 
3025
        self.assertEqual(True, result)
 
3026
 
 
3027
    def test_no_working_trees(self):
 
3028
        # ('no', ) for Repository.make_working_trees -> 'False'.
 
3029
        transport_path = 'qwack'
 
3030
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3031
        client.add_success_response('no')
 
3032
        result = repo.make_working_trees()
 
3033
        self.assertEqual(
 
3034
            [('call', 'Repository.make_working_trees', ('qwack/',))],
 
3035
            client._calls)
 
3036
        self.assertEqual(False, result)
 
3037
 
 
3038
 
2122
3039
class TestRepositoryLockWrite(TestRemoteRepository):
2123
3040
 
2124
3041
    def test_lock_write(self):
2125
3042
        transport_path = 'quack'
2126
3043
        repo, client = self.setup_fake_client_and_repository(transport_path)
2127
3044
        client.add_success_response('ok', 'a token')
2128
 
        result = repo.lock_write()
 
3045
        token = repo.lock_write().repository_token
2129
3046
        self.assertEqual(
2130
3047
            [('call', 'Repository.lock_write', ('quack/', ''))],
2131
3048
            client._calls)
2132
 
        self.assertEqual('a token', result)
 
3049
        self.assertEqual('a token', token)
2133
3050
 
2134
3051
    def test_lock_write_already_locked(self):
2135
3052
        transport_path = 'quack'
2150
3067
            client._calls)
2151
3068
 
2152
3069
 
 
3070
class TestRepositoryWriteGroups(TestRemoteRepository):
 
3071
 
 
3072
    def test_start_write_group(self):
 
3073
        transport_path = 'quack'
 
3074
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3075
        client.add_expected_call(
 
3076
            'Repository.lock_write', ('quack/', ''),
 
3077
            'success', ('ok', 'a token'))
 
3078
        client.add_expected_call(
 
3079
            'Repository.start_write_group', ('quack/', 'a token'),
 
3080
            'success', ('ok', ('token1', )))
 
3081
        repo.lock_write()
 
3082
        repo.start_write_group()
 
3083
 
 
3084
    def test_start_write_group_unsuspendable(self):
 
3085
        # Some repositories do not support suspending write
 
3086
        # groups. For those, fall back to the "real" repository.
 
3087
        transport_path = 'quack'
 
3088
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3089
        def stub_ensure_real():
 
3090
            client._calls.append(('_ensure_real',))
 
3091
            repo._real_repository = _StubRealPackRepository(client._calls)
 
3092
        repo._ensure_real = stub_ensure_real
 
3093
        client.add_expected_call(
 
3094
            'Repository.lock_write', ('quack/', ''),
 
3095
            'success', ('ok', 'a token'))
 
3096
        client.add_expected_call(
 
3097
            'Repository.start_write_group', ('quack/', 'a token'),
 
3098
            'error', ('UnsuspendableWriteGroup',))
 
3099
        repo.lock_write()
 
3100
        repo.start_write_group()
 
3101
        self.assertEqual(client._calls[-2:], [ 
 
3102
            ('_ensure_real',),
 
3103
            ('start_write_group',)])
 
3104
 
 
3105
    def test_commit_write_group(self):
 
3106
        transport_path = 'quack'
 
3107
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3108
        client.add_expected_call(
 
3109
            'Repository.lock_write', ('quack/', ''),
 
3110
            'success', ('ok', 'a token'))
 
3111
        client.add_expected_call(
 
3112
            'Repository.start_write_group', ('quack/', 'a token'),
 
3113
            'success', ('ok', ['token1']))
 
3114
        client.add_expected_call(
 
3115
            'Repository.commit_write_group', ('quack/', 'a token', ['token1']),
 
3116
            'success', ('ok',))
 
3117
        repo.lock_write()
 
3118
        repo.start_write_group()
 
3119
        repo.commit_write_group()
 
3120
 
 
3121
    def test_abort_write_group(self):
 
3122
        transport_path = 'quack'
 
3123
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3124
        client.add_expected_call(
 
3125
            'Repository.lock_write', ('quack/', ''),
 
3126
            'success', ('ok', 'a token'))
 
3127
        client.add_expected_call(
 
3128
            'Repository.start_write_group', ('quack/', 'a token'),
 
3129
            'success', ('ok', ['token1']))
 
3130
        client.add_expected_call(
 
3131
            'Repository.abort_write_group', ('quack/', 'a token', ['token1']),
 
3132
            'success', ('ok',))
 
3133
        repo.lock_write()
 
3134
        repo.start_write_group()
 
3135
        repo.abort_write_group(False)
 
3136
 
 
3137
    def test_suspend_write_group(self):
 
3138
        transport_path = 'quack'
 
3139
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3140
        self.assertEqual([], repo.suspend_write_group())
 
3141
 
 
3142
    def test_resume_write_group(self):
 
3143
        transport_path = 'quack'
 
3144
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3145
        client.add_expected_call(
 
3146
            'Repository.lock_write', ('quack/', ''),
 
3147
            'success', ('ok', 'a token'))
 
3148
        client.add_expected_call(
 
3149
            'Repository.check_write_group', ('quack/', 'a token', ['token1']),
 
3150
            'success', ('ok',))
 
3151
        repo.lock_write()
 
3152
        repo.resume_write_group(['token1'])
 
3153
 
 
3154
 
2153
3155
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
2154
3156
 
2155
3157
    def test_backwards_compat(self):
2214
3216
        self.assertEqual([], client._calls)
2215
3217
 
2216
3218
 
 
3219
class TestRepositoryIterFilesBytes(TestRemoteRepository):
 
3220
    """Test Repository.iter_file_bytes."""
 
3221
 
 
3222
    def test_single(self):
 
3223
        transport_path = 'quack'
 
3224
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3225
        client.add_expected_call(
 
3226
            'Repository.iter_files_bytes', ('quack/', ),
 
3227
            'success', ('ok',), iter(["ok\x000", "\n", zlib.compress("mydata" * 10)]))
 
3228
        for (identifier, byte_stream) in repo.iter_files_bytes([("somefile",
 
3229
                "somerev", "myid")]):
 
3230
            self.assertEqual("myid", identifier)
 
3231
            self.assertEqual("".join(byte_stream), "mydata" * 10)
 
3232
 
 
3233
    def test_missing(self):
 
3234
        transport_path = 'quack'
 
3235
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3236
        client.add_expected_call(
 
3237
            'Repository.iter_files_bytes',
 
3238
                ('quack/', ),
 
3239
            'error', ('RevisionNotPresent', 'somefile', 'somerev'),
 
3240
            iter(["absent\0somefile\0somerev\n"]))
 
3241
        self.assertRaises(errors.RevisionNotPresent, list,
 
3242
                repo.iter_files_bytes(
 
3243
                [("somefile", "somerev", "myid")]))
 
3244
 
 
3245
 
2217
3246
class TestRepositoryInsertStreamBase(TestRemoteRepository):
2218
3247
    """Base class for Repository.insert_stream and .insert_stream_1.19
2219
3248
    tests.
2226
3255
        the client is finished.
2227
3256
        """
2228
3257
        sink = repo._get_sink()
2229
 
        fmt = repository.RepositoryFormat.get_default_format()
 
3258
        fmt = repository.format_registry.get_default()
2230
3259
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2231
3260
        self.assertEqual([], resume_tokens)
2232
3261
        self.assertEqual(set(), missing_keys)
2241
3270
    """
2242
3271
 
2243
3272
    def setUp(self):
2244
 
        TestRemoteRepository.setUp(self)
 
3273
        super(TestRepositoryInsertStream, self).setUp()
2245
3274
        self.disable_verb('Repository.insert_stream_1.19')
2246
3275
 
2247
3276
    def test_unlocked_repo(self):
2326
3355
        class FakeRealRepository:
2327
3356
            def _get_sink(self):
2328
3357
                return fake_real_sink
 
3358
            def is_in_write_group(self):
 
3359
                return False
 
3360
            def refresh_data(self):
 
3361
                return True
2329
3362
        repo._real_repository = FakeRealRepository()
2330
3363
        sink = repo._get_sink()
2331
 
        fmt = repository.RepositoryFormat.get_default_format()
 
3364
        fmt = repository.format_registry.get_default()
2332
3365
        stream = self.make_stream_with_inv_deltas(fmt)
2333
3366
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
2334
3367
        # Every record from the first inventory delta should have been sent to
2469
3502
    """RemoteRepository.copy_content_into optimizations"""
2470
3503
 
2471
3504
    def test_copy_content_remote_to_local(self):
2472
 
        self.transport_server = server.SmartTCPServer_for_testing
 
3505
        self.transport_server = test_server.SmartTCPServer_for_testing
2473
3506
        src_repo = self.make_repository('repo1')
2474
3507
        src_repo = repository.Repository.open(self.get_url('repo1'))
2475
3508
        # At the moment the tarball-based copy_content_into can't write back
2490
3523
        self.calls = calls
2491
3524
        self._pack_collection = _StubPackCollection(calls)
2492
3525
 
 
3526
    def start_write_group(self):
 
3527
        self.calls.append(('start_write_group',))
 
3528
 
2493
3529
    def is_in_write_group(self):
2494
3530
        return False
2495
3531
 
2554
3590
             ('pack collection autopack',)],
2555
3591
            client._calls)
2556
3592
 
 
3593
    def test_oom_error_reporting(self):
 
3594
        """An out-of-memory condition on the server is reported clearly"""
 
3595
        transport_path = 'quack'
 
3596
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3597
        client.add_expected_call(
 
3598
            'PackRepository.autopack', ('quack/',),
 
3599
            'error', ('MemoryError',))
 
3600
        err = self.assertRaises(errors.BzrError, repo.autopack)
 
3601
        self.assertContainsRe(str(err), "^remote server out of mem")
 
3602
 
2557
3603
 
2558
3604
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
2559
3605
    """Base class for unit tests for bzrlib.remote._translate_error."""
2623
3669
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
2624
3670
        self.assertEqual(expected_error, translated_error)
2625
3671
 
 
3672
    def test_nobranch_one_arg(self):
 
3673
        bzrdir = self.make_bzrdir('')
 
3674
        translated_error = self.translateTuple(
 
3675
            ('nobranch', 'extra detail'), bzrdir=bzrdir)
 
3676
        expected_error = errors.NotBranchError(
 
3677
            path=bzrdir.root_transport.base,
 
3678
            detail='extra detail')
 
3679
        self.assertEqual(expected_error, translated_error)
 
3680
 
 
3681
    def test_norepository(self):
 
3682
        bzrdir = self.make_bzrdir('')
 
3683
        translated_error = self.translateTuple(('norepository',),
 
3684
            bzrdir=bzrdir)
 
3685
        expected_error = errors.NoRepositoryPresent(bzrdir)
 
3686
        self.assertEqual(expected_error, translated_error)
 
3687
 
2626
3688
    def test_LockContention(self):
2627
3689
        translated_error = self.translateTuple(('LockContention',))
2628
3690
        expected_error = errors.LockContention('(remote lock)')
2656
3718
        expected_error = errors.DivergedBranches(branch, other_branch)
2657
3719
        self.assertEqual(expected_error, translated_error)
2658
3720
 
 
3721
    def test_NotStacked(self):
 
3722
        branch = self.make_branch('')
 
3723
        translated_error = self.translateTuple(('NotStacked',), branch=branch)
 
3724
        expected_error = errors.NotStacked(branch)
 
3725
        self.assertEqual(expected_error, translated_error)
 
3726
 
2659
3727
    def test_ReadError_no_args(self):
2660
3728
        path = 'a path'
2661
3729
        translated_error = self.translateTuple(('ReadError',), path=path)
2668
3736
        expected_error = errors.ReadError(path)
2669
3737
        self.assertEqual(expected_error, translated_error)
2670
3738
 
 
3739
    def test_IncompatibleRepositories(self):
 
3740
        translated_error = self.translateTuple(('IncompatibleRepositories',
 
3741
            "repo1", "repo2", "details here"))
 
3742
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
 
3743
            "details here")
 
3744
        self.assertEqual(expected_error, translated_error)
 
3745
 
2671
3746
    def test_PermissionDenied_no_args(self):
2672
3747
        path = 'a path'
2673
 
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
 
3748
        translated_error = self.translateTuple(('PermissionDenied',),
 
3749
            path=path)
2674
3750
        expected_error = errors.PermissionDenied(path)
2675
3751
        self.assertEqual(expected_error, translated_error)
2676
3752
 
2699
3775
        expected_error = errors.PermissionDenied(path, extra)
2700
3776
        self.assertEqual(expected_error, translated_error)
2701
3777
 
 
3778
    # GZ 2011-03-02: TODO test for PermissionDenied with non-ascii 'extra'
 
3779
 
 
3780
    def test_NoSuchFile_context_path(self):
 
3781
        local_path = "local path"
 
3782
        translated_error = self.translateTuple(('ReadError', "remote path"),
 
3783
            path=local_path)
 
3784
        expected_error = errors.ReadError(local_path)
 
3785
        self.assertEqual(expected_error, translated_error)
 
3786
 
 
3787
    def test_NoSuchFile_without_context(self):
 
3788
        remote_path = "remote path"
 
3789
        translated_error = self.translateTuple(('ReadError', remote_path))
 
3790
        expected_error = errors.ReadError(remote_path)
 
3791
        self.assertEqual(expected_error, translated_error)
 
3792
 
 
3793
    def test_ReadOnlyError(self):
 
3794
        translated_error = self.translateTuple(('ReadOnlyError',))
 
3795
        expected_error = errors.TransportNotPossible("readonly transport")
 
3796
        self.assertEqual(expected_error, translated_error)
 
3797
 
 
3798
    def test_MemoryError(self):
 
3799
        translated_error = self.translateTuple(('MemoryError',))
 
3800
        self.assertStartsWith(str(translated_error),
 
3801
            "remote server out of memory")
 
3802
 
 
3803
    def test_generic_IndexError_no_classname(self):
 
3804
        err = errors.ErrorFromSmartServer(('error', "list index out of range"))
 
3805
        translated_error = self.translateErrorFromSmartServer(err)
 
3806
        expected_error = errors.UnknownErrorFromSmartServer(err)
 
3807
        self.assertEqual(expected_error, translated_error)
 
3808
 
 
3809
    # GZ 2011-03-02: TODO test generic non-ascii error string
 
3810
 
 
3811
    def test_generic_KeyError(self):
 
3812
        err = errors.ErrorFromSmartServer(('error', 'KeyError', "1"))
 
3813
        translated_error = self.translateErrorFromSmartServer(err)
 
3814
        expected_error = errors.UnknownErrorFromSmartServer(err)
 
3815
        self.assertEqual(expected_error, translated_error)
 
3816
 
2702
3817
 
2703
3818
class TestErrorTranslationRobustness(TestErrorTranslationBase):
2704
3819
    """Unit tests for bzrlib.remote._translate_error's robustness.
2734
3849
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2735
3850
        # been muttered to the log file for developer to look at.
2736
3851
        self.assertContainsRe(
2737
 
            self._get_log(keep_log_file=True),
 
3852
            self.get_log(),
2738
3853
            "Missing key 'branch' in context")
2739
3854
 
2740
3855
    def test_path_missing(self):
2748
3863
        self.assertEqual(server_error, translated_error)
2749
3864
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2750
3865
        # been muttered to the log file for developer to look at.
2751
 
        self.assertContainsRe(
2752
 
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
 
3866
        self.assertContainsRe(self.get_log(), "Missing key 'path' in context")
2753
3867
 
2754
3868
 
2755
3869
class TestStacking(tests.TestCaseWithTransport):
2773
3887
        stacked_branch = self.make_branch('stacked', format='1.9')
2774
3888
        stacked_branch.set_stacked_on_url('../base')
2775
3889
        # start a server looking at this
2776
 
        smart_server = server.SmartTCPServer_for_testing()
2777
 
        smart_server.setUp()
2778
 
        self.addCleanup(smart_server.tearDown)
 
3890
        smart_server = test_server.SmartTCPServer_for_testing()
 
3891
        self.start_server(smart_server)
2779
3892
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
2780
3893
        # can get its branch and repository
2781
3894
        remote_branch = remote_bzrdir.open_branch()
2842
3955
        :result: The revision ids in the stream, in the order seen,
2843
3956
            the topological order of revisions in the source.
2844
3957
        """
2845
 
        unordered_format = bzrdir.format_registry.get(format)()
 
3958
        unordered_format = controldir.format_registry.get(format)()
2846
3959
        target_repository_format = unordered_format.repository_format
2847
3960
        # Cross check
2848
3961
        self.assertEqual(order, target_repository_format._fetch_order)
2851
3964
        _, stacked = branch_factory()
2852
3965
        source = stacked.repository._get_source(target_repository_format)
2853
3966
        tip = stacked.last_revision()
2854
 
        revs = stacked.repository.get_ancestry(tip)
2855
 
        search = graph.PendingAncestryResult([tip], stacked.repository)
 
3967
        stacked.repository._ensure_real()
 
3968
        graph = stacked.repository.get_graph()
 
3969
        revs = [r for (r,ps) in graph.iter_ancestry([tip])
 
3970
                if r != NULL_REVISION]
 
3971
        revs.reverse()
 
3972
        search = vf_search.PendingAncestryResult([tip], stacked.repository)
2856
3973
        self.reset_smart_call_log()
2857
3974
        stream = source.get_stream(search)
2858
 
        if None in revs:
2859
 
            revs.remove(None)
2860
3975
        # We trust that if a revision is in the stream the rest of the new
2861
3976
        # content for it is too, as per our main fetch tests; here we are
2862
3977
        # checking that the revisions are actually included at all, and their
2884
3999
            local_tree.commit('more local changes are better')
2885
4000
            branch = Branch.open(self.get_url('tree3'))
2886
4001
            branch.lock_read()
 
4002
            self.addCleanup(branch.unlock)
2887
4003
            return None, branch
2888
4004
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
2889
4005
            branch_factory=make_stacked_stacked)
2900
4016
        self.assertEqual(expected_revs, rev_ord)
2901
4017
        # Getting topological sort requires VFS calls still - one of which is
2902
4018
        # pushing up from the bound branch.
2903
 
        self.assertLength(13, self.hpss_calls)
 
4019
        self.assertLength(14, self.hpss_calls)
2904
4020
 
2905
4021
    def test_stacked_get_stream_groupcompress(self):
2906
4022
        # Repository._get_source.get_stream() from a stacked repository with
2935
4051
        super(TestRemoteBranchEffort, self).setUp()
2936
4052
        # Create a smart server that publishes whatever the backing VFS server
2937
4053
        # does.
2938
 
        self.smart_server = server.SmartTCPServer_for_testing()
2939
 
        self.smart_server.setUp(self.get_server())
2940
 
        self.addCleanup(self.smart_server.tearDown)
 
4054
        self.smart_server = test_server.SmartTCPServer_for_testing()
 
4055
        self.start_server(self.smart_server, self.get_server())
2941
4056
        # Log all HPSS calls into self.hpss_calls.
2942
4057
        _SmartClient.hooks.install_named_hook(
2943
4058
            'call', self.capture_hpss_call, None)
2948
4063
 
2949
4064
    def test_copy_content_into_avoids_revision_history(self):
2950
4065
        local = self.make_branch('local')
2951
 
        remote_backing_tree = self.make_branch_and_tree('remote')
2952
 
        remote_backing_tree.commit("Commit.")
 
4066
        builder = self.make_branch_builder('remote')
 
4067
        builder.build_commit(message="Commit.")
2953
4068
        remote_branch_url = self.smart_server.get_url() + 'remote'
2954
4069
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
2955
4070
        local.repository.fetch(remote_branch.repository)
2956
4071
        self.hpss_calls = []
2957
4072
        remote_branch.copy_content_into(local)
2958
4073
        self.assertFalse('Branch.revision_history' in self.hpss_calls)
 
4074
 
 
4075
    def test_fetch_everything_needs_just_one_call(self):
 
4076
        local = self.make_branch('local')
 
4077
        builder = self.make_branch_builder('remote')
 
4078
        builder.build_commit(message="Commit.")
 
4079
        remote_branch_url = self.smart_server.get_url() + 'remote'
 
4080
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
 
4081
        self.hpss_calls = []
 
4082
        local.repository.fetch(
 
4083
            remote_branch.repository,
 
4084
            fetch_spec=vf_search.EverythingResult(remote_branch.repository))
 
4085
        self.assertEqual(['Repository.get_stream_1.19'], self.hpss_calls)
 
4086
 
 
4087
    def override_verb(self, verb_name, verb):
 
4088
        request_handlers = request.request_handlers
 
4089
        orig_verb = request_handlers.get(verb_name)
 
4090
        orig_info = request_handlers.get_info(verb_name)
 
4091
        request_handlers.register(verb_name, verb, override_existing=True)
 
4092
        self.addCleanup(request_handlers.register, verb_name, orig_verb,
 
4093
                override_existing=True, info=orig_info)
 
4094
 
 
4095
    def test_fetch_everything_backwards_compat(self):
 
4096
        """Can fetch with EverythingResult even with pre 2.4 servers.
 
4097
        
 
4098
        Pre-2.4 do not support 'everything' searches with the
 
4099
        Repository.get_stream_1.19 verb.
 
4100
        """
 
4101
        verb_log = []
 
4102
        class OldGetStreamVerb(SmartServerRepositoryGetStream_1_19):
 
4103
            """A version of the Repository.get_stream_1.19 verb patched to
 
4104
            reject 'everything' searches the way 2.3 and earlier do.
 
4105
            """
 
4106
            def recreate_search(self, repository, search_bytes,
 
4107
                                discard_excess=False):
 
4108
                verb_log.append(search_bytes.split('\n', 1)[0])
 
4109
                if search_bytes == 'everything':
 
4110
                    return (None,
 
4111
                            request.FailedSmartServerResponse(('BadSearch',)))
 
4112
                return super(OldGetStreamVerb,
 
4113
                        self).recreate_search(repository, search_bytes,
 
4114
                            discard_excess=discard_excess)
 
4115
        self.override_verb('Repository.get_stream_1.19', OldGetStreamVerb)
 
4116
        local = self.make_branch('local')
 
4117
        builder = self.make_branch_builder('remote')
 
4118
        builder.build_commit(message="Commit.")
 
4119
        remote_branch_url = self.smart_server.get_url() + 'remote'
 
4120
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
 
4121
        self.hpss_calls = []
 
4122
        local.repository.fetch(
 
4123
            remote_branch.repository,
 
4124
            fetch_spec=vf_search.EverythingResult(remote_branch.repository))
 
4125
        # make sure the overridden verb was used
 
4126
        self.assertLength(1, verb_log)
 
4127
        # more than one HPSS call is needed, but because it's a VFS callback
 
4128
        # its hard to predict exactly how many.
 
4129
        self.assertTrue(len(self.hpss_calls) > 1)
 
4130
 
 
4131
 
 
4132
class TestUpdateBoundBranchWithModifiedBoundLocation(
 
4133
    tests.TestCaseWithTransport):
 
4134
    """Ensure correct handling of bound_location modifications.
 
4135
 
 
4136
    This is tested against a smart server as http://pad.lv/786980 was about a
 
4137
    ReadOnlyError (write attempt during a read-only transaction) which can only
 
4138
    happen in this context.
 
4139
    """
 
4140
 
 
4141
    def setUp(self):
 
4142
        super(TestUpdateBoundBranchWithModifiedBoundLocation, self).setUp()
 
4143
        self.transport_server = test_server.SmartTCPServer_for_testing
 
4144
 
 
4145
    def make_master_and_checkout(self, master_name, checkout_name):
 
4146
        # Create the master branch and its associated checkout
 
4147
        self.master = self.make_branch_and_tree(master_name)
 
4148
        self.checkout = self.master.branch.create_checkout(checkout_name)
 
4149
        # Modify the master branch so there is something to update
 
4150
        self.master.commit('add stuff')
 
4151
        self.last_revid = self.master.commit('even more stuff')
 
4152
        self.bound_location = self.checkout.branch.get_bound_location()
 
4153
 
 
4154
    def assertUpdateSucceeds(self, new_location):
 
4155
        self.checkout.branch.set_bound_location(new_location)
 
4156
        self.checkout.update()
 
4157
        self.assertEqual(self.last_revid, self.checkout.last_revision())
 
4158
 
 
4159
    def test_without_final_slash(self):
 
4160
        self.make_master_and_checkout('master', 'checkout')
 
4161
        # For unclear reasons some users have a bound_location without a final
 
4162
        # '/', simulate that by forcing such a value
 
4163
        self.assertEndsWith(self.bound_location, '/')
 
4164
        self.assertUpdateSucceeds(self.bound_location.rstrip('/'))
 
4165
 
 
4166
    def test_plus_sign(self):
 
4167
        self.make_master_and_checkout('+master', 'checkout')
 
4168
        self.assertUpdateSucceeds(self.bound_location.replace('%2B', '+', 1))
 
4169
 
 
4170
    def test_tilda(self):
 
4171
        # Embed ~ in the middle of the path just to avoid any $HOME
 
4172
        # interpretation
 
4173
        self.make_master_and_checkout('mas~ter', 'checkout')
 
4174
        self.assertUpdateSucceeds(self.bound_location.replace('%2E', '~', 1))
 
4175
 
 
4176
 
 
4177
class TestWithCustomErrorHandler(RemoteBranchTestCase):
 
4178
 
 
4179
    def test_no_context(self):
 
4180
        class OutOfCoffee(errors.BzrError):
 
4181
            """A dummy exception for testing."""
 
4182
 
 
4183
            def __init__(self, urgency):
 
4184
                self.urgency = urgency
 
4185
        remote.no_context_error_translators.register("OutOfCoffee",
 
4186
            lambda err: OutOfCoffee(err.error_args[0]))
 
4187
        transport = MemoryTransport()
 
4188
        client = FakeClient(transport.base)
 
4189
        client.add_expected_call(
 
4190
            'Branch.get_stacked_on_url', ('quack/',),
 
4191
            'error', ('NotStacked',))
 
4192
        client.add_expected_call(
 
4193
            'Branch.last_revision_info',
 
4194
            ('quack/',),
 
4195
            'error', ('OutOfCoffee', 'low'))
 
4196
        transport.mkdir('quack')
 
4197
        transport = transport.clone('quack')
 
4198
        branch = self.make_remote_branch(transport, client)
 
4199
        self.assertRaises(OutOfCoffee, branch.last_revision_info)
 
4200
        self.assertFinished(client)
 
4201
 
 
4202
    def test_with_context(self):
 
4203
        class OutOfTea(errors.BzrError):
 
4204
            def __init__(self, branch, urgency):
 
4205
                self.branch = branch
 
4206
                self.urgency = urgency
 
4207
        remote.error_translators.register("OutOfTea",
 
4208
            lambda err, find, path: OutOfTea(err.error_args[0],
 
4209
                find("branch")))
 
4210
        transport = MemoryTransport()
 
4211
        client = FakeClient(transport.base)
 
4212
        client.add_expected_call(
 
4213
            'Branch.get_stacked_on_url', ('quack/',),
 
4214
            'error', ('NotStacked',))
 
4215
        client.add_expected_call(
 
4216
            'Branch.last_revision_info',
 
4217
            ('quack/',),
 
4218
            'error', ('OutOfTea', 'low'))
 
4219
        transport.mkdir('quack')
 
4220
        transport = transport.clone('quack')
 
4221
        branch = self.make_remote_branch(transport, client)
 
4222
        self.assertRaises(OutOfTea, branch.last_revision_info)
 
4223
        self.assertFinished(client)
 
4224
 
 
4225
 
 
4226
class TestRepositoryPack(TestRemoteRepository):
 
4227
 
 
4228
    def test_pack(self):
 
4229
        transport_path = 'quack'
 
4230
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4231
        client.add_expected_call(
 
4232
            'Repository.lock_write', ('quack/', ''),
 
4233
            'success', ('ok', 'token'))
 
4234
        client.add_expected_call(
 
4235
            'Repository.pack', ('quack/', 'token', 'False'),
 
4236
            'success', ('ok',), )
 
4237
        client.add_expected_call(
 
4238
            'Repository.unlock', ('quack/', 'token'),
 
4239
            'success', ('ok', ))
 
4240
        repo.pack()
 
4241
 
 
4242
    def test_pack_with_hint(self):
 
4243
        transport_path = 'quack'
 
4244
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4245
        client.add_expected_call(
 
4246
            'Repository.lock_write', ('quack/', ''),
 
4247
            'success', ('ok', 'token'))
 
4248
        client.add_expected_call(
 
4249
            'Repository.pack', ('quack/', 'token', 'False'),
 
4250
            'success', ('ok',), )
 
4251
        client.add_expected_call(
 
4252
            'Repository.unlock', ('quack/', 'token', 'False'),
 
4253
            'success', ('ok', ))
 
4254
        repo.pack(['hinta', 'hintb'])
 
4255
 
 
4256
 
 
4257
class TestRepositoryIterInventories(TestRemoteRepository):
 
4258
    """Test Repository.iter_inventories."""
 
4259
 
 
4260
    def _serialize_inv_delta(self, old_name, new_name, delta):
 
4261
        serializer = inventory_delta.InventoryDeltaSerializer(True, False)
 
4262
        return "".join(serializer.delta_to_lines(old_name, new_name, delta))
 
4263
 
 
4264
    def test_single_empty(self):
 
4265
        transport_path = 'quack'
 
4266
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4267
        fmt = controldir.format_registry.get('2a')().repository_format
 
4268
        repo._format = fmt
 
4269
        stream = [('inventory-deltas', [
 
4270
            versionedfile.FulltextContentFactory('somerevid', None, None,
 
4271
                self._serialize_inv_delta('null:', 'somerevid', []))])]
 
4272
        client.add_expected_call(
 
4273
            'VersionedFileRepository.get_inventories', ('quack/', 'unordered'),
 
4274
            'success', ('ok', ),
 
4275
            _stream_to_byte_stream(stream, fmt))
 
4276
        ret = list(repo.iter_inventories(["somerevid"]))
 
4277
        self.assertLength(1, ret)
 
4278
        inv = ret[0]
 
4279
        self.assertEqual("somerevid", inv.revision_id)
 
4280
 
 
4281
    def test_empty(self):
 
4282
        transport_path = 'quack'
 
4283
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4284
        ret = list(repo.iter_inventories([]))
 
4285
        self.assertEqual(ret, [])
 
4286
 
 
4287
    def test_missing(self):
 
4288
        transport_path = 'quack'
 
4289
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4290
        client.add_expected_call(
 
4291
            'VersionedFileRepository.get_inventories', ('quack/', 'unordered'),
 
4292
            'success', ('ok', ), iter([]))
 
4293
        self.assertRaises(errors.NoSuchRevision, list, repo.iter_inventories(
 
4294
            ["somerevid"]))