/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1
# Copyright (C) 2006, 2007, 2008, 2009 Canonical Ltd
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
16
17
"""Tests for remote bzrdir/branch/repo/etc
18
19
These are proxy objects which act on remote objects by sending messages
20
through a smart client.  The proxies are to be created when attempting to open
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
21
the object given a transport that supports smartserver rpc operations.
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
22
23
These tests correspond to tests.test_smart, which exercises the server side.
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
24
"""
25
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
26
import bz2
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
27
from cStringIO import StringIO
28
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
29
from bzrlib import (
3834.3.2 by Andrew Bennetts
Preserve BzrBranch5's _synchronize_history code without affecting Branch or BzrBranch7; add effort test for RemoteBranch.copy_content_into.
30
    bzrdir,
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
31
    config,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
32
    errors,
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
33
    graph,
2535.3.39 by Andrew Bennetts
Tidy some XXXs.
34
    pack,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
35
    remote,
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
36
    repository,
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
37
    smart,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
38
    tests,
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
39
    treebuilder,
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
40
    urlutils,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
41
    )
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
42
from bzrlib.branch import Branch
43
from bzrlib.bzrdir import BzrDir, BzrDirFormat
44
from bzrlib.remote import (
45
    RemoteBranch,
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
46
    RemoteBranchFormat,
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
47
    RemoteBzrDir,
48
    RemoteBzrDirFormat,
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
49
    RemoteRepository,
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
50
    RemoteRepositoryFormat,
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
51
    )
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
52
from bzrlib.repofmt import groupcompress_repo, pack_repo
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
53
from bzrlib.revision import NULL_REVISION
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
54
from bzrlib.smart import server, medium
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
55
from bzrlib.smart.client import _SmartClient
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
56
from bzrlib.smart.repository import SmartServerRepositoryGetParentMap
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
57
from bzrlib.tests import (
58
    condition_isinstance,
59
    split_suite_by_condition,
60
    multiply_tests,
4301.3.1 by Andrew Bennetts
Implement RemoteBranch.set_append_revisions_only.
61
    KnownFailure,
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
62
    )
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
63
from bzrlib.transport import get_transport, http
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
64
from bzrlib.transport.memory import MemoryTransport
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
65
from bzrlib.transport.remote import (
66
    RemoteTransport,
67
    RemoteSSHTransport,
68
    RemoteTCPTransport,
69
)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
70
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
71
def load_tests(standard_tests, module, loader):
72
    to_adapt, result = split_suite_by_condition(
73
        standard_tests, condition_isinstance(BasicRemoteObjectTests))
74
    smart_server_version_scenarios = [
4104.4.2 by Robert Collins
Fix test_source for 1.13 landing.
75
        ('HPSS-v2',
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
76
            {'transport_server': server.SmartTCPServer_for_testing_v2_only}),
4104.4.2 by Robert Collins
Fix test_source for 1.13 landing.
77
        ('HPSS-v3',
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
78
            {'transport_server': server.SmartTCPServer_for_testing})]
79
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
80
2018.5.24 by Andrew Bennetts
Setting NO_SMART_VFS in environment will disable VFS methods in the smart server. (Robert Collins, John Arbash Meinel, Andrew Bennetts)
81
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
82
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
83
84
    def setUp(self):
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
85
        super(BasicRemoteObjectTests, self).setUp()
86
        self.transport = self.get_transport()
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
87
        # make a branch that can be opened over the smart transport
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
88
        self.local_wt = BzrDir.create_standalone_workingtree('.')
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
89
2018.5.171 by Andrew Bennetts
Disconnect RemoteTransports in some tests to avoid tripping up test_strace with leftover threads from previous tests.
90
    def tearDown(self):
91
        self.transport.disconnect()
92
        tests.TestCaseWithTransport.tearDown(self)
93
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
94
    def test_create_remote_bzrdir(self):
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
95
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
96
        self.assertIsInstance(b, BzrDir)
97
98
    def test_open_remote_branch(self):
2018.6.1 by Robert Collins
Implement a BzrDir.open_branch smart server method for opening a branch without VFS.
99
        # open a standalone branch in the working directory
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
100
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
101
        branch = b.open_branch()
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
102
        self.assertIsInstance(branch, Branch)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
103
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
104
    def test_remote_repository(self):
105
        b = BzrDir.open_from_transport(self.transport)
106
        repo = b.open_repository()
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
107
        revid = u'\xc823123123'.encode('utf8')
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
108
        self.assertFalse(repo.has_revision(revid))
109
        self.local_wt.commit(message='test commit', rev_id=revid)
110
        self.assertTrue(repo.has_revision(revid))
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
111
112
    def test_remote_branch_revision_history(self):
113
        b = BzrDir.open_from_transport(self.transport).open_branch()
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
114
        self.assertEqual([], b.revision_history())
115
        r1 = self.local_wt.commit('1st commit')
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
116
        r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
117
        self.assertEqual([r1, r2], b.revision_history())
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
118
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
119
    def test_find_correct_format(self):
2018.5.20 by Andrew Bennetts
Move bzrlib/transport/smart/_smart.py to bzrlib/transport/remote.py and rename SmartTransport to RemoteTransport (Robert Collins, Andrew Bennetts)
120
        """Should open a RemoteBzrDir over a RemoteTransport"""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
121
        fmt = BzrDirFormat.find_format(self.transport)
2018.5.169 by Andrew Bennetts
Add a _server_formats flag to BzrDir.open_from_transport and BzrDirFormat.find_format, make RemoteBranch.control_files into a property.
122
        self.assertTrue(RemoteBzrDirFormat
123
                        in BzrDirFormat._control_server_formats)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
124
        self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
125
126
    def test_open_detected_smart_format(self):
127
        fmt = BzrDirFormat.find_format(self.transport)
128
        d = fmt.open(self.transport)
129
        self.assertIsInstance(d, BzrDir)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
130
2477.1.1 by Martin Pool
Add RemoteBranch repr
131
    def test_remote_branch_repr(self):
132
        b = BzrDir.open_from_transport(self.transport).open_branch()
133
        self.assertStartsWith(str(b), 'RemoteBranch(')
134
4103.2.2 by Andrew Bennetts
Fix RemoteBranchFormat.supports_stacking()
135
    def test_remote_branch_format_supports_stacking(self):
136
        t = self.transport
137
        self.make_branch('unstackable', format='pack-0.92')
138
        b = BzrDir.open_from_transport(t.clone('unstackable')).open_branch()
139
        self.assertFalse(b._format.supports_stacking())
140
        self.make_branch('stackable', format='1.9')
141
        b = BzrDir.open_from_transport(t.clone('stackable')).open_branch()
142
        self.assertTrue(b._format.supports_stacking())
143
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
144
    def test_remote_repo_format_supports_external_references(self):
145
        t = self.transport
146
        bd = self.make_bzrdir('unstackable', format='pack-0.92')
147
        r = bd.create_repository()
148
        self.assertFalse(r._format.supports_external_lookups)
149
        r = BzrDir.open_from_transport(t.clone('unstackable')).open_repository()
150
        self.assertFalse(r._format.supports_external_lookups)
151
        bd = self.make_bzrdir('stackable', format='1.9')
152
        r = bd.create_repository()
153
        self.assertTrue(r._format.supports_external_lookups)
154
        r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
155
        self.assertTrue(r._format.supports_external_lookups)
156
4301.3.1 by Andrew Bennetts
Implement RemoteBranch.set_append_revisions_only.
157
    def test_remote_branch_set_append_revisions_only(self):
158
        # Make a format 1.9 branch, which supports append_revisions_only
159
        branch = self.make_branch('branch', format='1.9')
160
        config = branch.get_config()
161
        branch.set_append_revisions_only(True)
162
        self.assertEqual(
163
            'True', config.get_user_option('append_revisions_only'))
164
        branch.set_append_revisions_only(False)
165
        self.assertEqual(
166
            'False', config.get_user_option('append_revisions_only'))
167
168
    def test_remote_branch_set_append_revisions_only_upgrade_reqd(self):
169
        branch = self.make_branch('branch', format='knit')
170
        config = branch.get_config()
171
        self.assertRaises(
4301.3.3 by Andrew Bennetts
Move check onto base Branch class, and add a supports_set_append_revisions_only method to BranchFormat, as suggested by Robert.
172
            errors.UpgradeRequired, branch.set_append_revisions_only, True)
4301.3.1 by Andrew Bennetts
Implement RemoteBranch.set_append_revisions_only.
173
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
174
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
175
class FakeProtocol(object):
176
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
177
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
178
    def __init__(self, body, fake_client):
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
179
        self.body = body
180
        self._body_buffer = None
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
181
        self._fake_client = fake_client
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
182
183
    def read_body_bytes(self, count=-1):
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
184
        if self._body_buffer is None:
185
            self._body_buffer = StringIO(self.body)
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
186
        bytes = self._body_buffer.read(count)
187
        if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
188
            self._fake_client.expecting_body = False
189
        return bytes
190
191
    def cancel_read_body(self):
192
        self._fake_client.expecting_body = False
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
193
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
194
    def read_streamed_body(self):
195
        return self.body
196
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
197
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
198
class FakeClient(_SmartClient):
199
    """Lookalike for _SmartClient allowing testing."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
200
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
201
    def __init__(self, fake_medium_base='fake base'):
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
202
        """Create a FakeClient."""
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
203
        self.responses = []
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
204
        self._calls = []
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
205
        self.expecting_body = False
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
206
        # if non-None, this is the list of expected calls, with only the
207
        # method name and arguments included.  the body might be hard to
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
208
        # compute so is not included. If a call is None, that call can
209
        # be anything.
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
210
        self._expected_calls = None
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
211
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
212
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
213
    def add_expected_call(self, call_name, call_args, response_type,
214
        response_args, response_body=None):
215
        if self._expected_calls is None:
216
            self._expected_calls = []
217
        self._expected_calls.append((call_name, call_args))
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
218
        self.responses.append((response_type, response_args, response_body))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
219
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
220
    def add_success_response(self, *args):
221
        self.responses.append(('success', args, None))
222
223
    def add_success_response_with_body(self, body, *args):
224
        self.responses.append(('success', args, body))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
225
        if self._expected_calls is not None:
226
            self._expected_calls.append(None)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
227
228
    def add_error_response(self, *args):
229
        self.responses.append(('error', args))
230
231
    def add_unknown_method_response(self, verb):
232
        self.responses.append(('unknown', verb))
233
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
234
    def finished_test(self):
235
        if self._expected_calls:
236
            raise AssertionError("%r finished but was still expecting %r"
237
                % (self, self._expected_calls[0]))
238
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
239
    def _get_next_response(self):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
240
        try:
241
            response_tuple = self.responses.pop(0)
242
        except IndexError, e:
243
            raise AssertionError("%r didn't expect any more calls"
244
                % (self,))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
245
        if response_tuple[0] == 'unknown':
246
            raise errors.UnknownSmartMethod(response_tuple[1])
247
        elif response_tuple[0] == 'error':
248
            raise errors.ErrorFromSmartServer(response_tuple[1])
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
249
        return response_tuple
250
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
251
    def _check_call(self, method, args):
252
        if self._expected_calls is None:
253
            # the test should be updated to say what it expects
254
            return
255
        try:
256
            next_call = self._expected_calls.pop(0)
257
        except IndexError:
258
            raise AssertionError("%r didn't expect any more calls "
259
                "but got %r%r"
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
260
                % (self, method, args,))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
261
        if next_call is None:
262
            return
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
263
        if method != next_call[0] or args != next_call[1]:
264
            raise AssertionError("%r expected %r%r "
265
                "but got %r%r"
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
266
                % (self, next_call[0], next_call[1], method, args,))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
267
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
268
    def call(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
269
        self._check_call(method, args)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
270
        self._calls.append(('call', method, args))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
271
        return self._get_next_response()[1]
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
272
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
273
    def call_expecting_body(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
274
        self._check_call(method, args)
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
275
        self._calls.append(('call_expecting_body', method, args))
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
276
        result = self._get_next_response()
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
277
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
278
        return result[1], FakeProtocol(result[2], self)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
279
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
280
    def call_with_body_bytes_expecting_body(self, method, args, body):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
281
        self._check_call(method, args)
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
282
        self._calls.append(('call_with_body_bytes_expecting_body', method,
283
            args, body))
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
284
        result = self._get_next_response()
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
285
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
286
        return result[1], FakeProtocol(result[2], self)
3184.1.10 by Robert Collins
Change the smart server verb for Repository.stream_revisions_chunked to use SearchResults as the request mechanism for downloads.
287
3842.3.9 by Andrew Bennetts
Backing up the stream so that we can fallback correctly.
288
    def call_with_body_stream(self, args, stream):
289
        # Explicitly consume the stream before checking for an error, because
290
        # that's what happens a real medium.
291
        stream = list(stream)
292
        self._check_call(args[0], args[1:])
293
        self._calls.append(('call_with_body_stream', args[0], args[1:], stream))
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
294
        result = self._get_next_response()
4144.3.3 by Andrew Bennetts
Tweaks based on review from Robert.
295
        # The second value returned from call_with_body_stream is supposed to
296
        # be a response_handler object, but so far no tests depend on that.
297
        response_handler = None 
298
        return result[1], response_handler
3842.3.9 by Andrew Bennetts
Backing up the stream so that we can fallback correctly.
299
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
300
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
301
class FakeMedium(medium.SmartClientMedium):
3104.4.2 by Andrew Bennetts
All tests passing.
302
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
303
    def __init__(self, client_calls, base):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
304
        medium.SmartClientMedium.__init__(self, base)
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
305
        self._client_calls = client_calls
3213.1.1 by Andrew Bennetts
Recover (by reconnecting) if the server turns out not to understand the new requests in 1.2 that send bodies.
306
307
    def disconnect(self):
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
308
        self._client_calls.append(('disconnect medium',))
3104.4.2 by Andrew Bennetts
All tests passing.
309
310
3192.2.1 by Andrew Bennetts
Don't transmit URL-escaped relpaths in the smart protocol, which is back to how things worked in bzr 1.1 and earlier.
311
class TestVfsHas(tests.TestCase):
312
313
    def test_unicode_path(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
314
        client = FakeClient('/')
315
        client.add_success_response('yes',)
3192.2.1 by Andrew Bennetts
Don't transmit URL-escaped relpaths in the smart protocol, which is back to how things worked in bzr 1.1 and earlier.
316
        transport = RemoteTransport('bzr://localhost/', _client=client)
317
        filename = u'/hell\u00d8'.encode('utf8')
318
        result = transport.has(filename)
319
        self.assertEqual(
320
            [('call', 'has', (filename,))],
321
            client._calls)
322
        self.assertTrue(result)
323
324
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
325
class TestRemote(tests.TestCaseWithMemoryTransport):
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
326
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
327
    def get_branch_format(self):
328
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
329
        return reference_bzrdir_format.get_branch_format()
330
4053.1.2 by Robert Collins
Actually make this branch work.
331
    def get_repo_format(self):
332
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
333
        return reference_bzrdir_format.repository_format
334
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
335
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
336
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
337
    """Tests for the behaviour of client_medium.remote_path_from_transport."""
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
338
339
    def assertRemotePath(self, expected, client_base, transport_base):
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
340
        """Assert that the result of
