/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to breezy/tests/test_remote.py

  • Committer: Martin
  • Date: 2017-11-19 20:33:06 UTC
  • mto: This revision was merged to the branch mainline in revision 6821.
  • Revision ID: gzlist@googlemail.com-20171119203306-lm94zmwsggx4dt3z
Create a cross compatible lsprof main()

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 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
23
23
These tests correspond to tests.test_smart, which exercises the server side.
24
24
"""
25
25
 
 
26
import base64
26
27
import bz2
27
 
from cStringIO import StringIO
 
28
import zlib
28
29
 
29
 
from bzrlib import (
 
30
from .. import (
 
31
    bencode,
30
32
    branch,
31
 
    bzrdir,
32
33
    config,
 
34
    controldir,
33
35
    errors,
34
 
    graph,
 
36
    repository,
 
37
    tests,
 
38
    transport,
 
39
    treebuilder,
 
40
    )
 
41
from ..branch import Branch
 
42
from ..bzr import (
 
43
    bzrdir,
35
44
    inventory,
36
45
    inventory_delta,
37
 
    pack,
38
46
    remote,
39
 
    repository,
40
 
    tests,
41
 
    treebuilder,
42
 
    urlutils,
43
47
    versionedfile,
44
 
    )
45
 
from bzrlib.branch import Branch
46
 
from bzrlib.bzrdir import BzrDir, BzrDirFormat
47
 
from bzrlib.remote import (
 
48
    vf_search,
 
49
    )
 
50
from ..bzr.bzrdir import (
 
51
    BzrDir,
 
52
    BzrDirFormat,
 
53
    )
 
54
from ..bzr import (
 
55
    RemoteBzrProber,
 
56
    )
 
57
from ..bzr.chk_serializer import chk_bencode_serializer
 
58
from ..bzr.remote import (
48
59
    RemoteBranch,
49
60
    RemoteBranchFormat,
50
61
    RemoteBzrDir,
52
63
    RemoteRepository,
53
64
    RemoteRepositoryFormat,
54
65
    )
55
 
from bzrlib.repofmt import groupcompress_repo, pack_repo
56
 
from bzrlib.revision import NULL_REVISION
57
 
from bzrlib.smart import medium
58
 
from bzrlib.smart.client import _SmartClient
59
 
from bzrlib.smart.repository import SmartServerRepositoryGetParentMap
60
 
from bzrlib.tests import (
61
 
    condition_isinstance,
62
 
    split_suite_by_condition,
63
 
    multiply_tests,
 
66
from ..bzr import groupcompress_repo, knitpack_repo
 
67
from ..revision import (
 
68
    NULL_REVISION,
 
69
    Revision,
 
70
    )
 
71
from ..sixish import (
 
72
    BytesIO,
 
73
    )
 
74
from ..bzr.smart import medium, request
 
75
from ..bzr.smart.client import _SmartClient
 
76
from ..bzr.smart.repository import (
 
77
    SmartServerRepositoryGetParentMap,
 
78
    SmartServerRepositoryGetStream_1_19,
 
79
    _stream_to_byte_stream,
 
80
    )
 
81
from . import (
64
82
    test_server,
65
83
    )
66
 
from bzrlib.transport import get_transport
67
 
from bzrlib.transport.memory import MemoryTransport
68
 
from bzrlib.transport.remote import (
 
84
from .scenarios import load_tests_apply_scenarios
 
85
from ..transport.memory import MemoryTransport
 
86
from ..transport.remote import (
69
87
    RemoteTransport,
70
88
    RemoteSSHTransport,
71
89
    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 = [
 
90
    )
 
91
 
 
92
 
 
93
load_tests = load_tests_apply_scenarios
 
94
 
 
95
 
 
96
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
 
97
 
 
98
    scenarios = [
78
99
        ('HPSS-v2',
79
 
         {'transport_server': test_server.SmartTCPServer_for_testing_v2_only}),
 
100
            {'transport_server': test_server.SmartTCPServer_for_testing_v2_only}),
80
101
        ('HPSS-v3',
81
 
         {'transport_server': test_server.SmartTCPServer_for_testing})]
82
 
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
83
 
 
84
 
 
85
 
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
 
102
            {'transport_server': test_server.SmartTCPServer_for_testing})]
 
103
 
86
104
 
87
105
    def setUp(self):
88
106
        super(BasicRemoteObjectTests, self).setUp()
89
107
        self.transport = self.get_transport()
90
108
        # make a branch that can be opened over the smart transport
91
109
        self.local_wt = BzrDir.create_standalone_workingtree('.')
92
 
 
93
 
    def tearDown(self):
94
 
        self.transport.disconnect()
95
 
        tests.TestCaseWithTransport.tearDown(self)
 
110
        self.addCleanup(self.transport.disconnect)
96
111
 
97
112
    def test_create_remote_bzrdir(self):
98
 
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
113
        b = remote.RemoteBzrDir(self.transport, RemoteBzrDirFormat())
99
114
        self.assertIsInstance(b, BzrDir)
100
115
 
101
116
    def test_open_remote_branch(self):
102
117
        # open a standalone branch in the working directory
103
 
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
 
118
        b = remote.RemoteBzrDir(self.transport, RemoteBzrDirFormat())
104
119
        branch = b.open_branch()
105
120
        self.assertIsInstance(branch, Branch)
106
121
 
112
127
        self.local_wt.commit(message='test commit', rev_id=revid)
113
128
        self.assertTrue(repo.has_revision(revid))
114
129
 
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
130
    def test_find_correct_format(self):
123
131
        """Should open a RemoteBzrDir over a RemoteTransport"""
124
132
        fmt = BzrDirFormat.find_format(self.transport)
125
 
        self.assertTrue(RemoteBzrDirFormat
126
 
                        in BzrDirFormat._control_server_formats)
127
 
        self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
 
133
        self.assertTrue(RemoteBzrProber
 
134
                        in controldir.ControlDirFormat._server_probers)
 
135
        self.assertIsInstance(fmt, RemoteBzrDirFormat)
128
136
 
129
137
    def test_open_detected_smart_format(self):
130
138
        fmt = BzrDirFormat.find_format(self.transport)
150
158
 
151
159
    def test_remote_repo_format_supports_external_references(self):
152
160
        t = self.transport
153
 
        bd = self.make_bzrdir('unstackable', format='pack-0.92')
 
161
        bd = self.make_controldir('unstackable', format='pack-0.92')
154
162
        r = bd.create_repository()
155
163
        self.assertFalse(r._format.supports_external_lookups)
156
164
        r = BzrDir.open_from_transport(t.clone('unstackable')).open_repository()
157
165
        self.assertFalse(r._format.supports_external_lookups)
158
 
        bd = self.make_bzrdir('stackable', format='1.9')
 
166
        bd = self.make_controldir('stackable', format='1.9')
159
167
        r = bd.create_repository()
160
168
        self.assertTrue(r._format.supports_external_lookups)
161
169
        r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
164
172
    def test_remote_branch_set_append_revisions_only(self):
165
173
        # Make a format 1.9 branch, which supports append_revisions_only
166
174
        branch = self.make_branch('branch', format='1.9')
167
 
        config = branch.get_config()
168
175
        branch.set_append_revisions_only(True)
 
176
        config = branch.get_config_stack()
169
177
        self.assertEqual(
170
 
            'True', config.get_user_option('append_revisions_only'))
 
178
            True, config.get('append_revisions_only'))
171
179
        branch.set_append_revisions_only(False)
 
180
        config = branch.get_config_stack()
172
181
        self.assertEqual(
173
 
            'False', config.get_user_option('append_revisions_only'))
 
182
            False, config.get('append_revisions_only'))
174
183
 
175
184
    def test_remote_branch_set_append_revisions_only_upgrade_reqd(self):
176
185
        branch = self.make_branch('branch', format='knit')
177
 
        config = branch.get_config()
178
186
        self.assertRaises(
179
187
            errors.UpgradeRequired, branch.set_append_revisions_only, True)
180
188
 
189
197
 
190
198
    def read_body_bytes(self, count=-1):
191
199
        if self._body_buffer is None:
192
 
            self._body_buffer = StringIO(self.body)
 
200
            self._body_buffer = BytesIO(self.body)
193
201
        bytes = self._body_buffer.read(count)
194
202
        if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
195
203
            self._fake_client.expecting_body = False
246
254
    def _get_next_response(self):
247
255
        try:
248
256
            response_tuple = self.responses.pop(0)
249
 
        except IndexError, e:
 
257
        except IndexError as e:
250
258
            raise AssertionError("%r didn't expect any more calls"
251
259
                % (self,))
252
260
        if response_tuple[0] == 'unknown':
338
346
class TestRemote(tests.TestCaseWithMemoryTransport):
339
347
 
340
348
    def get_branch_format(self):
341
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
349
        reference_bzrdir_format = controldir.format_registry.get('default')()
342
350
        return reference_bzrdir_format.get_branch_format()
343
351
 
344
352
    def get_repo_format(self):
345
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
353
        reference_bzrdir_format = controldir.format_registry.get('default')()
346
354
        return reference_bzrdir_format.repository_format
347
355
 
348
356
    def assertFinished(self, fake_client):
359
367
        a given client_base and transport_base.
360
368
        """
361
369
        client_medium = medium.SmartClientMedium(client_base)
362
 
        transport = get_transport(transport_base)
363
 
        result = client_medium.remote_path_from_transport(transport)
 
370
        t = transport.get_transport(transport_base)
 
371
        result = client_medium.remote_path_from_transport(t)
364
372
        self.assertEqual(expected, result)
365
373
 
366
374
    def test_remote_path_from_transport(self):
377
385
        a given transport_base and relpath of that transport.  (Note that
378
386
        HttpTransportBase is a subclass of SmartClientMedium)
