~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-08 12:39:40 UTC
  • mfrom: (4266.2.1 tests.output)
  • Revision ID: pqm@pqm.ubuntu.com-20090408123940-kaho6cwr21163fjn
(robertc) Remove clutter from bzr selftest --list. (Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
27
27
from cStringIO import StringIO
28
28
 
29
29
from bzrlib import (
30
 
    branch,
31
30
    bzrdir,
32
31
    config,
33
32
    errors,
34
33
    graph,
35
 
    inventory,
36
 
    inventory_delta,
37
34
    pack,
38
35
    remote,
39
36
    repository,
 
37
    smart,
40
38
    tests,
41
 
    transport,
42
39
    treebuilder,
43
40
    urlutils,
44
 
    versionedfile,
45
41
    )
46
42
from bzrlib.branch import Branch
47
43
from bzrlib.bzrdir import BzrDir, BzrDirFormat
55
51
    )
56
52
from bzrlib.repofmt import groupcompress_repo, pack_repo
57
53
from bzrlib.revision import NULL_REVISION
58
 
from bzrlib.smart import medium
 
54
from bzrlib.smart import server, medium
59
55
from bzrlib.smart.client import _SmartClient
60
56
from bzrlib.smart.repository import SmartServerRepositoryGetParentMap
61
57
from bzrlib.tests import (
62
58
    condition_isinstance,
63
59
    split_suite_by_condition,
64
60
    multiply_tests,
65
 
    test_server,
66
61
    )
 
62
from bzrlib.transport import get_transport, http
67
63
from bzrlib.transport.memory import MemoryTransport
68
64
from bzrlib.transport.remote import (
69
65
    RemoteTransport,
76
72
        standard_tests, condition_isinstance(BasicRemoteObjectTests))
77
73
    smart_server_version_scenarios = [
78
74
        ('HPSS-v2',
79
 
         {'transport_server': test_server.SmartTCPServer_for_testing_v2_only}),
 
75
            {'transport_server': server.SmartTCPServer_for_testing_v2_only}),
80
76
        ('HPSS-v3',
81
 
         {'transport_server': test_server.SmartTCPServer_for_testing})]
 
77
            {'transport_server': server.SmartTCPServer_for_testing})]
82
78
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
83
79
 
84
80
 
135
131
        b = BzrDir.open_from_transport(self.transport).open_branch()
136
132
        self.assertStartsWith(str(b), 'RemoteBranch(')
137
133
 
138
 
    def test_remote_bzrdir_repr(self):
139
 
        b = BzrDir.open_from_transport(self.transport)
140
 
        self.assertStartsWith(str(b), 'RemoteBzrDir(')
141
 
 
142
134
    def test_remote_branch_format_supports_stacking(self):
143
135
        t = self.transport
144
136
        self.make_branch('unstackable', format='pack-0.92')
161
153
        r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
162
154
        self.assertTrue(r._format.supports_external_lookups)
163
155
 
164
 
    def test_remote_branch_set_append_revisions_only(self):
165
 
        # Make a format 1.9 branch, which supports append_revisions_only
166
 
        branch = self.make_branch('branch', format='1.9')
167
 
        config = branch.get_config()
168
 
        branch.set_append_revisions_only(True)
169
 
        self.assertEqual(
170
 
            'True', config.get_user_option('append_revisions_only'))
171
 
        branch.set_append_revisions_only(False)
172
 
        self.assertEqual(
173
 
            'False', config.get_user_option('append_revisions_only'))
174
 
 
175
 
    def test_remote_branch_set_append_revisions_only_upgrade_reqd(self):
176
 
        branch = self.make_branch('branch', format='knit')
177
 
        config = branch.get_config()
178
 
        self.assertRaises(
179
 
            errors.UpgradeRequired, branch.set_append_revisions_only, True)
180
 
 
181
156
 
182
157
class FakeProtocol(object):
183
158
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
284
259
        self.expecting_body = True
285
260
        return result[1], FakeProtocol(result[2], self)
286
261
 
287
 
    def call_with_body_bytes(self, method, args, body):
288
 
        self._check_call(method, args)
289
 
        self._calls.append(('call_with_body_bytes', method, args, body))
290
 
        result = self._get_next_response()
291
 
        return result[1], FakeProtocol(result[2], self)
292
 
 
293
262
    def call_with_body_bytes_expecting_body(self, method, args, body):
294
263
        self._check_call(method, args)
295
264
        self._calls.append(('call_with_body_bytes_expecting_body', method,
345
314
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
346
315
        return reference_bzrdir_format.repository_format
347
316
 
348
 
    def assertFinished(self, fake_client):
349
 
        """Assert that all of a FakeClient's expected calls have occurred."""
350
 
        fake_client.finished_test()
 
317
    def disable_verb(self, verb):
 
318
        """Disable a verb for one test."""
 
319
        request_handlers = smart.request.request_handlers
 
320
        orig_method = request_handlers.get(verb)
 
321
        request_handlers.remove(verb)
 
322
        def restoreVerb():
 
323
            request_handlers.register(verb, orig_method)
 
324
        self.addCleanup(restoreVerb)
351
325
 
352
326
 
353
327
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
359
333
        a given client_base and transport_base.
360
334
        """
361
335
        client_medium = medium.SmartClientMedium(client_base)
362
 
        t = transport.get_transport(transport_base)
363
 
        result = client_medium.remote_path_from_transport(t)
 
336
        transport = get_transport(transport_base)
 
337
        result = client_medium.remote_path_from_transport(transport)
364
338
        self.assertEqual(expected, result)
365
339
 
366
340
    def test_remote_path_from_transport(self):
377
351
        a given transport_base and relpath of that transport.  (Note that
378
352
        HttpTransportBase is a subclass of SmartClientMedium)
379
353
        """
380
 
        base_transport = transport.get_transport(transport_base)
 
354
        base_transport = get_transport(transport_base)
381
355
        client_medium = base_transport.get_smart_medium()
382
356
        cloned_transport = base_transport.clone(relpath)
383
357
        result = client_medium.remote_path_from_transport(cloned_transport)
418
392
        # Calling _remember_remote_is_before again with a lower value works.
419
393
        client_medium._remember_remote_is_before((1, 5))
420
394
        self.assertTrue(client_medium._is_remote_before((1, 5)))
421
 
        # If you call _remember_remote_is_before with a higher value it logs a
422
 
        # warning, and continues to remember the lower value.
423
 
        self.assertNotContainsRe(self.get_log(), '_remember_remote_is_before')
424
 
        client_medium._remember_remote_is_before((1, 9))
425
 
        self.assertContainsRe(self.get_log(), '_remember_remote_is_before')
426
 
        self.assertTrue(client_medium._is_remote_before((1, 5)))
 
395
        # You cannot call _remember_remote_is_before with a larger value.
 
396
        self.assertRaises(
 
397
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
427
398
 
428
399
 
429
400
class TestBzrDirCloningMetaDir(TestRemote):
448
419
            'BzrDir.cloning_metadir', ('quack/', 'False'),
449
420
            'error', ('BranchReference',)),
450
421
        client.add_expected_call(
451
 
            'BzrDir.open_branchV3', ('quack/',),
 
422
            'BzrDir.open_branchV2', ('quack/',),
452
423
            'success', ('ref', self.get_url('referenced'))),
453
424
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
454
425
            _client=client)
457
428
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
458
429
        self.assertEqual(expected._repository_format, result._repository_format)
459
430
        self.assertEqual(expected._branch_format, result._branch_format)
460
 
        self.assertFinished(client)
 
431
        client.finished_test()
461
432
 
462
433
    def test_current_server(self):
463
434
        transport = self.get_transport('.')
478
449
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
479
450
        self.assertEqual(None, result._repository_format)
480
451
        self.assertEqual(None, result._branch_format)
481
 
        self.assertFinished(client)
482
 
 
483
 
 
484
 
class TestBzrDirOpen(TestRemote):
485
 
 
486
 
    def make_fake_client_and_transport(self, path='quack'):
487
 
        transport = MemoryTransport()
488
 
        transport.mkdir(path)
489
 
        transport = transport.clone(path)
490
 
        client = FakeClient(transport.base)
491
 
        return client, transport
492
 
 
493
 
    def test_absent(self):
494
 
        client, transport = self.make_fake_client_and_transport()
495
 
        client.add_expected_call(
496
 
            'BzrDir.open_2.1', ('quack/',), 'success', ('no',))
497
 
        self.assertRaises(errors.NotBranchError, RemoteBzrDir, transport,
498
 
                remote.RemoteBzrDirFormat(), _client=client, _force_probe=True)
499
 
        self.assertFinished(client)
500
 
 
501
 
    def test_present_without_workingtree(self):
502
 
        client, transport = self.make_fake_client_and_transport()
503
 
        client.add_expected_call(
504
 
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'no'))
505
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
506
 
            _client=client, _force_probe=True)