341
        SmartClientMedium.remote_path_from_transport is the expected value for
342
        a given client_base and transport_base.
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
343
        """
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
344
        client_medium = medium.SmartClientMedium(client_base)
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
345
        transport = get_transport(transport_base)
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
346
        result = client_medium.remote_path_from_transport(transport)
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
347
        self.assertEqual(expected, result)
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
348
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
349
    def test_remote_path_from_transport(self):
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
350
        """SmartClientMedium.remote_path_from_transport calculates a URL for
351
        the given transport relative to the root of the client base URL.
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
352
        """
353
        self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
354
        self.assertRemotePath(
355
            'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
356
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
357
    def assertRemotePathHTTP(self, expected, transport_base, relpath):
358
        """Assert that the result of
359
        HttpTransportBase.remote_path_from_transport is the expected value for
360
        a given transport_base and relpath of that transport.  (Note that
361
        HttpTransportBase is a subclass of SmartClientMedium)
362
        """
363
        base_transport = get_transport(transport_base)
364
        client_medium = base_transport.get_smart_medium()
365
        cloned_transport = base_transport.clone(relpath)
366
        result = client_medium.remote_path_from_transport(cloned_transport)
367
        self.assertEqual(expected, result)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
368
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
369
    def test_remote_path_from_transport_http(self):
370
        """Remote paths for HTTP transports are calculated differently to other
371
        transports.  They are just relative to the client base, not the root
372
        directory of the host.
373
        """
374
        for scheme in ['http:', 'https:', 'bzr+http:', 'bzr+https:']:
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
375
            self.assertRemotePathHTTP(
376
                '../xyz/', scheme + '//host/path', '../xyz/')
377
            self.assertRemotePathHTTP(
378
                'xyz/', scheme + '//host/path', 'xyz/')
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
379
380
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
381
class Test_ClientMedium_remote_is_at_least(tests.TestCase):
382
    """Tests for the behaviour of client_medium.remote_is_at_least."""
383
384
    def test_initially_unlimited(self):
385
        """A fresh medium assumes that the remote side supports all
386
        versions.
387
        """
388
        client_medium = medium.SmartClientMedium('dummy base')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
389
        self.assertFalse(client_medium._is_remote_before((99, 99)))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
390
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
391
    def test__remember_remote_is_before(self):
392
        """Calling _remember_remote_is_before ratchets down the known remote
393
        version.
394
        """
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
395
        client_medium = medium.SmartClientMedium('dummy base')
396
        # Mark the remote side as being less than 1.6.  The remote side may
397
        # still be 1.5.
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
398
        client_medium._remember_remote_is_before((1, 6))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
399
        self.assertTrue(client_medium._is_remote_before((1, 6)))
400
        self.assertFalse(client_medium._is_remote_before((1, 5)))
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
401
        # Calling _remember_remote_is_before again with a lower value works.
402
        client_medium._remember_remote_is_before((1, 5))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
403
        self.assertTrue(client_medium._is_remote_before((1, 5)))
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
404
        # You cannot call _remember_remote_is_before with a larger value.
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
405
        self.assertRaises(
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
406
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
407
408
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
409
class TestBzrDirCloningMetaDir(TestRemote):
410
411
    def test_backwards_compat(self):
412
        self.setup_smart_server_with_call_log()
413
        a_dir = self.make_bzrdir('.')
414
        self.reset_smart_call_log()
415
        verb = 'BzrDir.cloning_metadir'
416
        self.disable_verb(verb)
417
        format = a_dir.cloning_metadir()
418
        call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
419
            call.call.method == verb])
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
420
        self.assertEqual(1, call_count)
421
4160.2.9 by Andrew Bennetts
Fix BzrDir.cloning_metadir RPC to fail on branch references, and make
422
    def test_branch_reference(self):
423
        transport = self.get_transport('quack')
424
        referenced = self.make_branch('referenced')
425
        expected = referenced.bzrdir.cloning_metadir()
426
        client = FakeClient(transport.base)
427
        client.add_expected_call(
428
            'BzrDir.cloning_metadir', ('quack/', 'False'),
429
            'error', ('BranchReference',)),
430
        client.add_expected_call(
431
            'BzrDir.open_branchV2', ('quack/',),
432
            'success', ('ref', self.get_url('referenced'))),
433
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
434
            _client=client)
435
        result = a_bzrdir.cloning_metadir()
436
        # We should have got a control dir matching the referenced branch.
437
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
438
        self.assertEqual(expected._repository_format, result._repository_format)
439
        self.assertEqual(expected._branch_format, result._branch_format)
440
        client.finished_test()
441
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
442
    def test_current_server(self):
443
        transport = self.get_transport('.')
444
        transport = transport.clone('quack')
445
        self.make_bzrdir('quack')
446
        client = FakeClient(transport.base)
447
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
448
        control_name = reference_bzrdir_format.network_name()
449
        client.add_expected_call(
450
            'BzrDir.cloning_metadir', ('quack/', 'False'),
4084.2.2 by Robert Collins
Review feedback.
451
            'success', (control_name, '', ('branch', ''))),
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
452
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
453
            _client=client)
454
        result = a_bzrdir.cloning_metadir()
455
        # We should have got a reference control dir with default branch and
456
        # repository formats.
457
        # This pokes a little, just to be sure.
458
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
4070.2.8 by Robert Collins
Really test the current BzrDir.cloning_metadir contract.
459
        self.assertEqual(None, result._repository_format)
460
        self.assertEqual(None, result._branch_format)
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
461
        client.finished_test()
462
463
4053.1.2 by Robert Collins
Actually make this branch work.
464
class TestBzrDirOpenBranch(TestRemote):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
465
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
466
    def test_backwards_compat(self):
467
        self.setup_smart_server_with_call_log()
468
        self.make_branch('.')
469
        a_dir = BzrDir.open(self.get_url('.'))
470
        self.reset_smart_call_log()
471
        verb = 'BzrDir.open_branchV2'
472
        self.disable_verb(verb)
473
        format = a_dir.open_branch()
474
        call_count = len([call for call in self.hpss_calls if
475
            call.call.method == verb])
476
        self.assertEqual(1, call_count)
477
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
478
    def test_branch_present(self):
4053.1.2 by Robert Collins
Actually make this branch work.
479
        reference_format = self.get_repo_format()
480
        network_name = reference_format.network_name()
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
481
        branch_network_name = self.get_branch_format().network_name()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
482
        transport = MemoryTransport()
483
        transport.mkdir('quack')
484
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
485
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
486
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
487
            'BzrDir.open_branchV2', ('quack/',),
488
            'success', ('branch', branch_network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
489
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
490
            'BzrDir.find_repositoryV3', ('quack/',),
491
            'success', ('ok', '', 'no', 'no', 'no', network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
492
        client.add_expected_call(
493
            'Branch.get_stacked_on_url', ('quack/',),
494
            'error', ('NotStacked',))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
495
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
496
            _client=client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
497
        result = bzrdir.open_branch()
498
        self.assertIsInstance(result, RemoteBranch)
499
        self.assertEqual(bzrdir, result.bzrdir)
3691.2.10 by Martin Pool
Update more test_remote tests
500
        client.finished_test()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
501
502
    def test_branch_missing(self):
503
        transport = MemoryTransport()
504
        transport.mkdir('quack')
505
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
506
        client = FakeClient(transport.base)
507
        client.add_error_response('nobranch')
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
508
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
509
            _client=client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
510
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
511
        self.assertEqual(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
512
            [('call', 'BzrDir.open_branchV2', ('quack/',))],
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
513
            client._calls)
514
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
515
    def test__get_tree_branch(self):
516
        # _get_tree_branch is a form of open_branch, but it should only ask for
517
        # branch opening, not any other network requests.
518
        calls = []
519
        def open_branch():
520
            calls.append("Called")
521
            return "a-branch"
522
        transport = MemoryTransport()
523
        # no requests on the network - catches other api calls being made.
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
524
        client = FakeClient(transport.base)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
525
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
526
            _client=client)
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
527
        # patch the open_branch call to record that it was called.
528
        bzrdir.open_branch = open_branch
529
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
530
        self.assertEqual(["Called"], calls)
531
        self.assertEqual([], client._calls)
532
3192.2.1 by Andrew Bennetts
Don't transmit URL-escaped relpaths in the smart protocol, which is back to how things worked in bzr 1.1 and earlier.
533
    def test_url_quoting_of_path(self):
534
        # Relpaths on the wire should not be URL-escaped.  So "~" should be
535
        # transmitted as "~", not "%7E".
3431.3.1 by Andrew Bennetts
First rough cut of a fix for bug #230550, by adding .base to SmartClientMedia rather than relying on other objects to track this accurately while reusing client media.
536
        transport = RemoteTCPTransport('bzr://localhost/~hello/')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
537
        client = FakeClient(transport.base)
4053.1.2 by Robert Collins
Actually make this branch work.
538
        reference_format = self.get_repo_format()
539
        network_name = reference_format.network_name()
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
540
        branch_network_name = self.get_branch_format().network_name()
3691.2.10 by Martin Pool
Update more test_remote tests
541
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
542
            'BzrDir.open_branchV2', ('~hello/',),
543
            'success', ('branch', branch_network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
544
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
545
            'BzrDir.find_repositoryV3', ('~hello/',),
546
            'success', ('ok', '', 'no', 'no', 'no', network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
547
        client.add_expected_call(
548
            'Branch.get_stacked_on_url', ('~hello/',),
549
            'error', ('NotStacked',))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
550
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
551
            _client=client)
3192.2.1 by Andrew Bennetts
Don't transmit URL-escaped relpaths in the smart protocol, which is back to how things worked in bzr 1.1 and earlier.
552
        result = bzrdir.open_branch()
3691.2.10 by Martin Pool
Update more test_remote tests
553
        client.finished_test()
3192.2.1 by Andrew Bennetts
Don't transmit URL-escaped relpaths in the smart protocol, which is back to how things worked in bzr 1.1 and earlier.
554
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
555
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
4053.1.2 by Robert Collins
Actually make this branch work.
556
        reference_format = self.get_repo_format()
557
        network_name = reference_format.network_name()
3104.4.2 by Andrew Bennetts
All tests passing.
558
        transport = MemoryTransport()
559
        transport.mkdir('quack')
560
        transport = transport.clone('quack')
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
561
        if rich_root:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
562
            rich_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
563
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
564
            rich_response = 'no'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
565
        if subtrees:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
566
            subtree_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
567
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
568
            subtree_response = 'no'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
569
        client = FakeClient(transport.base)
570
        client.add_success_response(
4053.1.2 by Robert Collins
Actually make this branch work.
571
            'ok', '', rich_response, subtree_response, external_lookup,
572
            network_name)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
573
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
574
            _client=client)
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
575
        result = bzrdir.open_repository()
576
        self.assertEqual(
4053.1.2 by Robert Collins
Actually make this branch work.
577
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
578
            client._calls)
579
        self.assertIsInstance(result, RemoteRepository)
580
        self.assertEqual(bzrdir, result.bzrdir)
581
        self.assertEqual(rich_root, result._format.rich_root_data)
2018.5.138 by Robert Collins
Merge bzr.dev.
582
        self.assertEqual(subtrees, result._format.supports_tree_reference)
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
583
584
    def test_open_repository_sets_format_attributes(self):
585
        self.check_open_repository(True, True)
586
        self.check_open_repository(False, True)
587
        self.check_open_repository(True, False)
588
        self.check_open_repository(False, False)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
589
        self.check_open_repository(False, False, 'yes')
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
590
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
591
    def test_old_server(self):
592
        """RemoteBzrDirFormat should fail to probe if the server version is too
593
        old.
594
        """
595
        self.assertRaises(errors.NotBranchError,
596
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
597
598
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
599
class TestBzrDirCreateBranch(TestRemote):
600
601
    def test_backwards_compat(self):
602
        self.setup_smart_server_with_call_log()
603
        repo = self.make_repository('.')
604
        self.reset_smart_call_log()
605
        self.disable_verb('BzrDir.create_branch')
606
        branch = repo.bzrdir.create_branch()
607
        create_branch_call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
608
            call.call.method == 'BzrDir.create_branch'])
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
609
        self.assertEqual(1, create_branch_call_count)
610
611
    def test_current_server(self):
612
        transport = self.get_transport('.')
613
        transport = transport.clone('quack')
614
        self.make_repository('quack')
615
        client = FakeClient(transport.base)
616
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
617
        reference_format = reference_bzrdir_format.get_branch_format()
618
        network_name = reference_format.network_name()
619
        reference_repo_fmt = reference_bzrdir_format.repository_format
620
        reference_repo_name = reference_repo_fmt.network_name()
621
        client.add_expected_call(
622
            'BzrDir.create_branch', ('quack/', network_name),
623
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
624
            reference_repo_name))
625
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
626
            _client=client)
627
        branch = a_bzrdir.create_branch()
628
        # We should have got a remote branch
629
        self.assertIsInstance(branch, remote.RemoteBranch)
630
        # its format should have the settings from the response
631
        format = branch._format
632
        self.assertEqual(network_name, format.network_name())
633
634
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
635
class TestBzrDirCreateRepository(TestRemote):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
636
637
    def test_backwards_compat(self):
638
        self.setup_smart_server_with_call_log()
639
        bzrdir = self.make_bzrdir('.')
640
        self.reset_smart_call_log()
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
641
        self.disable_verb('BzrDir.create_repository')
642
        repo = bzrdir.create_repository()
643
        create_repo_call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
644
            call.call.method == 'BzrDir.create_repository'])
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
645
        self.assertEqual(1, create_repo_call_count)
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
646
647
    def test_current_server(self):
648
        transport = self.get_transport('.')
649
        transport = transport.clone('quack')
650
        self.make_bzrdir('quack')
651
        client = FakeClient(transport.base)
652
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
653
        reference_format = reference_bzrdir_format.repository_format
654
        network_name = reference_format.network_name()
655
        client.add_expected_call(
656
            'BzrDir.create_repository', ('quack/',
657
                'Bazaar pack repository format 1 (needs bzr 0.92)\n', 'False'),
658
            'success', ('ok', 'no', 'no', 'no', network_name))
659
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
660
            _client=client)
661
        repo = a_bzrdir.create_repository()
662
        # We should have got a remote repository
663
        self.assertIsInstance(repo, remote.RemoteRepository)
664
        # its format should have the settings from the response
665
        format = repo._format
666
        self.assertFalse(format.rich_root_data)
667
        self.assertFalse(format.supports_tree_reference)
668
        self.assertFalse(format.supports_external_lookups)
669
        self.assertEqual(network_name, format.network_name())
670
671
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
672
class TestBzrDirOpenRepository(TestRemote):
673
674
    def test_backwards_compat_1_2_3(self):
675
        # fallback all the way to the first version.
676
        reference_format = self.get_repo_format()
677
        network_name = reference_format.network_name()
678
        client = FakeClient('bzr://example.com/')
679
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
680
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
681
        client.add_success_response('ok', '', 'no', 'no')
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
682
        # A real repository instance will be created to determine the network
683
        # name.
684
        client.add_success_response_with_body(
685
            "Bazaar-NG meta directory, format 1\n", 'ok')
686
        client.add_success_response_with_body(
687
            reference_format.get_format_string(), 'ok')
688
        # PackRepository wants to do a stat
689
        client.add_success_response('stat', '0', '65535')
690
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
691
            _client=client)
692
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
693
            _client=client)
694
        repo = bzrdir.open_repository()
695
        self.assertEqual(
696
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
697
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
698
             ('call', 'BzrDir.find_repository', ('quack/',)),
699
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
700
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
701
             ('call', 'stat', ('/quack/.bzr/repository',)),
702
             ],
703
            client._calls)
704
        self.assertEqual(network_name, repo._format.network_name())
705
706
    def test_backwards_compat_2(self):
707
        # fallback to find_repositoryV2
708
        reference_format = self.get_repo_format()
709
        network_name = reference_format.network_name()
710
        client = FakeClient('bzr://example.com/')
711
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
712
        client.add_success_response('ok', '', 'no', 'no', 'no')
713
        # A real repository instance will be created to determine the network
714
        # name.
715
        client.add_success_response_with_body(
716
            "Bazaar-NG meta directory, format 1\n", 'ok')
717
        client.add_success_response_with_body(
718
            reference_format.get_format_string(), 'ok')
719
        # PackRepository wants to do a stat
720
        client.add_success_response('stat', '0', '65535')
721
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
722
            _client=client)
723
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
724
            _client=client)
725
        repo = bzrdir.open_repository()
726
        self.assertEqual(
727
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
728
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
729
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
730
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
731
             ('call', 'stat', ('/quack/.bzr/repository',)),
732
             ],
733
            client._calls)
734
        self.assertEqual(network_name, repo._format.network_name())
735
736
    def test_current_server(self):
737
        reference_format = self.get_repo_format()
738
        network_name = reference_format.network_name()
739
        transport = MemoryTransport()
740
        transport.mkdir('quack')
741
        transport = transport.clone('quack')
742
        client = FakeClient(transport.base)
743
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
744
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
745
            _client=client)
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
746
        repo = bzrdir.open_repository()
747
        self.assertEqual(
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
748
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
749
            client._calls)
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
750
        self.assertEqual(network_name, repo._format.network_name())
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
751
752
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
753
class TestBzrDirFormatInitializeEx(TestRemote):
754
755
    def test_success(self):
756
        """Simple test for typical successful call."""
757
        fmt = bzrdir.RemoteBzrDirFormat()
758
        default_format_name = BzrDirFormat.get_default_format().network_name()
759
        transport = self.get_transport()
760
        client = FakeClient(transport.base)
761
        client.add_expected_call(
4436.1.1 by Andrew Bennetts
Rename BzrDirFormat.initialize_ex verb to BzrDirFormat.initialize_ex_1.16.
762
            'BzrDirFormat.initialize_ex_1.16',
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
763
                (default_format_name, 'path', 'False', 'False', 'False', '',
764
                 '', '', '', 'False'),
765
            'success',
766
                ('.', 'no', 'no', 'yes', 'repo fmt', 'repo bzrdir fmt',
767
                 'bzrdir fmt', 'False', '', '', 'repo lock token'))
768
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
769
        # it's currently hard to test that without supplying a real remote
770
        # transport connected to a real server.
771
        result = fmt._initialize_on_transport_ex_rpc(client, 'path',
772
            transport, False, False, False, None, None, None, None, False)
773
        client.finished_test()
774
775
    def test_error(self):
776
        """Error responses are translated, e.g. 'PermissionDenied' raises the