379
387
        """
380
 
        base_transport = get_transport(transport_base)
 
388
        base_transport = transport.get_transport(transport_base)
381
389
        client_medium = base_transport.get_smart_medium()
382
390
        cloned_transport = base_transport.clone(relpath)
383
391
        result = client_medium.remote_path_from_transport(cloned_transport)
430
438
 
431
439
    def test_backwards_compat(self):
432
440
        self.setup_smart_server_with_call_log()
433
 
        a_dir = self.make_bzrdir('.')
 
441
        a_dir = self.make_controldir('.')
434
442
        self.reset_smart_call_log()
435
443
        verb = 'BzrDir.cloning_metadir'
436
444
        self.disable_verb(verb)
442
450
    def test_branch_reference(self):
443
451
        transport = self.get_transport('quack')
444
452
        referenced = self.make_branch('referenced')
445
 
        expected = referenced.bzrdir.cloning_metadir()
 
453
        expected = referenced.controldir.cloning_metadir()
446
454
        client = FakeClient(transport.base)
447
455
        client.add_expected_call(
448
456
            'BzrDir.cloning_metadir', ('quack/', 'False'),
450
458
        client.add_expected_call(
451
459
            'BzrDir.open_branchV3', ('quack/',),
452
460
            'success', ('ref', self.get_url('referenced'))),
453
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
461
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
454
462
            _client=client)
455
 
        result = a_bzrdir.cloning_metadir()
 
463
        result = a_controldir.cloning_metadir()
456
464
        # We should have got a control dir matching the referenced branch.
457
465
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
458
466
        self.assertEqual(expected._repository_format, result._repository_format)
462
470
    def test_current_server(self):
463
471
        transport = self.get_transport('.')
464
472
        transport = transport.clone('quack')
465
 
        self.make_bzrdir('quack')
 
473
        self.make_controldir('quack')
466
474
        client = FakeClient(transport.base)
467
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
475
        reference_bzrdir_format = controldir.format_registry.get('default')()
468
476
        control_name = reference_bzrdir_format.network_name()
469
477
        client.add_expected_call(
470
478
            'BzrDir.cloning_metadir', ('quack/', 'False'),
471
479
            'success', (control_name, '', ('branch', ''))),
472
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
480
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
473
481
            _client=client)
474
 
        result = a_bzrdir.cloning_metadir()
 
482
        result = a_controldir.cloning_metadir()
475
483
        # We should have got a reference control dir with default branch and
476
484
        # repository formats.
477
485
        # This pokes a little, just to be sure.
480
488
        self.assertEqual(None, result._branch_format)
481
489
        self.assertFinished(client)
482
490
 
 
491
    def test_unknown(self):
 
492
        transport = self.get_transport('quack')
 
493
        referenced = self.make_branch('referenced')
 
494
        expected = referenced.controldir.cloning_metadir()
 
495
        client = FakeClient(transport.base)
 
496
        client.add_expected_call(
 
497
            'BzrDir.cloning_metadir', ('quack/', 'False'),
 
498
            'success', ('unknown', 'unknown', ('branch', ''))),
 
499
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
500
            _client=client)
 
501
        self.assertRaises(errors.UnknownFormatError, a_controldir.cloning_metadir)
 
502
 
 
503
 
 
504
class TestBzrDirCheckoutMetaDir(TestRemote):
 
505
 
 
506
    def test__get_checkout_format(self):
 
507
        transport = MemoryTransport()
 
508
        client = FakeClient(transport.base)
 
509
        reference_bzrdir_format = controldir.format_registry.get('default')()
 
510
        control_name = reference_bzrdir_format.network_name()
 
511
        client.add_expected_call(
 
512
            'BzrDir.checkout_metadir', ('quack/', ),
 
513
            'success', (control_name, '', ''))
 
514
        transport.mkdir('quack')
 
515
        transport = transport.clone('quack')
 
516
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
517
            _client=client)
 
518
        result = a_controldir.checkout_metadir()
 
519
        # We should have got a reference control dir with default branch and
 
520
        # repository formats.
 
521
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
 
522
        self.assertEqual(None, result._repository_format)
 
523
        self.assertEqual(None, result._branch_format)
 
524
        self.assertFinished(client)
 
525
 
 
526
    def test_unknown_format(self):
 
527
        transport = MemoryTransport()
 
528
        client = FakeClient(transport.base)
 
529
        client.add_expected_call(
 
530
            'BzrDir.checkout_metadir', ('quack/',),
 
531
            'success', ('dontknow', '', ''))
 
532
        transport.mkdir('quack')
 
533
        transport = transport.clone('quack')
 
534
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
535
            _client=client)
 
536
        self.assertRaises(errors.UnknownFormatError,
 
537
            a_controldir.checkout_metadir)
 
538
        self.assertFinished(client)
 
539
 
 
540
 
 
541
class TestBzrDirGetBranches(TestRemote):
 
542
 
 
543
    def test_get_branches(self):
 
544
        transport = MemoryTransport()
 
545
        client = FakeClient(transport.base)
 
546
        reference_bzrdir_format = controldir.format_registry.get('default')()
 
547
        branch_name = reference_bzrdir_format.get_branch_format().network_name()
 
548
        client.add_success_response_with_body(
 
549
            bencode.bencode({
 
550
                "foo": ("branch", branch_name),
 
551
                "": ("branch", branch_name)}), "success")
 
552
        client.add_success_response(
 
553
            'ok', '', 'no', 'no', 'no',
 
554
                reference_bzrdir_format.repository_format.network_name())
 
555
        client.add_error_response('NotStacked')
 
556
        client.add_success_response(
 
557
            'ok', '', 'no', 'no', 'no',
 
558
                reference_bzrdir_format.repository_format.network_name())
 
559
        client.add_error_response('NotStacked')
 
560
        transport.mkdir('quack')
 
561
        transport = transport.clone('quack')
 
562
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
563
            _client=client)
 
564
        result = a_controldir.get_branches()
 
565
        self.assertEqual({"", "foo"}, set(result.keys()))
 
566
        self.assertEqual(
 
567
            [('call_expecting_body', 'BzrDir.get_branches', ('quack/',)),
 
568
             ('call', 'BzrDir.find_repositoryV3', ('quack/', )),
 
569
             ('call', 'Branch.get_stacked_on_url', ('quack/', )),
 
570
             ('call', 'BzrDir.find_repositoryV3', ('quack/', )),
 
571
             ('call', 'Branch.get_stacked_on_url', ('quack/', ))],
 
572
            client._calls)
 
573
 
 
574
 
 
575
class TestBzrDirDestroyBranch(TestRemote):
 
576
 
 
577
    def test_destroy_default(self):
 
578
        transport = self.get_transport('quack')
 
579
        referenced = self.make_branch('referenced')
 
580
        client = FakeClient(transport.base)
 
581
        client.add_expected_call(
 
582
            'BzrDir.destroy_branch', ('quack/', ),
 
583
            'success', ('ok',)),
 
584
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
585
            _client=client)
 
586
        a_controldir.destroy_branch()
 
587
        self.assertFinished(client)
 
588
 
 
589
 
 
590
class TestBzrDirHasWorkingTree(TestRemote):
 
591
 
 
592
    def test_has_workingtree(self):
 
593
        transport = self.get_transport('quack')
 
594
        client = FakeClient(transport.base)
 
595
        client.add_expected_call(
 
596
            'BzrDir.has_workingtree', ('quack/',),
 
597
            'success', ('yes',)),
 
598
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
599
            _client=client)
 
600
        self.assertTrue(a_controldir.has_workingtree())
 
601
        self.assertFinished(client)
 
602
 
 
603
    def test_no_workingtree(self):
 
604
        transport = self.get_transport('quack')
 
605
        client = FakeClient(transport.base)
 
606
        client.add_expected_call(
 
607
            'BzrDir.has_workingtree', ('quack/',),
 
608
            'success', ('no',)),
 
609
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
610
            _client=client)
 
611
        self.assertFalse(a_controldir.has_workingtree())
 
612
        self.assertFinished(client)
 
613
 
 
614
 
 
615
class TestBzrDirDestroyRepository(TestRemote):
 
616
 
 
617
    def test_destroy_repository(self):
 
618
        transport = self.get_transport('quack')
 
619
        client = FakeClient(transport.base)
 
620
        client.add_expected_call(
 
621
            'BzrDir.destroy_repository', ('quack/',),
 
622
            'success', ('ok',)),
 
623
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
624
            _client=client)
 
625
        a_controldir.destroy_repository()
 
626
        self.assertFinished(client)
 
627
 
483
628
 
484
629
class TestBzrDirOpen(TestRemote):
485
630
 
495
640
        client.add_expected_call(
496
641
            'BzrDir.open_2.1', ('quack/',), 'success', ('no',))
497
642
        self.assertRaises(errors.NotBranchError, RemoteBzrDir, transport,
498
 
                remote.RemoteBzrDirFormat(), _client=client, _force_probe=True)
 
643
                RemoteBzrDirFormat(), _client=client, _force_probe=True)
499
644
        self.assertFinished(client)
500
645
 
501
646
    def test_present_without_workingtree(self):
502
647
        client, transport = self.make_fake_client_and_transport()
503
648
        client.add_expected_call(
504
649
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'no'))
505
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
650
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
506
651
            _client=client, _force_probe=True)
507
652
        self.assertIsInstance(bd, RemoteBzrDir)
508
653
        self.assertFalse(bd.has_workingtree())
513
658
        client, transport = self.make_fake_client_and_transport()
514
659
        client.add_expected_call(
515
660
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'yes'))
516
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
661
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
517
662
            _client=client, _force_probe=True)
518
663
        self.assertIsInstance(bd, RemoteBzrDir)
519
664
        self.assertTrue(bd.has_workingtree())
526
671
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
527
672
        client.add_expected_call(
528
673
            'BzrDir.open', ('quack/',), 'success', ('yes',))
529
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
674
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
530
675
            _client=client, _force_probe=True)
531
676
        self.assertIsInstance(bd, RemoteBzrDir)
532
677
        self.assertFinished(client)
548
693
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
549
694
        client.add_expected_call(
550
695
            'BzrDir.open', ('quack/',), 'success', ('yes',))
551
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
696
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
552
697
            _client=client, _force_probe=True)
553
698
        self.assertIsInstance(bd, RemoteBzrDir)
554
699
        self.assertFinished(client)
585
730
        client.add_expected_call(
586
731
            'Branch.get_stacked_on_url', ('quack/',),
587
732
            'error', ('NotStacked',))
588
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
733
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
589
734
            _client=client)
590
735
        result = bzrdir.open_branch()
591
736
        self.assertIsInstance(result, RemoteBranch)
592
 
        self.assertEqual(bzrdir, result.bzrdir)
 
737
        self.assertEqual(bzrdir, result.controldir)
593
738
        self.assertFinished(client)
594
739
 
595
740
    def test_branch_missing(self):
598
743
        transport = transport.clone('quack')
599
744
        client = FakeClient(transport.base)
600
745
        client.add_error_response('nobranch')
601
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
746
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
602
747
            _client=client)
603
748
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
604
749
        self.assertEqual(
609
754
        # _get_tree_branch is a form of open_branch, but it should only ask for
610
755
        # branch opening, not any other network requests.
611
756
        calls = []
612
 
        def open_branch():
 
757
        def open_branch(name=None, possible_transports=None):
613
758
            calls.append("Called")
614
759
            return "a-branch"
615
760
        transport = MemoryTransport()
616
761
        # no requests on the network - catches other api calls being made.
617
762
        client = FakeClient(transport.base)
618
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
763
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
619
764
            _client=client)
620
765
        # patch the open_branch call to record that it was called.
621
766
        bzrdir.open_branch = open_branch
640
785
        client.add_expected_call(
641
786
            'Branch.get_stacked_on_url', ('~hello/',),
642
787
            'error', ('NotStacked',))
643
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
788
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
644
789
            _client=client)
645
790
        result = bzrdir.open_branch()
646
791
        self.assertFinished(client)
663
808
        client.add_success_response(
664
809
            'ok', '', rich_response, subtree_response, external_lookup,
665
810
            network_name)
666
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
811
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
667
812
            _client=client)
668
813
        result = bzrdir.open_repository()
669
814
        self.assertEqual(
670
815
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
671
816
            client._calls)
672
817
        self.assertIsInstance(result, RemoteRepository)
673
 
        self.assertEqual(bzrdir, result.bzrdir)
 
818
        self.assertEqual(bzrdir, result.controldir)
674
819
        self.assertEqual(rich_root, result._format.rich_root_data)
675
820
        self.assertEqual(subtrees, result._format.supports_tree_reference)
676
821
 
686
831
        old.
687
832
        """
688
833
        self.assertRaises(errors.NotBranchError,
689
 
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
 
834
            RemoteBzrProber.probe_transport, OldServerTransport())
690
835
 
691
836
 
692
837
class TestBzrDirCreateBranch(TestRemote):
696
841
        repo = self.make_repository('.')
697
842
        self.reset_smart_call_log()
698
843
        self.disable_verb('BzrDir.create_branch')
699
 
        branch = repo.bzrdir.create_branch()
 
844
        branch = repo.controldir.create_branch()
700
845
        create_branch_call_count = len([call for call in self.hpss_calls if
701
846
            call.call.method == 'BzrDir.create_branch'])
702
847
        self.assertEqual(1, create_branch_call_count)
706
851
        transport = transport.clone('quack')
707
852
        self.make_repository('quack')
708
853
        client = FakeClient(transport.base)
709
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
854
        reference_bzrdir_format = controldir.format_registry.get('default')()
710
855
        reference_format = reference_bzrdir_format.get_branch_format()
711
856
        network_name = reference_format.network_name()
712
857
        reference_repo_fmt = reference_bzrdir_format.repository_format
715
860
            'BzrDir.create_branch', ('quack/', network_name),
716
861
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
717
862
            reference_repo_name))
718
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
719
 
            _client=client)
720
 
        branch = a_bzrdir.create_branch()
 
863
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
864
            _client=client)
 
865
        branch = a_controldir.create_branch()
 
866
        # We should have got a remote branch
 
867
        self.assertIsInstance(branch, remote.RemoteBranch)
 
868
        # its format should have the settings from the response
 
869
        format = branch._format
 
870
        self.assertEqual(network_name, format.network_name())
 
871
 
 
872
    def test_already_open_repo_and_reused_medium(self):
 
873
        """Bug 726584: create_branch(..., repository=repo) should work
 
874
        regardless of what the smart medium's base URL is.
 
875
        """
 
876
        self.transport_server = test_server.SmartTCPServer_for_testing
 
877
        transport = self.get_transport('.')
 
878
        repo = self.make_repository('quack')
 
879
        # Client's medium rooted a transport root (not at the bzrdir)
 
880
        client = FakeClient(transport.base)
 
881
        transport = transport.clone('quack')
 
882
        reference_bzrdir_format = controldir.format_registry.get('default')()
 
883
        reference_format = reference_bzrdir_format.get_branch_format()
 
884
        network_name = reference_format.network_name()
 
885
        reference_repo_fmt = reference_bzrdir_format.repository_format
 
886
        reference_repo_name = reference_repo_fmt.network_name()
 
887
        client.add_expected_call(
 
888
            'BzrDir.create_branch', ('extra/quack/', network_name),
 
889
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
 
890
            reference_repo_name))
 
891
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
 
892
            _client=client)
 
893
        branch = a_controldir.create_branch(repository=repo)
721
894
        # We should have got a remote branch
722
895
        self.assertIsInstance(branch, remote.RemoteBranch)
723
896
        # its format should have the settings from the response
729
902
 
730
903
    def test_backwards_compat(self):
731
904
        self.setup_smart_server_with_call_log()
732
 
        bzrdir = self.make_bzrdir('.')
 
905
        bzrdir = self.make_controldir('.')
733
906
        self.reset_smart_call_log()
734
907
        self.disable_verb('BzrDir.create_repository')
735
908
        repo = bzrdir.create_repository()
740
913
    def test_current_server(self):
741
914
        transport = self.get_transport('.')
742
915
        transport = transport.clone('quack')