507
 
        self.assertIsInstance(bd, RemoteBzrDir)
508
 
        self.assertFalse(bd.has_workingtree())
509
 
        self.assertRaises(errors.NoWorkingTree, bd.open_workingtree)
510
 
        self.assertFinished(client)
511
 
 
512
 
    def test_present_with_workingtree(self):
513
 
        client, transport = self.make_fake_client_and_transport()
514
 
        client.add_expected_call(
515
 
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'yes'))
516
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
517
 
            _client=client, _force_probe=True)
518
 
        self.assertIsInstance(bd, RemoteBzrDir)
519
 
        self.assertTrue(bd.has_workingtree())
520
 
        self.assertRaises(errors.NotLocalUrl, bd.open_workingtree)
521
 
        self.assertFinished(client)
522
 
 
523
 
    def test_backwards_compat(self):
524
 
        client, transport = self.make_fake_client_and_transport()
525
 
        client.add_expected_call(
526
 
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
527
 
        client.add_expected_call(
528
 
            'BzrDir.open', ('quack/',), 'success', ('yes',))
529
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
530
 
            _client=client, _force_probe=True)
531
 
        self.assertIsInstance(bd, RemoteBzrDir)
532
 
        self.assertFinished(client)
533
 
 
534
 
    def test_backwards_compat_hpss_v2(self):
535
 
        client, transport = self.make_fake_client_and_transport()
536
 
        # Monkey-patch fake client to simulate real-world behaviour with v2
537
 
        # server: upon first RPC call detect the protocol version, and because
538
 
        # the version is 2 also do _remember_remote_is_before((1, 6)) before
539
 
        # continuing with the RPC.
540
 
        orig_check_call = client._check_call
541
 
        def check_call(method, args):
542
 
            client._medium._protocol_version = 2
543
 
            client._medium._remember_remote_is_before((1, 6))
544
 
            client._check_call = orig_check_call
545
 
            client._check_call(method, args)
546
 
        client._check_call = check_call
547
 
        client.add_expected_call(
548
 
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
549
 
        client.add_expected_call(
550
 
            'BzrDir.open', ('quack/',), 'success', ('yes',))
551
 
        bd = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
552
 
            _client=client, _force_probe=True)
553
 
        self.assertIsInstance(bd, RemoteBzrDir)
554
 
        self.assertFinished(client)
 
452
        client.finished_test()
555
453
 
556
454
 
557
455
class TestBzrDirOpenBranch(TestRemote):
561
459
        self.make_branch('.')
562
460
        a_dir = BzrDir.open(self.get_url('.'))
563
461
        self.reset_smart_call_log()
564
 
        verb = 'BzrDir.open_branchV3'
 
462
        verb = 'BzrDir.open_branchV2'
565
463
        self.disable_verb(verb)
566
464
        format = a_dir.open_branch()
567
465
        call_count = len([call for call in self.hpss_calls if
577
475
        transport = transport.clone('quack')
578
476
        client = FakeClient(transport.base)
579
477
        client.add_expected_call(
580
 
            'BzrDir.open_branchV3', ('quack/',),
 
478
            'BzrDir.open_branchV2', ('quack/',),
581
479
            'success', ('branch', branch_network_name))
582
480
        client.add_expected_call(
583
481
            'BzrDir.find_repositoryV3', ('quack/',),
590
488
        result = bzrdir.open_branch()
591
489
        self.assertIsInstance(result, RemoteBranch)
592
490
        self.assertEqual(bzrdir, result.bzrdir)
593
 
        self.assertFinished(client)
 
491
        client.finished_test()
594
492
 
595
493
    def test_branch_missing(self):
596
494
        transport = MemoryTransport()
602
500
            _client=client)
603
501
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
604
502
        self.assertEqual(
605
 
            [('call', 'BzrDir.open_branchV3', ('quack/',))],
 
503
            [('call', 'BzrDir.open_branchV2', ('quack/',))],
606
504
            client._calls)
607
505
 
608
506
    def test__get_tree_branch(self):
609
507
        # _get_tree_branch is a form of open_branch, but it should only ask for
610
508
        # branch opening, not any other network requests.
611
509
        calls = []
612
 
        def open_branch(name=None):
 
510
        def open_branch():
613
511
            calls.append("Called")
614
512
            return "a-branch"
615
513
        transport = MemoryTransport()
632
530
        network_name = reference_format.network_name()
633
531
        branch_network_name = self.get_branch_format().network_name()
634
532
        client.add_expected_call(
635
 
            'BzrDir.open_branchV3', ('~hello/',),
 
533
            'BzrDir.open_branchV2', ('~hello/',),
636
534
            'success', ('branch', branch_network_name))
637
535
        client.add_expected_call(
638
536
            'BzrDir.find_repositoryV3', ('~hello/',),
643
541
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
644
542
            _client=client)
645
543
        result = bzrdir.open_branch()
646
 
        self.assertFinished(client)
 
544
        client.finished_test()
647
545
 
648
546
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
649
547
        reference_format = self.get_repo_format()
747
645
        network_name = reference_format.network_name()
748
646
        client.add_expected_call(
749
647
            'BzrDir.create_repository', ('quack/',
750
 
                'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
751
 
                'False'),
752
 
            'success', ('ok', 'yes', 'yes', 'yes', network_name))
 
648
                'Bazaar pack repository format 1 (needs bzr 0.92)\n', 'False'),
 
649
            'success', ('ok', 'no', 'no', 'no', network_name))
753
650
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
754
651
            _client=client)
755
652
        repo = a_bzrdir.create_repository()
757
654
        self.assertIsInstance(repo, remote.RemoteRepository)
758
655
        # its format should have the settings from the response
759
656
        format = repo._format
760
 
        self.assertTrue(format.rich_root_data)
761
 
        self.assertTrue(format.supports_tree_reference)
762
 
        self.assertTrue(format.supports_external_lookups)
 
657
        self.assertFalse(format.rich_root_data)
 
658
        self.assertFalse(format.supports_tree_reference)
 
659
        self.assertFalse(format.supports_external_lookups)
763
660
        self.assertEqual(network_name, format.network_name())
764
661
 
765
662
 
769
666
        # fallback all the way to the first version.
770
667
        reference_format = self.get_repo_format()
771
668
        network_name = reference_format.network_name()
772
 
        server_url = 'bzr://example.com/'
773
 
        self.permit_url(server_url)
774
 
        client = FakeClient(server_url)
 
669
        client = FakeClient('bzr://example.com/')
775
670
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
776
671
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
777
672
        client.add_success_response('ok', '', 'no', 'no')
783
678
            reference_format.get_format_string(), 'ok')
784
679
        # PackRepository wants to do a stat
785
680
        client.add_success_response('stat', '0', '65535')
786
 
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
 
681
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
787
682
            _client=client)
788
683
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
789
684
            _client=client)
803
698
        # fallback to find_repositoryV2
804
699
        reference_format = self.get_repo_format()
805
700
        network_name = reference_format.network_name()
806
 
        server_url = 'bzr://example.com/'
807
 
        self.permit_url(server_url)
808
 
        client = FakeClient(server_url)
 
701
        client = FakeClient('bzr://example.com/')
809
702
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
810
703
        client.add_success_response('ok', '', 'no', 'no', 'no')
811
704
        # A real repository instance will be created to determine the network
816
709
            reference_format.get_format_string(), 'ok')
817
710
        # PackRepository wants to do a stat
818
711
        client.add_success_response('stat', '0', '65535')
819
 
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
 
712
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
820
713
            _client=client)
821
714
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
822
715
            _client=client)
848
741
        self.assertEqual(network_name, repo._format.network_name())
849
742
 
850
743
 
851
 
class TestBzrDirFormatInitializeEx(TestRemote):
852
 
 
853
 
    def test_success(self):
854
 
        """Simple test for typical successful call."""
855
 
        fmt = bzrdir.RemoteBzrDirFormat()