777
        corresponding error from the client.
778
        """
779
        fmt = bzrdir.RemoteBzrDirFormat()
780
        default_format_name = BzrDirFormat.get_default_format().network_name()
781
        transport = self.get_transport()
782
        client = FakeClient(transport.base)
783
        client.add_expected_call(
4436.1.1 by Andrew Bennetts
Rename BzrDirFormat.initialize_ex verb to BzrDirFormat.initialize_ex_1.16.
784
            'BzrDirFormat.initialize_ex_1.16',
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
785
                (default_format_name, 'path', 'False', 'False', 'False', '',
786
                 '', '', '', 'False'),
787
            'error',
788
                ('PermissionDenied', 'path', 'extra info'))
789
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
790
        # it's currently hard to test that without supplying a real remote
791
        # transport connected to a real server.
792
        err = self.assertRaises(errors.PermissionDenied,
793
            fmt._initialize_on_transport_ex_rpc, client, 'path', transport,
794
            False, False, False, None, None, None, None, False)
795
        self.assertEqual('path', err.path)
796
        self.assertEqual(': extra info', err.extra)
797
        client.finished_test()
798
4384.1.3 by Andrew Bennetts
Add test suggested by John.
799
    def test_error_from_real_server(self):
800
        """Integration test for error translation."""
801
        transport = self.make_smart_server('foo')
802
        transport = transport.clone('no-such-path')
803
        fmt = bzrdir.RemoteBzrDirFormat()
804
        err = self.assertRaises(errors.NoSuchFile,
805
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
806
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
807
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
808
class OldSmartClient(object):
809
    """A fake smart client for test_old_version that just returns a version one
810
    response to the 'hello' (query version) command.
811
    """
812
813
    def get_request(self):
814
        input_file = StringIO('ok\x011\n')
815
        output_file = StringIO()
816
        client_medium = medium.SmartSimplePipesClientMedium(
817
            input_file, output_file)
818
        return medium.SmartClientStreamMediumRequest(client_medium)
819
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
820
    def protocol_version(self):
821
        return 1
822
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
823
824
class OldServerTransport(object):
825
    """A fake transport for test_old_server that reports it's smart server
826
    protocol version as version one.
827
    """
828
829
    def __init__(self):
830
        self.base = 'fake:'
831
832
    def get_smart_client(self):
833
        return OldSmartClient()
834
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
835
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
836
class RemoteBzrDirTestCase(TestRemote):
837
838
    def make_remote_bzrdir(self, transport, client):
839
        """Make a RemotebzrDir using 'client' as the _client."""
840
        return RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
841
            _client=client)
842
843
844
class RemoteBranchTestCase(RemoteBzrDirTestCase):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
845
846
    def make_remote_branch(self, transport, client):
847
        """Make a RemoteBranch using 'client' as its _SmartClient.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
848
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
849
        A RemoteBzrDir and RemoteRepository will also be created to fill out
850
        the RemoteBranch, albeit with stub values for some of their attributes.
851
        """
852
        # we do not want bzrdir to make any remote calls, so use False as its
853
        # _client.  If it tries to make a remote call, this will fail
854
        # immediately.
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
855
        bzrdir = self.make_remote_bzrdir(transport, False)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
856
        repo = RemoteRepository(bzrdir, None, _client=client)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
857
        branch_format = self.get_branch_format()
858
        format = RemoteBranchFormat(network_name=branch_format.network_name())
859
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
860
861
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
862
class TestBranchGetParent(RemoteBranchTestCase):
863
864
    def test_no_parent(self):
865
        # in an empty branch we decode the response properly
866
        transport = MemoryTransport()
867
        client = FakeClient(transport.base)
868
        client.add_expected_call(
869
            'Branch.get_stacked_on_url', ('quack/',),
870
            'error', ('NotStacked',))
871
        client.add_expected_call(
872
            'Branch.get_parent', ('quack/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
873
            'success', ('',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
874
        transport.mkdir('quack')
875
        transport = transport.clone('quack')
876
        branch = self.make_remote_branch(transport, client)
877
        result = branch.get_parent()
878
        client.finished_test()
879
        self.assertEqual(None, result)
880
881
    def test_parent_relative(self):
882
        transport = MemoryTransport()
883
        client = FakeClient(transport.base)
884
        client.add_expected_call(
885
            'Branch.get_stacked_on_url', ('kwaak/',),
886
            'error', ('NotStacked',))
887
        client.add_expected_call(
888
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
889
            'success', ('../foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
890
        transport.mkdir('kwaak')
891
        transport = transport.clone('kwaak')
892
        branch = self.make_remote_branch(transport, client)
893
        result = branch.get_parent()
894
        self.assertEqual(transport.clone('../foo').base, result)
895
896
    def test_parent_absolute(self):
897
        transport = MemoryTransport()
898
        client = FakeClient(transport.base)
899
        client.add_expected_call(
900
            'Branch.get_stacked_on_url', ('kwaak/',),
901
            'error', ('NotStacked',))
902
        client.add_expected_call(
903
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
904
            'success', ('http://foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
905
        transport.mkdir('kwaak')
906
        transport = transport.clone('kwaak')
907
        branch = self.make_remote_branch(transport, client)
908
        result = branch.get_parent()
909
        self.assertEqual('http://foo/', result)
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
910
        client.finished_test()
911
912
913
class TestBranchSetParentLocation(RemoteBranchTestCase):
914
915
    def test_no_parent(self):
916
        # We call the verb when setting parent to None
917
        transport = MemoryTransport()
918
        client = FakeClient(transport.base)
919
        client.add_expected_call(
920
            'Branch.get_stacked_on_url', ('quack/',),
921
            'error', ('NotStacked',))
922
        client.add_expected_call(
923
            'Branch.set_parent_location', ('quack/', 'b', 'r', ''),
924
            'success', ())
925
        transport.mkdir('quack')
926
        transport = transport.clone('quack')
927
        branch = self.make_remote_branch(transport, client)
928
        branch._lock_token = 'b'
929
        branch._repo_lock_token = 'r'
930
        branch._set_parent_location(None)
931
        client.finished_test()
932
933
    def test_parent(self):
934
        transport = MemoryTransport()
935
        client = FakeClient(transport.base)
936
        client.add_expected_call(
937
            'Branch.get_stacked_on_url', ('kwaak/',),
938
            'error', ('NotStacked',))
939
        client.add_expected_call(
940
            'Branch.set_parent_location', ('kwaak/', 'b', 'r', 'foo'),
941
            'success', ())
942
        transport.mkdir('kwaak')
943
        transport = transport.clone('kwaak')
944
        branch = self.make_remote_branch(transport, client)
945
        branch._lock_token = 'b'
946
        branch._repo_lock_token = 'r'
947
        branch._set_parent_location('foo')
948
        client.finished_test()
949
950
    def test_backwards_compat(self):
951
        self.setup_smart_server_with_call_log()
952
        branch = self.make_branch('.')
953
        self.reset_smart_call_log()
954
        verb = 'Branch.set_parent_location'
955
        self.disable_verb(verb)
956
        branch.set_parent('http://foo/')
957
        self.assertLength(12, self.hpss_calls)
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
958
959
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
960
class TestBranchGetTagsBytes(RemoteBranchTestCase):
961
962
    def test_backwards_compat(self):
963
        self.setup_smart_server_with_call_log()
964
        branch = self.make_branch('.')
965
        self.reset_smart_call_log()
966
        verb = 'Branch.get_tags_bytes'
967
        self.disable_verb(verb)
968
        branch.tags.get_tag_dict()
969
        call_count = len([call for call in self.hpss_calls if
970
            call.call.method == verb])
971
        self.assertEqual(1, call_count)
972
973
    def test_trivial(self):
974
        transport = MemoryTransport()
975
        client = FakeClient(transport.base)
976
        client.add_expected_call(
977
            'Branch.get_stacked_on_url', ('quack/',),
978
            'error', ('NotStacked',))
979
        client.add_expected_call(
980
            'Branch.get_tags_bytes', ('quack/',),
981
            'success', ('',))
982
        transport.mkdir('quack')
983
        transport = transport.clone('quack')
984
        branch = self.make_remote_branch(transport, client)
985
        result = branch.tags.get_tag_dict()
986
        client.finished_test()
987
        self.assertEqual({}, result)
988
989
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
990
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
991
992
    def test_empty_branch(self):
993
        # in an empty branch we decode the response properly
994
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
995
        client = FakeClient(transport.base)
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
996
        client.add_expected_call(
997
            'Branch.get_stacked_on_url', ('quack/',),
998
            'error', ('NotStacked',))
999
        client.add_expected_call(
1000
            'Branch.last_revision_info', ('quack/',),
1001
            'success', ('ok', '0', 'null:'))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1002
        transport.mkdir('quack')
1003
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1004
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1005
        result = branch.last_revision_info()
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
1006
        client.finished_test()
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1007
        self.assertEqual((0, NULL_REVISION), result)
1008
1009
    def test_non_empty_branch(self):
1010
        # in a non-empty branch we also decode the response properly
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1011
        revid = u'\xc8'.encode('utf8')
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1012
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1013
        client = FakeClient(transport.base)
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
1014
        client.add_expected_call(
1015
            'Branch.get_stacked_on_url', ('kwaak/',),
1016
            'error', ('NotStacked',))
1017
        client.add_expected_call(
1018
            'Branch.last_revision_info', ('kwaak/',),
1019
            'success', ('ok', '2', revid))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1020
        transport.mkdir('kwaak')
1021
        transport = transport.clone('kwaak')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1022
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1023
        result = branch.last_revision_info()
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1024
        self.assertEqual((2, revid), result)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1025
1026
4053.1.2 by Robert Collins
Actually make this branch work.
1027
class TestBranch_get_stacked_on_url(TestRemote):
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1028
    """Test Branch._get_stacked_on_url rpc"""
1029
3691.2.10 by Martin Pool
Update more test_remote tests
1030
    def test_get_stacked_on_invalid_url(self):
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1031
        # test that asking for a stacked on url the server can't access works.
1032
        # This isn't perfect, but then as we're in the same process there
1033
        # really isn't anything we can do to be 100% sure that the server
1034
        # doesn't just open in - this test probably needs to be rewritten using
1035
        # a spawn()ed server.
1036
        stacked_branch = self.make_branch('stacked', format='1.9')
1037
        memory_branch = self.make_branch('base', format='1.9')
1038
        vfs_url = self.get_vfs_only_url('base')
1039
        stacked_branch.set_stacked_on_url(vfs_url)
1040
        transport = stacked_branch.bzrdir.root_transport
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1041
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1042
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1043
            'Branch.get_stacked_on_url', ('stacked/',),
1044
            'success', ('ok', vfs_url))
1045
        # XXX: Multiple calls are bad, this second call documents what is
1046
        # today.
1047
        client.add_expected_call(
1048
            'Branch.get_stacked_on_url', ('stacked/',),
1049
            'success', ('ok', vfs_url))
1050
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
1051
            _client=client)
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
1052
        repo_fmt = remote.RemoteRepositoryFormat()
1053
        repo_fmt._custom_format = stacked_branch.repository._format
1054
        branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, repo_fmt),
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1055
            _client=client)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1056
        result = branch.get_stacked_on_url()
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1057
        self.assertEqual(vfs_url, result)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1058
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1059
    def test_backwards_compatible(self):
1060
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
1061
        base_branch = self.make_branch('base', format='1.6')
1062
        stacked_branch = self.make_branch('stacked', format='1.6')
1063
        stacked_branch.set_stacked_on_url('../base')
1064
        client = FakeClient(self.get_url())
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1065
        branch_network_name = self.get_branch_format().network_name()
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1066
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1067
            'BzrDir.open_branchV2', ('stacked/',),
1068
            'success', ('branch', branch_network_name))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1069
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
1070
            'BzrDir.find_repositoryV3', ('stacked/',),
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
1071
            'success', ('ok', '', 'no', 'no', 'yes',
4053.1.2 by Robert Collins
Actually make this branch work.
1072
                stacked_branch.repository._format.network_name()))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1073
        # called twice, once from constructor and then again by us
1074
        client.add_expected_call(
1075
            'Branch.get_stacked_on_url', ('stacked/',),
1076
            'unknown', ('Branch.get_stacked_on_url',))
1077
        client.add_expected_call(
1078
            'Branch.get_stacked_on_url', ('stacked/',),
1079
            'unknown', ('Branch.get_stacked_on_url',))
1080
        # this will also do vfs access, but that goes direct to the transport
1081
        # and isn't seen by the FakeClient.
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1082
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1083
            remote.RemoteBzrDirFormat(), _client=client)
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1084
        branch = bzrdir.open_branch()
1085
        result = branch.get_stacked_on_url()
1086
        self.assertEqual('../base', result)
1087
        client.finished_test()
1088
        # it's in the fallback list both for the RemoteRepository and its vfs
1089
        # repository
1090
        self.assertEqual(1, len(branch.repository._fallback_repositories))
1091
        self.assertEqual(1,
1092
            len(branch.repository._real_repository._fallback_repositories))
1093
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1094
    def test_get_stacked_on_real_branch(self):
1095
        base_branch = self.make_branch('base', format='1.6')
1096
        stacked_branch = self.make_branch('stacked', format='1.6')
1097
        stacked_branch.set_stacked_on_url('../base')
4053.1.2 by Robert Collins
Actually make this branch work.
1098
        reference_format = self.get_repo_format()
1099
        network_name = reference_format.network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1100
        client = FakeClient(self.get_url())
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1101
        branch_network_name = self.get_branch_format().network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1102
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1103
            'BzrDir.open_branchV2', ('stacked/',),
1104
            'success', ('branch', branch_network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1105
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
1106
            'BzrDir.find_repositoryV3', ('stacked/',),
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
1107
            'success', ('ok', '', 'no', 'no', 'yes', network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1108
        # called twice, once from constructor and then again by us
1109
        client.add_expected_call(
1110
            'Branch.get_stacked_on_url', ('stacked/',),
1111
            'success', ('ok', '../base'))
1112
        client.add_expected_call(
1113
            'Branch.get_stacked_on_url', ('stacked/',),
1114
            'success', ('ok', '../base'))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1115
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
1116
            remote.RemoteBzrDirFormat(), _client=client)
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1117
        branch = bzrdir.open_branch()
1118
        result = branch.get_stacked_on_url()
1119
        self.assertEqual('../base', result)
1120
        client.finished_test()
4226.1.2 by Robert Collins
Fix test_remote failing because of less _real_repository objects.
1121
        # it's in the fallback list both for the RemoteRepository.
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1122
        self.assertEqual(1, len(branch.repository._fallback_repositories))
4226.1.2 by Robert Collins
Fix test_remote failing because of less _real_repository objects.
1123
        # And we haven't had to construct a real repository.
1124
        self.assertEqual(None, branch.repository._real_repository)
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1125
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1126
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1127
class TestBranchSetLastRevision(RemoteBranchTestCase):
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1128
1129
    def test_set_empty(self):
1130
        # set_revision_history([]) is translated to calling
1131
        # Branch.set_last_revision(path, '') on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
1132
        transport = MemoryTransport()
1133
        transport.mkdir('branch')
1134
        transport = transport.clone('branch')
1135
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1136
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1137
        client.add_expected_call(
1138
            'Branch.get_stacked_on_url', ('branch/',),
1139
            'error', ('NotStacked',))
1140
        client.add_expected_call(
1141
            'Branch.lock_write', ('branch/', '', ''),
1142
            'success', ('ok', 'branch token', 'repo token'))
1143
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1144
            'Branch.last_revision_info',
1145
            ('branch/',),
1146
            'success', ('ok', '0', 'null:'))
1147
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1148
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
1149
            'success', ('ok',))
1150
        client.add_expected_call(
1151
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1152
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1153
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1154
        # This is a hack to work around the problem that RemoteBranch currently
1155
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1156
        branch._ensure_real = lambda: None
1157
        branch.lock_write()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1158
        result = branch.set_revision_history([])
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1159
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1160
        self.assertEqual(None, result)
3691.2.10 by Martin Pool
Update more test_remote tests
1161
        client.finished_test()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1162
1163
    def test_set_nonempty(self):
1164
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
1165
        # Branch.set_last_revision(path, rev-idN) on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
1166
        transport = MemoryTransport()
1167
        transport.mkdir('branch')
1168
        transport = transport.clone('branch')
1169
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1170
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1171
        client.add_expected_call(
1172
            'Branch.get_stacked_on_url', ('branch/',),
1173
            'error', ('NotStacked',))
1174
        client.add_expected_call(
1175
            'Branch.lock_write', ('branch/', '', ''),
1176
            'success', ('ok', 'branch token', 'repo token'))
1177
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1178
            'Branch.last_revision_info',
1179
            ('branch/',),
1180
            'success', ('ok', '0', 'null:'))
1181
        lines = ['rev-id2']
1182
        encoded_body = bz2.compress('\n'.join(lines))
1183
        client.add_success_response_with_body(encoded_body, 'ok')
1184
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1185
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
1186
            'success', ('ok',))
1187
        client.add_expected_call(
1188
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1189
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1190
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1191
        # This is a hack to work around the problem that RemoteBranch currently
1192
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1193
        branch._ensure_real = lambda: None
1194
        # Lock the branch, reset the record of remote calls.
1195
        branch.lock_write()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1196
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1197
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1198
        self.assertEqual(None, result)
3691.2.10 by Martin Pool
Update more test_remote tests
1199
        client.finished_test()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1200
1201
    def test_no_such_revision(self):
1202
        transport = MemoryTransport()
1203
        transport.mkdir('branch')
1204
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1205
        # A response of 'NoSuchRevision' is translated into an exception.
1206
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1207
        client.add_expected_call(
1208
            'Branch.get_stacked_on_url', ('branch/',),
1209
            'error', ('NotStacked',))
1210
        client.add_expected_call(
1211
            'Branch.lock_write', ('branch/', '', ''),
1212
            'success', ('ok', 'branch token', 'repo token'))
1213
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1214
            'Branch.last_revision_info',
1215
            ('branch/',),
1216
            'success', ('ok', '0', 'null:'))
1217
        # get_graph calls to construct the revision history, for the set_rh
1218
        # hook
1219
        lines = ['rev-id']
1220
        encoded_body = bz2.compress('\n'.join(lines))
1221
        client.add_success_response_with_body(encoded_body, 'ok')
1222
        client.add_expected_call(
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1223
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1224
            'error', ('NoSuchRevision', 'rev-id'))
1225
        client.add_expected_call(
1226
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1227
            'success', ('ok',))
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1228
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1229
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1230
        branch.lock_write()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1231
        self.assertRaises(
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1232
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1233
        branch.unlock()
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1234
        client.finished_test()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1235
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1236
    def test_tip_change_rejected(self):
1237
        """TipChangeRejected responses cause a TipChangeRejected exception to