743
 
        self.make_bzrdir('quack')
 
916
        self.make_controldir('quack')
744
917
        client = FakeClient(transport.base)
745
 
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
 
918
        reference_bzrdir_format = controldir.format_registry.get('default')()
746
919
        reference_format = reference_bzrdir_format.repository_format
747
920
        network_name = reference_format.network_name()
748
921
        client.add_expected_call(
750
923
                'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
751
924
                'False'),
752
925
            'success', ('ok', 'yes', 'yes', 'yes', network_name))
753
 
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
926
        a_controldir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
754
927
            _client=client)
755
 
        repo = a_bzrdir.create_repository()
 
928
        repo = a_controldir.create_repository()
756
929
        # We should have got a remote repository
757
930
        self.assertIsInstance(repo, remote.RemoteRepository)
758
931
        # its format should have the settings from the response
779
952
        # name.
780
953
        client.add_success_response_with_body(
781
954
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
955
        client.add_success_response('stat', '0', '65535')
782
956
        client.add_success_response_with_body(
783
957
            reference_format.get_format_string(), 'ok')
784
958
        # PackRepository wants to do a stat
785
959
        client.add_success_response('stat', '0', '65535')
786
960
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
787
961
            _client=client)
788
 
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
962
        bzrdir = RemoteBzrDir(remote_transport, RemoteBzrDirFormat(),
789
963
            _client=client)
790
964
        repo = bzrdir.open_repository()
791
965
        self.assertEqual(
793
967
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
794
968
             ('call', 'BzrDir.find_repository', ('quack/',)),
795
969
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
970
             ('call', 'stat', ('/quack/.bzr',)),
796
971
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
797
972
             ('call', 'stat', ('/quack/.bzr/repository',)),
798
973
             ],
812
987
        # name.
813
988
        client.add_success_response_with_body(
814
989
            "Bazaar-NG meta directory, format 1\n", 'ok')
 
990
        client.add_success_response('stat', '0', '65535')
815
991
        client.add_success_response_with_body(
816
992
            reference_format.get_format_string(), 'ok')
817
993
        # PackRepository wants to do a stat
818
994
        client.add_success_response('stat', '0', '65535')
819
995
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
820
996
            _client=client)
821
 
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
 
997
        bzrdir = RemoteBzrDir(remote_transport, RemoteBzrDirFormat(),
822
998
            _client=client)
823
999
        repo = bzrdir.open_repository()
824
1000
        self.assertEqual(
825
1001
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
826
1002
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
827
1003
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
 
1004
             ('call', 'stat', ('/quack/.bzr',)),
828
1005
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
829
1006
             ('call', 'stat', ('/quack/.bzr/repository',)),
830
1007
             ],
839
1016
        transport = transport.clone('quack')
840
1017
        client = FakeClient(transport.base)
841
1018
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
842
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1019
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
843
1020
            _client=client)
844
1021
        repo = bzrdir.open_repository()