856
 
        default_format_name = BzrDirFormat.get_default_format().network_name()
857
 
        transport = self.get_transport()
858
 
        client = FakeClient(transport.base)
859
 
        client.add_expected_call(
860
 
            'BzrDirFormat.initialize_ex_1.16',
861
 
                (default_format_name, 'path', 'False', 'False', 'False', '',
862
 
                 '', '', '', 'False'),
863
 
            'success',
864
 
                ('.', 'no', 'no', 'yes', 'repo fmt', 'repo bzrdir fmt',
865
 
                 'bzrdir fmt', 'False', '', '', 'repo lock token'))
866
 
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
867
 
        # it's currently hard to test that without supplying a real remote
868
 
        # transport connected to a real server.
869
 
        result = fmt._initialize_on_transport_ex_rpc(client, 'path',
870
 
            transport, False, False, False, None, None, None, None, False)
871
 
        self.assertFinished(client)
872
 
 
873
 
    def test_error(self):
874
 
        """Error responses are translated, e.g. 'PermissionDenied' raises the
875
 
        corresponding error from the client.
876
 
        """
877
 
        fmt = bzrdir.RemoteBzrDirFormat()
878
 
        default_format_name = BzrDirFormat.get_default_format().network_name()
879
 
        transport = self.get_transport()
880
 
        client = FakeClient(transport.base)
881
 
        client.add_expected_call(
882
 
            'BzrDirFormat.initialize_ex_1.16',
883
 
                (default_format_name, 'path', 'False', 'False', 'False', '',
884
 
                 '', '', '', 'False'),
885
 
            'error',
886
 
                ('PermissionDenied', 'path', 'extra info'))
887
 
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
888
 
        # it's currently hard to test that without supplying a real remote
889
 
        # transport connected to a real server.
890
 
        err = self.assertRaises(errors.PermissionDenied,
891
 
            fmt._initialize_on_transport_ex_rpc, client, 'path', transport,
892
 
            False, False, False, None, None, None, None, False)
893
 
        self.assertEqual('path', err.path)
894
 
        self.assertEqual(': extra info', err.extra)
895
 
        self.assertFinished(client)
896
 
 
897
 
    def test_error_from_real_server(self):
898
 
        """Integration test for error translation."""
899
 
        transport = self.make_smart_server('foo')
900
 
        transport = transport.clone('no-such-path')
901
 
        fmt = bzrdir.RemoteBzrDirFormat()
902
 
        err = self.assertRaises(errors.NoSuchFile,
903
 
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
904
 
 
905
 
 
906
744
class OldSmartClient(object):
907
745
    """A fake smart client for test_old_version that just returns a version one
908
746
    response to the 'hello' (query version) command.
931
769
        return OldSmartClient()
932
770
 
933
771
 
934
 
class RemoteBzrDirTestCase(TestRemote):
935
 
 
936
 
    def make_remote_bzrdir(self, transport, client):
937
 
        """Make a RemotebzrDir using 'client' as the _client."""
938
 
        return RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
939
 
            _client=client)
940
 
 
941
 
 
942
 
class RemoteBranchTestCase(RemoteBzrDirTestCase):
943
 
 
944
 
    def lock_remote_branch(self, branch):
945
 
        """Trick a RemoteBranch into thinking it is locked."""
946
 
        branch._lock_mode = 'w'
947
 
        branch._lock_count = 2
948
 
        branch._lock_token = 'branch token'
949
 
        branch._repo_lock_token = 'repo token'
950
 
        branch.repository._lock_mode = 'w'
951
 
        branch.repository._lock_count = 2
952
 
        branch.repository._lock_token = 'repo token'
 
772
class RemoteBranchTestCase(TestRemote):
953
773
 
954
774
    def make_remote_branch(self, transport, client):
955
775
        """Make a RemoteBranch using 'client' as its _SmartClient.
960
780
        # we do not want bzrdir to make any remote calls, so use False as its
961
781
        # _client.  If it tries to make a remote call, this will fail
962
782
        # immediately.
963
 
        bzrdir = self.make_remote_bzrdir(transport, False)
 
783
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
 
784
            _client=False)
964
785
        repo = RemoteRepository(bzrdir, None, _client=client)
965
786
        branch_format = self.get_branch_format()
966
787
        format = RemoteBranchFormat(network_name=branch_format.network_name())
983
804
        transport = transport.clone('quack')
984
805
        branch = self.make_remote_branch(transport, client)
985
806
        result = branch.get_parent()
986
 
        self.assertFinished(client)
 
807
        client.finished_test()
987
808
        self.assertEqual(None, result)
988
809
 
989
810
    def test_parent_relative(self):
1015
836
        branch = self.make_remote_branch(transport, client)
1016
837
        result = branch.get_parent()
1017
838
        self.assertEqual('http://foo/', result)
1018
 
        self.assertFinished(client)
1019
 
 
1020
 
 
1021
 
class TestBranchSetParentLocation(RemoteBranchTestCase):
1022
 
 
1023
 
    def test_no_parent(self):
1024
 
        # We call the verb when setting parent to None
1025
 
        transport = MemoryTransport()
1026
 
        client = FakeClient(transport.base)
1027
 
        client.add_expected_call(
1028
 
            'Branch.get_stacked_on_url', ('quack/',),
1029
 
            'error', ('NotStacked',))
1030
 
        client.add_expected_call(
1031
 
            'Branch.set_parent_location', ('quack/', 'b', 'r', ''),
1032
 
            'success', ())
1033
 
        transport.mkdir('quack')
1034
 
        transport = transport.clone('quack')
1035
 
        branch = self.make_remote_branch(transport, client)
1036
 
        branch._lock_token = 'b'
1037
 
        branch._repo_lock_token = 'r'
1038
 
        branch._set_parent_location(None)
1039
 
        self.assertFinished(client)
1040
 
 
1041
 
    def test_parent(self):
1042
 
        transport = MemoryTransport()
1043
 
        client = FakeClient(transport.base)
1044
 
        client.add_expected_call(
1045
 
            'Branch.get_stacked_on_url', ('kwaak/',),
1046
 
            'error', ('NotStacked',))
1047
 
        client.add_expected_call(
1048
 
            'Branch.set_parent_location', ('kwaak/', 'b', 'r', 'foo'),
1049
 
            'success', ())
1050
 
        transport.mkdir('kwaak')
1051
 
        transport = transport.clone('kwaak')
1052
 
        branch = self.make_remote_branch(transport, client)
1053
 
        branch._lock_token = 'b'
1054
 
        branch._repo_lock_token = 'r'
1055
 
        branch._set_parent_location('foo')
1056
 
        self.assertFinished(client)
1057
 
 
1058
 
    def test_backwards_compat(self):
1059
 
        self.setup_smart_server_with_call_log()
1060
 
        branch = self.make_branch('.')
1061
 
        self.reset_smart_call_log()
1062
 
        verb = 'Branch.set_parent_location'
1063
 
        self.disable_verb(verb)
1064
 
        branch.set_parent('http://foo/')
1065
 
        self.assertLength(12, self.hpss_calls)
1066
839
 
1067
840
 
1068
841
class TestBranchGetTagsBytes(RemoteBranchTestCase):
1091
864
        transport = transport.clone('quack')
1092
865
        branch = self.make_remote_branch(transport, client)
1093
866
        result = branch.tags.get_tag_dict()
1094
 
        self.assertFinished(client)
 
867
        client.finished_test()
1095
868
        self.assertEqual({}, result)
1096
869
 
1097
870
 
1098
 
class TestBranchSetTagsBytes(RemoteBranchTestCase):
1099
 
 
1100
 
    def test_trivial(self):
1101
 
        transport = MemoryTransport()
1102
 
        client = FakeClient(transport.base)
1103
 
        client.add_expected_call(
1104
 
            'Branch.get_stacked_on_url', ('quack/',),
1105
 
            'error', ('NotStacked',))
1106
 
        client.add_expected_call(
1107
 
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1108
 
            'success', ('',))
1109
 
        transport.mkdir('quack')
1110
 
        transport = transport.clone('quack')
1111
 
        branch = self.make_remote_branch(transport, client)
1112
 
        self.lock_remote_branch(branch)
1113
 
        branch._set_tags_bytes('tags bytes')
1114
 
        self.assertFinished(client)
1115
 
        self.assertEqual('tags bytes', client._calls[-1][-1])