1238
        be raised.
1239
        """
1240
        transport = MemoryTransport()
1241
        transport.mkdir('branch')
1242
        transport = transport.clone('branch')
1243
        client = FakeClient(transport.base)
1244
        rejection_msg_unicode = u'rejection message\N{INTERROBANG}'
1245
        rejection_msg_utf8 = rejection_msg_unicode.encode('utf8')
3691.2.10 by Martin Pool
Update more test_remote tests
1246
        client.add_expected_call(
1247
            'Branch.get_stacked_on_url', ('branch/',),
1248
            'error', ('NotStacked',))
1249
        client.add_expected_call(
1250
            'Branch.lock_write', ('branch/', '', ''),
1251
            'success', ('ok', 'branch token', 'repo token'))
1252
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1253
            'Branch.last_revision_info',
1254
            ('branch/',),
1255
            'success', ('ok', '0', 'null:'))
1256
        lines = ['rev-id']
1257
        encoded_body = bz2.compress('\n'.join(lines))
1258
        client.add_success_response_with_body(encoded_body, 'ok')
1259
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1260
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1261
            'error', ('TipChangeRejected', rejection_msg_utf8))
1262
        client.add_expected_call(
1263
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1264
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1265
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1266
        branch._ensure_real = lambda: None
1267
        branch.lock_write()
1268
        # The 'TipChangeRejected' error response triggered by calling
1269
        # set_revision_history causes a TipChangeRejected exception.
1270
        err = self.assertRaises(
1271
            errors.TipChangeRejected, branch.set_revision_history, ['rev-id'])
1272
        # The UTF-8 message from the response has been decoded into a unicode
1273
        # object.
1274
        self.assertIsInstance(err.msg, unicode)
1275
        self.assertEqual(rejection_msg_unicode, err.msg)
3691.2.10 by Martin Pool
Update more test_remote tests
1276
        branch.unlock()
1277
        client.finished_test()
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1278
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1279
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1280
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1281
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1282
    def test_set_last_revision_info(self):
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1283
        # set_last_revision_info(num, 'rev-id') is translated to calling
1284
        # Branch.set_last_revision_info(num, 'rev-id') on the wire.
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
1285
        transport = MemoryTransport()
1286
        transport.mkdir('branch')
1287
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1288
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1289
        # get_stacked_on_url
1290
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1291
        # lock_write
1292
        client.add_success_response('ok', 'branch token', 'repo token')
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1293
        # query the current revision
1294
        client.add_success_response('ok', '0', 'null:')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1295
        # set_last_revision
1296
        client.add_success_response('ok')
1297
        # unlock
1298
        client.add_success_response('ok')
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1299
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1300
        branch = self.make_remote_branch(transport, client)
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1301
        # Lock the branch, reset the record of remote calls.
1302
        branch.lock_write()
1303
        client._calls = []
1304
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1305
        self.assertEqual(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1306
            [('call', 'Branch.last_revision_info', ('branch/',)),
1307
             ('call', 'Branch.set_last_revision_info',
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
1308
                ('branch/', 'branch token', 'repo token',
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1309
                 '1234', 'a-revision-id'))],
1310
            client._calls)
1311
        self.assertEqual(None, result)
1312
1313
    def test_no_such_revision(self):
1314
        # A response of 'NoSuchRevision' is translated into an exception.
1315
        transport = MemoryTransport()
1316
        transport.mkdir('branch')
1317
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1318
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1319
        # get_stacked_on_url
1320
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1321
        # lock_write
1322
        client.add_success_response('ok', 'branch token', 'repo token')
1323
        # set_last_revision
1324
        client.add_error_response('NoSuchRevision', 'revid')
1325
        # unlock
1326
        client.add_success_response('ok')
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1327
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1328
        branch = self.make_remote_branch(transport, client)
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1329
        # Lock the branch, reset the record of remote calls.
1330
        branch.lock_write()
1331
        client._calls = []
1332
1333
        self.assertRaises(
1334
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1335
        branch.unlock()
1336
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1337
    def lock_remote_branch(self, branch):
1338
        """Trick a RemoteBranch into thinking it is locked."""
1339
        branch._lock_mode = 'w'
1340
        branch._lock_count = 2
1341
        branch._lock_token = 'branch token'
1342
        branch._repo_lock_token = 'repo token'
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1343
        branch.repository._lock_mode = 'w'
1344
        branch.repository._lock_count = 2
1345
        branch.repository._lock_token = 'repo token'
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1346
1347
    def test_backwards_compatibility(self):
1348
        """If the server does not support the Branch.set_last_revision_info
1349
        verb (which is new in 1.4), then the client falls back to VFS methods.
1350
        """
1351
        # This test is a little messy.  Unlike most tests in this file, it
1352
        # doesn't purely test what a Remote* object sends over the wire, and
1353
        # how it reacts to responses from the wire.  It instead relies partly
1354
        # on asserting that the RemoteBranch will call
1355
        # self._real_branch.set_last_revision_info(...).
1356
1357
        # First, set up our RemoteBranch with a FakeClient that raises
1358
        # UnknownSmartMethod, and a StubRealBranch that logs how it is called.
1359
        transport = MemoryTransport()
1360
        transport.mkdir('branch')
1361
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1362
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1363
        client.add_expected_call(
1364
            'Branch.get_stacked_on_url', ('branch/',),
1365
            'error', ('NotStacked',))
1366
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1367
            'Branch.last_revision_info',
1368
            ('branch/',),
1369
            'success', ('ok', '0', 'null:'))
1370
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1371
            'Branch.set_last_revision_info',
1372
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
1373
            'unknown', 'Branch.set_last_revision_info')
1374
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1375
        branch = self.make_remote_branch(transport, client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1376
        class StubRealBranch(object):
1377
            def __init__(self):
1378
                self.calls = []
1379
            def set_last_revision_info(self, revno, revision_id):
1380
                self.calls.append(
1381
                    ('set_last_revision_info', revno, revision_id))
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1382
            def _clear_cached_state(self):
1383
                pass
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1384
        real_branch = StubRealBranch()
1385
        branch._real_branch = real_branch
1386
        self.lock_remote_branch(branch)
1387
1388
        # Call set_last_revision_info, and verify it behaved as expected.
1389
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1390
        self.assertEqual(
1391
            [('set_last_revision_info', 1234, 'a-revision-id')],
1392
            real_branch.calls)
3691.2.10 by Martin Pool
Update more test_remote tests
1393
        client.finished_test()
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1394
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1395
    def test_unexpected_error(self):
3697.2.6 by Martin Pool
Merge 261315 fix into 1.7 branch
1396
        # If the server sends an error the client doesn't understand, it gets
1397
        # turned into an UnknownErrorFromSmartServer, which is presented as a
1398
        # non-internal error to the user.
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1399
        transport = MemoryTransport()
1400
        transport.mkdir('branch')
1401
        transport = transport.clone('branch')
1402
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1403
        # get_stacked_on_url
1404
        client.add_error_response('NotStacked')
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1405
        # lock_write
1406
        client.add_success_response('ok', 'branch token', 'repo token')
1407
        # set_last_revision
1408
        client.add_error_response('UnexpectedError')
1409
        # unlock
1410
        client.add_success_response('ok')
1411
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1412
        branch = self.make_remote_branch(transport, client)
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1413
        # Lock the branch, reset the record of remote calls.
1414
        branch.lock_write()
1415
        client._calls = []
1416
1417
        err = self.assertRaises(
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1418
            errors.UnknownErrorFromSmartServer,
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1419
            branch.set_last_revision_info, 123, 'revid')
1420
        self.assertEqual(('UnexpectedError',), err.error_tuple)
1421
        branch.unlock()
1422
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1423
    def test_tip_change_rejected(self):
1424
        """TipChangeRejected responses cause a TipChangeRejected exception to
1425
        be raised.