845
1022
        self.assertEqual(
852
1029
 
853
1030
    def test_success(self):
854
1031
        """Simple test for typical successful call."""
855
 
        fmt = bzrdir.RemoteBzrDirFormat()
 
1032
        fmt = RemoteBzrDirFormat()
856
1033
        default_format_name = BzrDirFormat.get_default_format().network_name()
857
1034
        transport = self.get_transport()
858
1035
        client = FakeClient(transport.base)
874
1051
        """Error responses are translated, e.g. 'PermissionDenied' raises the
875
1052
        corresponding error from the client.
876
1053
        """
877
 
        fmt = bzrdir.RemoteBzrDirFormat()
 
1054
        fmt = RemoteBzrDirFormat()
878
1055
        default_format_name = BzrDirFormat.get_default_format().network_name()
879
1056
        transport = self.get_transport()
880
1057
        client = FakeClient(transport.base)
898
1075
        """Integration test for error translation."""
899
1076
        transport = self.make_smart_server('foo')
900
1077
        transport = transport.clone('no-such-path')
901
 
        fmt = bzrdir.RemoteBzrDirFormat()
 
1078
        fmt = RemoteBzrDirFormat()
902
1079
        err = self.assertRaises(errors.NoSuchFile,
903
1080
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
904
1081
 
909
1086
    """
910
1087
 
911
1088
    def get_request(self):
912
 
        input_file = StringIO('ok\x011\n')
913
 
        output_file = StringIO()
 
1089
        input_file = BytesIO(b'ok\x011\n')
 
1090
        output_file = BytesIO()
914
1091
        client_medium = medium.SmartSimplePipesClientMedium(
915
1092
            input_file, output_file)
916
1093
        return medium.SmartClientStreamMediumRequest(client_medium)
935
1112
 
936
1113
    def make_remote_bzrdir(self, transport, client):
937
1114
        """Make a RemotebzrDir using 'client' as the _client."""
938
 
        return RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1115
        return RemoteBzrDir(transport, RemoteBzrDirFormat(),
939
1116
            _client=client)
940
1117
 
941
1118
 
967
1144
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
968
1145
 
969
1146
 
 
1147
class TestBranchBreakLock(RemoteBranchTestCase):
 
1148
 
 
1149
    def test_break_lock(self):
 
1150
        transport_path = 'quack'
 
1151
        transport = MemoryTransport()
 
1152
        client = FakeClient(transport.base)
 
1153
        client.add_expected_call(
 
1154
            'Branch.get_stacked_on_url', ('quack/',),
 
1155
            'error', ('NotStacked',))
 
1156
        client.add_expected_call(
 
1157
            'Branch.break_lock', ('quack/',),
 
1158
            'success', ('ok',))
 
1159
        transport.mkdir('quack')
 
1160
        transport = transport.clone('quack')
 
1161
        branch = self.make_remote_branch(transport, client)
 
1162
        branch.break_lock()
 
1163
        self.assertFinished(client)
 
1164
 
 
1165
 
 
1166
class TestBranchGetPhysicalLockStatus(RemoteBranchTestCase):
 
1167
 
 
1168
    def test_get_physical_lock_status_yes(self):
 
1169
        transport = MemoryTransport()
 
1170
        client = FakeClient(transport.base)
 
1171
        client.add_expected_call(
 
1172
            'Branch.get_stacked_on_url', ('quack/',),
 
1173
            'error', ('NotStacked',))
 
1174
        client.add_expected_call(
 
1175
            'Branch.get_physical_lock_status', ('quack/',),
 
1176
            'success', ('yes',))
 
1177
        transport.mkdir('quack')
 
1178
        transport = transport.clone('quack')
 
1179
        branch = self.make_remote_branch(transport, client)
 
1180
        result = branch.get_physical_lock_status()
 
1181
        self.assertFinished(client)
 
1182
        self.assertEqual(True, result)
 
1183
 
 
1184
    def test_get_physical_lock_status_no(self):
 
1185
        transport = MemoryTransport()
 
1186
        client = FakeClient(transport.base)
 
1187
        client.add_expected_call(
 
1188
            'Branch.get_stacked_on_url', ('quack/',),
 
1189
            'error', ('NotStacked',))
 
1190
        client.add_expected_call(
 
1191
            'Branch.get_physical_lock_status', ('quack/',),
 
1192
            'success', ('no',))
 
1193
        transport.mkdir('quack')
 
1194
        transport = transport.clone('quack')
 
1195
        branch = self.make_remote_branch(transport, client)
 
1196
        result = branch.get_physical_lock_status()
 
1197
        self.assertFinished(client)
 
1198
        self.assertEqual(False, result)
 
1199
 
 
1200
 
970
1201
class TestBranchGetParent(RemoteBranchTestCase):
971
1202
 
972
1203
    def test_no_parent(self):
1062
1293
        verb = 'Branch.set_parent_location'
1063
1294
        self.disable_verb(verb)
1064
1295
        branch.set_parent('http://foo/')
1065
 
        self.assertLength(12, self.hpss_calls)
 
1296
        self.assertLength(14, self.hpss_calls)
1066
1297
 
1067
1298
 
1068
1299
class TestBranchGetTagsBytes(RemoteBranchTestCase):
1143
1374
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
1144
1375
 
1145
1376
 
 
1377
class TestBranchHeadsToFetch(RemoteBranchTestCase):
 
1378
 
 
1379
    def test_uses_last_revision_info_and_tags_by_default(self):
 
1380
        transport = MemoryTransport()
 
1381
        client = FakeClient(transport.base)
 
1382
        client.add_expected_call(
 
1383
            'Branch.get_stacked_on_url', ('quack/',),
 
1384
            'error', ('NotStacked',))
 
1385
        client.add_expected_call(
 
1386
            'Branch.last_revision_info', ('quack/',),
 
1387
            'success', ('ok', '1', 'rev-tip'))
 
1388
        client.add_expected_call(
 
1389
            'Branch.get_config_file', ('quack/',),
 
1390
            'success', ('ok',), '')
 
1391
        transport.mkdir('quack')
 
1392
        transport = transport.clone('quack')
 
1393
        branch = self.make_remote_branch(transport, client)
 
1394
        result = branch.heads_to_fetch()
 
1395
        self.assertFinished(client)
 
1396
        self.assertEqual(({'rev-tip'}, set()), result)
 
1397
 
 
1398
    def test_uses_last_revision_info_and_tags_when_set(self):
 
1399
        transport = MemoryTransport()
 
1400
        client = FakeClient(transport.base)
 
1401
        client.add_expected_call(
 
1402
            'Branch.get_stacked_on_url', ('quack/',),
 
1403
            'error', ('NotStacked',))
 
1404
        client.add_expected_call(
 
1405
            'Branch.last_revision_info', ('quack/',),
 
1406
            'success', ('ok', '1', 'rev-tip'))
 
1407
        client.add_expected_call(
 
1408
            'Branch.get_config_file', ('quack/',),
 
1409
            'success', ('ok',), 'branch.fetch_tags = True')
 
1410
        # XXX: this will break if the default format's serialization of tags
 
1411
        # changes, or if the RPC for fetching tags changes from get_tags_bytes.
 
1412
        client.add_expected_call(
 
1413
            'Branch.get_tags_bytes', ('quack/',),
 
1414
            'success', ('d5:tag-17:rev-foo5:tag-27:rev-bare',))
 
1415
        transport.mkdir('quack')
 
1416
        transport = transport.clone('quack')
 
1417
        branch = self.make_remote_branch(transport, client)
 
1418
        result = branch.heads_to_fetch()
 
1419
        self.assertFinished(client)
 
1420
        self.assertEqual(
 
1421
            ({'rev-tip'}, {'rev-foo', 'rev-bar'}), result)
 
1422
 
 
1423
    def test_uses_rpc_for_formats_with_non_default_heads_to_fetch(self):
 
1424
        transport = MemoryTransport()
 
1425
        client = FakeClient(transport.base)
 
1426
        client.add_expected_call(
 
1427
            'Branch.get_stacked_on_url', ('quack/',),
 
1428
            'error', ('NotStacked',))
 
1429
        client.add_expected_call(
 
1430
            'Branch.heads_to_fetch', ('quack/',),
 
1431
            'success', (['tip'], ['tagged-1', 'tagged-2']))
 
1432
        transport.mkdir('quack')
 
1433
        transport = transport.clone('quack')
 
1434
        branch = self.make_remote_branch(transport, client)
 
1435
        branch._format._use_default_local_heads_to_fetch = lambda: False
 
1436
        result = branch.heads_to_fetch()
 
1437
        self.assertFinished(client)
 
1438
        self.assertEqual(({'tip'}, {'tagged-1', 'tagged-2'}), result)
 
1439
 
 
1440
    def make_branch_with_tags(self):
 
1441
        self.setup_smart_server_with_call_log()
 
1442
        # Make a branch with a single revision.
 
1443
        builder = self.make_branch_builder('foo')
 
1444
        builder.start_series()
 
1445
        builder.build_snapshot('tip', None, [
 
1446
            ('add', ('', 'root-id', 'directory', ''))])
 
1447
        builder.finish_series()
 
1448
        branch = builder.get_branch()
 
1449
        # Add two tags to that branch
 
1450
        branch.tags.set_tag('tag-1', 'rev-1')
 
1451
        branch.tags.set_tag('tag-2', 'rev-2')
 
1452
        return branch
 
1453
 
 
1454
    def test_backwards_compatible(self):
 
1455
        br = self.make_branch_with_tags()
 
1456
        br.get_config_stack().set('branch.fetch_tags', True)
 
1457
        self.addCleanup(br.lock_read().unlock)
 
1458
        # Disable the heads_to_fetch verb
 
1459
        verb = 'Branch.heads_to_fetch'
 
1460
        self.disable_verb(verb)
 
1461
        self.reset_smart_call_log()
 
1462
        result = br.heads_to_fetch()
 
1463
        self.assertEqual(({'tip'}, {'rev-1', 'rev-2'}), result)
 
1464
        self.assertEqual(
 
1465
            ['Branch.last_revision_info', 'Branch.get_tags_bytes'],
 
1466
            [call.call.method for call in self.hpss_calls])
 
1467
 
 
1468
    def test_backwards_compatible_no_tags(self):
 
1469
        br = self.make_branch_with_tags()
 
1470
        br.get_config_stack().set('branch.fetch_tags', False)
 
1471
        self.addCleanup(br.lock_read().unlock)
 
1472
        # Disable the heads_to_fetch verb
 
1473
        verb = 'Branch.heads_to_fetch'
 
1474
        self.disable_verb(verb)
 
1475
        self.reset_smart_call_log()
 
1476
        result = br.heads_to_fetch()
 
1477
        self.assertEqual(({'tip'}, set()), result)
 
1478
        self.assertEqual(
 
1479
            ['Branch.last_revision_info'],
 
1480
            [call.call.method for call in self.hpss_calls])
 
1481
 
 
1482
 
1146
1483
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
1147
1484
 
1148
1485
    def test_empty_branch(self):
1193
1530
        memory_branch = self.make_branch('base', format='1.9')
1194
1531
        vfs_url = self.get_vfs_only_url('base')
1195
1532
        stacked_branch.set_stacked_on_url(vfs_url)
1196
 
        transport = stacked_branch.bzrdir.root_transport
 
1533
        transport = stacked_branch.controldir.root_transport
1197
1534
        client = FakeClient(transport.base)
1198
1535
        client.add_expected_call(
1199
1536
            'Branch.get_stacked_on_url', ('stacked/',),
1203
1540
        client.add_expected_call(
1204
1541
            'Branch.get_stacked_on_url', ('stacked/',),
1205
1542
            'success', ('ok', vfs_url))
1206
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
1543
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
1207
1544
            _client=client)
1208
1545
        repo_fmt = remote.RemoteRepositoryFormat()
1209
1546
        repo_fmt._custom_format = stacked_branch.repository._format
1236
1573
        # this will also do vfs access, but that goes direct to the transport
1237
1574
        # and isn't seen by the FakeClient.
1238
1575
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1239
 
            remote.RemoteBzrDirFormat(), _client=client)
 
1576
            RemoteBzrDirFormat(), _client=client)
1240
1577
        branch = bzrdir.open_branch()
1241
1578
        result = branch.get_stacked_on_url()
1242
1579
        self.assertEqual('../base', result)
1269
1606
            'Branch.get_stacked_on_url', ('stacked/',),
1270
1607
            'success', ('ok', '../base'))
1271
1608
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1272
 
            remote.RemoteBzrDirFormat(), _client=client)
 
1609
            RemoteBzrDirFormat(), _client=client)
1273
1610
        branch = bzrdir.open_branch()
1274
1611
        result = branch.get_stacked_on_url()
1275
1612
        self.assertEqual('../base', result)
1283
1620
class TestBranchSetLastRevision(RemoteBranchTestCase):
1284
1621
 
1285
1622
    def test_set_empty(self):
1286
 
        # set_revision_history([]) is translated to calling
 
1623
        # _set_last_revision_info('null:') is translated to calling
1287
1624
        # Branch.set_last_revision(path, '') on the wire.
1288
1625
        transport = MemoryTransport()
1289
1626
        transport.mkdir('branch')
1307
1644
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1308
1645
            'success', ('ok',))
1309
1646
        branch = self.make_remote_branch(transport, client)
1310
 
        # This is a hack to work around the problem that RemoteBranch currently
1311
 
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1312
 
        branch._ensure_real = lambda: None
1313
1647
        branch.lock_write()
1314
 
        result = branch.set_revision_history([])
 
1648
        result = branch._set_last_revision(NULL_REVISION)
1315
1649
        branch.unlock()
1316
1650
        self.assertEqual(None, result)
1317
1651
        self.assertFinished(client)
1318
1652
 
1319
1653
    def test_set_nonempty(self):
1320
 
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
 
1654
        # set_last_revision_info(N, rev-idN) is translated to calling
1321
1655
        # Branch.set_last_revision(path, rev-idN) on the wire.
1322
1656
        transport = MemoryTransport()
1323
1657
        transport.mkdir('branch')
1344
1678
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1345
1679
            'success', ('ok',))
1346
1680
        branch = self.make_remote_branch(transport, client)
1347
 
        # This is a hack to work around the problem that RemoteBranch currently
1348
 
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1349
 
        branch._ensure_real = lambda: None
1350
1681
        # Lock the branch, reset the record of remote calls.
1351
1682
        branch.lock_write()
1352
 
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
 
1683
        result = branch._set_last_revision('rev-id2')
1353
1684
        branch.unlock()
1354
1685
        self.assertEqual(None, result)
1355
1686
        self.assertFinished(client)
1385
1716
        branch = self.make_remote_branch(transport, client)
1386
1717
        branch.lock_write()
1387
1718
        self.assertRaises(
1388
 
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
 
1719
            errors.NoSuchRevision, branch._set_last_revision, 'rev-id')
1389
1720
        branch.unlock()
1390
1721
        self.assertFinished(client)
1391
1722
 
1419
1750
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1420
1751
            'success', ('ok',))
1421
1752
        branch = self.make_remote_branch(transport, client)
1422
 
        branch._ensure_real = lambda: None
1423
1753
        branch.lock_write()
1424
1754
        # The 'TipChangeRejected' error response triggered by calling
1425
 
        # set_revision_history causes a TipChangeRejected exception.
 
1755
        # set_last_revision_info causes a TipChangeRejected exception.
1426
1756
        err = self.assertRaises(
1427
 
            errors.TipChangeRejected, branch.set_revision_history, ['rev-id'])
 
1757
            errors.TipChangeRejected,
 
1758
            branch._set_last_revision, 'rev-id')
1428
1759
        # The UTF-8 message from the response has been decoded into a unicode
1429
1760
        # object.
1430
1761
        self.assertIsInstance(err.msg, unicode)
1618
1949
    def test_get_multi_line_branch_conf(self):
1619
1950
        # Make sure that multiple-line branch.conf files are supported
1620
1951
        #
1621
 
        # https://bugs.edge.launchpad.net/bzr/+bug/354075
 
1952
        # https://bugs.launchpad.net/bzr/+bug/354075
1622
1953
        client = FakeClient()
1623
1954
        client.add_expected_call(
1624
1955
            'Branch.get_stacked_on_url', ('memory:///',),
1652
1983
        branch.unlock()
1653
1984
        self.assertFinished(client)
1654
1985
 
 
1986
    def test_set_option_with_dict(self):
 
1987
        client = FakeClient()
 
1988
        client.add_expected_call(
 
1989
            'Branch.get_stacked_on_url', ('memory:///',),
 
1990
            'error', ('NotStacked',),)
 
1991
        client.add_expected_call(
 
1992
            'Branch.lock_write', ('memory:///', '', ''),
 
1993
            'success', ('ok', 'branch token', 'repo token'))
 
1994
        encoded_dict_value = 'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde'
 
1995
        client.add_expected_call(
 
1996
            'Branch.set_config_option_dict', ('memory:///', 'branch token',
 
1997
            'repo token', encoded_dict_value, 'foo', ''),
 
1998
            'success', ())
 
1999
        client.add_expected_call(
 
2000
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
 
2001
            'success', ('ok',))
 
2002
        transport = MemoryTransport()
 
2003
        branch = self.make_remote_branch(transport, client)
 
2004
        branch.lock_write()
 
2005
        config = branch._get_config()
 
2006
        config.set_option(
 
2007
            {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'},
 
2008
            'foo')
 
2009
        branch.unlock()
 
2010
        self.assertFinished(client)
 
2011
 
1655
2012
    def test_backwards_compat_set_option(self):
1656
2013
        self.setup_smart_server_with_call_log()
1657
2014
        branch = self.make_branch('.')
1661
2018
        self.addCleanup(branch.unlock)
1662
2019
        self.reset_smart_call_log()
1663
2020
        branch._get_config().set_option('value', 'name')
1664
 
        self.assertLength(10, self.hpss_calls)
 
2021
        self.assertLength(11, self.hpss_calls)
1665
2022
        self.assertEqual('value', branch._get_config().get_option('name'))
1666
2023
 
 
2024
    def test_backwards_compat_set_option_with_dict(self):
 
2025
        self.setup_smart_server_with_call_log()
 
2026
        branch = self.make_branch('.')
 
2027
        verb = 'Branch.set_config_option_dict'
 
2028
        self.disable_verb(verb)
 
2029
        branch.lock_write()
 
2030
        self.addCleanup(branch.unlock)
 
2031
        self.reset_smart_call_log()
 
2032
        config = branch._get_config()
 
2033
        value_dict = {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
 
2034
        config.set_option(value_dict, 'name')
 
2035
        self.assertLength(11, self.hpss_calls)
 
2036
        self.assertEqual(value_dict, branch._get_config().get_option('name'))
 
2037
 
 
2038
 
 
2039
class TestBranchGetPutConfigStore(RemoteBranchTestCase):
 
2040
 
 
2041
    def test_get_branch_conf(self):
 
2042
        # in an empty branch we decode the response properly
 
2043
        client = FakeClient()
 
2044
        client.add_expected_call(
 
2045
            'Branch.get_stacked_on_url', ('memory:///',),
 
2046
            'error', ('NotStacked',),)
 
2047
        client.add_success_response_with_body('# config file body', 'ok')
 
2048
        transport = MemoryTransport()
 
2049
        branch = self.make_remote_branch(transport, client)
 
2050
        config = branch.get_config_stack()
 
2051
        config.get("email")
 
2052
        config.get("log_format")
 
2053
        self.assertEqual(
 
2054
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
 
2055
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
 
2056
            client._calls)
 
2057
 
 
2058
    def test_set_branch_conf(self):
 
2059
        client = FakeClient()
 
2060
        client.add_expected_call(
 
2061
            'Branch.get_stacked_on_url', ('memory:///',),
 
2062
            'error', ('NotStacked',),)
 
2063
        client.add_expected_call(
 
2064
            'Branch.lock_write', ('memory:///', '', ''),
 
2065
            'success', ('ok', 'branch token', 'repo token'))
 
2066
        client.add_expected_call(
 
2067
            'Branch.get_config_file', ('memory:///', ),
 
2068
            'success', ('ok', ), "# line 1\n")
 
2069
        client.add_expected_call(
 
2070
            'Branch.get_config_file', ('memory:///', ),
 
2071
            'success', ('ok', ), "# line 1\n")
 
2072
        client.add_expected_call(
 
2073
            'Branch.put_config_file', ('memory:///', 'branch token',
 
2074
            'repo token'),
 
2075
            'success', ('ok',))
 
2076
        client.add_expected_call(
 
2077
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
 
2078
            'success', ('ok',))
 
2079
        transport = MemoryTransport()
 
2080
        branch = self.make_remote_branch(transport, client)
 
2081
        branch.lock_write()
 
2082
        config = branch.get_config_stack()
 
2083
        config.set('email', 'The Dude <lebowski@example.com>')
 
2084
        branch.unlock()
 
2085
        self.assertFinished(client)
 
2086
        self.assertEqual(
 
2087
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
 
2088
             ('call', 'Branch.lock_write', ('memory:///', '', '')),
 
2089
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',)),
 
2090
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',)),
 
2091
             ('call_with_body_bytes_expecting_body', 'Branch.put_config_file',
 
2092
                 ('memory:///', 'branch token', 'repo token'),
 
2093
                 '# line 1\nemail = The Dude <lebowski@example.com>\n'),
 
2094
             ('call', 'Branch.unlock', ('memory:///', 'branch token', 'repo token'))],
 
2095
            client._calls)
 
2096
 
1667
2097
 
1668
2098
class TestBranchLockWrite(RemoteBranchTestCase):
1669
2099
 
1683
2113
        self.assertFinished(client)
1684
2114
 
1685
2115
 
 
2116
class TestBranchRevisionIdToRevno(RemoteBranchTestCase):
 
2117
 
 
2118
    def test_simple(self):
 
2119
        transport = MemoryTransport()
 
2120
        client = FakeClient(transport.base)
 
2121
        client.add_expected_call(
 
2122
            'Branch.get_stacked_on_url', ('quack/',),
 
2123
            'error', ('NotStacked',),)
 
2124
        client.add_expected_call(
 
2125
            'Branch.revision_id_to_revno', ('quack/', 'null:'),
 
2126
            'success', ('ok', '0',),)
 
2127
        client.add_expected_call(
 
2128
            'Branch.revision_id_to_revno', ('quack/', 'unknown'),
 
2129
            'error', ('NoSuchRevision', 'unknown',),)
 
2130
        transport.mkdir('quack')
 
2131
        transport = transport.clone('quack')
 
2132
        branch = self.make_remote_branch(transport, client)
 
2133
        self.assertEqual(0, branch.revision_id_to_revno('null:'))
 
2134
        self.assertRaises(errors.NoSuchRevision,
 
2135
            branch.revision_id_to_revno, 'unknown')
 
2136
        self.assertFinished(client)
 
2137
 
 
2138
    def test_dotted(self):
 
2139
        transport = MemoryTransport()
 
2140
        client = FakeClient(transport.base)
 
2141
        client.add_expected_call(
 
2142
            'Branch.get_stacked_on_url', ('quack/',),
 
2143
            'error', ('NotStacked',),)
 
2144
        client.add_expected_call(
 
2145
            'Branch.revision_id_to_revno', ('quack/', 'null:'),
 
2146
            'success', ('ok', '0',),)
 
2147
        client.add_expected_call(
 
2148
            'Branch.revision_id_to_revno', ('quack/', 'unknown'),
 
2149
            'error', ('NoSuchRevision', 'unknown',),)
 
2150
        transport.mkdir('quack')
 
2151
        transport = transport.clone('quack')
 
2152
        branch = self.make_remote_branch(transport, client)
 
2153
        self.assertEqual((0, ), branch.revision_id_to_dotted_revno('null:'))
 
2154
        self.assertRaises(errors.NoSuchRevision,
 
2155
            branch.revision_id_to_dotted_revno, 'unknown')
 
2156
        self.assertFinished(client)
 
2157
 
 
2158
    def test_dotted_no_smart_verb(self):
 
2159
        self.setup_smart_server_with_call_log()
 
2160
        branch = self.make_branch('.')
 
2161
        self.disable_verb('Branch.revision_id_to_revno')
 
2162
        self.reset_smart_call_log()
 
2163
        self.assertEqual((0, ),
 
2164
            branch.revision_id_to_dotted_revno('null:'))
 
2165
        self.assertLength(8, self.hpss_calls)
 
2166
 
 
2167
 
1686
2168
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
1687
2169
 
1688
2170
    def test__get_config(self):
1698
2180
 
1699
2181
    def test_set_option_uses_vfs(self):
1700
2182
        self.setup_smart_server_with_call_log()
1701
 
        bzrdir = self.make_bzrdir('.')
 
2183
        bzrdir = self.make_controldir('.')
1702
2184
        self.reset_smart_call_log()
1703
2185
        config = bzrdir.get_config()
1704
2186
        config.set_default_stack_on('/')
1705
 
        self.assertLength(3, self.hpss_calls)
 
2187
        self.assertLength(4, self.hpss_calls)
1706
2188
 
1707
2189
    def test_backwards_compat_get_option(self):
1708
2190
        self.setup_smart_server_with_call_log()
1709
 
        bzrdir = self.make_bzrdir('.')
 
2191
        bzrdir = self.make_controldir('.')
1710
2192
        verb = 'BzrDir.get_config_file'
1711
2193
        self.disable_verb(verb)
1712
2194
        self.reset_smart_call_log()
1713
2195
        self.assertEqual(None,
1714
2196
            bzrdir._get_config().get_option('default_stack_on'))
1715
 
        self.assertLength(3, self.hpss_calls)
 
2197
        self.assertLength(4, self.hpss_calls)
1716
2198
 
1717
2199
 
1718
2200
class TestTransportIsReadonly(tests.TestCase):
1805
2287
        client = FakeClient(transport.base)
1806
2288
        transport = transport.clone(transport_path)
1807
2289
        # we do not want bzrdir to make any remote calls
1808
 
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
2290
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
1809
2291
            _client=False)
1810
2292
        repo = RemoteRepository(bzrdir, None, _client=client)
1811
2293
        return repo, client
1819
2301
 
1820
2302
    def test_get_format_description(self):
1821
2303
        remote_format = RemoteBranchFormat()
1822
 
        real_format = branch.BranchFormat.get_default_format()
 
2304
        real_format = branch.format_registry.get_default()
1823
2305
        remote_format._network_name = real_format.network_name()
1824
2306
        self.assertEqual(remoted_description(real_format),
1825
2307
            remote_format.get_format_description())
1828
2310
class TestRepositoryFormat(TestRemoteRepository):
1829
2311
 
1830
2312
    def test_fast_delta(self):
1831
 
        true_name = groupcompress_repo.RepositoryFormatCHK1().network_name()
 
2313
        true_name = groupcompress_repo.RepositoryFormat2a().network_name()
1832
2314
        true_format = RemoteRepositoryFormat()
1833
2315
        true_format._network_name = true_name
1834
2316
        self.assertEqual(True, true_format.fast_deltas)
1835
 
        false_name = pack_repo.RepositoryFormatKnitPack1().network_name()
 
2317
        false_name = knitpack_repo.RepositoryFormatKnitPack1().network_name()
1836
2318
        false_format = RemoteRepositoryFormat()
1837
2319
        false_format._network_name = false_name
1838
2320
        self.assertEqual(False, false_format.fast_deltas)
1839
2321
 
1840
2322
    def test_get_format_description(self):
1841
2323
        remote_repo_format = RemoteRepositoryFormat()
1842
 
        real_format = repository.RepositoryFormat.get_default_format()
 
2324
        real_format = repository.format_registry.get_default()
1843
2325
        remote_repo_format._network_name = real_format.network_name()
1844
2326
        self.assertEqual(remoted_description(real_format),
1845
2327
            remote_repo_format.get_format_description())
1846
2328
 
1847
2329
 
 
2330
class TestRepositoryAllRevisionIds(TestRemoteRepository):
 
2331
 
 
2332
    def test_empty(self):
 
2333
        transport_path = 'quack'
 
2334
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2335
        client.add_success_response_with_body('', 'ok')
 
2336
        self.assertEqual([], repo.all_revision_ids())
 
2337
        self.assertEqual(
 
2338
            [('call_expecting_body', 'Repository.all_revision_ids',
 
2339
             ('quack/',))],
 
2340
            client._calls)
 
2341
 
 
2342
    def test_with_some_content(self):
 
2343
        transport_path = 'quack'
 
2344
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2345
        client.add_success_response_with_body(
 
2346
            'rev1\nrev2\nanotherrev\n', 'ok')
 
2347
        self.assertEqual(["rev1", "rev2", "anotherrev"],
 
2348
            repo.all_revision_ids())
 
2349
        self.assertEqual(
 
2350
            [('call_expecting_body', 'Repository.all_revision_ids',
 
2351
             ('quack/',))],
 
2352
            client._calls)
 
2353
 
 
2354
 
1848
2355
class TestRepositoryGatherStats(TestRemoteRepository):
1849
2356
 
1850
2357
    def test_revid_none(self):
1856
2363
        result = repo.gather_stats(None)
1857
2364
        self.assertEqual(
1858
2365
            [('call_expecting_body', 'Repository.gather_stats',
1859
 
             ('quack/','','no'))],
 
2366
             ('quack/', '', 'no'))],
1860
2367
            client._calls)
1861
2368
        self.assertEqual({'revisions': 2, 'size': 18}, result)
1862
2369
 
1903
2410
                         result)
1904
2411
 
1905
2412
 
 
2413
class TestRepositoryBreakLock(TestRemoteRepository):
 
2414
 
 
2415
    def test_break_lock(self):
 
2416
        transport_path = 'quack'
 
2417
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2418
        client.add_success_response('ok')
 
2419
        repo.break_lock()
 
2420
        self.assertEqual(
 
2421
            [('call', 'Repository.break_lock', ('quack/',))],
 
2422
            client._calls)
 
2423
 
 
2424
 
 
2425
class TestRepositoryGetSerializerFormat(TestRemoteRepository):
 
2426
 
 
2427
    def test_get_serializer_format(self):
 
2428
        transport_path = 'hill'
 
2429
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2430
        client.add_success_response('ok', '7')
 
2431
        self.assertEqual('7', repo.get_serializer_format())
 
2432
        self.assertEqual(
 
2433
            [('call', 'VersionedFileRepository.get_serializer_format',
 
2434
              ('hill/', ))],
 
2435
            client._calls)
 
2436
 
 
2437
 
 
2438
class TestRepositoryReconcile(TestRemoteRepository):
 
2439
 
 
2440
    def test_reconcile(self):
 
2441
        transport_path = 'hill'
 
2442
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2443
        body = ("garbage_inventories: 2\n"
 
2444
                "inconsistent_parents: 3\n")
 
2445
        client.add_expected_call(
 
2446
            'Repository.lock_write', ('hill/', ''),
 
2447
            'success', ('ok', 'a token'))
 
2448
        client.add_success_response_with_body(body, 'ok')
 
2449
        reconciler = repo.reconcile()
 
2450
        self.assertEqual(
 
2451
            [('call', 'Repository.lock_write', ('hill/', '')),
 
2452
             ('call_expecting_body', 'Repository.reconcile',
 
2453
                ('hill/', 'a token'))],
 
2454
            client._calls)
 
2455
        self.assertEqual(2, reconciler.garbage_inventories)
 
2456
        self.assertEqual(3, reconciler.inconsistent_parents)
 
2457
 
 
2458
 
 
2459
class TestRepositoryGetRevisionSignatureText(TestRemoteRepository):
 
2460
 
 
2461
    def test_text(self):
 
2462
        # ('ok',), body with signature text
 
2463
        transport_path = 'quack'
 
2464
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2465
        client.add_success_response_with_body(
 
2466
            'THETEXT', 'ok')
 
2467
        self.assertEqual("THETEXT", repo.get_signature_text("revid"))
 
2468
        self.assertEqual(
 
2469
            [('call_expecting_body', 'Repository.get_revision_signature_text',
 
2470
             ('quack/', 'revid'))],
 
2471
            client._calls)
 
2472
 
 
2473
    def test_no_signature(self):
 
2474
        transport_path = 'quick'
 
2475
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2476
        client.add_error_response('nosuchrevision', 'unknown')
 
2477
        self.assertRaises(errors.NoSuchRevision, repo.get_signature_text,
 
2478
                "unknown")
 
2479
        self.assertEqual(
 
2480
            [('call_expecting_body', 'Repository.get_revision_signature_text',
 
2481
              ('quick/', 'unknown'))],
 
2482
            client._calls)
 
2483
 
 
2484
 
1906
2485
class TestRepositoryGetGraph(TestRemoteRepository):
1907
2486
 
1908
2487
    def test_get_graph(self):
1913
2492
        self.assertNotEqual(graph._parents_provider, repo)
1914
2493
 
1915
2494
 
 
2495
class TestRepositoryAddSignatureText(TestRemoteRepository):
 
2496
 
 
2497
    def test_add_signature_text(self):
 
2498
        transport_path = 'quack'
 
2499
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2500
        client.add_expected_call(
 
2501
            'Repository.lock_write', ('quack/', ''),
 
2502
            'success', ('ok', 'a token'))
 
2503
        client.add_expected_call(
 
2504
            'Repository.start_write_group', ('quack/', 'a token'),
 
2505
            'success', ('ok', ('token1', )))
 
2506
        client.add_expected_call(
 
2507
            'Repository.add_signature_text', ('quack/', 'a token', 'rev1',
 
2508
                'token1'),
 
2509
            'success', ('ok', ), None)
 
2510
        repo.lock_write()
 
2511
        repo.start_write_group()
 
2512
        self.assertIs(None,
 
2513
            repo.add_signature_text("rev1", "every bloody emperor"))
 
2514
        self.assertEqual(
 
2515
            ('call_with_body_bytes_expecting_body',
 
2516
              'Repository.add_signature_text',
 
2517
                ('quack/', 'a token', 'rev1', 'token1'),
 
2518
              'every bloody emperor'),
 
2519
            client._calls[-1])
 
2520
 
 
2521
 
1916
2522
class TestRepositoryGetParentMap(TestRemoteRepository):
1917
2523
 
1918
2524
    def test_get_parent_map_caching(self):
1968
2574
        parents = repo.get_parent_map([rev_id])
1969
2575
        self.assertEqual(
1970
2576
            [('call_with_body_bytes_expecting_body',
1971
 
              'Repository.get_parent_map', ('quack/', 'include-missing:',
1972
 
              rev_id), '\n\n0'),
 
2577
              'Repository.get_parent_map',
 
2578
              ('quack/', 'include-missing:', rev_id), '\n\n0'),
1973
2579
             ('disconnect medium',),
1974
2580
             ('call_expecting_body', 'Repository.get_revision_graph',
1975
2581
              ('quack/', ''))],
2095
2701
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
2096
2702
        self.assertLength(0, self.hpss_calls)
2097
2703
 
 
2704
    def test_exposes_get_cached_parent_map(self):
 
2705
        """RemoteRepository exposes get_cached_parent_map from
 
2706
        _unstacked_provider
 
2707
        """
 
2708
        r1 = u'\u0e33'.encode('utf8')
 
2709
        r2 = u'\u0dab'.encode('utf8')
 
2710
        lines = [' '.join([r2, r1]), r1]
 
2711
        encoded_body = bz2.compress('\n'.join(lines))
 
2712
 
 
2713
        transport_path = 'quack'
 
2714
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2715
        client.add_success_response_with_body(encoded_body, 'ok')
 
2716
        repo.lock_read()
 
2717
        # get_cached_parent_map should *not* trigger an RPC
 
2718
        self.assertEqual({}, repo.get_cached_parent_map([r1]))
 
2719
        self.assertEqual([], client._calls)
 
2720
        self.assertEqual({r2: (r1,)}, repo.get_parent_map([r2]))
 
2721
        self.assertEqual({r1: (NULL_REVISION,)},
 
2722
            repo.get_cached_parent_map([r1]))
 
2723
        self.assertEqual(
 
2724
            [('call_with_body_bytes_expecting_body',
 
2725
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
 
2726
              '\n\n0')],
 
2727
            client._calls)
 
2728
        repo.unlock()
 
2729
 
2098
2730
 
2099
2731
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
2100
2732
 
2115
2747
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
2116
2748
 
2117
2749
 
 
2750
class TestRepositoryGetRevisions(TestRemoteRepository):
 
2751
 
 
2752
    def test_hpss_missing_revision(self):
 
2753
        transport_path = 'quack'
 
2754
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2755
        client.add_success_response_with_body(
 
2756
            '', 'ok', '10')
 
2757
        self.assertRaises(errors.NoSuchRevision, repo.get_revisions,
 
2758
            ['somerev1', 'anotherrev2'])
 
2759
        self.assertEqual(
 
2760
            [('call_with_body_bytes_expecting_body', 'Repository.iter_revisions',
 
2761
             ('quack/', ), "somerev1\nanotherrev2")],
 
2762
            client._calls)
 
2763
 
 
2764
    def test_hpss_get_single_revision(self):
 
2765
        transport_path = 'quack'
 
2766
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2767
        somerev1 = Revision("somerev1")
 
2768
        somerev1.committer = "Joe Committer <joe@example.com>"
 
2769
        somerev1.timestamp = 1321828927
 
2770
        somerev1.timezone = -60
 
2771
        somerev1.inventory_sha1 = "691b39be74c67b1212a75fcb19c433aaed903c2b"
 
2772
        somerev1.message = "Message"
 
2773
        body = zlib.compress(chk_bencode_serializer.write_revision_to_string(
 
2774
            somerev1))
 
2775
        # Split up body into two bits to make sure the zlib compression object
 
2776
        # gets data fed twice.
 
2777
        client.add_success_response_with_body(
 
2778
                [body[:10], body[10:]], 'ok', '10')
 
2779
        revs = repo.get_revisions(['somerev1'])
 
2780
        self.assertEqual(revs, [somerev1])
 
2781
        self.assertEqual(
 
2782
            [('call_with_body_bytes_expecting_body', 'Repository.iter_revisions',
 
2783
             ('quack/', ), "somerev1")],
 
2784
            client._calls)
 
2785
 
 
2786
 
2118
2787
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
2119
2788
 
2120
2789
    def test_null_revision(self):
2231
2900
        # Then it should ask the fallback, using revno/revid from the
2232
2901
        # history-incomplete response as the known revno/revid.
2233
2902
        client.add_expected_call(
2234
 
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
 
2903
            'Repository.get_rev_id_for_revno', ('fallback/', 1, (2, 'rev-two')),
2235
2904
            'success', ('ok', 'rev-one'))
2236
2905
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
2237
2906
        self.assertEqual((True, 'rev-one'), result)
2257
2926
        self.setup_smart_server_with_call_log()
2258
2927
        tree = self.make_branch_and_memory_tree('.')
2259
2928
        tree.lock_write()
 
2929
        tree.add('')
2260
2930
        rev1 = tree.commit('First')
2261
2931
        rev2 = tree.commit('Second')
2262
2932
        tree.unlock()
2270
2940
                              call.call.method == verb])
2271
2941
 
2272
2942
 
 
2943
class TestRepositoryHasSignatureForRevisionId(TestRemoteRepository):
 
2944
 
 
2945
    def test_has_signature_for_revision_id(self):
 
2946
        # ('yes', ) for Repository.has_signature_for_revision_id -> 'True'.
 
2947
        transport_path = 'quack'
 
2948
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2949
        client.add_success_response('yes')
 
2950
        result = repo.has_signature_for_revision_id('A')
 
2951
        self.assertEqual(
 
2952
            [('call', 'Repository.has_signature_for_revision_id',
 
2953
              ('quack/', 'A'))],
 
2954
            client._calls)
 
2955
        self.assertEqual(True, result)
 
2956
 
 
2957
    def test_is_not_shared(self):
 
2958
        # ('no', ) for Repository.has_signature_for_revision_id -> 'False'.
 
2959
        transport_path = 'qwack'
 
2960
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2961
        client.add_success_response('no')
 
2962
        result = repo.has_signature_for_revision_id('A')
 
2963
        self.assertEqual(
 
2964
            [('call', 'Repository.has_signature_for_revision_id',
 
2965
              ('qwack/', 'A'))],
 
2966
            client._calls)
 
2967
        self.assertEqual(False, result)
 
2968
 
 
2969
 
 
2970
class TestRepositoryPhysicalLockStatus(TestRemoteRepository):
 
2971
 
 
2972
    def test_get_physical_lock_status_yes(self):
 
2973
        transport_path = 'qwack'
 
2974
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2975
        client.add_success_response('yes')
 
2976
        result = repo.get_physical_lock_status()
 
2977
        self.assertEqual(
 
2978
            [('call', 'Repository.get_physical_lock_status',
 
2979
              ('qwack/', ))],
 
2980
            client._calls)
 
2981
        self.assertEqual(True, result)
 
2982
 
 
2983
    def test_get_physical_lock_status_no(self):
 
2984
        transport_path = 'qwack'
 
2985
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2986
        client.add_success_response('no')
 
2987
        result = repo.get_physical_lock_status()
 
2988
        self.assertEqual(
 
2989
            [('call', 'Repository.get_physical_lock_status',
 
2990
              ('qwack/', ))],
 
2991
            client._calls)
 
2992
        self.assertEqual(False, result)
 
2993
 
 
2994
 
2273
2995
class TestRepositoryIsShared(TestRemoteRepository):
2274
2996
 
2275
2997
    def test_is_shared(self):
2295
3017
        self.assertEqual(False, result)
2296
3018
 
2297
3019
 
 
3020
class TestRepositoryMakeWorkingTrees(TestRemoteRepository):
 
3021
 
 
3022
    def test_make_working_trees(self):
 
3023
        # ('yes', ) for Repository.make_working_trees -> 'True'.
 
3024
        transport_path = 'quack'
 
3025
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3026
        client.add_success_response('yes')
 
3027
        result = repo.make_working_trees()
 
3028
        self.assertEqual(
 
3029
            [('call', 'Repository.make_working_trees', ('quack/',))],
 
3030
            client._calls)
 
3031
        self.assertEqual(True, result)
 
3032
 
 
3033
    def test_no_working_trees(self):
 
3034
        # ('no', ) for Repository.make_working_trees -> 'False'.
 
3035
        transport_path = 'qwack'
 
3036
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3037
        client.add_success_response('no')
 
3038
        result = repo.make_working_trees()
 
3039
        self.assertEqual(
 
3040
            [('call', 'Repository.make_working_trees', ('qwack/',))],
 
3041
            client._calls)
 
3042
        self.assertEqual(False, result)
 
3043
 
 
3044
 
2298
3045
class TestRepositoryLockWrite(TestRemoteRepository):
2299
3046
 
2300
3047
    def test_lock_write(self):
2301
3048
        transport_path = 'quack'
2302
3049
        repo, client = self.setup_fake_client_and_repository(transport_path)
2303
3050
        client.add_success_response('ok', 'a token')
2304
 
        result = repo.lock_write()
 
3051
        token = repo.lock_write().repository_token
2305
3052
        self.assertEqual(
2306
3053
            [('call', 'Repository.lock_write', ('quack/', ''))],
2307
3054
            client._calls)
2308
 
        self.assertEqual('a token', result)
 
3055
        self.assertEqual('a token', token)
2309
3056
 
2310
3057
    def test_lock_write_already_locked(self):
2311
3058
        transport_path = 'quack'
2326
3073
            client._calls)
2327
3074
 
2328
3075
 
 
3076
class TestRepositoryWriteGroups(TestRemoteRepository):
 
3077
 
 
3078
    def test_start_write_group(self):
 
3079
        transport_path = 'quack'
 
3080
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3081
        client.add_expected_call(
 
3082
            'Repository.lock_write', ('quack/', ''),
 
3083
            'success', ('ok', 'a token'))
 
3084
        client.add_expected_call(
 
3085
            'Repository.start_write_group', ('quack/', 'a token'),
 
3086
            'success', ('ok', ('token1', )))
 
3087
        repo.lock_write()
 
3088
        repo.start_write_group()
 
3089
 
 
3090
    def test_start_write_group_unsuspendable(self):
 
3091
        # Some repositories do not support suspending write
 
3092
        # groups. For those, fall back to the "real" repository.
 
3093
        transport_path = 'quack'
 
3094
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3095
        def stub_ensure_real():
 
3096
            client._calls.append(('_ensure_real',))
 
3097
            repo._real_repository = _StubRealPackRepository(client._calls)
 
3098
        repo._ensure_real = stub_ensure_real
 
3099
        client.add_expected_call(
 
3100
            'Repository.lock_write', ('quack/', ''),
 
3101
            'success', ('ok', 'a token'))
 
3102
        client.add_expected_call(
 
3103
            'Repository.start_write_group', ('quack/', 'a token'),
 
3104
            'error', ('UnsuspendableWriteGroup',))
 
3105
        repo.lock_write()
 
3106
        repo.start_write_group()
 
3107
        self.assertEqual(client._calls[-2:], [ 
 
3108
            ('_ensure_real',),
 
3109
            ('start_write_group',)])
 
3110
 
 
3111
    def test_commit_write_group(self):
 
3112
        transport_path = 'quack'
 
3113
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3114
        client.add_expected_call(
 
3115
            'Repository.lock_write', ('quack/', ''),
 
3116
            'success', ('ok', 'a token'))
 
3117
        client.add_expected_call(
 
3118
            'Repository.start_write_group', ('quack/', 'a token'),
 
3119
            'success', ('ok', ['token1']))
 
3120
        client.add_expected_call(
 
3121
            'Repository.commit_write_group', ('quack/', 'a token', ['token1']),
 
3122
            'success', ('ok',))
 
3123
        repo.lock_write()
 
3124
        repo.start_write_group()
 
3125
        repo.commit_write_group()
 
3126
 
 
3127
    def test_abort_write_group(self):
 
3128
        transport_path = 'quack'
 
3129
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3130
        client.add_expected_call(
 
3131
            'Repository.lock_write', ('quack/', ''),
 
3132
            'success', ('ok', 'a token'))
 
3133
        client.add_expected_call(
 
3134
            'Repository.start_write_group', ('quack/', 'a token'),
 
3135
            'success', ('ok', ['token1']))
 
3136
        client.add_expected_call(
 
3137
            'Repository.abort_write_group', ('quack/', 'a token', ['token1']),
 
3138
            'success', ('ok',))
 
3139
        repo.lock_write()
 
3140
        repo.start_write_group()
 
3141
        repo.abort_write_group(False)
 
3142
 
 
3143
    def test_suspend_write_group(self):
 
3144
        transport_path = 'quack'
 
3145
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3146
        self.assertEqual([], repo.suspend_write_group())
 
3147
 
 
3148
    def test_resume_write_group(self):
 
3149
        transport_path = 'quack'
 
3150
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3151
        client.add_expected_call(
 
3152
            'Repository.lock_write', ('quack/', ''),
 
3153
            'success', ('ok', 'a token'))
 
3154
        client.add_expected_call(
 
3155
            'Repository.check_write_group', ('quack/', 'a token', ['token1']),
 
3156
            'success', ('ok',))
 
3157
        repo.lock_write()
 
3158
        repo.resume_write_group(['token1'])
 
3159
 
 
3160
 
2329
3161
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
2330
3162
 
2331
3163
    def test_backwards_compat(self):
2390
3222
        self.assertEqual([], client._calls)
2391
3223
 
2392
3224
 
 
3225
class TestRepositoryIterFilesBytes(TestRemoteRepository):
 
3226
    """Test Repository.iter_file_bytes."""
 
3227
 
 
3228
    def test_single(self):
 
3229
        transport_path = 'quack'
 
3230
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3231
        client.add_expected_call(
 
3232
            'Repository.iter_files_bytes', ('quack/', ),
 
3233
            'success', ('ok',), iter(["ok\x000", "\n", zlib.compress("mydata" * 10)]))
 
3234
        for (identifier, byte_stream) in repo.iter_files_bytes([("somefile",
 
3235
                "somerev", "myid")]):
 
3236
            self.assertEqual("myid", identifier)
 
3237
            self.assertEqual("".join(byte_stream), "mydata" * 10)
 
3238
 
 
3239
    def test_missing(self):
 
3240
        transport_path = 'quack'
 
3241
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3242
        client.add_expected_call(
 
3243
            'Repository.iter_files_bytes',
 
3244
                ('quack/', ),
 
3245
            'error', ('RevisionNotPresent', 'somefile', 'somerev'),
 
3246
            iter(["absent\0somefile\0somerev\n"]))
 
3247
        self.assertRaises(errors.RevisionNotPresent, list,
 
3248
                repo.iter_files_bytes(
 
3249
                [("somefile", "somerev", "myid")]))
 
3250
 
 
3251
 
2393
3252
class TestRepositoryInsertStreamBase(TestRemoteRepository):
2394
3253
    """Base class for Repository.insert_stream and .insert_stream_1.19
2395
3254
    tests.
2402
3261
        the client is finished.
2403
3262
        """
2404
3263
        sink = repo._get_sink()
2405
 
        fmt = repository.RepositoryFormat.get_default_format()
 
3264
        fmt = repository.format_registry.get_default()
2406
3265
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2407
3266
        self.assertEqual([], resume_tokens)
2408
3267
        self.assertEqual(set(), missing_keys)
2417
3276
    """
2418
3277
 
2419
3278
    def setUp(self):
2420
 
        TestRemoteRepository.setUp(self)
 
3279
        super(TestRepositoryInsertStream, self).setUp()
2421
3280
        self.disable_verb('Repository.insert_stream_1.19')
2422
3281
 
2423
3282
    def test_unlocked_repo(self):
2508
3367
                return True
2509
3368
        repo._real_repository = FakeRealRepository()
2510
3369
        sink = repo._get_sink()
2511
 
        fmt = repository.RepositoryFormat.get_default_format()
 
3370
        fmt = repository.format_registry.get_default()
2512
3371
        stream = self.make_stream_with_inv_deltas(fmt)
2513
3372
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
2514
3373
        # Every record from the first inventory delta should have been sent to
2613
3472
class TestRepositoryTarball(TestRemoteRepository):
2614
3473
 
2615
3474
    # This is a canned tarball reponse we can validate against
2616
 
    tarball_content = (
 
3475
    tarball_content = base64.b64decode(
2617
3476
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
2618
3477
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
2619
3478
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
2626
3485
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
2627
3486
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
2628
3487
        'nWQ7QH/F3JFOFCQ0aSPfA='
2629
 
        ).decode('base64')
 
3488
        )
2630
3489
 
2631
3490
    def test_repository_tarball(self):
2632
3491
        # Test that Repository.tarball generates the right operations
2670
3529
        self.calls = calls
2671
3530
        self._pack_collection = _StubPackCollection(calls)
2672
3531
 
 
3532
    def start_write_group(self):
 
3533
        self.calls.append(('start_write_group',))
 
3534
 
2673
3535
    def is_in_write_group(self):
2674
3536
        return False
2675
3537
 
2734
3596
             ('pack collection autopack',)],
2735
3597
            client._calls)