1116
 
 
1117
 
    def test_backwards_compatible(self):
1118
 
        transport = MemoryTransport()
1119
 
        client = FakeClient(transport.base)
1120
 
        client.add_expected_call(
1121
 
            'Branch.get_stacked_on_url', ('quack/',),
1122
 
            'error', ('NotStacked',))
1123
 
        client.add_expected_call(
1124
 
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1125
 
            'unknown', ('Branch.set_tags_bytes',))
1126
 
        transport.mkdir('quack')
1127
 
        transport = transport.clone('quack')
1128
 
        branch = self.make_remote_branch(transport, client)
1129
 
        self.lock_remote_branch(branch)
1130
 
        class StubRealBranch(object):
1131
 
            def __init__(self):
1132
 
                self.calls = []
1133
 
            def _set_tags_bytes(self, bytes):
1134
 
                self.calls.append(('set_tags_bytes', bytes))
1135
 
        real_branch = StubRealBranch()
1136
 
        branch._real_branch = real_branch
1137
 
        branch._set_tags_bytes('tags bytes')
1138
 
        # Call a second time, to exercise the 'remote version already inferred'
1139
 
        # code path.
1140
 
        branch._set_tags_bytes('tags bytes')
1141
 
        self.assertFinished(client)
1142
 
        self.assertEqual(
1143
 
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
1144
 
 
1145
 
 
1146
871
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
1147
872
 
1148
873
    def test_empty_branch(self):
1159
884
        transport = transport.clone('quack')
1160
885
        branch = self.make_remote_branch(transport, client)
1161
886
        result = branch.last_revision_info()
1162
 
        self.assertFinished(client)
 
887
        client.finished_test()
1163
888
        self.assertEqual((0, NULL_REVISION), result)
1164
889
 
1165
890
    def test_non_empty_branch(self):
1220
945
        client = FakeClient(self.get_url())
1221
946
        branch_network_name = self.get_branch_format().network_name()
1222
947
        client.add_expected_call(
1223
 
            'BzrDir.open_branchV3', ('stacked/',),
 
948
            'BzrDir.open_branchV2', ('stacked/',),
1224
949
            'success', ('branch', branch_network_name))
1225
950
        client.add_expected_call(
1226
951
            'BzrDir.find_repositoryV3', ('stacked/',),
1240
965
        branch = bzrdir.open_branch()
1241
966
        result = branch.get_stacked_on_url()
1242
967
        self.assertEqual('../base', result)
1243
 
        self.assertFinished(client)
 
968
        client.finished_test()
1244
969
        # it's in the fallback list both for the RemoteRepository and its vfs
1245
970
        # repository
1246
971
        self.assertEqual(1, len(branch.repository._fallback_repositories))
1248
973
            len(branch.repository._real_repository._fallback_repositories))
1249
974
 
1250
975
    def test_get_stacked_on_real_branch(self):
1251
 
        base_branch = self.make_branch('base')
1252
 
        stacked_branch = self.make_branch('stacked')
 
976
        base_branch = self.make_branch('base', format='1.6')
 
977
        stacked_branch = self.make_branch('stacked', format='1.6')
1253
978
        stacked_branch.set_stacked_on_url('../base')
1254
979
        reference_format = self.get_repo_format()
1255
980
        network_name = reference_format.network_name()
1256
981
        client = FakeClient(self.get_url())
1257
982
        branch_network_name = self.get_branch_format().network_name()
1258
983
        client.add_expected_call(
1259
 
            'BzrDir.open_branchV3', ('stacked/',),
 
984
            'BzrDir.open_branchV2', ('stacked/',),
1260
985
            'success', ('branch', branch_network_name))
1261
986
        client.add_expected_call(
1262
987
            'BzrDir.find_repositoryV3', ('stacked/',),
1263
 
            'success', ('ok', '', 'yes', 'no', 'yes', network_name))
 
988
            'success', ('ok', '', 'no', 'no', 'yes', network_name))
1264
989
        # called twice, once from constructor and then again by us