1426
        """
1427
        transport = MemoryTransport()
1428
        transport.mkdir('branch')
1429
        transport = transport.clone('branch')
1430
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1431
        # get_stacked_on_url
1432
        client.add_error_response('NotStacked')
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1433
        # lock_write
1434
        client.add_success_response('ok', 'branch token', 'repo token')
1435
        # set_last_revision
1436
        client.add_error_response('TipChangeRejected', 'rejection message')
1437
        # unlock
1438
        client.add_success_response('ok')
1439
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1440
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1441
        # Lock the branch, reset the record of remote calls.
1442
        branch.lock_write()
1443
        self.addCleanup(branch.unlock)
1444
        client._calls = []
1445
1446
        # The 'TipChangeRejected' error response triggered by calling
1447
        # set_last_revision_info causes a TipChangeRejected exception.
1448
        err = self.assertRaises(
1449
            errors.TipChangeRejected,
1450
            branch.set_last_revision_info, 123, 'revid')
1451
        self.assertEqual('rejection message', err.msg)
1452
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1453
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1454
class TestBranchGetSetConfig(RemoteBranchTestCase):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1455
1456
    def test_get_branch_conf(self):
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
1457
        # in an empty branch we decode the response properly
1458
        client = FakeClient()
1459
        client.add_expected_call(
1460
            'Branch.get_stacked_on_url', ('memory:///',),
1461
            'error', ('NotStacked',),)
1462
        client.add_success_response_with_body('# config file body', 'ok')
1463
        transport = MemoryTransport()
1464
        branch = self.make_remote_branch(transport, client)
1465
        config = branch.get_config()
1466
        config.has_explicit_nickname()
1467
        self.assertEqual(
1468
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
1469
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
1470
            client._calls)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1471
4241.5.2 by Matt Nordhoff
Add a test
1472
    def test_get_multi_line_branch_conf(self):
1473
        # Make sure that multiple-line branch.conf files are supported
1474
        #
1475
        # https://bugs.edge.launchpad.net/bzr/+bug/354075
1476
        client = FakeClient()
1477
        client.add_expected_call(
1478
            'Branch.get_stacked_on_url', ('memory:///',),
1479
            'error', ('NotStacked',),)
1480
        client.add_success_response_with_body('a = 1\nb = 2\nc = 3\n', 'ok')
1481
        transport = MemoryTransport()
1482
        branch = self.make_remote_branch(transport, client)
1483
        config = branch.get_config()
1484
        self.assertEqual(u'2', config.get_user_option('b'))
1485
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1486
    def test_set_option(self):
1487
        client = FakeClient()
1488
        client.add_expected_call(
1489
            'Branch.get_stacked_on_url', ('memory:///',),
1490
            'error', ('NotStacked',),)
1491
        client.add_expected_call(
1492
            'Branch.lock_write', ('memory:///', '', ''),
1493
            'success', ('ok', 'branch token', 'repo token'))
1494
        client.add_expected_call(
1495
            'Branch.set_config_option', ('memory:///', 'branch token',
1496
            'repo token', 'foo', 'bar', ''),
1497
            'success', ())
1498
        client.add_expected_call(
1499
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1500
            'success', ('ok',))
1501
        transport = MemoryTransport()
1502
        branch = self.make_remote_branch(transport, client)
1503
        branch.lock_write()
1504
        config = branch._get_config()
1505
        config.set_option('foo', 'bar')
1506
        branch.unlock()
1507
        client.finished_test()
1508
1509
    def test_backwards_compat_set_option(self):
1510
        self.setup_smart_server_with_call_log()
1511
        branch = self.make_branch('.')
1512
        verb = 'Branch.set_config_option'
1513
        self.disable_verb(verb)
1514
        branch.lock_write()
1515
        self.addCleanup(branch.unlock)
1516
        self.reset_smart_call_log()
1517
        branch._get_config().set_option('value', 'name')
1518
        self.assertLength(10, self.hpss_calls)
1519
        self.assertEqual('value', branch._get_config().get_option('name'))
1520
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1521
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1522
class TestBranchLockWrite(RemoteBranchTestCase):
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
1523
1524
    def test_lock_write_unlockable(self):
1525
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1526
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1527
        client.add_expected_call(
1528
            'Branch.get_stacked_on_url', ('quack/',),
1529
            'error', ('NotStacked',),)
1530
        client.add_expected_call(
1531
            'Branch.lock_write', ('quack/', '', ''),
1532
            'error', ('UnlockableTransport',))
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
1533
        transport.mkdir('quack')
1534
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1535
        branch = self.make_remote_branch(transport, client)
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
1536
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1537
        client.finished_test()
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
1538
1539
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1540
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
1541
1542
    def test__get_config(self):
1543
        client = FakeClient()
1544
        client.add_success_response_with_body('default_stack_on = /\n', 'ok')
1545
        transport = MemoryTransport()
1546
        bzrdir = self.make_remote_bzrdir(transport, client)
1547
        config = bzrdir.get_config()
1548
        self.assertEqual('/', config.get_default_stack_on())
1549
        self.assertEqual(
1550
            [('call_expecting_body', 'BzrDir.get_config_file', ('memory:///',))],
1551
            client._calls)
1552
1553
    def test_set_option_uses_vfs(self):
1554
        self.setup_smart_server_with_call_log()
1555
        bzrdir = self.make_bzrdir('.')
1556
        self.reset_smart_call_log()
1557
        config = bzrdir.get_config()
1558
        config.set_default_stack_on('/')
1559
        self.assertLength(3, self.hpss_calls)
1560
1561
    def test_backwards_compat_get_option(self):
1562
        self.setup_smart_server_with_call_log()
1563
        bzrdir = self.make_bzrdir('.')
1564
        verb = 'BzrDir.get_config_file'
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
1565
        self.disable_verb(verb)
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1566
        self.reset_smart_call_log()
1567
        self.assertEqual(None,
1568
            bzrdir._get_config().get_option('default_stack_on'))
1569
        self.assertLength(3, self.hpss_calls)
1570
1571
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1572
class TestTransportIsReadonly(tests.TestCase):
1573
1574
    def test_true(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1575
        client = FakeClient()
1576
        client.add_success_response('yes')
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1577
        transport = RemoteTransport('bzr://example.com/', medium=False,
1578
                                    _client=client)
1579
        self.assertEqual(True, transport.is_readonly())
1580
        self.assertEqual(
1581
            [('call', 'Transport.is_readonly', ())],
1582
            client._calls)
1583
1584
    def test_false(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1585
        client = FakeClient()
1586
        client.add_success_response('no')
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1587
        transport = RemoteTransport('bzr://example.com/', medium=False,
1588
                                    _client=client)
1589
        self.assertEqual(False, transport.is_readonly())
1590
        self.assertEqual(
1591
            [('call', 'Transport.is_readonly', ())],
1592
            client._calls)
1593
1594
    def test_error_from_old_server(self):
1595
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1596
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1597
        Clients should treat it as a "no" response, because is_readonly is only
1598
        advisory anyway (a transport could be read-write, but then the
1599
        underlying filesystem could be readonly anyway).
1600
        """
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1601
        client = FakeClient()
1602
        client.add_unknown_method_response('Transport.is_readonly')
2471.2.1 by Andrew Bennetts
Fix trivial incompatibility with bzr 0.11 servers, which give a slightly different error to bzr 0.15 servers.
1603
        transport = RemoteTransport('bzr://example.com/', medium=False,
1604
                                    _client=client)
1605
        self.assertEqual(False, transport.is_readonly())
1606
        self.assertEqual(
1607
            [('call', 'Transport.is_readonly', ())],
1608
            client._calls)
1609
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1610
3840.1.1 by Andrew Bennetts
Fix RemoteTransport's translation of errors involving paths; it wasn't passing orig_path to _translate_error.
1611
class TestTransportMkdir(tests.TestCase):
1612
1613
    def test_permissiondenied(self):
1614
        client = FakeClient()
1615
        client.add_error_response('PermissionDenied', 'remote path', 'extra')
1616
        transport = RemoteTransport('bzr://example.com/', medium=False,
1617
                                    _client=client)
1618
        exc = self.assertRaises(
1619
            errors.PermissionDenied, transport.mkdir, 'client path')
1620
        expected_error = errors.PermissionDenied('/client path', 'extra')
1621
        self.assertEqual(expected_error, exc)
1622
1623
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1624
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
1625
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1626
    def test_defaults_to_none(self):
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1627
        t = RemoteSSHTransport('bzr+ssh://example.com')
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1628
        self.assertIs(None, t._get_credentials()[0])
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1629
1630
    def test_uses_authentication_config(self):
1631
        conf = config.AuthenticationConfig()
1632
        conf._get_config().update(
1633
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
1634
            'example.com'}})
1635
        conf._save()
1636
        t = RemoteSSHTransport('bzr+ssh://example.com')
1637
        self.assertEqual('bar', t._get_credentials()[0])
1638
1639
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1640
class TestRemoteRepository(TestRemote):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1641
    """Base for testing RemoteRepository protocol usage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1642
1643
    These tests contain frozen requests and responses.  We want any changes to
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1644
    what is sent or expected to be require a thoughtful update to these tests
1645
    because they might break compatibility with different-versioned servers.
1646
    """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1647
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1648
    def setup_fake_client_and_repository(self, transport_path):
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1649
        """Create the fake client and repository for testing with.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1650
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1651
        There's no real server here; we just have canned responses sent
1652
        back one by one.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1653
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1654
        :param transport_path: Path below the root of the MemoryTransport
1655
            where the repository will be created.
1656
        """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1657
        transport = MemoryTransport()
1658
        transport.mkdir(transport_path)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1659
        client = FakeClient(transport.base)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1660
        transport = transport.clone(transport_path)
1661
        # we do not want bzrdir to make any remote calls
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1662
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
1663
            _client=False)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1664
        repo = RemoteRepository(bzrdir, None, _client=client)
1665
        return repo, client
1666
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1667
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
1668
class TestRepositoryFormat(TestRemoteRepository):
1669
1670
    def test_fast_delta(self):
4241.6.8 by Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil
Add --development6-rich-root, disabling the legacy and unneeded development2 format, and activating the tests for CHK features disabled pending this format. (Robert Collins, John Arbash Meinel, Ian Clatworthy, Vincent Ladeuil)
1671
        true_name = groupcompress_repo.RepositoryFormatCHK1().network_name()
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
1672
        true_format = RemoteRepositoryFormat()
1673
        true_format._network_name = true_name
1674
        self.assertEqual(True, true_format.fast_deltas)
1675
        false_name = pack_repo.RepositoryFormatKnitPack1().network_name()
1676
        false_format = RemoteRepositoryFormat()
1677
        false_format._network_name = false_name
1678
        self.assertEqual(False, false_format.fast_deltas)
1679
1680
2018.12.2 by Andrew Bennetts
Remove some duplicate code in test_remote
1681
class TestRepositoryGatherStats(TestRemoteRepository):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1682
1683
    def test_revid_none(self):
1684
        # ('ok',), body with revisions and size
1685
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1686
        repo, client = self.setup_fake_client_and_repository(transport_path)