2736
3598
 
 
3599
    def test_oom_error_reporting(self):
 
3600
        """An out-of-memory condition on the server is reported clearly"""
 
3601
        transport_path = 'quack'
 
3602
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
3603
        client.add_expected_call(
 
3604
            'PackRepository.autopack', ('quack/',),
 
3605
            'error', ('MemoryError',))
 
3606
        err = self.assertRaises(errors.BzrError, repo.autopack)
 
3607
        self.assertContainsRe(str(err), "^remote server out of mem")
 
3608
 
2737
3609
 
2738
3610
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
2739
 
    """Base class for unit tests for bzrlib.remote._translate_error."""
 
3611
    """Base class for unit tests for breezy.bzr.remote._translate_error."""
2740
3612
 
2741
3613
    def translateTuple(self, error_tuple, **context):
2742
3614
        """Call _translate_error with an ErrorFromSmartServer built from the
2762
3634
        """
2763
3635
        try:
2764
3636
            raise error_object
2765
 
        except errors.ErrorFromSmartServer, server_error:
 
3637
        except errors.ErrorFromSmartServer as server_error:
2766
3638
            translated_error = self.assertRaises(
2767
3639
                errors.BzrError, remote._translate_error, server_error,
2768
3640
                **context)
2770
3642
 
2771
3643
 