1265
990
        client.add_expected_call(
1266
991
            'Branch.get_stacked_on_url', ('stacked/',),
1273
998
        branch = bzrdir.open_branch()
1274
999
        result = branch.get_stacked_on_url()
1275
1000
        self.assertEqual('../base', result)
1276
 
        self.assertFinished(client)
 
1001
        client.finished_test()
1277
1002
        # it's in the fallback list both for the RemoteRepository.
1278
1003
        self.assertEqual(1, len(branch.repository._fallback_repositories))
1279
1004
        # And we haven't had to construct a real repository.
1314
1039
        result = branch.set_revision_history([])
1315
1040
        branch.unlock()
1316
1041
        self.assertEqual(None, result)
1317
 
        self.assertFinished(client)
 
1042
        client.finished_test()
1318
1043
 
1319
1044
    def test_set_nonempty(self):
1320
1045
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
1352
1077
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
1353
1078
        branch.unlock()
1354
1079
        self.assertEqual(None, result)
1355
 
        self.assertFinished(client)
 
1080
        client.finished_test()
1356
1081
 
1357
1082
    def test_no_such_revision(self):
1358
1083
        transport = MemoryTransport()
1387
1112
        self.assertRaises(
1388
1113
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
1389
1114
        branch.unlock()
1390
 
        self.assertFinished(client)
 
1115
        client.finished_test()
1391
1116
 
1392
1117
    def test_tip_change_rejected(self):
1393
1118
        """TipChangeRejected responses cause a TipChangeRejected exception to
1430
1155
        self.assertIsInstance(err.msg, unicode)
1431
1156
        self.assertEqual(rejection_msg_unicode, err.msg)
1432
1157
        branch.unlock()
1433
 
        self.assertFinished(client)
 
1158
        client.finished_test()
1434
1159
 
1435
1160
 
1436
1161
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
1490
1215
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1491
1216
        branch.unlock()
1492
1217
 
 
1218
    def lock_remote_branch(self, branch):
 
1219
        """Trick a RemoteBranch into thinking it is locked."""
 
1220
        branch._lock_mode = 'w'
 
1221
        branch._lock_count = 2
 
1222
        branch._lock_token = 'branch token'
 
1223
        branch._repo_lock_token = 'repo token'
 
1224
        branch.repository._lock_mode = 'w'
 
1225
        branch.repository._lock_count = 2
 
1226
        branch.repository._lock_token = 'repo token'
 
1227
 
1493
1228
    def test_backwards_compatibility(self):
1494
1229
        """If the server does not support the Branch.set_last_revision_info
1495
1230
        verb (which is new in 1.4), then the client falls back to VFS methods.
1536
1271
        self.assertEqual(
1537
1272
            [('set_last_revision_info', 1234, 'a-revision-id')],
1538
1273
            real_branch.calls)
1539
 
        self.assertFinished(client)
 
1274
        client.finished_test()
1540
1275
 
1541
1276
    def test_unexpected_error(self):
1542
1277
        # If the server sends an error the client doesn't understand, it gets
1618
1353
    def test_get_multi_line_branch_conf(self):
1619
1354
        # Make sure that multiple-line branch.conf files are supported
1620
1355
        #
1621
 
        # https://bugs.launchpad.net/bzr/+bug/354075
 
1356
        # https://bugs.edge.launchpad.net/bzr/+bug/354075
1622
1357
        client = FakeClient()
1623
1358
        client.add_expected_call(
1624
1359
            'Branch.get_stacked_on_url', ('memory:///',),
1650
1385
        config = branch._get_config()
1651
1386
        config.set_option('foo', 'bar')
1652
1387
        branch.unlock()
1653
 
        self.assertFinished(client)
1654
 
 
1655
 
    def test_set_option_with_dict(self):
1656
 
        client = FakeClient()
1657
 
        client.add_expected_call(
1658
 
            'Branch.get_stacked_on_url', ('memory:///',),
1659
 
            'error', ('NotStacked',),)
1660
 
        client.add_expected_call(
1661
 
            'Branch.lock_write', ('memory:///', '', ''),
1662
 
            'success', ('ok', 'branch token', 'repo token'))
1663
 
        encoded_dict_value = 'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde'
1664
 
        client.add_expected_call(
1665
 
            'Branch.set_config_option_dict', ('memory:///', 'branch token',
1666
 
            'repo token', encoded_dict_value, 'foo', ''),
1667
 
            'success', ())
1668
 
        client.add_expected_call(
1669
 
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1670
 
            'success', ('ok',))
1671
 
        transport = MemoryTransport()
1672
 
        branch = self.make_remote_branch(transport, client)
1673
 
        branch.lock_write()
1674
 
        config = branch._get_config()
1675
 
        config.set_option(
1676
 
            {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'},
1677
 
            'foo')
1678
 
        branch.unlock()
1679
 
        self.assertFinished(client)
 
1388
        client.finished_test()
1680
1389
 
1681
1390
    def test_backwards_compat_set_option(self):
1682
1391
        self.setup_smart_server_with_call_log()
1690
1399
        self.assertLength(10, self.hpss_calls)
1691
1400
        self.assertEqual('value', branch._get_config().get_option('name'))
1692
1401
 
1693
 
    def test_backwards_compat_set_option_with_dict(self):
1694
 
        self.setup_smart_server_with_call_log()
1695
 
        branch = self.make_branch('.')
1696
 
        verb = 'Branch.set_config_option_dict'
1697
 
        self.disable_verb(verb)
1698
 
        branch.lock_write()
1699
 
        self.addCleanup(branch.unlock)
1700
 
        self.reset_smart_call_log()
1701
 
        config = branch._get_config()
1702
 
        value_dict = {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
1703
 
        config.set_option(value_dict, 'name')
1704
 
        self.assertLength(10, self.hpss_calls)
1705
 
        self.assertEqual(value_dict, branch._get_config().get_option('name'))
1706
 
 
1707
1402
 
1708
1403
class TestBranchLockWrite(RemoteBranchTestCase):
1709
1404
 
1720
1415
        transport = transport.clone('quack')
1721
1416
        branch = self.make_remote_branch(transport, client)
1722
1417
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
1723
 
        self.assertFinished(client)
1724
 
 
1725
 
 
1726
 
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
1727
 
 
1728
 
    def test__get_config(self):
1729
 
        client = FakeClient()
1730
 
        client.add_success_response_with_body('default_stack_on = /\n', 'ok')
1731
 
        transport = MemoryTransport()
1732
 
        bzrdir = self.make_remote_bzrdir(transport, client)
1733
 
        config = bzrdir.get_config()
1734
 
        self.assertEqual('/', config.get_default_stack_on())
1735
 
        self.assertEqual(
1736
 
            [('call_expecting_body', 'BzrDir.get_config_file', ('memory:///',))],
1737
 
            client._calls)
1738
 
 
1739
 
    def test_set_option_uses_vfs(self):
1740
 
        self.setup_smart_server_with_call_log()
1741
 
        bzrdir = self.make_bzrdir('.')
1742
 
        self.reset_smart_call_log()
1743
 
        config = bzrdir.get_config()
1744
 
        config.set_default_stack_on('/')
1745
 
        self.assertLength(3, self.hpss_calls)
1746
 
 
1747
 
    def test_backwards_compat_get_option(self):
1748
 
        self.setup_smart_server_with_call_log()
1749
 
        bzrdir = self.make_bzrdir('.')
1750
 
        verb = 'BzrDir.get_config_file'
1751
 
        self.disable_verb(verb)
1752
 
        self.reset_smart_call_log()
1753
 
        self.assertEqual(None,
1754
 
            bzrdir._get_config().get_option('default_stack_on'))
1755
 
        self.assertLength(3, self.hpss_calls)
 
1418
        client.finished_test()
1756
1419
 
1757
1420
 
1758
1421
class TestTransportIsReadonly(tests.TestCase):
1851
1514
        return repo, client
1852
1515
 
1853
1516
 
1854
 
def remoted_description(format):
1855
 
    return 'Remote: ' + format.get_format_description()
1856
 
 
1857
 
 
1858
 
class TestBranchFormat(tests.TestCase):
1859
 
 
1860
 
    def test_get_format_description(self):
1861
 
        remote_format = RemoteBranchFormat()
1862
 
        real_format = branch.BranchFormat.get_default_format()
1863
 
        remote_format._network_name = real_format.network_name()
1864
 
        self.assertEqual(remoted_description(real_format),
1865
 
            remote_format.get_format_description())
1866
 
 
1867
 
 
1868
1517
class TestRepositoryFormat(TestRemoteRepository):
1869
1518
 
1870
1519
    def test_fast_delta(self):
1877
1526
        false_format._network_name = false_name
1878
1527
        self.assertEqual(False, false_format.fast_deltas)
1879
1528
 
1880
 
    def test_get_format_description(self):
1881
 
        remote_repo_format = RemoteRepositoryFormat()
1882
 
        real_format = repository.RepositoryFormat.get_default_format()
1883
 
        remote_repo_format._network_name = real_format.network_name()
1884
 
        self.assertEqual(remoted_description(real_format),
1885
 
            remote_repo_format.get_format_description())
1886
 
 
1887
1529
 
1888
1530
class TestRepositoryGatherStats(TestRemoteRepository):
1889
1531
 
2074
1716
        self.assertLength(1, self.hpss_calls)
2075
1717
 
2076
1718
    def disableExtraResults(self):
2077
 
        self.overrideAttr(SmartServerRepositoryGetParentMap,
2078
 
                          'no_extra_results', True)
 
1719
        old_flag = SmartServerRepositoryGetParentMap.no_extra_results
 
1720
        SmartServerRepositoryGetParentMap.no_extra_results = True
 
1721
        def reset_values():
 
1722
            SmartServerRepositoryGetParentMap.no_extra_results = old_flag
 
1723
        self.addCleanup(reset_values)
2079
1724
 
2080
1725
    def test_null_cached_missing_and_stop_key(self):
2081
1726
        self.setup_smart_server_with_call_log()
2140
1785
 
2141
1786
    def test_allows_new_revisions(self):
2142
1787
        """get_parent_map's results can be updated by commit."""
2143
 
        smart_server = test_server.SmartTCPServer_for_testing()
2144
 
        self.start_server(smart_server)
 
1788
        smart_server = server.SmartTCPServer_for_testing()
 
1789
        smart_server.setUp()
 
1790
        self.addCleanup(smart_server.tearDown)
2145
1791
        self.make_branch('branch')
2146
1792
        branch = Branch.open(smart_server.get_url() + '/branch')
2147
1793
        tree = branch.create_checkout('tree', lightweight=True)
2230
1876
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
2231
1877
 
2232
1878
 
2233
 
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
2234
 
 
2235
 
    def test_ok(self):
2236
 
        repo, client = self.setup_fake_client_and_repository('quack')
2237
 
        client.add_expected_call(
2238
 
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2239
 
            'success', ('ok', 'rev-five'))
2240
 
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2241
 
        self.assertEqual((True, 'rev-five'), result)
2242
 
        self.assertFinished(client)
2243
 
 
2244
 
    def test_history_incomplete(self):
2245
 
        repo, client = self.setup_fake_client_and_repository('quack')
2246
 
        client.add_expected_call(
2247
 
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2248
 
            'success', ('history-incomplete', 10, 'rev-ten'))
2249
 
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2250
 
        self.assertEqual((False, (10, 'rev-ten')), result)
2251
 
        self.assertFinished(client)
2252
 
 
2253
 
    def test_history_incomplete_with_fallback(self):
2254
 
        """A 'history-incomplete' response causes the fallback repository to be
2255
 
        queried too, if one is set.
2256
 
        """
2257
 
        # Make a repo with a fallback repo, both using a FakeClient.
2258
 
        format = remote.response_tuple_to_repo_format(
2259
 
            ('yes', 'no', 'yes', self.get_repo_format().network_name()))
2260
 
        repo, client = self.setup_fake_client_and_repository('quack')
2261
 
        repo._format = format
2262
 
        fallback_repo, ignored = self.setup_fake_client_and_repository(
2263
 
            'fallback')
2264
 
        fallback_repo._client = client
2265
 
        fallback_repo._format = format
2266
 
        repo.add_fallback_repository(fallback_repo)
2267
 
        # First the client should ask the primary repo
2268
 
        client.add_expected_call(
2269
 
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
2270
 
            'success', ('history-incomplete', 2, 'rev-two'))
2271
 
        # Then it should ask the fallback, using revno/revid from the
2272
 
        # history-incomplete response as the known revno/revid.
2273
 
        client.add_expected_call(
2274
 
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
2275
 
            'success', ('ok', 'rev-one'))
2276
 
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
2277
 
        self.assertEqual((True, 'rev-one'), result)
2278
 
        self.assertFinished(client)
2279
 
 
2280
 
    def test_nosuchrevision(self):
2281
 
        # 'nosuchrevision' is returned when the known-revid is not found in the
2282
 
        # remote repo.  The client translates that response to NoSuchRevision.
2283
 
        repo, client = self.setup_fake_client_and_repository('quack')
2284
 
        client.add_expected_call(
2285
 
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2286
 
            'error', ('nosuchrevision', 'rev-foo'))
2287
 
        self.assertRaises(
2288
 
            errors.NoSuchRevision,
2289
 
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
2290
 
        self.assertFinished(client)
2291
 
 
2292
 
    def test_branch_fallback_locking(self):
2293
 
        """RemoteBranch.get_rev_id takes a read lock, and tries to call the
2294
 
        get_rev_id_for_revno verb.  If the verb is unknown the VFS fallback
2295
 
        will be invoked, which will fail if the repo is unlocked.
2296
 
        """
2297
 
        self.setup_smart_server_with_call_log()
2298
 
        tree = self.make_branch_and_memory_tree('.')
2299
 
        tree.lock_write()
2300
 
        tree.add('')
2301
 
        rev1 = tree.commit('First')
2302
 
        rev2 = tree.commit('Second')
2303
 
        tree.unlock()
2304
 
        branch = tree.branch
2305
 
        self.assertFalse(branch.is_locked())
2306
 
        self.reset_smart_call_log()
2307
 
        verb = 'Repository.get_rev_id_for_revno'
2308
 
        self.disable_verb(verb)
2309
 
        self.assertEqual(rev1, branch.get_rev_id(1))
2310
 
        self.assertLength(1, [call for call in self.hpss_calls if
2311
 
                              call.call.method == verb])
2312
 
 
2313
 
 
2314
1879
class TestRepositoryIsShared(TestRemoteRepository):
2315
1880
 
2316
1881
    def test_is_shared(self):
2342
1907
        transport_path = 'quack'
2343
1908
        repo, client = self.setup_fake_client_and_repository(transport_path)
2344
1909
        client.add_success_response('ok', 'a token')
2345
 
        token = repo.lock_write().repository_token
 
1910
        result = repo.lock_write()
2346
1911
        self.assertEqual(
2347
1912
            [('call', 'Repository.lock_write', ('quack/', ''))],
2348
1913
            client._calls)
2349
 
        self.assertEqual('a token', token)
 
1914
        self.assertEqual('a token', result)
2350
1915
 
2351
1916
    def test_lock_write_already_locked(self):
2352
1917
        transport_path = 'quack'
2431
1996
        self.assertEqual([], client._calls)
2432
1997
 
2433
1998
 
2434
 
class TestRepositoryInsertStreamBase(TestRemoteRepository):
2435
 
    """Base class for Repository.insert_stream and .insert_stream_1.19
2436
 
    tests.
2437
 
    """
2438
 
    
2439
 
    def checkInsertEmptyStream(self, repo, client):
2440
 
        """Insert an empty stream, checking the result.
2441
 
 
2442
 
        This checks that there are no resume_tokens or missing_keys, and that
2443
 
        the client is finished.
2444
 
        """
2445
 
        sink = repo._get_sink()
2446
 
        fmt = repository.RepositoryFormat.get_default_format()
2447
 
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2448
 
        self.assertEqual([], resume_tokens)
2449
 
        self.assertEqual(set(), missing_keys)
2450
 
        self.assertFinished(client)
2451
 
 
2452
 
 
2453
 
class TestRepositoryInsertStream(TestRepositoryInsertStreamBase):
2454
 
    """Tests for using Repository.insert_stream verb when the _1.19 variant is
2455
 
    not available.
2456
 
 
2457
 
    This test case is very similar to TestRepositoryInsertStream_1_19.
2458
 
    """
2459
 
 
2460
 
    def setUp(self):
2461
 
        TestRemoteRepository.setUp(self)
2462
 
        self.disable_verb('Repository.insert_stream_1.19')
2463
 
 
2464
 
    def test_unlocked_repo(self):
2465
 
        transport_path = 'quack'
2466
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2467
 
        client.add_expected_call(
2468
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2469
 
            'unknown', ('Repository.insert_stream_1.19',))
2470
 
        client.add_expected_call(
2471
 
            'Repository.insert_stream', ('quack/', ''),
2472
 
            'success', ('ok',))
2473
 
        client.add_expected_call(
2474
 
            'Repository.insert_stream', ('quack/', ''),
2475
 
            'success', ('ok',))
2476
 
        self.checkInsertEmptyStream(repo, client)
2477
 
 
2478
 
    def test_locked_repo_with_no_lock_token(self):
2479
 
        transport_path = 'quack'
2480
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2481
 
        client.add_expected_call(
2482
 
            'Repository.lock_write', ('quack/', ''),
2483
 
            'success', ('ok', ''))
2484
 
        client.add_expected_call(
2485
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2486
 
            'unknown', ('Repository.insert_stream_1.19',))
2487
 
        client.add_expected_call(
2488
 
            'Repository.insert_stream', ('quack/', ''),
2489
 
            'success', ('ok',))
2490
 
        client.add_expected_call(
2491
 
            'Repository.insert_stream', ('quack/', ''),
2492
 
            'success', ('ok',))
2493
 
        repo.lock_write()
2494
 
        self.checkInsertEmptyStream(repo, client)
2495
 
 
2496
 
    def test_locked_repo_with_lock_token(self):
2497
 
        transport_path = 'quack'
2498
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2499
 
        client.add_expected_call(
2500
 
            'Repository.lock_write', ('quack/', ''),
2501
 
            'success', ('ok', 'a token'))
2502
 
        client.add_expected_call(
2503
 
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2504
 
            'unknown', ('Repository.insert_stream_1.19',))
2505
 
        client.add_expected_call(
2506
 
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2507
 
            'success', ('ok',))
2508
 
        client.add_expected_call(
2509
 
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2510
 
            'success', ('ok',))
2511
 
        repo.lock_write()
2512
 
        self.checkInsertEmptyStream(repo, client)
2513
 
 
2514
 
    def test_stream_with_inventory_deltas(self):
2515
 
        """'inventory-deltas' substreams cannot be sent to the
2516
 
        Repository.insert_stream verb, because not all servers that implement
2517
 
        that verb will accept them.  So when one is encountered the RemoteSink
2518
 
        immediately stops using that verb and falls back to VFS insert_stream.
2519
 
        """
2520
 
        transport_path = 'quack'
2521
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2522
 
        client.add_expected_call(
2523
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2524
 
            'unknown', ('Repository.insert_stream_1.19',))
2525
 
        client.add_expected_call(
2526
 
            'Repository.insert_stream', ('quack/', ''),
2527
 
            'success', ('ok',))
2528
 
        client.add_expected_call(
2529
 
            'Repository.insert_stream', ('quack/', ''),
2530
 
            'success', ('ok',))
2531
 
        # Create a fake real repository for insert_stream to fall back on, so
2532
 
        # that we can directly see the records the RemoteSink passes to the
2533
 
        # real sink.
2534
 
        class FakeRealSink:
2535
 
            def __init__(self):
2536
 
                self.records = []
2537
 
            def insert_stream(self, stream, src_format, resume_tokens):
2538
 
                for substream_kind, substream in stream:
2539
 
                    self.records.append(
2540
 
                        (substream_kind, [record.key for record in substream]))
2541
 
                return ['fake tokens'], ['fake missing keys']
2542
 
        fake_real_sink = FakeRealSink()
2543
 
        class FakeRealRepository:
2544
 
            def _get_sink(self):
2545
 
                return fake_real_sink
2546
 
            def is_in_write_group(self):
2547
 
                return False
2548
 
            def refresh_data(self):
2549
 
                return True
2550
 
        repo._real_repository = FakeRealRepository()
2551
 
        sink = repo._get_sink()
2552
 
        fmt = repository.RepositoryFormat.get_default_format()
2553
 
        stream = self.make_stream_with_inv_deltas(fmt)
2554
 
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
2555
 
        # Every record from the first inventory delta should have been sent to
2556
 
        # the VFS sink.
2557
 
        expected_records = [
2558
 
            ('inventory-deltas', [('rev2',), ('rev3',)]),
2559
 
            ('texts', [('some-rev', 'some-file')])]
2560
 
        self.assertEqual(expected_records, fake_real_sink.records)
2561
 
        # The return values from the real sink's insert_stream are propagated
2562
 
        # back to the original caller.
2563
 
        self.assertEqual(['fake tokens'], resume_tokens)
2564
 
        self.assertEqual(['fake missing keys'], missing_keys)
2565
 
        self.assertFinished(client)
2566
 
 
2567
 
    def make_stream_with_inv_deltas(self, fmt):
2568
 
        """Make a simple stream with an inventory delta followed by more
2569
 
        records and more substreams to test that all records and substreams
2570
 
        from that point on are used.
2571
 
 
2572
 
        This sends, in order:
2573
 
           * inventories substream: rev1, rev2, rev3.  rev2 and rev3 are
2574
 
             inventory-deltas.
2575
 
           * texts substream: (some-rev, some-file)
2576
 
        """
2577
 
        # Define a stream using generators so that it isn't rewindable.
2578
 
        inv = inventory.Inventory(revision_id='rev1')
2579
 
        inv.root.revision = 'rev1'
2580
 
        def stream_with_inv_delta():
2581
 
            yield ('inventories', inventories_substream())
2582
 
            yield ('inventory-deltas', inventory_delta_substream())
2583
 
            yield ('texts', [
2584
 
                versionedfile.FulltextContentFactory(
2585
 
                    ('some-rev', 'some-file'), (), None, 'content')])
2586
 
        def inventories_substream():
2587
 
            # An empty inventory fulltext.  This will be streamed normally.
2588
 
            text = fmt._serializer.write_inventory_to_string(inv)
2589
 
            yield versionedfile.FulltextContentFactory(
2590
 
                ('rev1',), (), None, text)
2591
 
        def inventory_delta_substream():
2592
 
            # An inventory delta.  This can't be streamed via this verb, so it
2593
 
            # will trigger a fallback to VFS insert_stream.
2594
 
            entry = inv.make_entry(
2595
 
                'directory', 'newdir', inv.root.file_id, 'newdir-id')
2596
 
            entry.revision = 'ghost'
2597
 
            delta = [(None, 'newdir', 'newdir-id', entry)]
2598
 
            serializer = inventory_delta.InventoryDeltaSerializer(
2599
 
                versioned_root=True, tree_references=False)
2600
 
            lines = serializer.delta_to_lines('rev1', 'rev2', delta)
2601
 
            yield versionedfile.ChunkedContentFactory(
2602
 
                ('rev2',), (('rev1',)), None, lines)
2603
 
            # Another delta.
2604
 
            lines = serializer.delta_to_lines('rev1', 'rev3', delta)
2605
 
            yield versionedfile.ChunkedContentFactory(
2606
 
                ('rev3',), (('rev1',)), None, lines)
2607
 
        return stream_with_inv_delta()
2608
 
 
2609
 
 
2610
 
class TestRepositoryInsertStream_1_19(TestRepositoryInsertStreamBase):
2611
 
 
2612
 
    def test_unlocked_repo(self):
2613
 
        transport_path = 'quack'
2614
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2615
 
        client.add_expected_call(
2616
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2617
 
            'success', ('ok',))
2618
 
        client.add_expected_call(
2619
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2620
 
            'success', ('ok',))
2621
 
        self.checkInsertEmptyStream(repo, client)
2622
 
 
2623
 
    def test_locked_repo_with_no_lock_token(self):
2624
 
        transport_path = 'quack'
2625
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2626
 
        client.add_expected_call(
2627
 
            'Repository.lock_write', ('quack/', ''),
2628
 
            'success', ('ok', ''))
2629
 
        client.add_expected_call(
2630
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2631
 
            'success', ('ok',))
2632
 
        client.add_expected_call(
2633
 
            'Repository.insert_stream_1.19', ('quack/', ''),
2634
 
            'success', ('ok',))
2635
 
        repo.lock_write()
2636
 
        self.checkInsertEmptyStream(repo, client)
2637
 
 
2638
 
    def test_locked_repo_with_lock_token(self):
2639
 
        transport_path = 'quack'
2640
 
        repo, client = self.setup_fake_client_and_repository(transport_path)
2641
 
        client.add_expected_call(
2642
 
            'Repository.lock_write', ('quack/', ''),
2643
 
            'success', ('ok', 'a token'))
2644
 
        client.add_expected_call(
2645
 
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2646
 
            'success', ('ok',))
2647
 
        client.add_expected_call(
2648
 
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2649
 
            'success', ('ok',))
2650
 
        repo.lock_write()
2651
 
        self.checkInsertEmptyStream(repo, client)
 
1999
class TestRepositoryInsertStream(TestRemoteRepository):
 
2000
 
 
2001
    def test_unlocked_repo(self):
 
2002
        transport_path = 'quack'
 
2003
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2004
        client.add_expected_call(
 
2005
            'Repository.insert_stream', ('quack/', ''),
 
2006
            'success', ('ok',))
 
2007
        client.add_expected_call(
 
2008
            'Repository.insert_stream', ('quack/', ''),
 
2009
            'success', ('ok',))
 
2010
        sink = repo._get_sink()
 
2011
        fmt = repository.RepositoryFormat.get_default_format()
 
2012
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
 
2013
        self.assertEqual([], resume_tokens)
 
2014
        self.assertEqual(set(), missing_keys)
 
2015
        client.finished_test()
 
2016
 
 
2017
    def test_locked_repo_with_no_lock_token(self):
 
2018
        transport_path = 'quack'
 
2019
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2020
        client.add_expected_call(
 
2021
            'Repository.lock_write', ('quack/', ''),
 
2022
            'success', ('ok', ''))
 
2023
        client.add_expected_call(
 
2024
            'Repository.insert_stream', ('quack/', ''),
 
2025
            'success', ('ok',))
 
2026
        client.add_expected_call(
 
2027
            'Repository.insert_stream', ('quack/', ''),
 
2028
            'success', ('ok',))
 
2029
        repo.lock_write()
 
2030
        sink = repo._get_sink()
 
2031
        fmt = repository.RepositoryFormat.get_default_format()
 
2032
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
 
2033
        self.assertEqual([], resume_tokens)
 
2034
        self.assertEqual(set(), missing_keys)
 
2035
        client.finished_test()
 
2036
 
 
2037
    def test_locked_repo_with_lock_token(self):
 
2038
        transport_path = 'quack'
 
2039
        repo, client = self.setup_fake_client_and_repository(transport_path)
 
2040
        client.add_expected_call(
 
2041
            'Repository.lock_write', ('quack/', ''),
 
2042
            'success', ('ok', 'a token'))
 
2043
        client.add_expected_call(
 
2044
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2045
            'success', ('ok',))
 
2046
        client.add_expected_call(
 
2047
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
 
2048
            'success', ('ok',))
 
2049
        repo.lock_write()
 
2050
        sink = repo._get_sink()
 
2051
        fmt = repository.RepositoryFormat.get_default_format()
 
2052
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
 
2053
        self.assertEqual([], resume_tokens)
 
2054
        self.assertEqual(set(), missing_keys)
 
2055
        client.finished_test()
2652
2056
 
2653
2057
 
2654
2058
class TestRepositoryTarball(TestRemoteRepository):
2690
2094
    """RemoteRepository.copy_content_into optimizations"""
2691
2095
 
2692
2096
    def test_copy_content_remote_to_local(self):
2693
 
        self.transport_server = test_server.SmartTCPServer_for_testing
 
2097
        self.transport_server = server.SmartTCPServer_for_testing
2694
2098
        src_repo = self.make_repository('repo1')
2695
2099
        src_repo = repository.Repository.open(self.get_url('repo1'))
2696
2100
        # At the moment the tarball-based copy_content_into can't write back
2739
2143
        client.add_expected_call(
2740
2144
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
2741
2145
        repo.autopack()
2742
 
        self.assertFinished(client)
 
2146
        client.finished_test()
2743
2147
 
2744
2148
    def test_ok_with_real_repo(self):
2745
2149
        """When the server returns 'ok' and there is a _real_repository, then
2844
2248
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
2845
2249
        self.assertEqual(expected_error, translated_error)
2846
2250
 
2847
 
    def test_nobranch_one_arg(self):
2848
 
        bzrdir = self.make_bzrdir('')
2849
 
        translated_error = self.translateTuple(
2850
 
            ('nobranch', 'extra detail'), bzrdir=bzrdir)
2851
 
        expected_error = errors.NotBranchError(
2852
 
            path=bzrdir.root_transport.base,
2853
 
            detail='extra detail')
2854
 
        self.assertEqual(expected_error, translated_error)
2855
 
 
2856
2251
    def test_LockContention(self):
2857
2252
        translated_error = self.translateTuple(('LockContention',))
2858
2253
        expected_error = errors.LockContention('(remote lock)')
2898
2293
        expected_error = errors.ReadError(path)
2899
2294
        self.assertEqual(expected_error, translated_error)
2900
2295
 
2901
 
    def test_IncompatibleRepositories(self):
2902
 
        translated_error = self.translateTuple(('IncompatibleRepositories',
2903
 
            "repo1", "repo2", "details here"))
2904
 
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
2905
 
            "details here")
2906
 
        self.assertEqual(expected_error, translated_error)
2907
 
 
2908
2296
    def test_PermissionDenied_no_args(self):
2909
2297
        path = 'a path'
2910
2298
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
2971
2359
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2972
2360
        # been muttered to the log file for developer to look at.
2973
2361
        self.assertContainsRe(
2974
 
            self.get_log(),
 
2362
            self._get_log(keep_log_file=True),
2975
2363
            "Missing key 'branch' in context")
2976
2364
 
2977
2365
    def test_path_missing(self):
2985
2373
        self.assertEqual(server_error, translated_error)
2986
2374
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2987
2375
        # been muttered to the log file for developer to look at.
2988
 
        self.assertContainsRe(self.get_log(), "Missing key 'path' in context")
 
2376
        self.assertContainsRe(
 
2377
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
2989
2378
 
2990
2379
 
2991
2380
class TestStacking(tests.TestCaseWithTransport):
3009
2398
        stacked_branch = self.make_branch('stacked', format='1.9')
3010
2399
        stacked_branch.set_stacked_on_url('../base')
3011
2400
        # start a server looking at this
3012
 
        smart_server = test_server.SmartTCPServer_for_testing()
3013
 
        self.start_server(smart_server)
 
2401
        smart_server = server.SmartTCPServer_for_testing()
 
2402
        smart_server.setUp()
 
2403
        self.addCleanup(smart_server.tearDown)
3014
2404
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
3015
2405
        # can get its branch and repository
3016
2406
        remote_branch = remote_bzrdir.open_branch()
3019
2409
        try:
3020
2410
            # it should have an appropriate fallback repository, which should also
3021
2411
            # be a RemoteRepository
3022
 
            self.assertLength(1, remote_repo._fallback_repositories)
 
2412
            self.assertEquals(len(remote_repo._fallback_repositories), 1)
3023
2413
            self.assertIsInstance(remote_repo._fallback_repositories[0],
3024
2414
                RemoteRepository)
3025
2415
            # and it has the revision committed to the underlying repository;
3038
2428
        tree1.commit('rev1', rev_id='rev1')
3039
2429
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
3040
2430
            ).open_workingtree()
3041
 
        local_tree = tree2.branch.create_checkout('local')
3042
 
        local_tree.commit('local changes make me feel good.')
 
2431
        tree2.commit('local changes make me feel good.')
3043
2432
        branch2 = Branch.open(self.get_url('tree2'))
3044
2433
        branch2.lock_read()
3045
2434
        self.addCleanup(branch2.unlock)
3067
2456
                    result.append(content.key[-1])
3068
2457
        return result
3069
2458
 
3070
 
    def get_ordered_revs(self, format, order, branch_factory=None):
 
2459
    def get_ordered_revs(self, format, order):
3071
2460
        """Get a list of the revisions in a stream to format format.
3072
2461
 
3073
2462
        :param format: The format of the target.
3074
2463
        :param order: the order that target should have requested.
3075
 
        :param branch_factory: A callable to create a trunk and stacked branch
3076
 
            to fetch from. If none, self.prepare_stacked_remote_branch is used.
3077
2464
        :result: The revision ids in the stream, in the order seen,
3078
2465
            the topological order of revisions in the source.
3079
2466
        """
3081
2468
        target_repository_format = unordered_format.repository_format
3082
2469
        # Cross check
3083
2470
        self.assertEqual(order, target_repository_format._fetch_order)
3084
 
        if branch_factory is None:
3085
 
            branch_factory = self.prepare_stacked_remote_branch
3086
 
        _, stacked = branch_factory()
 
2471
        trunk, stacked = self.prepare_stacked_remote_branch()
3087
2472
        source = stacked.repository._get_source(target_repository_format)
3088
2473
        tip = stacked.last_revision()
3089
2474
        revs = stacked.repository.get_ancestry(tip)
3108
2493
        # from the server, then one from the backing branch.
3109
2494
        self.assertLength(2, self.hpss_calls)
3110
2495
 
3111
 
    def test_stacked_on_stacked_get_stream_unordered(self):
3112
 
        # Repository._get_source.get_stream() from a stacked repository which
3113
 
        # is itself stacked yields the full data from all three sources.
3114
 
        def make_stacked_stacked():
3115
 
            _, stacked = self.prepare_stacked_remote_branch()
3116
 
            tree = stacked.bzrdir.sprout('tree3', stacked=True
3117
 
                ).open_workingtree()
3118
 
            local_tree = tree.branch.create_checkout('local-tree3')
3119
 
            local_tree.commit('more local changes are better')
3120
 
            branch = Branch.open(self.get_url('tree3'))
3121
 
            branch.lock_read()
3122
 
            self.addCleanup(branch.unlock)
3123
 
            return None, branch
3124
 
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
3125
 
            branch_factory=make_stacked_stacked)
3126
 
        self.assertEqual(set(expected_revs), set(rev_ord))
3127
 
        # Getting unordered results should have made a streaming data request
3128
 
        # from the server, and one from each backing repo
3129
 
        self.assertLength(3, self.hpss_calls)
3130
 
 
3131
2496
    def test_stacked_get_stream_topological(self):
3132
2497
        # Repository._get_source.get_stream() from a stacked repository with
3133
2498
        # topological sorting yields the full data from both stacked and
3134
2499
        # stacked upon sources in topological order.
3135
2500
        rev_ord, expected_revs = self.get_ordered_revs('knit', 'topological')
3136
2501
        self.assertEqual(expected_revs, rev_ord)
3137
 
        # Getting topological sort requires VFS calls still - one of which is
3138
 
        # pushing up from the bound branch.
3139
 
        self.assertLength(13, self.hpss_calls)
 
2502
        # Getting topological sort requires VFS calls still
 
2503
        self.assertLength(12, self.hpss_calls)
3140
2504
 
3141
2505
    def test_stacked_get_stream_groupcompress(self):
3142
2506
        # Repository._get_source.get_stream() from a stacked repository with
3149
2513
        # from the backing branch, and one from the stacked on branch.
3150
2514
        self.assertLength(2, self.hpss_calls)
3151
2515
 
3152
 
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
3153
 
        # When pulling some fixed amount of content that is more than the
3154
 
        # source has (because some is coming from a fallback branch, no error
3155
 
        # should be received. This was reported as bug 360791.
3156
 
        # Need three branches: a trunk, a stacked branch, and a preexisting
3157
 
        # branch pulling content from stacked and trunk.
3158
 
        self.setup_smart_server_with_call_log()
3159
 
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
3160
 
        r1 = trunk.commit('start')
3161
 
        stacked_branch = trunk.branch.create_clone_on_transport(
3162
 
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
3163
 
        local = self.make_branch('local', format='1.9-rich-root')
3164
 
        local.repository.fetch(stacked_branch.repository,
3165
 
            stacked_branch.last_revision())
3166
 
 
3167
2516
 
3168
2517
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
3169
2518
 
3171
2520
        super(TestRemoteBranchEffort, self).setUp()
3172
2521
        # Create a smart server that publishes whatever the backing VFS server
3173
2522
        # does.
3174
 
        self.smart_server = test_server.SmartTCPServer_for_testing()
3175
 
        self.start_server(self.smart_server, self.get_server())
 
2523
        self.smart_server = server.SmartTCPServer_for_testing()
 
2524
        self.smart_server.setUp(self.get_server())
 
2525
        self.addCleanup(self.smart_server.tearDown)
3176
2526
        # Log all HPSS calls into self.hpss_calls.
3177
2527
        _SmartClient.hooks.install_named_hook(
3178
2528
            'call', self.capture_hpss_call, None)