1687
        client.add_success_response_with_body(
1688
            'revisions: 2\nsize: 18\n', 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1689
        result = repo.gather_stats(None)
1690
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1691
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1692
             ('quack/','','no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1693
            client._calls)
1694
        self.assertEqual({'revisions': 2, 'size': 18}, result)
1695
1696
    def test_revid_no_committers(self):
1697
        # ('ok',), body without committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1698
        body = ('firstrev: 123456.300 3600\n'
1699
                'latestrev: 654231.400 0\n'
1700
                'revisions: 2\n'
1701
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1702
        transport_path = 'quick'
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1703
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1704
        repo, client = self.setup_fake_client_and_repository(transport_path)
1705
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1706
        result = repo.gather_stats(revid)
1707
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1708
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1709
              ('quick/', revid, 'no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1710
            client._calls)
1711
        self.assertEqual({'revisions': 2, 'size': 18,
1712
                          'firstrev': (123456.300, 3600),
1713
                          'latestrev': (654231.400, 0),},
1714
                         result)
1715
1716
    def test_revid_with_committers(self):
1717
        # ('ok',), body with committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1718
        body = ('committers: 128\n'
1719
                'firstrev: 123456.300 3600\n'
1720
                'latestrev: 654231.400 0\n'
1721
                'revisions: 2\n'
1722
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1723
        transport_path = 'buick'
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1724
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1725
        repo, client = self.setup_fake_client_and_repository(transport_path)
1726
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1727
        result = repo.gather_stats(revid, True)
1728
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1729
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1730
              ('buick/', revid, 'yes'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1731
            client._calls)
1732
        self.assertEqual({'revisions': 2, 'size': 18,
1733
                          'committers': 128,
1734
                          'firstrev': (123456.300, 3600),
1735
                          'latestrev': (654231.400, 0),},
1736
                         result)
1737
1738
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1739
class TestRepositoryGetGraph(TestRemoteRepository):
1740
1741
    def test_get_graph(self):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1742
        # get_graph returns a graph with a custom parents provider.
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1743
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1744
        repo, client = self.setup_fake_client_and_repository(transport_path)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1745
        graph = repo.get_graph()
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1746
        self.assertNotEqual(graph._parents_provider, repo)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1747
1748
1749
class TestRepositoryGetParentMap(TestRemoteRepository):
1750
1751
    def test_get_parent_map_caching(self):
1752
        # get_parent_map returns from cache until unlock()
1753
        # setup a reponse with two revisions
1754
        r1 = u'\u0e33'.encode('utf8')
1755
        r2 = u'\u0dab'.encode('utf8')
1756
        lines = [' '.join([r2, r1]), r1]
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
1757
        encoded_body = bz2.compress('\n'.join(lines))
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1758
1759
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1760
        repo, client = self.setup_fake_client_and_repository(transport_path)
1761
        client.add_success_response_with_body(encoded_body, 'ok')
1762
        client.add_success_response_with_body(encoded_body, 'ok')
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1763
        repo.lock_read()
1764
        graph = repo.get_graph()
1765
        parents = graph.get_parent_map([r2])
1766
        self.assertEqual({r2: (r1,)}, parents)
1767
        # locking and unlocking deeper should not reset
1768
        repo.lock_read()
1769
        repo.unlock()
1770
        parents = graph.get_parent_map([r1])
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1771
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1772
        self.assertEqual(
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1773
            [('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
1774
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
1775
              '\n\n0')],
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1776
            client._calls)
1777
        repo.unlock()
1778
        # now we call again, and it should use the second response.
1779
        repo.lock_read()
1780
        graph = repo.get_graph()
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1781
        parents = graph.get_parent_map([r1])
1782
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1783
        self.assertEqual(
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1784
            [('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
1785
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
1786
              '\n\n0'),
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
1787
             ('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
1788
              'Repository.get_parent_map', ('quack/', 'include-missing:', r1),
1789
              '\n\n0'),
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1790
            ],
1791
            client._calls)
1792
        repo.unlock()
1793
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1794
    def test_get_parent_map_reconnects_if_unknown_method(self):
1795
        transport_path = 'quack'
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1796
        rev_id = 'revision-id'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1797
        repo, client = self.setup_fake_client_and_repository(transport_path)
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1798
        client.add_unknown_method_response('Repository.get_parent_map')
1799
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1800
        self.assertFalse(client._medium._is_remote_before((1, 2)))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1801
        parents = repo.get_parent_map([rev_id])
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1802
        self.assertEqual(
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1803
            [('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
1804
              'Repository.get_parent_map', ('quack/', 'include-missing:',
1805
              rev_id), '\n\n0'),
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1806
             ('disconnect medium',),
1807
             ('call_expecting_body', 'Repository.get_revision_graph',
1808
              ('quack/', ''))],
1809
            client._calls)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1810
        # The medium is now marked as being connected to an older server
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1811
        self.assertTrue(client._medium._is_remote_before((1, 2)))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1812
        self.assertEqual({rev_id: ('null:',)}, parents)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1813
1814
    def test_get_parent_map_fallback_parentless_node(self):
1815
        """get_parent_map falls back to get_revision_graph on old servers.  The
1816
        results from get_revision_graph are tweaked to match the get_parent_map
1817
        API.
1818
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1819
        Specifically, a {key: ()} result from get_revision_graph means "no
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1820
        parents" for that key, which in get_parent_map results should be
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1821
        represented as {key: ('null:',)}.
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1822
1823
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
1824
        """
1825
        rev_id = 'revision-id'
1826
        transport_path = 'quack'
3245.4.40 by Andrew Bennetts
Merge from bzr.dev.
1827
        repo, client = self.setup_fake_client_and_repository(transport_path)
1828
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
1829
        client._medium._remember_remote_is_before((1, 2))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
1830
        parents = repo.get_parent_map([rev_id])
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1831
        self.assertEqual(
1832
            [('call_expecting_body', 'Repository.get_revision_graph',
1833
             ('quack/', ''))],
1834
            client._calls)
1835
        self.assertEqual({rev_id: ('null:',)}, parents)
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1836
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1837
    def test_get_parent_map_unexpected_response(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1838
        repo, client = self.setup_fake_client_and_repository('path')
1839
        client.add_success_response('something unexpected!')
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1840
        self.assertRaises(
1841
            errors.UnexpectedSmartServerResponse,
1842
            repo.get_parent_map, ['a-revision-id'])
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1843
4190.1.1 by Robert Collins
Negatively cache misses during read-locks in RemoteRepository.
1844
    def test_get_parent_map_negative_caches_missing_keys(self):
1845
        self.setup_smart_server_with_call_log()
1846
        repo = self.make_repository('foo')
1847
        self.assertIsInstance(repo, RemoteRepository)
1848
        repo.lock_read()
1849
        self.addCleanup(repo.unlock)
1850
        self.reset_smart_call_log()
1851
        graph = repo.get_graph()
1852
        self.assertEqual({},
1853
            graph.get_parent_map(['some-missing', 'other-missing']))
1854
        self.assertLength(1, self.hpss_calls)
1855
        # No call if we repeat this
1856
        self.reset_smart_call_log()
1857
        graph = repo.get_graph()
1858
        self.assertEqual({},
1859
            graph.get_parent_map(['some-missing', 'other-missing']))
1860
        self.assertLength(0, self.hpss_calls)
1861
        # Asking for more unknown keys makes a request.
1862
        self.reset_smart_call_log()
1863
        graph = repo.get_graph()
1864
        self.assertEqual({},
1865
            graph.get_parent_map(['some-missing', 'other-missing',
1866
                'more-missing']))
1867
        self.assertLength(1, self.hpss_calls)
1868
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
1869
    def disableExtraResults(self):
1870
        old_flag = SmartServerRepositoryGetParentMap.no_extra_results
1871
        SmartServerRepositoryGetParentMap.no_extra_results = True
1872
        def reset_values():
1873
            SmartServerRepositoryGetParentMap.no_extra_results = old_flag
1874
        self.addCleanup(reset_values)
1875
4214.2.5 by Andrew Bennetts
Fix the bug.
1876
    def test_null_cached_missing_and_stop_key(self):
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
1877
        self.setup_smart_server_with_call_log()
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
1878
        # Make a branch with a single revision.
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
1879
        builder = self.make_branch_builder('foo')
1880
        builder.start_series()
1881
        builder.build_snapshot('first', None, [
1882
            ('add', ('', 'root-id', 'directory', ''))])
1883
        builder.finish_series()
1884
        branch = builder.get_branch()
1885
        repo = branch.repository
1886
        self.assertIsInstance(repo, RemoteRepository)
4214.2.3 by Andrew Bennetts
Further simplify test case, and add more comments.
1887
        # Stop the server from sending extra results.
1888
        self.disableExtraResults()
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
1889
        repo.lock_read()
1890
        self.addCleanup(repo.unlock)
1891
        self.reset_smart_call_log()
1892
        graph = repo.get_graph()
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
1893
        # Query for 'first' and 'null:'.  Because 'null:' is a parent of
4214.2.5 by Andrew Bennetts
Fix the bug.
1894
        # 'first' it will be a candidate for the stop_keys of subsequent
1895
        # requests, and because 'null:' was queried but not returned it will be
1896
        # cached as missing.
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
1897
        self.assertEqual({'first': ('null:',)},
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
1898
            graph.get_parent_map(['first', 'null:']))
1899
        # Now query for another key.  This request will pass along a recipe of
1900
        # start and stop keys describing the already cached results, and this
4214.2.5 by Andrew Bennetts
Fix the bug.
1901
        # recipe's revision count must be correct (or else it will trigger an
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
1902
        # error from the server).
4214.2.5 by Andrew Bennetts
Fix the bug.
1903
        self.assertEqual({}, graph.get_parent_map(['another-key']))
4214.2.3 by Andrew Bennetts
Further simplify test case, and add more comments.
1904
        # This assertion guards against disableExtraResults silently failing to
1905
        # work, thus invalidating the test.
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
1906
        self.assertLength(2, self.hpss_calls)
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
1907
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
1908
    def test_get_parent_map_gets_ghosts_from_result(self):
1909
        # asking for a revision should negatively cache close ghosts in its
1910
        # ancestry.
1911
        self.setup_smart_server_with_call_log()
1912
        tree = self.make_branch_and_memory_tree('foo')
1913
        tree.lock_write()
1914
        try:
1915
            builder = treebuilder.TreeBuilder()
1916
            builder.start_tree(tree)
1917
            builder.build([])
1918
            builder.finish_tree()
1919
            tree.set_parent_ids(['non-existant'], allow_leftmost_as_ghost=True)
1920
            rev_id = tree.commit('')
1921
        finally:
1922
            tree.unlock()
1923
        tree.lock_read()
1924
        self.addCleanup(tree.unlock)
1925
        repo = tree.branch.repository
1926
        self.assertIsInstance(repo, RemoteRepository)
1927
        # ask for rev_id
1928
        repo.get_parent_map([rev_id])
1929
        self.reset_smart_call_log()
1930
        # Now asking for rev_id's ghost parent should not make calls
1931
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
1932
        self.assertLength(0, self.hpss_calls)
1933
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1934
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
1935
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
1936
1937
    def test_allows_new_revisions(self):
1938
        """get_parent_map's results can be updated by commit."""
1939
        smart_server = server.SmartTCPServer_for_testing()
1940
        smart_server.setUp()
1941
        self.addCleanup(smart_server.tearDown)
1942
        self.make_branch('branch')
1943
        branch = Branch.open(smart_server.get_url() + '/branch')
1944
        tree = branch.create_checkout('tree', lightweight=True)
1945
        tree.lock_write()
1946
        self.addCleanup(tree.unlock)
1947
        graph = tree.branch.repository.get_graph()
1948
        # This provides an opportunity for the missing rev-id to be cached.
1949
        self.assertEqual({}, graph.get_parent_map(['rev1']))
1950
        tree.commit('message', rev_id='rev1')
1951
        graph = tree.branch.repository.get_graph()
1952
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
1953
1954
3948.3.9 by Martin Pool
Undelete TestRepositoryGetRevisionGraph but make it use private client methods to simulate old clients
1955
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
1956
1957
    def test_null_revision(self):
1958
        # a null revision has the predictable result {}, we should have no wire
1959
        # traffic when calling it with this argument
1960
        transport_path = 'empty'
1961
        repo, client = self.setup_fake_client_and_repository(transport_path)
1962
        client.add_success_response('notused')
1963
        # actual RemoteRepository.get_revision_graph is gone, but there's an
1964
        # equivalent private method for testing
1965
        result = repo._get_revision_graph(NULL_REVISION)
1966
        self.assertEqual([], client._calls)
1967
        self.assertEqual({}, result)
1968
1969
    def test_none_revision(self):
1970
        # with none we want the entire graph
1971
        r1 = u'\u0e33'.encode('utf8')
1972
        r2 = u'\u0dab'.encode('utf8')
1973
        lines = [' '.join([r2, r1]), r1]
1974
        encoded_body = '\n'.join(lines)
1975
1976
        transport_path = 'sinhala'
1977
        repo, client = self.setup_fake_client_and_repository(transport_path)
1978
        client.add_success_response_with_body(encoded_body, 'ok')
1979
        # actual RemoteRepository.get_revision_graph is gone, but there's an
1980
        # equivalent private method for testing
1981
        result = repo._get_revision_graph(None)
1982
        self.assertEqual(
1983
            [('call_expecting_body', 'Repository.get_revision_graph',
1984
             ('sinhala/', ''))],
1985
            client._calls)
1986
        self.assertEqual({r1: (), r2: (r1, )}, result)
1987
1988
    def test_specific_revision(self):
1989
        # with a specific revision we want the graph for that
1990
        # with none we want the entire graph
1991
        r11 = u'\u0e33'.encode('utf8')
1992
        r12 = u'\xc9'.encode('utf8')
1993
        r2 = u'\u0dab'.encode('utf8')
1994
        lines = [' '.join([r2, r11, r12]), r11, r12]
1995
        encoded_body = '\n'.join(lines)
1996
1997
        transport_path = 'sinhala'
1998
        repo, client = self.setup_fake_client_and_repository(transport_path)
1999
        client.add_success_response_with_body(encoded_body, 'ok')
2000
        result = repo._get_revision_graph(r2)
2001
        self.assertEqual(
2002
            [('call_expecting_body', 'Repository.get_revision_graph',
2003
             ('sinhala/', r2))],
2004
            client._calls)
2005
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
2006
2007
    def test_no_such_revision(self):
2008
        revid = '123'
2009
        transport_path = 'sinhala'
2010
        repo, client = self.setup_fake_client_and_repository(transport_path)
2011
        client.add_error_response('nosuchrevision', revid)
2012
        # also check that the right revision is reported in the error
2013
        self.assertRaises(errors.NoSuchRevision,
2014
            repo._get_revision_graph, revid)
2015
        self.assertEqual(
2016
            [('call_expecting_body', 'Repository.get_revision_graph',
2017
             ('sinhala/', revid))],
2018
            client._calls)
2019
2020
    def test_unexpected_error(self):
2021
        revid = '123'
2022
        transport_path = 'sinhala'
2023
        repo, client = self.setup_fake_client_and_repository(transport_path)
2024
        client.add_error_response('AnUnexpectedError')
2025
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
2026
            repo._get_revision_graph, revid)
2027
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
2028
2029
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2030
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
2031
2032
    def test_ok(self):
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2033
        repo, client = self.setup_fake_client_and_repository('quack')
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2034
        client.add_expected_call(
2035
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2036
            'success', ('ok', 'rev-five'))
2037
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2038
        self.assertEqual((True, 'rev-five'), result)
2039
        client.finished_test()
2040
2041
    def test_history_incomplete(self):
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2042
        repo, client = self.setup_fake_client_and_repository('quack')
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2043
        client.add_expected_call(
2044
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2045
            'success', ('history-incomplete', 10, 'rev-ten'))
2046
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2047
        self.assertEqual((False, (10, 'rev-ten')), result)
2048
        client.finished_test()
2049
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2050
    def test_history_incomplete_with_fallback(self):
2051
        """A 'history-incomplete' response causes the fallback repository to be
2052
        queried too, if one is set.
2053
        """
2054
        # Make a repo with a fallback repo, both using a FakeClient.
2055
        format = remote.response_tuple_to_repo_format(
2056
            ('yes', 'no', 'yes', 'fake-network-name'))
2057
        repo, client = self.setup_fake_client_and_repository('quack')
2058
        repo._format = format
2059
        fallback_repo, ignored = self.setup_fake_client_and_repository(
2060
            'fallback')
2061
        fallback_repo._client = client
2062
        repo.add_fallback_repository(fallback_repo)
2063
        # First the client should ask the primary repo
2064
        client.add_expected_call(
2065
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
2066
            'success', ('history-incomplete', 2, 'rev-two'))
2067
        # Then it should ask the fallback, using revno/revid from the
2068
        # history-incomplete response as the known revno/revid.
2069
        client.add_expected_call(
2070
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
2071
            'success', ('ok', 'rev-one'))
2072
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
2073
        self.assertEqual((True, 'rev-one'), result)
2074
        client.finished_test()
2075
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2076
    def test_nosuchrevision(self):
2077
        # 'nosuchrevision' is returned when the known-revid is not found in the
2078
        # remote repo.  The client translates that response to NoSuchRevision.
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2079
        repo, client = self.setup_fake_client_and_repository('quack')
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2080
        client.add_expected_call(
2081
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2082
            'error', ('nosuchrevision', 'rev-foo'))
2083
        self.assertRaises(
2084
            errors.NoSuchRevision,
2085
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
2086
        client.finished_test()
2087
2088
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
2089
class TestRepositoryIsShared(TestRemoteRepository):
2090
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2091
    def test_is_shared(self):
2092
        # ('yes', ) for Repository.is_shared -> 'True'.
2093
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2094
        repo, client = self.setup_fake_client_and_repository(transport_path)
2095
        client.add_success_response('yes')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2096
        result = repo.is_shared()
2097
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2098
            [('call', 'Repository.is_shared', ('quack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2099
            client._calls)
2100
        self.assertEqual(True, result)
2101
2102
    def test_is_not_shared(self):
2103
        # ('no', ) for Repository.is_shared -> 'False'.
2104
        transport_path = 'qwack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2105
        repo, client = self.setup_fake_client_and_repository(transport_path)
2106
        client.add_success_response('no')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2107
        result = repo.is_shared()
2108
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2109
            [('call', 'Repository.is_shared', ('qwack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2110
            client._calls)
2111
        self.assertEqual(False, result)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2112
2113
2114
class TestRepositoryLockWrite(TestRemoteRepository):
2115
2116
    def test_lock_write(self):
2117
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2118
        repo, client = self.setup_fake_client_and_repository(transport_path)
2119
        client.add_success_response('ok', 'a token')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2120
        result = repo.lock_write()
2121
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2122
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2123
            client._calls)
2124
        self.assertEqual('a token', result)
2125
2126
    def test_lock_write_already_locked(self):
2127
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2128
        repo, client = self.setup_fake_client_and_repository(transport_path)
2129
        client.add_error_response('LockContention')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2130
        self.assertRaises(errors.LockContention, repo.lock_write)
2131
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2132
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
2133
            client._calls)
2134
2135
    def test_lock_write_unlockable(self):
2136
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2137
        repo, client = self.setup_fake_client_and_repository(transport_path)
2138
        client.add_error_response('UnlockableTransport')
2018.5.95 by Andrew Bennetts
Add a Transport.is_readonly remote call, let {Branch,Repository}.lock_write remote call return UnlockableTransport, and miscellaneous test fixes.
2139
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
2140
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2141
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2142
            client._calls)
2143
2144
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2145
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
2146
2147
    def test_backwards_compat(self):
2148
        self.setup_smart_server_with_call_log()
2149
        repo = self.make_repository('.')
2150
        self.reset_smart_call_log()
2151
        verb = 'Repository.set_make_working_trees'
2152
        self.disable_verb(verb)
2153
        repo.set_make_working_trees(True)
2154
        call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
2155
            call.call.method == verb])
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2156
        self.assertEqual(1, call_count)
2157
2158
    def test_current(self):
2159
        transport_path = 'quack'
2160
        repo, client = self.setup_fake_client_and_repository(transport_path)
2161
        client.add_expected_call(
2162
            'Repository.set_make_working_trees', ('quack/', 'True'),
2163
            'success', ('ok',))
2164
        client.add_expected_call(
2165
            'Repository.set_make_working_trees', ('quack/', 'False'),
2166
            'success', ('ok',))
2167
        repo.set_make_working_trees(True)
2168
        repo.set_make_working_trees(False)
2169
2170
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2171
class TestRepositoryUnlock(TestRemoteRepository):
2172
2173
    def test_unlock(self):
2174
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2175
        repo, client = self.setup_fake_client_and_repository(transport_path)
2176
        client.add_success_response('ok', 'a token')
2177
        client.add_success_response('ok')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2178
        repo.lock_write()
2179
        repo.unlock()
2180
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2181
            [('call', 'Repository.lock_write', ('quack/', '')),
2182
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2183
            client._calls)
2184
2185
    def test_unlock_wrong_token(self):
2186
        # If somehow the token is wrong, unlock will raise TokenMismatch.
2187
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2188
        repo, client = self.setup_fake_client_and_repository(transport_path)
2189
        client.add_success_response('ok', 'a token')
2190
        client.add_error_response('TokenMismatch')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2191
        repo.lock_write()
2192
        self.assertRaises(errors.TokenMismatch, repo.unlock)
2193
2194
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2195
class TestRepositoryHasRevision(TestRemoteRepository):
2196
2197
    def test_none(self):
2198
        # repo.has_revision(None) should not cause any traffic.
2199
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2200
        repo, client = self.setup_fake_client_and_repository(transport_path)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2201
2202
        # The null revision is always there, so has_revision(None) == True.
3172.3.3 by Robert Collins
Missed one occurence of None -> NULL_REVISION.
2203
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2204
2205
        # The remote repo shouldn't be accessed.
2206
        self.assertEqual([], client._calls)
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2207
2208
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2209
class TestRepositoryInsertStream(TestRemoteRepository):
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2210
    """Tests for using Repository.insert_stream verb when the _1.18 variant is
2211
    not available.
2212
2213
    This test case is very similar to TestRepositoryInsertStream_1_18.
2214
    """
2215
2216
    def setUp(self):
2217
        TestRemoteRepository.setUp(self)
2218
        self.disable_verb('Repository.insert_stream_1.18')
2219
2220
    def test_unlocked_repo(self):
2221
        transport_path = 'quack'
2222
        repo, client = self.setup_fake_client_and_repository(transport_path)
2223
        client.add_expected_call(
2224
            'Repository.insert_stream_1.18', ('quack/', ''),
2225
            'unknown', ('Repository.insert_stream_1.18',))
2226
        client.add_expected_call(
2227
            'Repository.insert_stream', ('quack/', ''),
2228
            'success', ('ok',))
2229
        client.add_expected_call(
2230
            'Repository.insert_stream', ('quack/', ''),
2231
            'success', ('ok',))
2232
        sink = repo._get_sink()
2233
        fmt = repository.RepositoryFormat.get_default_format()
2234
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2235
        self.assertEqual([], resume_tokens)
2236
        self.assertEqual(set(), missing_keys)
2237
        client.finished_test()
2238
2239
    def test_locked_repo_with_no_lock_token(self):
2240
        transport_path = 'quack'
2241
        repo, client = self.setup_fake_client_and_repository(transport_path)
2242
        client.add_expected_call(
2243
            'Repository.lock_write', ('quack/', ''),
2244
            'success', ('ok', ''))
2245
        client.add_expected_call(
2246
            'Repository.insert_stream_1.18', ('quack/', ''),
2247
            'unknown', ('Repository.insert_stream_1.18',))
2248
        client.add_expected_call(
2249
            'Repository.insert_stream', ('quack/', ''),
2250
            'success', ('ok',))
2251
        client.add_expected_call(
2252
            'Repository.insert_stream', ('quack/', ''),
2253
            'success', ('ok',))
2254
        repo.lock_write()
2255
        sink = repo._get_sink()
2256
        fmt = repository.RepositoryFormat.get_default_format()
2257
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2258
        self.assertEqual([], resume_tokens)
2259
        self.assertEqual(set(), missing_keys)
2260
        client.finished_test()
2261
2262
    def test_locked_repo_with_lock_token(self):
2263
        transport_path = 'quack'
2264
        repo, client = self.setup_fake_client_and_repository(transport_path)
2265
        client.add_expected_call(
2266
            'Repository.lock_write', ('quack/', ''),
2267
            'success', ('ok', 'a token'))
2268
        client.add_expected_call(
2269
            'Repository.insert_stream_1.18', ('quack/', '', 'a token'),
2270
            'unknown', ('Repository.insert_stream_1.18',))
2271
        client.add_expected_call(
2272
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2273
            'success', ('ok',))
2274
        client.add_expected_call(
2275
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2276
            'success', ('ok',))
2277
        repo.lock_write()
2278
        sink = repo._get_sink()
2279
        fmt = repository.RepositoryFormat.get_default_format()
2280
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2281
        self.assertEqual([], resume_tokens)
2282
        self.assertEqual(set(), missing_keys)
2283
        client.finished_test()
2284
2285
2286
class TestRepositoryInsertStream_1_18(TestRemoteRepository):
2287
2288
    def test_unlocked_repo(self):
2289
        transport_path = 'quack'
2290
        repo, client = self.setup_fake_client_and_repository(transport_path)
2291
        client.add_expected_call(
2292
            'Repository.insert_stream_1.18', ('quack/', ''),
2293
            'success', ('ok',))
2294
        client.add_expected_call(
2295
            'Repository.insert_stream_1.18', ('quack/', ''),
2296
            'success', ('ok',))
2297
        sink = repo._get_sink()
2298
        fmt = repository.RepositoryFormat.get_default_format()
2299
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2300
        self.assertEqual([], resume_tokens)
2301
        self.assertEqual(set(), missing_keys)
2302
        client.finished_test()
2303
2304
    def test_locked_repo_with_no_lock_token(self):
2305
        transport_path = 'quack'
2306
        repo, client = self.setup_fake_client_and_repository(transport_path)
2307
        client.add_expected_call(
2308
            'Repository.lock_write', ('quack/', ''),
2309
            'success', ('ok', ''))
2310
        client.add_expected_call(
2311
            'Repository.insert_stream_1.18', ('quack/', ''),
2312
            'success', ('ok',))
2313
        client.add_expected_call(
2314
            'Repository.insert_stream_1.18', ('quack/', ''),
2315
            'success', ('ok',))
2316
        repo.lock_write()
2317
        sink = repo._get_sink()
2318
        fmt = repository.RepositoryFormat.get_default_format()
2319
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2320
        self.assertEqual([], resume_tokens)
2321
        self.assertEqual(set(), missing_keys)
2322
        client.finished_test()
2323
2324
    def test_locked_repo_with_lock_token(self):
2325
        transport_path = 'quack'
2326
        repo, client = self.setup_fake_client_and_repository(transport_path)
2327
        client.add_expected_call(
2328
            'Repository.lock_write', ('quack/', ''),
2329
            'success', ('ok', 'a token'))
2330
        client.add_expected_call(
2331
            'Repository.insert_stream_1.18', ('quack/', '', 'a token'),
2332
            'success', ('ok',))
2333
        client.add_expected_call(
2334
            'Repository.insert_stream_1.18', ('quack/', '', 'a token'),
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2335
            'success', ('ok',))
2336
        repo.lock_write()
2337
        sink = repo._get_sink()
2338
        fmt = repository.RepositoryFormat.get_default_format()
2339
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2340
        self.assertEqual([], resume_tokens)
2341
        self.assertEqual(set(), missing_keys)
2342
        client.finished_test()
2343
2344
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2345
class TestRepositoryTarball(TestRemoteRepository):
2346
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2347
    # This is a canned tarball reponse we can validate against
2018.18.18 by Martin Pool
reformat
2348
    tarball_content = (
2018.18.23 by Martin Pool
review cleanups
2349
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
2350
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
2351
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
2352
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
2353
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
2354
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
2355
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
2356
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
2357
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
2358
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
2359
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
2360
        'nWQ7QH/F3JFOFCQ0aSPfA='
2361
        ).decode('base64')
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2362
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2363
    def test_repository_tarball(self):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2364
        # Test that Repository.tarball generates the right operations
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2365
        transport_path = 'repo'
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
2366
        expected_calls = [('call_expecting_body', 'Repository.tarball',
3104.4.2 by Andrew Bennetts
All tests passing.
2367
                           ('repo/', 'bz2',),),
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2368
            ]
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2369
        repo, client = self.setup_fake_client_and_repository(transport_path)
2370
        client.add_success_response_with_body(self.tarball_content, 'ok')
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2371
        # Now actually ask for the tarball
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2372
        tarball_file = repo._get_tarball('bz2')
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2373
        try:
2374
            self.assertEqual(expected_calls, client._calls)
2375
            self.assertEqual(self.tarball_content, tarball_file.read())
2376
        finally:
2377
            tarball_file.close()
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2378
2379
2380
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
2381
    """RemoteRepository.copy_content_into optimizations"""
2382
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
2383
    def test_copy_content_remote_to_local(self):
2384
        self.transport_server = server.SmartTCPServer_for_testing
2385
        src_repo = self.make_repository('repo1')
2386
        src_repo = repository.Repository.open(self.get_url('repo1'))
2387
        # At the moment the tarball-based copy_content_into can't write back
2388
        # into a smart server.  It would be good if it could upload the
2389
        # tarball; once that works we'd have to create repositories of
2390
        # different formats. -- mbp 20070410
2391
        dest_url = self.get_vfs_only_url('repo2')
2392
        dest_bzrdir = BzrDir.create(dest_url)
2393
        dest_repo = dest_bzrdir.create_repository()
2394
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
2395
        self.assertTrue(isinstance(src_repo, RemoteRepository))
2396
        src_repo.copy_content_into(dest_repo)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2397
2398
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2399
class _StubRealPackRepository(object):
2400
2401
    def __init__(self, calls):
4145.1.6 by Robert Collins
More test fallout, but all caught now.
2402
        self.calls = calls
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2403
        self._pack_collection = _StubPackCollection(calls)
2404
4145.1.6 by Robert Collins
More test fallout, but all caught now.
2405
    def is_in_write_group(self):
2406
        return False
2407
2408
    def refresh_data(self):
2409
        self.calls.append(('pack collection reload_pack_names',))
2410
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2411
2412
class _StubPackCollection(object):
2413
2414
    def __init__(self, calls):
2415
        self.calls = calls
2416
2417
    def autopack(self):
2418
        self.calls.append(('pack collection autopack',))
2419
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2420
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2421
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
2422
    """Tests for RemoteRepository.autopack implementation."""
2423
2424
    def test_ok(self):
2425
        """When the server returns 'ok' and there's no _real_repository, then
2426
        nothing else happens: the autopack method is done.
2427
        """
2428
        transport_path = 'quack'
2429
        repo, client = self.setup_fake_client_and_repository(transport_path)
2430
        client.add_expected_call(
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
2431
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2432
        repo.autopack()
2433
        client.finished_test()
2434
2435
    def test_ok_with_real_repo(self):
2436
        """When the server returns 'ok' and there is a _real_repository, then
2437
        the _real_repository's reload_pack_name's method will be called.
2438
        """
2439
        transport_path = 'quack'
2440
        repo, client = self.setup_fake_client_and_repository(transport_path)
2441
        client.add_expected_call(
2442
            'PackRepository.autopack', ('quack/',),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
2443
            'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2444
        repo._real_repository = _StubRealPackRepository(client._calls)
2445
        repo.autopack()
2446
        self.assertEqual(
2447
            [('call', 'PackRepository.autopack', ('quack/',)),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
2448
             ('pack collection reload_pack_names',)],
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2449
            client._calls)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2450
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2451
    def test_backwards_compatibility(self):
2452
        """If the server does not recognise the PackRepository.autopack verb,
2453
        fallback to the real_repository's implementation.
2454
        """
2455
        transport_path = 'quack'
2456
        repo, client = self.setup_fake_client_and_repository(transport_path)
2457
        client.add_unknown_method_response('PackRepository.autopack')
2458
        def stub_ensure_real():
2459
            client._calls.append(('_ensure_real',))
2460
            repo._real_repository = _StubRealPackRepository(client._calls)
2461
        repo._ensure_real = stub_ensure_real
2462
        repo.autopack()
2463
        self.assertEqual(
2464
            [('call', 'PackRepository.autopack', ('quack/',)),
2465
             ('_ensure_real',),
2466
             ('pack collection autopack',)],
2467
            client._calls)
2468
2469
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2470
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
2471
    """Base class for unit tests for bzrlib.remote._translate_error."""
2472
2473
    def translateTuple(self, error_tuple, **context):
2474
        """Call _translate_error with an ErrorFromSmartServer built from the
2475
        given error_tuple.
2476
2477
        :param error_tuple: A tuple of a smart server response, as would be
2478
            passed to an ErrorFromSmartServer.
2479
        :kwargs context: context items to call _translate_error with.
2480
2481
        :returns: The error raised by _translate_error.
2482
        """
2483
        # Raise the ErrorFromSmartServer before passing it as an argument,
2484
        # because _translate_error may need to re-raise it with a bare 'raise'
2485
        # statement.
2486
        server_error = errors.ErrorFromSmartServer(error_tuple)
2487
        translated_error = self.translateErrorFromSmartServer(
2488
            server_error, **context)
2489
        return translated_error
2490
2491
    def translateErrorFromSmartServer(self, error_object, **context):
2492
        """Like translateTuple, but takes an already constructed
2493
        ErrorFromSmartServer rather than a tuple.
2494
        """
2495
        try:
2496
            raise error_object
2497
        except errors.ErrorFromSmartServer, server_error:
2498
            translated_error = self.assertRaises(
2499
                errors.BzrError, remote._translate_error, server_error,
2500
                **context)
2501
        return translated_error
2502
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2503
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2504
class TestErrorTranslationSuccess(TestErrorTranslationBase):
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2505
    """Unit tests for bzrlib.remote._translate_error.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2506
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2507
    Given an ErrorFromSmartServer (which has an error tuple from a smart
2508
    server) and some context, _translate_error raises more specific errors from
2509
    bzrlib.errors.
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2510
2511
    This test case covers the cases where _translate_error succeeds in
2512
    translating an ErrorFromSmartServer to something better.  See
2513
    TestErrorTranslationRobustness for other cases.
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2514
    """
2515
2516
    def test_NoSuchRevision(self):
2517
        branch = self.make_branch('')
2518
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2519
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2520
            ('NoSuchRevision', revid), branch=branch)
2521
        expected_error = errors.NoSuchRevision(branch, revid)
2522
        self.assertEqual(expected_error, translated_error)
2523
2524
    def test_nosuchrevision(self):
2525
        repository = self.make_repository('')
2526
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2527
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2528
            ('nosuchrevision', revid), repository=repository)
2529
        expected_error = errors.NoSuchRevision(repository, revid)
2530
        self.assertEqual(expected_error, translated_error)
2531
2532
    def test_nobranch(self):
2533
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2534
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2535
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
2536
        self.assertEqual(expected_error, translated_error)
2537
2538
    def test_LockContention(self):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2539
        translated_error = self.translateTuple(('LockContention',))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2540
        expected_error = errors.LockContention('(remote lock)')
2541
        self.assertEqual(expected_error, translated_error)
2542
2543
    def test_UnlockableTransport(self):
2544
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2545
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2546
            ('UnlockableTransport',), bzrdir=bzrdir)
2547
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
2548
        self.assertEqual(expected_error, translated_error)
2549
2550
    def test_LockFailed(self):
2551
        lock = 'str() of a server lock'
2552
        why = 'str() of why'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2553
        translated_error = self.translateTuple(('LockFailed', lock, why))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2554
        expected_error = errors.LockFailed(lock, why)
2555
        self.assertEqual(expected_error, translated_error)
2556
2557
    def test_TokenMismatch(self):
2558
        token = 'a lock token'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2559
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2560
        expected_error = errors.TokenMismatch(token, '(remote token)')
2561
        self.assertEqual(expected_error, translated_error)
2562
2563
    def test_Diverged(self):
2564
        branch = self.make_branch('a')
2565
        other_branch = self.make_branch('b')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2566
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2567
            ('Diverged',), branch=branch, other_branch=other_branch)
2568
        expected_error = errors.DivergedBranches(branch, other_branch)
2569
        self.assertEqual(expected_error, translated_error)
2570
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
2571
    def test_ReadError_no_args(self):
2572
        path = 'a path'
2573
        translated_error = self.translateTuple(('ReadError',), path=path)
2574
        expected_error = errors.ReadError(path)
2575
        self.assertEqual(expected_error, translated_error)
2576
2577
    def test_ReadError(self):
2578
        path = 'a path'
2579
        translated_error = self.translateTuple(('ReadError', path))
2580
        expected_error = errors.ReadError(path)
2581
        self.assertEqual(expected_error, translated_error)
2582
2583
    def test_PermissionDenied_no_args(self):
2584
        path = 'a path'
2585
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
2586
        expected_error = errors.PermissionDenied(path)
2587
        self.assertEqual(expected_error, translated_error)
2588
2589
    def test_PermissionDenied_one_arg(self):
2590
        path = 'a path'
2591
        translated_error = self.translateTuple(('PermissionDenied', path))
2592
        expected_error = errors.PermissionDenied(path)
2593
        self.assertEqual(expected_error, translated_error)
2594
2595
    def test_PermissionDenied_one_arg_and_context(self):
2596
        """Given a choice between a path from the local context and a path on
2597
        the wire, _translate_error prefers the path from the local context.
2598
        """
2599
        local_path = 'local path'
2600
        remote_path = 'remote path'
2601
        translated_error = self.translateTuple(
2602
            ('PermissionDenied', remote_path), path=local_path)
2603
        expected_error = errors.PermissionDenied(local_path)
2604
        self.assertEqual(expected_error, translated_error)
2605
2606
    def test_PermissionDenied_two_args(self):
2607
        path = 'a path'
2608
        extra = 'a string with extra info'
2609
        translated_error = self.translateTuple(
2610
            ('PermissionDenied', path, extra))
2611
        expected_error = errors.PermissionDenied(path, extra)
2612
        self.assertEqual(expected_error, translated_error)
2613
2614
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2615
class TestErrorTranslationRobustness(TestErrorTranslationBase):
2616
    """Unit tests for bzrlib.remote._translate_error's robustness.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2617
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2618
    TestErrorTranslationSuccess is for cases where _translate_error can
2619
    translate successfully.  This class about how _translate_err behaves when
2620
    it fails to translate: it re-raises the original error.
2621
    """
2622
2623
    def test_unrecognised_server_error(self):
2624
        """If the error code from the server is not recognised, the original
2625
        ErrorFromSmartServer is propagated unmodified.
2626
        """
2627
        error_tuple = ('An unknown error tuple',)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2628
        server_error = errors.ErrorFromSmartServer(error_tuple)
2629
        translated_error = self.translateErrorFromSmartServer(server_error)
2630
        expected_error = errors.UnknownErrorFromSmartServer(server_error)
3690.1.1 by Andrew Bennetts
Unexpected error responses from a smart server no longer cause the client to traceback.
2631
        self.assertEqual(expected_error, translated_error)
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2632
2633
    def test_context_missing_a_key(self):
2634
        """In case of a bug in the client, or perhaps an unexpected response
2635
        from a server, _translate_error returns the original error tuple from
2636
        the server and mutters a warning.
2637
        """
2638
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
2639
        # in the context dict.  So let's give it an empty context dict instead
2640
        # to exercise its error recovery.
2641
        empty_context = {}
2642
        error_tuple = ('NoSuchRevision', 'revid')
2643
        server_error = errors.ErrorFromSmartServer(error_tuple)
2644
        translated_error = self.translateErrorFromSmartServer(server_error)
2645
        self.assertEqual(server_error, translated_error)
2646
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2647
        # been muttered to the log file for developer to look at.
2648
        self.assertContainsRe(
2649
            self._get_log(keep_log_file=True),
2650
            "Missing key 'branch' in context")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2651
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
2652
    def test_path_missing(self):
2653
        """Some translations (PermissionDenied, ReadError) can determine the
2654
        'path' variable from either the wire or the local context.  If neither
2655
        has it, then an error is raised.
2656
        """
2657
        error_tuple = ('ReadError',)
2658
        server_error = errors.ErrorFromSmartServer(error_tuple)
2659
        translated_error = self.translateErrorFromSmartServer(server_error)
2660
        self.assertEqual(server_error, translated_error)
2661
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2662
        # been muttered to the log file for developer to look at.
2663
        self.assertContainsRe(
2664
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
2665
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
2666
2667
class TestStacking(tests.TestCaseWithTransport):
2668
    """Tests for operations on stacked remote repositories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2669
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
2670
    The underlying format type must support stacking.
2671
    """
2672
2673
    def test_access_stacked_remote(self):
2674
        # based on <http://launchpad.net/bugs/261315>
2675
        # make a branch stacked on another repository containing an empty
2676
        # revision, then open it over hpss - we should be able to see that
2677
        # revision.
2678
        base_transport = self.get_transport()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2679
        base_builder = self.make_branch_builder('base', format='1.9')
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
2680
        base_builder.start_series()
2681
        base_revid = base_builder.build_snapshot('rev-id', None,
2682
            [('add', ('', None, 'directory', None))],
2683
            'message')
2684
        base_builder.finish_series()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2685
        stacked_branch = self.make_branch('stacked', format='1.9')
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
2686
        stacked_branch.set_stacked_on_url('../base')
2687
        # start a server looking at this
2688
        smart_server = server.SmartTCPServer_for_testing()
2689
        smart_server.setUp()
2690
        self.addCleanup(smart_server.tearDown)
2691
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
2692
        # can get its branch and repository
2693
        remote_branch = remote_bzrdir.open_branch()
2694
        remote_repo = remote_branch.repository
3691.2.6 by Martin Pool
Disable RemoteBranch stacking, but get get_stacked_on_url working, and passing back exceptions
2695
        remote_repo.lock_read()
2696
        try:
2697
            # it should have an appropriate fallback repository, which should also
2698
            # be a RemoteRepository
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
2699
            self.assertLength(1, remote_repo._fallback_repositories)
3691.2.6 by Martin Pool
Disable RemoteBranch stacking, but get get_stacked_on_url working, and passing back exceptions
2700
            self.assertIsInstance(remote_repo._fallback_repositories[0],
2701
                RemoteRepository)
2702
            # and it has the revision committed to the underlying repository;
2703
            # these have varying implementations so we try several of them
2704
            self.assertTrue(remote_repo.has_revisions([base_revid]))
2705
            self.assertTrue(remote_repo.has_revision(base_revid))
2706
            self.assertEqual(remote_repo.get_revision(base_revid).message,
2707
                'message')
2708
        finally:
2709
            remote_repo.unlock()
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
2710
3835.1.7 by Aaron Bentley
Updates from review
2711
    def prepare_stacked_remote_branch(self):
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2712
        """Get stacked_upon and stacked branches with content in each."""
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2713
        self.setup_smart_server_with_call_log()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2714
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
2715
        tree1.commit('rev1', rev_id='rev1')
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2716
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
2717
            ).open_workingtree()
2718
        tree2.commit('local changes make me feel good.')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2719
        branch2 = Branch.open(self.get_url('tree2'))
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
2720
        branch2.lock_read()
2721
        self.addCleanup(branch2.unlock)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2722
        return tree1.branch, branch2
3835.1.7 by Aaron Bentley
Updates from review
2723
2724
    def test_stacked_get_parent_map(self):
2725
        # the public implementation of get_parent_map obeys stacking
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2726
        _, branch = self.prepare_stacked_remote_branch()
3835.1.7 by Aaron Bentley
Updates from review
2727
        repo = branch.repository
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
2728
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
3835.1.7 by Aaron Bentley
Updates from review
2729
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
2730
    def test_unstacked_get_parent_map(self):
2731
        # _unstacked_provider.get_parent_map ignores stacking
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2732
        _, branch = self.prepare_stacked_remote_branch()
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
2733
        provider = branch.repository._unstacked_provider
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
2734
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
2735
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2736
    def fetch_stream_to_rev_order(self, stream):
2737
        result = []
2738
        for kind, substream in stream:
2739
            if not kind == 'revisions':
2740
                list(substream)
2741
            else:
2742
                for content in substream:
2743
                    result.append(content.key[-1])
2744
        return result
2745
2746
    def get_ordered_revs(self, format, order):
2747
        """Get a list of the revisions in a stream to format format.
2748
2749
        :param format: The format of the target.
2750
        :param order: the order that target should have requested.
2751
        :result: The revision ids in the stream, in the order seen,
2752
            the topological order of revisions in the source.
2753
        """
2754
        unordered_format = bzrdir.format_registry.get(format)()
2755
        target_repository_format = unordered_format.repository_format
2756
        # Cross check
2757
        self.assertEqual(order, target_repository_format._fetch_order)
2758
        trunk, stacked = self.prepare_stacked_remote_branch()
2759
        source = stacked.repository._get_source(target_repository_format)
2760
        tip = stacked.last_revision()
2761
        revs = stacked.repository.get_ancestry(tip)
2762
        search = graph.PendingAncestryResult([tip], stacked.repository)
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2763
        self.reset_smart_call_log()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2764
        stream = source.get_stream(search)
2765
        if None in revs:
2766
            revs.remove(None)
2767
        # We trust that if a revision is in the stream the rest of the new
2768
        # content for it is too, as per our main fetch tests; here we are
2769
        # checking that the revisions are actually included at all, and their
2770
        # order.
2771
        return self.fetch_stream_to_rev_order(stream), revs
2772
2773
    def test_stacked_get_stream_unordered(self):
2774
        # Repository._get_source.get_stream() from a stacked repository with
2775
        # unordered yields the full data from both stacked and stacked upon
2776
        # sources.
2777
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2778
        self.assertEqual(set(expected_revs), set(rev_ord))
2779
        # Getting unordered results should have made a streaming data request
2780
        # from the server, then one from the backing branch.
2781
        self.assertLength(2, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2782
2783
    def test_stacked_get_stream_topological(self):
2784
        # Repository._get_source.get_stream() from a stacked repository with
2785
        # topological sorting yields the full data from both stacked and
2786
        # stacked upon sources in topological order.
2787
        rev_ord, expected_revs = self.get_ordered_revs('knit', 'topological')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2788
        self.assertEqual(expected_revs, rev_ord)
2789
        # Getting topological sort requires VFS calls still
4190.1.6 by Robert Collins
Missed some unit tests.
2790
        self.assertLength(12, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2791
2792
    def test_stacked_get_stream_groupcompress(self):
2793
        # Repository._get_source.get_stream() from a stacked repository with
2794
        # groupcompress sorting yields the full data from both stacked and
2795
        # stacked upon sources in groupcompress order.
2796
        raise tests.TestSkipped('No groupcompress ordered format available')
2797
        rev_ord, expected_revs = self.get_ordered_revs('dev5', 'groupcompress')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
2798
        self.assertEqual(expected_revs, reversed(rev_ord))
2799
        # Getting unordered results should have made a streaming data request
2800
        # from the backing branch, and one from the stacked on branch.
2801
        self.assertLength(2, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
2802
4332.2.1 by Robert Collins
Fix bug 360791 by not raising an error when a smart server is asked for more content than it has locally; the client is assumed to be monitoring what it gets.
2803
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
2804
        # When pulling some fixed amount of content that is more than the
2805
        # source has (because some is coming from a fallback branch, no error
2806
        # should be received. This was reported as bug 360791.
2807
        # Need three branches: a trunk, a stacked branch, and a preexisting
2808
        # branch pulling content from stacked and trunk.
2809
        self.setup_smart_server_with_call_log()
2810
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
2811
        r1 = trunk.commit('start')
2812
        stacked_branch = trunk.branch.create_clone_on_transport(
2813
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
2814
        local = self.make_branch('local', format='1.9-rich-root')
2815
        local.repository.fetch(stacked_branch.repository,
2816
            stacked_branch.last_revision())
2817
3834.3.2 by Andrew Bennetts
Preserve BzrBranch5's _synchronize_history code without affecting Branch or BzrBranch7; add effort test for RemoteBranch.copy_content_into.
2818
2819
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
2820
2821
    def setUp(self):
2822
        super(TestRemoteBranchEffort, self).setUp()
2823
        # Create a smart server that publishes whatever the backing VFS server
2824
        # does.
2825
        self.smart_server = server.SmartTCPServer_for_testing()
2826
        self.smart_server.setUp(self.get_server())
2827
        self.addCleanup(self.smart_server.tearDown)
2828
        # Log all HPSS calls into self.hpss_calls.
2829
        _SmartClient.hooks.install_named_hook(
2830
            'call', self.capture_hpss_call, None)
2831
        self.hpss_calls = []
2832
2833
    def capture_hpss_call(self, params):
2834
        self.hpss_calls.append(params.method)
2835
2836
    def test_copy_content_into_avoids_revision_history(self):
2837
        local = self.make_branch('local')
2838
        remote_backing_tree = self.make_branch_and_tree('remote')
2839
        remote_backing_tree.commit("Commit.")
2840
        remote_branch_url = self.smart_server.get_url() + 'remote'
2841
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
2842
        local.repository.fetch(remote_branch.repository)
2843
        self.hpss_calls = []
2844
        remote_branch.copy_content_into(local)
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
2845
        self.assertFalse('Branch.revision_history' in self.hpss_calls)