2772
3644
class TestErrorTranslationSuccess(TestErrorTranslationBase):
2773
 
    """Unit tests for bzrlib.remote._translate_error.
 
3645
    """Unit tests for breezy.bzr.remote._translate_error.
2774
3646
 
2775
3647
    Given an ErrorFromSmartServer (which has an error tuple from a smart
2776
3648
    server) and some context, _translate_error raises more specific errors from
2777
 
    bzrlib.errors.
 
3649
    breezy.errors.
2778
3650
 
2779
3651
    This test case covers the cases where _translate_error succeeds in
2780
3652
    translating an ErrorFromSmartServer to something better.  See
2798
3670
        self.assertEqual(expected_error, translated_error)
2799
3671
 
2800
3672
    def test_nobranch(self):
2801
 
        bzrdir = self.make_bzrdir('')
 
3673
        bzrdir = self.make_controldir('')
2802
3674
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
2803
3675
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
2804
3676
        self.assertEqual(expected_error, translated_error)
2805
3677
 
2806
3678
    def test_nobranch_one_arg(self):
2807
 
        bzrdir = self.make_bzrdir('')
 
3679
        bzrdir = self.make_controldir('')
2808
3680
        translated_error = self.translateTuple(
2809
3681
            ('nobranch', 'extra detail'), bzrdir=bzrdir)
2810
3682
        expected_error = errors.NotBranchError(
2812
3684
            detail='extra detail')
2813
3685
        self.assertEqual(expected_error, translated_error)
2814
3686
 
 
3687
    def test_norepository(self):
 
3688
        bzrdir = self.make_controldir('')
 
3689
        translated_error = self.translateTuple(('norepository',),
 
3690
            bzrdir=bzrdir)
 
3691
        expected_error = errors.NoRepositoryPresent(bzrdir)
 
3692
        self.assertEqual(expected_error, translated_error)
 
3693
 
2815
3694
    def test_LockContention(self):
2816
3695
        translated_error = self.translateTuple(('LockContention',))
2817
3696
        expected_error = errors.LockContention('(remote lock)')
2818
3697
        self.assertEqual(expected_error, translated_error)
2819
3698
 
2820
3699
    def test_UnlockableTransport(self):
2821
 
        bzrdir = self.make_bzrdir('')
 
3700
        bzrdir = self.make_controldir('')
2822
3701
        translated_error = self.translateTuple(
2823
3702
            ('UnlockableTransport',), bzrdir=bzrdir)
2824
3703
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
2845
3724
        expected_error = errors.DivergedBranches(branch, other_branch)
2846
3725
        self.assertEqual(expected_error, translated_error)
2847
3726
 
 
3727
    def test_NotStacked(self):
 
3728
        branch = self.make_branch('')
 
3729
        translated_error = self.translateTuple(('NotStacked',), branch=branch)
 
3730
        expected_error = errors.NotStacked(branch)
 
3731
        self.assertEqual(expected_error, translated_error)
 
3732
 
2848
3733
    def test_ReadError_no_args(self):
2849
3734
        path = 'a path'
2850
3735
        translated_error = self.translateTuple(('ReadError',), path=path)
2866
3751
 
2867
3752
    def test_PermissionDenied_no_args(self):
2868
3753
        path = 'a path'
2869
 
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
 
3754
        translated_error = self.translateTuple(('PermissionDenied',),
 
3755
            path=path)
2870
3756
        expected_error = errors.PermissionDenied(path)
2871
3757
        self.assertEqual(expected_error, translated_error)
2872
3758
 
2895
3781
        expected_error = errors.PermissionDenied(path, extra)
2896
3782
        self.assertEqual(expected_error, translated_error)
2897
3783
 
 
3784
    # GZ 2011-03-02: TODO test for PermissionDenied with non-ascii 'extra'
 
3785
 
 
3786
    def test_NoSuchFile_context_path(self):
 
3787
        local_path = "local path"
 
3788
        translated_error = self.translateTuple(('ReadError', "remote path"),
 
3789
            path=local_path)
 
3790
        expected_error = errors.ReadError(local_path)
 
3791
        self.assertEqual(expected_error, translated_error)
 
3792
 
 
3793
    def test_NoSuchFile_without_context(self):
 
3794
        remote_path = "remote path"
 
3795
        translated_error = self.translateTuple(('ReadError', remote_path))
 
3796
        expected_error = errors.ReadError(remote_path)
 
3797
        self.assertEqual(expected_error, translated_error)
 
3798
 
 
3799
    def test_ReadOnlyError(self):
 
3800
        translated_error = self.translateTuple(('ReadOnlyError',))
 
3801
        expected_error = errors.TransportNotPossible("readonly transport")
 
3802
        self.assertEqual(expected_error, translated_error)
 
3803
 
 
3804
    def test_MemoryError(self):
 
3805
        translated_error = self.translateTuple(('MemoryError',))
 
3806
        self.assertStartsWith(str(translated_error),
 
3807
            "remote server out of memory")
 
3808
 
 
3809
    def test_generic_IndexError_no_classname(self):
 
3810
        err = errors.ErrorFromSmartServer(('error', "list index out of range"))
 
3811
        translated_error = self.translateErrorFromSmartServer(err)
 
3812
        expected_error = errors.UnknownErrorFromSmartServer(err)
 
3813
        self.assertEqual(expected_error, translated_error)
 
3814
 
 
3815
    # GZ 2011-03-02: TODO test generic non-ascii error string
 
3816
 
 
3817
    def test_generic_KeyError(self):
 
3818
        err = errors.ErrorFromSmartServer(('error', 'KeyError', "1"))
 
3819
        translated_error = self.translateErrorFromSmartServer(err)
 
3820
        expected_error = errors.UnknownErrorFromSmartServer(err)
 
3821
        self.assertEqual(expected_error, translated_error)
 
3822
 
2898
3823
 
2899
3824
class TestErrorTranslationRobustness(TestErrorTranslationBase):
2900
 
    """Unit tests for bzrlib.remote._translate_error's robustness.
 
3825
    """Unit tests for breezy.bzr.remote._translate_error's robustness.
2901
3826
 
2902
3827
    TestErrorTranslationSuccess is for cases where _translate_error can
2903
3828
    translate successfully.  This class about how _translate_err behaves when
2995
3920
        self.setup_smart_server_with_call_log()
2996
3921
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
2997
3922
        tree1.commit('rev1', rev_id='rev1')
2998
 
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
 
3923
        tree2 = tree1.branch.controldir.sprout('tree2', stacked=True
2999
3924
            ).open_workingtree()
3000
3925
        local_tree = tree2.branch.create_checkout('local')
3001
3926
        local_tree.commit('local changes make me feel good.')
3008
3933
        # the public implementation of get_parent_map obeys stacking
3009
3934
        _, branch = self.prepare_stacked_remote_branch()
3010
3935
        repo = branch.repository
3011
 
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
 
3936
        self.assertEqual({'rev1'}, set(repo.get_parent_map(['rev1'])))
3012
3937
 
3013
3938
    def test_unstacked_get_parent_map(self):
3014
3939
        # _unstacked_provider.get_parent_map ignores stacking
3015
3940
        _, branch = self.prepare_stacked_remote_branch()
3016
3941
        provider = branch.repository._unstacked_provider
3017
 
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
 
3942
        self.assertEqual(set(), set(provider.get_parent_map(['rev1'])))
3018
3943
 
3019
3944
    def fetch_stream_to_rev_order(self, stream):
3020
3945
        result = []
3036
3961
        :result: The revision ids in the stream, in the order seen,
3037
3962
            the topological order of revisions in the source.
3038
3963
        """
3039
 
        unordered_format = bzrdir.format_registry.get(format)()
 
3964
        unordered_format = controldir.format_registry.get(format)()
3040
3965
        target_repository_format = unordered_format.repository_format
3041
3966
        # Cross check
3042
3967
        self.assertEqual(order, target_repository_format._fetch_order)
3045
3970
        _, stacked = branch_factory()
3046
3971
        source = stacked.repository._get_source(target_repository_format)
3047
3972
        tip = stacked.last_revision()
3048
 
        revs = stacked.repository.get_ancestry(tip)
3049
 
        search = graph.PendingAncestryResult([tip], stacked.repository)
 
3973
        stacked.repository._ensure_real()
 
3974
        graph = stacked.repository.get_graph()
 
3975
        revs = [r for (r, ps) in graph.iter_ancestry([tip])
 
3976
                if r != NULL_REVISION]
 
3977
        revs.reverse()
 
3978
        search = vf_search.PendingAncestryResult([tip], stacked.repository)
3050
3979
        self.reset_smart_call_log()
3051
3980
        stream = source.get_stream(search)
3052
 
        if None in revs:
3053
 
            revs.remove(None)
3054
3981
        # We trust that if a revision is in the stream the rest of the new
3055
3982
        # content for it is too, as per our main fetch tests; here we are
3056
3983
        # checking that the revisions are actually included at all, and their
3072
3999
        # is itself stacked yields the full data from all three sources.
3073
4000
        def make_stacked_stacked():
3074
4001
            _, stacked = self.prepare_stacked_remote_branch()
3075
 
            tree = stacked.bzrdir.sprout('tree3', stacked=True
 
4002
            tree = stacked.controldir.sprout('tree3', stacked=True
3076
4003
                ).open_workingtree()
3077
4004
            local_tree = tree.branch.create_checkout('local-tree3')
3078
4005
            local_tree.commit('more local changes are better')
3095
4022
        self.assertEqual(expected_revs, rev_ord)
3096
4023
        # Getting topological sort requires VFS calls still - one of which is
3097
4024
        # pushing up from the bound branch.
3098
 
        self.assertLength(13, self.hpss_calls)
 
4025
        self.assertLength(14, self.hpss_calls)
3099
4026
 
3100
4027
    def test_stacked_get_stream_groupcompress(self):
3101
4028
        # Repository._get_source.get_stream() from a stacked repository with
3142
4069
 
3143
4070
    def test_copy_content_into_avoids_revision_history(self):
3144
4071
        local = self.make_branch('local')
3145
 
        remote_backing_tree = self.make_branch_and_tree('remote')
3146
 
        remote_backing_tree.commit("Commit.")
 
4072
        builder = self.make_branch_builder('remote')
 
4073
        builder.build_commit(message="Commit.")
3147
4074
        remote_branch_url = self.smart_server.get_url() + 'remote'
3148
4075
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3149
4076
        local.repository.fetch(remote_branch.repository)
3150
4077
        self.hpss_calls = []
3151
4078
        remote_branch.copy_content_into(local)
3152
4079
        self.assertFalse('Branch.revision_history' in self.hpss_calls)
 
4080
 
 
4081
    def test_fetch_everything_needs_just_one_call(self):
 
4082
        local = self.make_branch('local')
 
4083
        builder = self.make_branch_builder('remote')
 
4084
        builder.build_commit(message="Commit.")
 
4085
        remote_branch_url = self.smart_server.get_url() + 'remote'
 
4086
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
 
4087
        self.hpss_calls = []
 
4088
        local.repository.fetch(
 
4089
            remote_branch.repository,
 
4090
            fetch_spec=vf_search.EverythingResult(remote_branch.repository))
 
4091
        self.assertEqual(['Repository.get_stream_1.19'], self.hpss_calls)
 
4092
 
 
4093
    def override_verb(self, verb_name, verb):
 
4094
        request_handlers = request.request_handlers
 
4095
        orig_verb = request_handlers.get(verb_name)
 
4096
        orig_info = request_handlers.get_info(verb_name)
 
4097
        request_handlers.register(verb_name, verb, override_existing=True)
 
4098
        self.addCleanup(request_handlers.register, verb_name, orig_verb,
 
4099
                override_existing=True, info=orig_info)
 
4100
 
 
4101
    def test_fetch_everything_backwards_compat(self):
 
4102
        """Can fetch with EverythingResult even with pre 2.4 servers.
 
4103
        
 
4104
        Pre-2.4 do not support 'everything' searches with the
 
4105
        Repository.get_stream_1.19 verb.
 
4106
        """
 
4107
        verb_log = []
 
4108
        class OldGetStreamVerb(SmartServerRepositoryGetStream_1_19):
 
4109
            """A version of the Repository.get_stream_1.19 verb patched to
 
4110
            reject 'everything' searches the way 2.3 and earlier do.
 
4111
            """
 
4112
            def recreate_search(self, repository, search_bytes,
 
4113
                                discard_excess=False):
 
4114
                verb_log.append(search_bytes.split('\n', 1)[0])
 
4115
                if search_bytes == 'everything':
 
4116
                    return (None,
 
4117
                            request.FailedSmartServerResponse(('BadSearch',)))
 
4118
                return super(OldGetStreamVerb,
 
4119
                        self).recreate_search(repository, search_bytes,
 
4120
                            discard_excess=discard_excess)
 
4121
        self.override_verb('Repository.get_stream_1.19', OldGetStreamVerb)
 
4122
        local = self.make_branch('local')
 
4123
        builder = self.make_branch_builder('remote')
 
4124
        builder.build_commit(message="Commit.")
 
4125
        remote_branch_url = self.smart_server.get_url() + 'remote'
 
4126
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
 
4127
        self.hpss_calls = []
 
4128
        local.repository.fetch(
 
4129
            remote_branch.repository,
 
4130
            fetch_spec=vf_search.EverythingResult(remote_branch.repository))
 
4131
        # make sure the overridden verb was used
 
4132
        self.assertLength(1, verb_log)
 
4133
        # more than one HPSS call is needed, but because it's a VFS callback
 
4134
        # its hard to predict exactly how many.
 
4135
        self.assertTrue(len(self.hpss_calls) > 1)
 
4136
 
 
4137
 
 
4138
class TestUpdateBoundBranchWithModifiedBoundLocation(
 
4139
    tests.TestCaseWithTransport):
 
4140
    """Ensure correct handling of bound_location modifications.
 
4141
 
 
4142
    This is tested against a smart server as http://pad.lv/786980 was about a
 
4143
    ReadOnlyError (write attempt during a read-only transaction) which can only
 
4144
    happen in this context.
 
4145
    """
 
4146
 
 
4147
    def setUp(self):
 
4148
        super(TestUpdateBoundBranchWithModifiedBoundLocation, self).setUp()
 
4149
        self.transport_server = test_server.SmartTCPServer_for_testing
 
4150
 
 
4151
    def make_master_and_checkout(self, master_name, checkout_name):
 
4152
        # Create the master branch and its associated checkout
 
4153
        self.master = self.make_branch_and_tree(master_name)
 
4154
        self.checkout = self.master.branch.create_checkout(checkout_name)
 
4155
        # Modify the master branch so there is something to update
 
4156
        self.master.commit('add stuff')
 
4157
        self.last_revid = self.master.commit('even more stuff')
 
4158
        self.bound_location = self.checkout.branch.get_bound_location()
 
4159
 
 
4160
    def assertUpdateSucceeds(self, new_location):
 
4161
        self.checkout.branch.set_bound_location(new_location)
 
4162
        self.checkout.update()
 
4163
        self.assertEqual(self.last_revid, self.checkout.last_revision())
 
4164
 
 
4165
    def test_without_final_slash(self):
 
4166
        self.make_master_and_checkout('master', 'checkout')
 
4167
        # For unclear reasons some users have a bound_location without a final
 
4168
        # '/', simulate that by forcing such a value
 
4169
        self.assertEndsWith(self.bound_location, '/')
 
4170
        self.assertUpdateSucceeds(self.bound_location.rstrip('/'))
 
4171
 
 
4172
    def test_plus_sign(self):
 
4173
        self.make_master_and_checkout('+master', 'checkout')
 
4174
        self.assertUpdateSucceeds(self.bound_location.replace('%2B', '+', 1))
 
4175
 
 
4176
    def test_tilda(self):
 
4177
        # Embed ~ in the middle of the path just to avoid any $HOME
 
4178
        # interpretation
 
4179
        self.make_master_and_checkout('mas~ter', 'checkout')
 
4180
        self.assertUpdateSucceeds(self.bound_location.replace('%2E', '~', 1))
 
4181
 
 
4182
 
 
4183
class TestWithCustomErrorHandler(RemoteBranchTestCase):
 
4184
 
 
4185
    def test_no_context(self):
 
4186
        class OutOfCoffee(errors.BzrError):
 
4187
            """A dummy exception for testing."""
 
4188
 
 
4189
            def __init__(self, urgency):
 
4190
                self.urgency = urgency
 
4191
        remote.no_context_error_translators.register("OutOfCoffee",
 
4192
            lambda err: OutOfCoffee(err.error_args[0]))
 
4193
        transport = MemoryTransport()
 
4194
        client = FakeClient(transport.base)
 
4195
        client.add_expected_call(
 
4196
            'Branch.get_stacked_on_url', ('quack/',),
 
4197
            'error', ('NotStacked',))
 
4198
        client.add_expected_call(
 
4199
            'Branch.last_revision_info',
 
4200
            ('quack/',),
 
4201
            'error', ('OutOfCoffee', 'low'))
 
4202
        transport.mkdir('quack')
 
4203
        transport = transport.clone('quack')
 
4204
        branch = self.make_remote_branch(transport, client)
 
4205
        self.assertRaises(OutOfCoffee, branch.last_revision_info)
 
4206
        self.assertFinished(client)
 
4207
 
 
4208
    def test_with_context(self):
 
4209
        class OutOfTea(errors.BzrError):
 
4210
            def __init__(self, branch, urgency):
 
4211
                self.branch = branch
 
4212
                self.urgency = urgency
 
4213
        remote.error_translators.register("OutOfTea",
 
4214
            lambda err, find, path: OutOfTea(err.error_args[0],
 
4215
                find("branch")))
 
4216
        transport = MemoryTransport()
 
4217
        client = FakeClient(transport.base)
 
4218
        client.add_expected_call(
 
4219
            'Branch.get_stacked_on_url', ('quack/',),
 
4220
            'error', ('NotStacked',))
 
4221
        client.add_expected_call(
 
4222
            'Branch.last_revision_info',
 
4223
            ('quack/',),
 
4224
            'error', ('OutOfTea', 'low'))
 
4225
        transport.mkdir('quack')
 
4226
        transport = transport.clone('quack')
 
4227
        branch = self.make_remote_branch(transport, client)
 
4228
        self.assertRaises(OutOfTea, branch.last_revision_info)
 
4229
        self.assertFinished(client)
 
4230
 
 
4231
 
 
4232
class TestRepositoryPack(TestRemoteRepository):
 
4233
 
 
4234
    def test_pack(self):
 
4235
        transport_path = 'quack'
 
4236
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4237
        client.add_expected_call(
 
4238
            'Repository.lock_write', ('quack/', ''),
 
4239
            'success', ('ok', 'token'))
 
4240
        client.add_expected_call(
 
4241
            'Repository.pack', ('quack/', 'token', 'False'),
 
4242
            'success', ('ok',), )
 
4243
        client.add_expected_call(
 
4244
            'Repository.unlock', ('quack/', 'token'),
 
4245
            'success', ('ok', ))
 
4246
        repo.pack()
 
4247
 
 
4248
    def test_pack_with_hint(self):
 
4249
        transport_path = 'quack'
 
4250
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4251
        client.add_expected_call(
 
4252
            'Repository.lock_write', ('quack/', ''),
 
4253
            'success', ('ok', 'token'))
 
4254
        client.add_expected_call(
 
4255
            'Repository.pack', ('quack/', 'token', 'False'),
 
4256
            'success', ('ok',), )
 
4257
        client.add_expected_call(
 
4258
            'Repository.unlock', ('quack/', 'token', 'False'),
 
4259
            'success', ('ok', ))
 
4260
        repo.pack(['hinta', 'hintb'])
 
4261
 
 
4262
 
 
4263
class TestRepositoryIterInventories(TestRemoteRepository):
 
4264
    """Test Repository.iter_inventories."""
 
4265
 
 
4266
    def _serialize_inv_delta(self, old_name, new_name, delta):
 
4267
        serializer = inventory_delta.InventoryDeltaSerializer(True, False)
 
4268
        return "".join(serializer.delta_to_lines(old_name, new_name, delta))
 
4269
 
 
4270
    def test_single_empty(self):
 
4271
        transport_path = 'quack'
 
4272
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4273
        fmt = controldir.format_registry.get('2a')().repository_format
 
4274
        repo._format = fmt
 
4275
        stream = [('inventory-deltas', [
 
4276
            versionedfile.FulltextContentFactory('somerevid', None, None,
 
4277
                self._serialize_inv_delta('null:', 'somerevid', []))])]
 
4278
        client.add_expected_call(
 
4279
            'VersionedFileRepository.get_inventories', ('quack/', 'unordered'),
 
4280
            'success', ('ok', ),
 
4281
            _stream_to_byte_stream(stream, fmt))
 
4282
        ret = list(repo.iter_inventories(["somerevid"]))
 
4283
        self.assertLength(1, ret)
 
4284
        inv = ret[0]
 
4285
        self.assertEqual("somerevid", inv.revision_id)
 
4286
 
 
4287
    def test_empty(self):
 
4288
        transport_path = 'quack'
 
4289
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4290
        ret = list(repo.iter_inventories([]))
 
4291
        self.assertEqual(ret, [])
 
4292
 
 
4293
    def test_missing(self):
 
4294
        transport_path = 'quack'
 
4295
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
4296
        client.add_expected_call(
 
4297
            'VersionedFileRepository.get_inventories', ('quack/', 'unordered'),
 
4298
            'success', ('ok', ), iter([]))
 
4299
        self.assertRaises(errors.NoSuchRevision, list, repo.iter_inventories(
 
4300
            ["somerevid"]))