/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3407.2.2 by Martin Pool
Remove special case in RemoteBranchLockableFiles for branch.conf
1
# Copyright (C) 2006, 2007, 2008 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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
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
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,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
37
    tests,
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
38
    urlutils,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
39
    )
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
40
from bzrlib.branch import Branch
41
from bzrlib.bzrdir import BzrDir, BzrDirFormat
42
from bzrlib.remote import (
43
    RemoteBranch,
44
    RemoteBzrDir,
45
    RemoteBzrDirFormat,
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
46
    RemoteRepository,
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
47
    )
48
from bzrlib.revision import NULL_REVISION
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
49
from bzrlib.smart import server, medium
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
50
from bzrlib.smart.client import _SmartClient
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
51
from bzrlib.symbol_versioning import one_four
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
52
from bzrlib.transport import get_transport, http
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
53
from bzrlib.transport.memory import MemoryTransport
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
54
from bzrlib.transport.remote import (
55
    RemoteTransport,
56
    RemoteSSHTransport,
57
    RemoteTCPTransport,
58
)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
59
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)
60
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
61
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
62
63
    def setUp(self):
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.
64
        self.transport_server = server.SmartTCPServer_for_testing
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
65
        super(BasicRemoteObjectTests, self).setUp()
66
        self.transport = self.get_transport()
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
67
        # 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
68
        self.local_wt = BzrDir.create_standalone_workingtree('.')
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
69
2018.5.171 by Andrew Bennetts
Disconnect RemoteTransports in some tests to avoid tripping up test_strace with leftover threads from previous tests.
70
    def tearDown(self):
71
        self.transport.disconnect()
72
        tests.TestCaseWithTransport.tearDown(self)
73
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
74
    def test_create_remote_bzrdir(self):
75
        b = remote.RemoteBzrDir(self.transport)
76
        self.assertIsInstance(b, BzrDir)
77
78
    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.
79
        # open a standalone branch in the working directory
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
80
        b = remote.RemoteBzrDir(self.transport)
81
        branch = b.open_branch()
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
82
        self.assertIsInstance(branch, Branch)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
83
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
84
    def test_remote_repository(self):
85
        b = BzrDir.open_from_transport(self.transport)
86
        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.
87
        revid = u'\xc823123123'.encode('utf8')
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
88
        self.assertFalse(repo.has_revision(revid))
89
        self.local_wt.commit(message='test commit', rev_id=revid)
90
        self.assertTrue(repo.has_revision(revid))
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
91
92
    def test_remote_branch_revision_history(self):
93
        b = BzrDir.open_from_transport(self.transport).open_branch()
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
94
        self.assertEqual([], b.revision_history())
95
        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.
96
        r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
97
        self.assertEqual([r1, r2], b.revision_history())
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
98
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
99
    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)
100
        """Should open a RemoteBzrDir over a RemoteTransport"""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
101
        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.
102
        self.assertTrue(RemoteBzrDirFormat
103
                        in BzrDirFormat._control_server_formats)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
104
        self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
105
106
    def test_open_detected_smart_format(self):
107
        fmt = BzrDirFormat.find_format(self.transport)
108
        d = fmt.open(self.transport)
109
        self.assertIsInstance(d, BzrDir)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
110
2477.1.1 by Martin Pool
Add RemoteBranch repr
111
    def test_remote_branch_repr(self):
112
        b = BzrDir.open_from_transport(self.transport).open_branch()
113
        self.assertStartsWith(str(b), 'RemoteBranch(')
114
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
115
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
116
class FakeRemoteTransport(object):
117
    """This class provides the minimum support for use in place of a RemoteTransport.
118
    
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
119
    It doesn't actually transmit requests, but rather expects them to be
120
    handled by a FakeClient which holds canned responses.  It does not allow
121
    any vfs access, therefore is not suitable for testing any operation that
122
    will fallback to vfs access.  Backing the test by an instance of this
123
    class guarantees that it's - done using non-vfs operations.
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
124
    """
125
126
    _default_url = 'fakeremotetransport://host/path/'
127
128
    def __init__(self, url=None):
129
        if url is None:
130
            url = self._default_url
131
        self.base = url
132
133
    def __repr__(self):
134
        return "%r(%r)" % (self.__class__.__name__,
135
            self.base)
136
137
    def clone(self, relpath):
138
        return FakeRemoteTransport(urlutils.join(self.base, relpath))
139
140
    def get(self, relpath):
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
141
        # only get is specifically stubbed out, because it's usually the first
142
        # thing we do.  anything else will fail with an AttributeError.
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
143
        raise AssertionError("%r doesn't support file access to %r"
144
            % (self, relpath))
145
146
147
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
148
class FakeProtocol(object):
149
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
150
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
151
    def __init__(self, body, fake_client):
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
152
        self.body = body
153
        self._body_buffer = None
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
154
        self._fake_client = fake_client
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
155
156
    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.
157
        if self._body_buffer is None:
158
            self._body_buffer = StringIO(self.body)
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
159
        bytes = self._body_buffer.read(count)
160
        if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
161
            self._fake_client.expecting_body = False
162
        return bytes
163
164
    def cancel_read_body(self):
165
        self._fake_client.expecting_body = False
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
166
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
167
    def read_streamed_body(self):
168
        return self.body
169
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
170
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
171
class FakeClient(_SmartClient):
172
    """Lookalike for _SmartClient allowing testing."""
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
173
    
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
174
    def __init__(self, fake_medium_base='fake base'):
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
175
        """Create a FakeClient."""
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
176
        self.responses = []
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
177
        self._calls = []
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
178
        self.expecting_body = False
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
179
        # if non-None, this is the list of expected calls, with only the
180
        # method name and arguments included.  the body might be hard to
181
        # compute so is not included
182
        self._expected_calls = None
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
183
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
184
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
185
    def add_expected_call(self, call_name, call_args, response_type,
186
        response_args, response_body=None):
187
        if self._expected_calls is None:
188
            self._expected_calls = []
189
        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
190
        self.responses.append((response_type, response_args, response_body))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
191
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
192
    def add_success_response(self, *args):
193
        self.responses.append(('success', args, None))
194
195
    def add_success_response_with_body(self, body, *args):
196
        self.responses.append(('success', args, body))
197
198
    def add_error_response(self, *args):
199
        self.responses.append(('error', args))
200
201
    def add_unknown_method_response(self, verb):
202
        self.responses.append(('unknown', verb))
203
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
204
    def finished_test(self):
205
        if self._expected_calls:
206
            raise AssertionError("%r finished but was still expecting %r"
207
                % (self, self._expected_calls[0]))
208
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.
209
    def _get_next_response(self):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
210
        try:
211
            response_tuple = self.responses.pop(0)
212
        except IndexError, e:
213
            raise AssertionError("%r didn't expect any more calls"
214
                % (self,))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
215
        if response_tuple[0] == 'unknown':
216
            raise errors.UnknownSmartMethod(response_tuple[1])
217
        elif response_tuple[0] == 'error':
218
            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.
219
        return response_tuple
220
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
221
    def _check_call(self, method, args):
222
        if self._expected_calls is None:
223
            # the test should be updated to say what it expects
224
            return
225
        try:
226
            next_call = self._expected_calls.pop(0)
227
        except IndexError:
228
            raise AssertionError("%r didn't expect any more calls "
229
                "but got %r%r"
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
230
                % (self, method, args,))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
231
        if method != next_call[0] or args != next_call[1]:
232
            raise AssertionError("%r expected %r%r "
233
                "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
234
                % (self, next_call[0], next_call[1], method, args,))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
235
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
236
    def call(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
237
        self._check_call(method, args)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
238
        self._calls.append(('call', method, args))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
239
        return self._get_next_response()[1]
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
240
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
241
    def call_expecting_body(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
242
        self._check_call(method, args)
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
243
        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.
244
        result = self._get_next_response()
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
245
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
246
        return result[1], FakeProtocol(result[2], self)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
247
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.
248
    def call_with_body_bytes_expecting_body(self, method, args, body):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
249
        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.
250
        self._calls.append(('call_with_body_bytes_expecting_body', method,
251
            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.
252
        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.
253
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
254
        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.
255
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
256
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
257
class FakeMedium(medium.SmartClientMedium):
3104.4.2 by Andrew Bennetts
All tests passing.
258
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.
259
    def __init__(self, client_calls, base):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
260
        medium.SmartClientMedium.__init__(self, base)
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
261
        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.
262
263
    def disconnect(self):
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
264
        self._client_calls.append(('disconnect medium',))
3104.4.2 by Andrew Bennetts
All tests passing.
265
266
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.
267
class TestVfsHas(tests.TestCase):
268
269
    def test_unicode_path(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
270
        client = FakeClient('/')
271
        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.
272
        transport = RemoteTransport('bzr://localhost/', _client=client)
273
        filename = u'/hell\u00d8'.encode('utf8')
274
        result = transport.has(filename)
275
        self.assertEqual(
276
            [('call', 'has', (filename,))],
277
            client._calls)
278
        self.assertTrue(result)
279
280
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
281
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
282
    """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.
283
284
    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.
285
        """Assert that the result of
286
        SmartClientMedium.remote_path_from_transport is the expected value for
287
        a given client_base and transport_base.
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
288
        """
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
289
        client_medium = medium.SmartClientMedium(client_base)
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
290
        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.
291
        result = client_medium.remote_path_from_transport(transport)
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
292
        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.
293
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
294
    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.
295
        """SmartClientMedium.remote_path_from_transport calculates a URL for
296
        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.
297
        """
298
        self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
299
        self.assertRemotePath(
300
            'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
301
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
302
    def assertRemotePathHTTP(self, expected, transport_base, relpath):
303
        """Assert that the result of
304
        HttpTransportBase.remote_path_from_transport is the expected value for
305
        a given transport_base and relpath of that transport.  (Note that
306
        HttpTransportBase is a subclass of SmartClientMedium)
307
        """
308
        base_transport = get_transport(transport_base)
309
        client_medium = base_transport.get_smart_medium()
310
        cloned_transport = base_transport.clone(relpath)
311
        result = client_medium.remote_path_from_transport(cloned_transport)
312
        self.assertEqual(expected, result)
313
        
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
314
    def test_remote_path_from_transport_http(self):
315
        """Remote paths for HTTP transports are calculated differently to other
316
        transports.  They are just relative to the client base, not the root
317
        directory of the host.
318
        """
319
        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.
320
            self.assertRemotePathHTTP(
321
                '../xyz/', scheme + '//host/path', '../xyz/')
322
            self.assertRemotePathHTTP(
323
                'xyz/', scheme + '//host/path', 'xyz/')
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
324
325
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
326
class Test_ClientMedium_remote_is_at_least(tests.TestCase):
327
    """Tests for the behaviour of client_medium.remote_is_at_least."""
328
329
    def test_initially_unlimited(self):
330
        """A fresh medium assumes that the remote side supports all
331
        versions.
332
        """
333
        client_medium = medium.SmartClientMedium('dummy base')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
334
        self.assertFalse(client_medium._is_remote_before((99, 99)))
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
335
    
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
336
    def test__remember_remote_is_before(self):
337
        """Calling _remember_remote_is_before ratchets down the known remote
338
        version.
339
        """
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
340
        client_medium = medium.SmartClientMedium('dummy base')
341
        # Mark the remote side as being less than 1.6.  The remote side may
342
        # still be 1.5.
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
343
        client_medium._remember_remote_is_before((1, 6))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
344
        self.assertTrue(client_medium._is_remote_before((1, 6)))
345
        self.assertFalse(client_medium._is_remote_before((1, 5)))
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
346
        # Calling _remember_remote_is_before again with a lower value works.
347
        client_medium._remember_remote_is_before((1, 5))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
348
        self.assertTrue(client_medium._is_remote_before((1, 5)))
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
349
        # 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.
350
        self.assertRaises(
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
351
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
352
353
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
354
class TestBzrDirOpenBranch(tests.TestCase):
355
356
    def test_branch_present(self):
357
        transport = MemoryTransport()
358
        transport.mkdir('quack')
359
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
360
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
361
        client.add_expected_call(
362
            'BzrDir.open_branch', ('quack/',),
363
            'success', ('ok', ''))
364
        client.add_expected_call(
365
            'BzrDir.find_repositoryV2', ('quack/',),
366
            'success', ('ok', '', 'no', 'no', 'no'))
367
        client.add_expected_call(
368
            'Branch.get_stacked_on_url', ('quack/',),
369
            'error', ('NotStacked',))
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
370
        bzrdir = RemoteBzrDir(transport, _client=client)
371
        result = bzrdir.open_branch()
372
        self.assertIsInstance(result, RemoteBranch)
373
        self.assertEqual(bzrdir, result.bzrdir)
3691.2.10 by Martin Pool
Update more test_remote tests
374
        client.finished_test()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
375
376
    def test_branch_missing(self):
377
        transport = MemoryTransport()
378
        transport.mkdir('quack')
379
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
380
        client = FakeClient(transport.base)
381
        client.add_error_response('nobranch')
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
382
        bzrdir = RemoteBzrDir(transport, _client=client)
383
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
384
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
385
            [('call', 'BzrDir.open_branch', ('quack/',))],
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
386
            client._calls)
387
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
388
    def test__get_tree_branch(self):
389
        # _get_tree_branch is a form of open_branch, but it should only ask for
390
        # branch opening, not any other network requests.
391
        calls = []
392
        def open_branch():
393
            calls.append("Called")
394
            return "a-branch"
395
        transport = MemoryTransport()
396
        # 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.
397
        client = FakeClient(transport.base)
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
398
        bzrdir = RemoteBzrDir(transport, _client=client)
399
        # patch the open_branch call to record that it was called.
400
        bzrdir.open_branch = open_branch
401
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
402
        self.assertEqual(["Called"], calls)
403
        self.assertEqual([], client._calls)
404
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.
405
    def test_url_quoting_of_path(self):
406
        # Relpaths on the wire should not be URL-escaped.  So "~" should be
407
        # 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.
408
        transport = RemoteTCPTransport('bzr://localhost/~hello/')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
409
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
410
        client.add_expected_call(
411
            'BzrDir.open_branch', ('~hello/',),
412
            'success', ('ok', ''))
413
        client.add_expected_call(
414
            'BzrDir.find_repositoryV2', ('~hello/',),
415
            'success', ('ok', '', 'no', 'no', 'no'))
416
        client.add_expected_call(
417
            'Branch.get_stacked_on_url', ('~hello/',),
418
            'error', ('NotStacked',))
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.
419
        bzrdir = RemoteBzrDir(transport, _client=client)
420
        result = bzrdir.open_branch()
3691.2.10 by Martin Pool
Update more test_remote tests
421
        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.
422
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
423
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
3104.4.2 by Andrew Bennetts
All tests passing.
424
        transport = MemoryTransport()
425
        transport.mkdir('quack')
426
        transport = transport.clone('quack')
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
427
        if rich_root:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
428
            rich_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
429
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
430
            rich_response = 'no'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
431
        if subtrees:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
432
            subtree_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
433
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
434
            subtree_response = 'no'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
435
        client = FakeClient(transport.base)
436
        client.add_success_response(
437
            'ok', '', rich_response, subtree_response, external_lookup)
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
438
        bzrdir = RemoteBzrDir(transport, _client=client)
439
        result = bzrdir.open_repository()
440
        self.assertEqual(
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
441
            [('call', 'BzrDir.find_repositoryV2', ('quack/',))],
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
442
            client._calls)
443
        self.assertIsInstance(result, RemoteRepository)
444
        self.assertEqual(bzrdir, result.bzrdir)
445
        self.assertEqual(rich_root, result._format.rich_root_data)
2018.5.138 by Robert Collins
Merge bzr.dev.
446
        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.
447
448
    def test_open_repository_sets_format_attributes(self):
449
        self.check_open_repository(True, True)
450
        self.check_open_repository(False, True)
451
        self.check_open_repository(True, False)
452
        self.check_open_repository(False, False)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
453
        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.
454
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
455
    def test_old_server(self):
456
        """RemoteBzrDirFormat should fail to probe if the server version is too
457
        old.
458
        """
459
        self.assertRaises(errors.NotBranchError,
460
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
461
462
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.
463
class TestBzrDirOpenRepository(tests.TestCase):
464
465
    def test_backwards_compat_1_2(self):
466
        transport = MemoryTransport()
467
        transport.mkdir('quack')
468
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
469
        client = FakeClient(transport.base)
470
        client.add_unknown_method_response('RemoteRepository.find_repositoryV2')
471
        client.add_success_response('ok', '', 'no', 'no')
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.
472
        bzrdir = RemoteBzrDir(transport, _client=client)
473
        repo = bzrdir.open_repository()
474
        self.assertEqual(
475
            [('call', 'BzrDir.find_repositoryV2', ('quack/',)),
476
             ('call', 'BzrDir.find_repository', ('quack/',))],
477
            client._calls)
478
479
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
480
class OldSmartClient(object):
481
    """A fake smart client for test_old_version that just returns a version one
482
    response to the 'hello' (query version) command.
483
    """
484
485
    def get_request(self):
486
        input_file = StringIO('ok\x011\n')
487
        output_file = StringIO()
488
        client_medium = medium.SmartSimplePipesClientMedium(
489
            input_file, output_file)
490
        return medium.SmartClientStreamMediumRequest(client_medium)
491
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
492
    def protocol_version(self):
493
        return 1
494
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
495
496
class OldServerTransport(object):
497
    """A fake transport for test_old_server that reports it's smart server
498
    protocol version as version one.
499
    """
500
501
    def __init__(self):
502
        self.base = 'fake:'
503
504
    def get_smart_client(self):
505
        return OldSmartClient()
506
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
507
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
508
class RemoteBranchTestCase(tests.TestCase):
509
510
    def make_remote_branch(self, transport, client):
511
        """Make a RemoteBranch using 'client' as its _SmartClient.
512
        
513
        A RemoteBzrDir and RemoteRepository will also be created to fill out
514
        the RemoteBranch, albeit with stub values for some of their attributes.
515
        """
516
        # we do not want bzrdir to make any remote calls, so use False as its
517
        # _client.  If it tries to make a remote call, this will fail
518
        # immediately.
519
        bzrdir = RemoteBzrDir(transport, _client=False)
520
        repo = RemoteRepository(bzrdir, None, _client=client)
521
        return RemoteBranch(bzrdir, repo, _client=client)
522
523
524
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
525
526
    def test_empty_branch(self):
527
        # in an empty branch we decode the response properly
528
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
529
        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
530
        client.add_expected_call(
531
            'Branch.get_stacked_on_url', ('quack/',),
532
            'error', ('NotStacked',))
533
        client.add_expected_call(
534
            'Branch.last_revision_info', ('quack/',),
535
            'success', ('ok', '0', 'null:'))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
536
        transport.mkdir('quack')
537
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
538
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
539
        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
540
        client.finished_test()
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
541
        self.assertEqual((0, NULL_REVISION), result)
542
543
    def test_non_empty_branch(self):
544
        # 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.
545
        revid = u'\xc8'.encode('utf8')
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
546
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
547
        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
548
        client.add_expected_call(
549
            'Branch.get_stacked_on_url', ('kwaak/',),
550
            'error', ('NotStacked',))
551
        client.add_expected_call(
552
            'Branch.last_revision_info', ('kwaak/',),
553
            'success', ('ok', '2', revid))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
554
        transport.mkdir('kwaak')
555
        transport = transport.clone('kwaak')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
556
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
557
        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.
558
        self.assertEqual((2, revid), result)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
559
560
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
561
class TestBranch_get_stacked_on_url(tests.TestCaseWithMemoryTransport):
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
562
    """Test Branch._get_stacked_on_url rpc"""
563
3691.2.10 by Martin Pool
Update more test_remote tests
564
    def test_get_stacked_on_invalid_url(self):
565
        raise tests.KnownFailure('opening a branch requires the server to open the fallback repository')
566
        transport = FakeRemoteTransport('fakeremotetransport:///')
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
567
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
568
        client.add_expected_call(
569
            'Branch.get_stacked_on_url', ('.',),
570
            'success', ('ok', 'file:///stacked/on'))
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
571
        bzrdir = RemoteBzrDir(transport, _client=client)
572
        branch = RemoteBranch(bzrdir, None, _client=client)
573
        result = branch.get_stacked_on_url()
574
        self.assertEqual(
575
            'file:///stacked/on', result)
576
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
577
    def test_backwards_compatible(self):
578
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
579
        base_branch = self.make_branch('base', format='1.6')
580
        stacked_branch = self.make_branch('stacked', format='1.6')
581
        stacked_branch.set_stacked_on_url('../base')
582
        client = FakeClient(self.get_url())
583
        client.add_expected_call(
584
            'BzrDir.open_branch', ('stacked/',),
585
            'success', ('ok', ''))
586
        client.add_expected_call(
587
            'BzrDir.find_repositoryV2', ('stacked/',),
588
            'success', ('ok', '', 'no', 'no', 'no'))
589
        # called twice, once from constructor and then again by us
590
        client.add_expected_call(
591
            'Branch.get_stacked_on_url', ('stacked/',),
592
            'unknown', ('Branch.get_stacked_on_url',))
593
        client.add_expected_call(
594
            'Branch.get_stacked_on_url', ('stacked/',),
595
            'unknown', ('Branch.get_stacked_on_url',))
596
        # this will also do vfs access, but that goes direct to the transport
597
        # and isn't seen by the FakeClient.
598
        bzrdir = RemoteBzrDir(self.get_transport('stacked'), _client=client)
599
        branch = bzrdir.open_branch()
600
        result = branch.get_stacked_on_url()
601
        self.assertEqual('../base', result)
602
        client.finished_test()
603
        # it's in the fallback list both for the RemoteRepository and its vfs
604
        # repository
605
        self.assertEqual(1, len(branch.repository._fallback_repositories))
606
        self.assertEqual(1,
607
            len(branch.repository._real_repository._fallback_repositories))
608
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
609
    def test_get_stacked_on_real_branch(self):
610
        base_branch = self.make_branch('base', format='1.6')
611
        stacked_branch = self.make_branch('stacked', format='1.6')
612
        stacked_branch.set_stacked_on_url('../base')
613
        client = FakeClient(self.get_url())
614
        client.add_expected_call(
615
            'BzrDir.open_branch', ('stacked/',),
616
            'success', ('ok', ''))
617
        client.add_expected_call(
618
            'BzrDir.find_repositoryV2', ('stacked/',),
619
            'success', ('ok', '', 'no', 'no', 'no'))
620
        # called twice, once from constructor and then again by us
621
        client.add_expected_call(
622
            'Branch.get_stacked_on_url', ('stacked/',),
623
            'success', ('ok', '../base'))
624
        client.add_expected_call(
625
            'Branch.get_stacked_on_url', ('stacked/',),
626
            'success', ('ok', '../base'))
627
        bzrdir = RemoteBzrDir(self.get_transport('stacked'), _client=client)
628
        branch = bzrdir.open_branch()
629
        result = branch.get_stacked_on_url()
630
        self.assertEqual('../base', result)
631
        client.finished_test()
632
        # it's in the fallback list both for the RemoteRepository and its vfs
633
        # repository
634
        self.assertEqual(1, len(branch.repository._fallback_repositories))
635
        self.assertEqual(1,
636
            len(branch.repository._real_repository._fallback_repositories))
637
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
638
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
639
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.
640
641
    def test_set_empty(self):
642
        # set_revision_history([]) is translated to calling
643
        # Branch.set_last_revision(path, '') on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
644
        transport = MemoryTransport()
645
        transport.mkdir('branch')
646
        transport = transport.clone('branch')
647
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
648
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
649
        client.add_expected_call(
650
            'Branch.get_stacked_on_url', ('branch/',),
651
            'error', ('NotStacked',))
652
        client.add_expected_call(
653
            'Branch.lock_write', ('branch/', '', ''),
654
            'success', ('ok', 'branch token', 'repo token'))
655
        client.add_expected_call(
656
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
657
            'success', ('ok',))
658
        client.add_expected_call(
659
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
660
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
661
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
662
        # This is a hack to work around the problem that RemoteBranch currently
663
        # unnecessarily invokes _ensure_real upon a call to lock_write.
664
        branch._ensure_real = lambda: None
665
        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.
666
        result = branch.set_revision_history([])
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
667
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
668
        self.assertEqual(None, result)
3691.2.10 by Martin Pool
Update more test_remote tests
669
        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.
670
671
    def test_set_nonempty(self):
672
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
673
        # Branch.set_last_revision(path, rev-idN) on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
674
        transport = MemoryTransport()
675
        transport.mkdir('branch')
676
        transport = transport.clone('branch')
677
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
678
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
679
        client.add_expected_call(
680
            'Branch.get_stacked_on_url', ('branch/',),
681
            'error', ('NotStacked',))
682
        client.add_expected_call(
683
            'Branch.lock_write', ('branch/', '', ''),
684
            'success', ('ok', 'branch token', 'repo token'))
685
        client.add_expected_call(
686
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
687
            'success', ('ok',))
688
        client.add_expected_call(
689
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
690
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
691
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
692
        # This is a hack to work around the problem that RemoteBranch currently
693
        # unnecessarily invokes _ensure_real upon a call to lock_write.
694
        branch._ensure_real = lambda: None
695
        # Lock the branch, reset the record of remote calls.
696
        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.
697
        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.
698
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
699
        self.assertEqual(None, result)
3691.2.10 by Martin Pool
Update more test_remote tests
700
        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.
701
702
    def test_no_such_revision(self):
703
        transport = MemoryTransport()
704
        transport.mkdir('branch')
705
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
706
        # A response of 'NoSuchRevision' is translated into an exception.
707
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
708
        client.add_expected_call(
709
            'Branch.get_stacked_on_url', ('branch/',),
710
            'error', ('NotStacked',))
711
        client.add_expected_call(
712
            'Branch.lock_write', ('branch/', '', ''),
713
            'success', ('ok', 'branch token', 'repo token'))
714
        client.add_expected_call(
715
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
716
            'error', ('NoSuchRevision', 'rev-id'))
717
        client.add_expected_call(
718
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
719
            'success', ('ok',))
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
720
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
721
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
722
        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.
723
        self.assertRaises(
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
724
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
725
        branch.unlock()
3691.2.9 by Martin Pool
Convert and update more test_remote tests
726
        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.
727
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
728
    def test_tip_change_rejected(self):
729
        """TipChangeRejected responses cause a TipChangeRejected exception to
730
        be raised.
731
        """
732
        transport = MemoryTransport()
733
        transport.mkdir('branch')
734
        transport = transport.clone('branch')
735
        client = FakeClient(transport.base)
736
        rejection_msg_unicode = u'rejection message\N{INTERROBANG}'
737
        rejection_msg_utf8 = rejection_msg_unicode.encode('utf8')
3691.2.10 by Martin Pool
Update more test_remote tests
738
        client.add_expected_call(
739
            'Branch.get_stacked_on_url', ('branch/',),
740
            'error', ('NotStacked',))
741
        client.add_expected_call(
742
            'Branch.lock_write', ('branch/', '', ''),
743
            'success', ('ok', 'branch token', 'repo token'))
744
        client.add_expected_call(
745
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
746
            'error', ('TipChangeRejected', rejection_msg_utf8))
747
        client.add_expected_call(
748
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
749
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
750
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
751
        branch._ensure_real = lambda: None
752
        branch.lock_write()
753
        self.addCleanup(branch.unlock)
754
        # The 'TipChangeRejected' error response triggered by calling
755
        # set_revision_history causes a TipChangeRejected exception.
756
        err = self.assertRaises(
757
            errors.TipChangeRejected, branch.set_revision_history, ['rev-id'])
758
        # The UTF-8 message from the response has been decoded into a unicode
759
        # object.
760
        self.assertIsInstance(err.msg, unicode)
761
        self.assertEqual(rejection_msg_unicode, err.msg)
3691.2.10 by Martin Pool
Update more test_remote tests
762
        branch.unlock()
763
        client.finished_test()
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
764
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
765
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
766
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
767
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
768
    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.
769
        # set_last_revision_info(num, 'rev-id') is translated to calling
770
        # 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'.
771
        transport = MemoryTransport()
772
        transport.mkdir('branch')
773
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
774
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
775
        # get_stacked_on_url
776
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
777
        # lock_write
778
        client.add_success_response('ok', 'branch token', 'repo token')
779
        # set_last_revision
780
        client.add_success_response('ok')
781
        # unlock
782
        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.
783
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
784
        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.
785
        # Lock the branch, reset the record of remote calls.
786
        branch.lock_write()
787
        client._calls = []
788
        result = branch.set_last_revision_info(1234, 'a-revision-id')
789
        self.assertEqual(
790
            [('call', 'Branch.set_last_revision_info',
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
791
                ('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.
792
                 '1234', 'a-revision-id'))],
793
            client._calls)
794
        self.assertEqual(None, result)
795
796
    def test_no_such_revision(self):
797
        # A response of 'NoSuchRevision' is translated into an exception.
798
        transport = MemoryTransport()
799
        transport.mkdir('branch')
800
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
801
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
802
        # get_stacked_on_url
803
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
804
        # lock_write
805
        client.add_success_response('ok', 'branch token', 'repo token')
806
        # set_last_revision
807
        client.add_error_response('NoSuchRevision', 'revid')
808
        # unlock
809
        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.
810
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
811
        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.
812
        # Lock the branch, reset the record of remote calls.
813
        branch.lock_write()
814
        client._calls = []
815
816
        self.assertRaises(
817
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
818
        branch.unlock()
819
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
820
    def lock_remote_branch(self, branch):
821
        """Trick a RemoteBranch into thinking it is locked."""
822
        branch._lock_mode = 'w'
823
        branch._lock_count = 2
824
        branch._lock_token = 'branch token'
825
        branch._repo_lock_token = 'repo token'
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
826
        branch.repository._lock_mode = 'w'
827
        branch.repository._lock_count = 2
828
        branch.repository._lock_token = 'repo token'
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
829
830
    def test_backwards_compatibility(self):
831
        """If the server does not support the Branch.set_last_revision_info
832
        verb (which is new in 1.4), then the client falls back to VFS methods.
833
        """
834
        # This test is a little messy.  Unlike most tests in this file, it
835
        # doesn't purely test what a Remote* object sends over the wire, and
836
        # how it reacts to responses from the wire.  It instead relies partly
837
        # on asserting that the RemoteBranch will call
838
        # self._real_branch.set_last_revision_info(...).
839
840
        # First, set up our RemoteBranch with a FakeClient that raises
841
        # UnknownSmartMethod, and a StubRealBranch that logs how it is called.
842
        transport = MemoryTransport()
843
        transport.mkdir('branch')
844
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
845
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
846
        client.add_expected_call(
847
            'Branch.get_stacked_on_url', ('branch/',),
848
            'error', ('NotStacked',))
849
        client.add_expected_call(
850
            'Branch.set_last_revision_info',
851
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
852
            'unknown', 'Branch.set_last_revision_info')
853
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
854
        branch = self.make_remote_branch(transport, client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
855
        class StubRealBranch(object):
856
            def __init__(self):
857
                self.calls = []
858
            def set_last_revision_info(self, revno, revision_id):
859
                self.calls.append(
860
                    ('set_last_revision_info', revno, revision_id))
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
861
            def _clear_cached_state(self):
862
                pass
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
863
        real_branch = StubRealBranch()
864
        branch._real_branch = real_branch
865
        self.lock_remote_branch(branch)
866
867
        # Call set_last_revision_info, and verify it behaved as expected.
868
        result = branch.set_last_revision_info(1234, 'a-revision-id')
869
        self.assertEqual(
870
            [('set_last_revision_info', 1234, 'a-revision-id')],
871
            real_branch.calls)
3691.2.10 by Martin Pool
Update more test_remote tests
872
        client.finished_test()
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
873
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
874
    def test_unexpected_error(self):
3697.2.6 by Martin Pool
Merge 261315 fix into 1.7 branch
875
        # If the server sends an error the client doesn't understand, it gets
876
        # turned into an UnknownErrorFromSmartServer, which is presented as a
877
        # non-internal error to the user.
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
878
        transport = MemoryTransport()
879
        transport.mkdir('branch')
880
        transport = transport.clone('branch')
881
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
882
        # get_stacked_on_url
883
        client.add_error_response('NotStacked')
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
884
        # lock_write
885
        client.add_success_response('ok', 'branch token', 'repo token')
886
        # set_last_revision
887
        client.add_error_response('UnexpectedError')
888
        # unlock
889
        client.add_success_response('ok')
890
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
891
        branch = self.make_remote_branch(transport, client)
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
892
        # Lock the branch, reset the record of remote calls.
893
        branch.lock_write()
894
        client._calls = []
895
896
        err = self.assertRaises(
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
897
            errors.UnknownErrorFromSmartServer,
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
898
            branch.set_last_revision_info, 123, 'revid')
899
        self.assertEqual(('UnexpectedError',), err.error_tuple)
900
        branch.unlock()
901
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
902
    def test_tip_change_rejected(self):
903
        """TipChangeRejected responses cause a TipChangeRejected exception to
904
        be raised.
905
        """
906
        transport = MemoryTransport()
907
        transport.mkdir('branch')
908
        transport = transport.clone('branch')
909
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
910
        # get_stacked_on_url
911
        client.add_error_response('NotStacked')
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
912
        # lock_write
913
        client.add_success_response('ok', 'branch token', 'repo token')
914
        # set_last_revision
915
        client.add_error_response('TipChangeRejected', 'rejection message')
916
        # unlock
917
        client.add_success_response('ok')
918
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
919
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
920
        # Lock the branch, reset the record of remote calls.
921
        branch.lock_write()
922
        self.addCleanup(branch.unlock)
923
        client._calls = []
924
925
        # The 'TipChangeRejected' error response triggered by calling
926
        # set_last_revision_info causes a TipChangeRejected exception.
927
        err = self.assertRaises(
928
            errors.TipChangeRejected,
929
            branch.set_last_revision_info, 123, 'revid')
930
        self.assertEqual('rejection message', err.msg)
931
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
932
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.
933
class TestBranchControlGetBranchConf(tests.TestCaseWithMemoryTransport):
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
934
    """Getting the branch configuration should use an abstract method not vfs.
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
935
    """
936
937
    def test_get_branch_conf(self):
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
938
        raise tests.KnownFailure('branch.conf is not retrieved by get_config_file')
3407.2.10 by Martin Pool
Merge trunk
939
        ## # We should see that branch.get_config() does a single rpc to get the
940
        ## # remote configuration file, abstracting away where that is stored on
941
        ## # the server.  However at the moment it always falls back to using the
942
        ## # vfs, and this would need some changes in config.py.
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
943
3407.2.10 by Martin Pool
Merge trunk
944
        ## # in an empty branch we decode the response properly
945
        ## client = FakeClient([(('ok', ), '# config file body')], self.get_url())
946
        ## # we need to make a real branch because the remote_branch.control_files
947
        ## # will trigger _ensure_real.
948
        ## branch = self.make_branch('quack')
949
        ## transport = branch.bzrdir.root_transport
950
        ## # we do not want bzrdir to make any remote calls
951
        ## bzrdir = RemoteBzrDir(transport, _client=False)
952
        ## branch = RemoteBranch(bzrdir, None, _client=client)
953
        ## config = branch.get_config()
954
        ## self.assertEqual(
955
        ##     [('call_expecting_body', 'Branch.get_config_file', ('quack/',))],
956
        ##     client._calls)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
957
958
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
959
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.
960
961
    def test_lock_write_unlockable(self):
962
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
963
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
964
        client.add_expected_call(
965
            'Branch.get_stacked_on_url', ('quack/',),
966
            'error', ('NotStacked',),)
967
        client.add_expected_call(
968
            'Branch.lock_write', ('quack/', '', ''),
969
            '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.
970
        transport.mkdir('quack')
971
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
972
        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.
973
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
974
        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.
975
976
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
977
class TestTransportIsReadonly(tests.TestCase):
978
979
    def test_true(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
980
        client = FakeClient()
981
        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.
982
        transport = RemoteTransport('bzr://example.com/', medium=False,
983
                                    _client=client)
984
        self.assertEqual(True, transport.is_readonly())
985
        self.assertEqual(
986
            [('call', 'Transport.is_readonly', ())],
987
            client._calls)
988
989
    def test_false(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
990
        client = FakeClient()
991
        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.
992
        transport = RemoteTransport('bzr://example.com/', medium=False,
993
                                    _client=client)
994
        self.assertEqual(False, transport.is_readonly())
995
        self.assertEqual(
996
            [('call', 'Transport.is_readonly', ())],
997
            client._calls)
998
999
    def test_error_from_old_server(self):
1000
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
1001
        
1002
        Clients should treat it as a "no" response, because is_readonly is only
1003
        advisory anyway (a transport could be read-write, but then the
1004
        underlying filesystem could be readonly anyway).
1005
        """
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1006
        client = FakeClient()
1007
        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.
1008
        transport = RemoteTransport('bzr://example.com/', medium=False,
1009
                                    _client=client)
1010
        self.assertEqual(False, transport.is_readonly())
1011
        self.assertEqual(
1012
            [('call', 'Transport.is_readonly', ())],
1013
            client._calls)
1014
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1015
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1016
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
1017
1018
    def test_defaults_to_none(self):
1019
        t = RemoteSSHTransport('bzr+ssh://example.com')
1020
        self.assertIs(None, t._get_credentials()[0])
1021
1022
    def test_uses_authentication_config(self):
1023
        conf = config.AuthenticationConfig()
1024
        conf._get_config().update(
1025
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
1026
            'example.com'}})
1027
        conf._save()
1028
        t = RemoteSSHTransport('bzr+ssh://example.com')
1029
        self.assertEqual('bar', t._get_credentials()[0])
1030
1031
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1032
class TestRemoteRepository(tests.TestCase):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1033
    """Base for testing RemoteRepository protocol usage.
1034
    
1035
    These tests contain frozen requests and responses.  We want any changes to 
1036
    what is sent or expected to be require a thoughtful update to these tests
1037
    because they might break compatibility with different-versioned servers.
1038
    """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1039
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1040
    def setup_fake_client_and_repository(self, transport_path):
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1041
        """Create the fake client and repository for testing with.
1042
        
1043
        There's no real server here; we just have canned responses sent
1044
        back one by one.
1045
        
1046
        :param transport_path: Path below the root of the MemoryTransport
1047
            where the repository will be created.
1048
        """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1049
        transport = MemoryTransport()
1050
        transport.mkdir(transport_path)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1051
        client = FakeClient(transport.base)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1052
        transport = transport.clone(transport_path)
1053
        # we do not want bzrdir to make any remote calls
1054
        bzrdir = RemoteBzrDir(transport, _client=False)
1055
        repo = RemoteRepository(bzrdir, None, _client=client)
1056
        return repo, client
1057
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1058
2018.12.2 by Andrew Bennetts
Remove some duplicate code in test_remote
1059
class TestRepositoryGatherStats(TestRemoteRepository):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1060
1061
    def test_revid_none(self):
1062
        # ('ok',), body with revisions and size
1063
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1064
        repo, client = self.setup_fake_client_and_repository(transport_path)
1065
        client.add_success_response_with_body(
1066
            'revisions: 2\nsize: 18\n', 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1067
        result = repo.gather_stats(None)
1068
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1069
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1070
             ('quack/','','no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1071
            client._calls)
1072
        self.assertEqual({'revisions': 2, 'size': 18}, result)
1073
1074
    def test_revid_no_committers(self):
1075
        # ('ok',), body without committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1076
        body = ('firstrev: 123456.300 3600\n'
1077
                'latestrev: 654231.400 0\n'
1078
                'revisions: 2\n'
1079
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1080
        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.
1081
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1082
        repo, client = self.setup_fake_client_and_repository(transport_path)
1083
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1084
        result = repo.gather_stats(revid)
1085
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1086
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1087
              ('quick/', revid, 'no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1088
            client._calls)
1089
        self.assertEqual({'revisions': 2, 'size': 18,
1090
                          'firstrev': (123456.300, 3600),
1091
                          'latestrev': (654231.400, 0),},
1092
                         result)
1093
1094
    def test_revid_with_committers(self):
1095
        # ('ok',), body with committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1096
        body = ('committers: 128\n'
1097
                'firstrev: 123456.300 3600\n'
1098
                'latestrev: 654231.400 0\n'
1099
                'revisions: 2\n'
1100
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1101
        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.
1102
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1103
        repo, client = self.setup_fake_client_and_repository(transport_path)
1104
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1105
        result = repo.gather_stats(revid, True)
1106
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1107
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1108
              ('buick/', revid, 'yes'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1109
            client._calls)
1110
        self.assertEqual({'revisions': 2, 'size': 18,
1111
                          'committers': 128,
1112
                          'firstrev': (123456.300, 3600),
1113
                          'latestrev': (654231.400, 0),},
1114
                         result)
1115
1116
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1117
class TestRepositoryGetGraph(TestRemoteRepository):
1118
1119
    def test_get_graph(self):
3172.5.8 by Robert Collins
Review feedback.
1120
        # get_graph returns a graph with the repository as the
1121
        # parents_provider.
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1122
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1123
        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.
1124
        graph = repo.get_graph()
3441.5.24 by Andrew Bennetts
Remove RemoteGraph experiment.
1125
        self.assertEqual(graph._parents_provider, repo)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1126
1127
1128
class TestRepositoryGetParentMap(TestRemoteRepository):
1129
1130
    def test_get_parent_map_caching(self):
1131
        # get_parent_map returns from cache until unlock()
1132
        # setup a reponse with two revisions
1133
        r1 = u'\u0e33'.encode('utf8')
1134
        r2 = u'\u0dab'.encode('utf8')
1135
        lines = [' '.join([r2, r1]), r1]
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
1136
        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.
1137
1138
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1139
        repo, client = self.setup_fake_client_and_repository(transport_path)
1140
        client.add_success_response_with_body(encoded_body, 'ok')
1141
        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.
1142
        repo.lock_read()
1143
        graph = repo.get_graph()
1144
        parents = graph.get_parent_map([r2])
1145
        self.assertEqual({r2: (r1,)}, parents)
1146
        # locking and unlocking deeper should not reset
1147
        repo.lock_read()
1148
        repo.unlock()
1149
        parents = graph.get_parent_map([r1])
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1150
        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.
1151
        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.
1152
            [('call_with_body_bytes_expecting_body',
1153
              'Repository.get_parent_map', ('quack/', r2), '\n\n0')],
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1154
            client._calls)
1155
        repo.unlock()
1156
        # now we call again, and it should use the second response.
1157
        repo.lock_read()
1158
        graph = repo.get_graph()
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1159
        parents = graph.get_parent_map([r1])
1160
        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.
1161
        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.
1162
            [('call_with_body_bytes_expecting_body',
1163
              'Repository.get_parent_map', ('quack/', r2), '\n\n0'),
1164
             ('call_with_body_bytes_expecting_body',
1165
              'Repository.get_parent_map', ('quack/', r1), '\n\n0'),
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1166
            ],
1167
            client._calls)
1168
        repo.unlock()
1169
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1170
    def test_get_parent_map_reconnects_if_unknown_method(self):
1171
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1172
        repo, client = self.setup_fake_client_and_repository(transport_path)
1173
        client.add_unknown_method_response('Repository,get_parent_map')
1174
        client.add_success_response_with_body('', 'ok')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1175
        self.assertFalse(client._medium._is_remote_before((1, 2)))
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1176
        rev_id = 'revision-id'
3297.3.5 by Andrew Bennetts
Suppress a deprecation warning.
1177
        expected_deprecations = [
1178
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1179
            'in version 1.4.']
1180
        parents = self.callDeprecated(
1181
            expected_deprecations, 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.
1182
        self.assertEqual(
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1183
            [('call_with_body_bytes_expecting_body',
1184
              'Repository.get_parent_map', ('quack/', rev_id), '\n\n0'),
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1185
             ('disconnect medium',),
1186
             ('call_expecting_body', 'Repository.get_revision_graph',
1187
              ('quack/', ''))],
1188
            client._calls)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1189
        # 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.
1190
        self.assertTrue(client._medium._is_remote_before((1, 2)))
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1191
1192
    def test_get_parent_map_fallback_parentless_node(self):
1193
        """get_parent_map falls back to get_revision_graph on old servers.  The
1194
        results from get_revision_graph are tweaked to match the get_parent_map
1195
        API.
1196
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1197
        Specifically, a {key: ()} result from get_revision_graph means "no
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1198
        parents" for that key, which in get_parent_map results should be
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1199
        represented as {key: ('null:',)}.
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1200
1201
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
1202
        """
1203
        rev_id = 'revision-id'
1204
        transport_path = 'quack'
3245.4.40 by Andrew Bennetts
Merge from bzr.dev.
1205
        repo, client = self.setup_fake_client_and_repository(transport_path)
1206
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
1207
        client._medium._remember_remote_is_before((1, 2))
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1208
        expected_deprecations = [
1209
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1210
            'in version 1.4.']
1211
        parents = self.callDeprecated(
1212
            expected_deprecations, repo.get_parent_map, [rev_id])
1213
        self.assertEqual(
1214
            [('call_expecting_body', 'Repository.get_revision_graph',
1215
             ('quack/', ''))],
1216
            client._calls)
1217
        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.
1218
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1219
    def test_get_parent_map_unexpected_response(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1220
        repo, client = self.setup_fake_client_and_repository('path')
1221
        client.add_success_response('something unexpected!')
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1222
        self.assertRaises(
1223
            errors.UnexpectedSmartServerResponse,
1224
            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.
1225
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1226
2018.5.68 by Wouter van Heyst
Merge RemoteRepository.gather_stats.
1227
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
1228
    
1229
    def test_null_revision(self):
1230
        # a null revision has the predictable result {}, we should have no wire
1231
        # traffic when calling it with this argument
1232
        transport_path = 'empty'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1233
        repo, client = self.setup_fake_client_and_repository(transport_path)
1234
        client.add_success_response('notused')
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1235
        result = self.applyDeprecated(one_four, repo.get_revision_graph,
1236
            NULL_REVISION)
2018.5.68 by Wouter van Heyst
Merge RemoteRepository.gather_stats.
1237
        self.assertEqual([], client._calls)
1238
        self.assertEqual({}, result)
1239
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1240
    def test_none_revision(self):
1241
        # with none we want the entire graph
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1242
        r1 = u'\u0e33'.encode('utf8')
1243
        r2 = u'\u0dab'.encode('utf8')
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1244
        lines = [' '.join([r2, r1]), r1]
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1245
        encoded_body = '\n'.join(lines)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1246
1247
        transport_path = 'sinhala'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1248
        repo, client = self.setup_fake_client_and_repository(transport_path)
1249
        client.add_success_response_with_body(encoded_body, 'ok')
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1250
        result = self.applyDeprecated(one_four, repo.get_revision_graph)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1251
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1252
            [('call_expecting_body', 'Repository.get_revision_graph',
3104.4.2 by Andrew Bennetts
All tests passing.
1253
             ('sinhala/', ''))],
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1254
            client._calls)
2625.8.1 by Robert Collins
LIBRARY API BREAKS:
1255
        self.assertEqual({r1: (), r2: (r1, )}, result)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1256
1257
    def test_specific_revision(self):
1258
        # with a specific revision we want the graph for that
1259
        # with none we want the entire graph
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1260
        r11 = u'\u0e33'.encode('utf8')
1261
        r12 = u'\xc9'.encode('utf8')
1262
        r2 = u'\u0dab'.encode('utf8')
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1263
        lines = [' '.join([r2, r11, r12]), r11, r12]
2018.5.106 by Andrew Bennetts
Update tests in test_remote to use utf-8 byte strings for revision IDs, rather than unicode strings.
1264
        encoded_body = '\n'.join(lines)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1265
1266
        transport_path = 'sinhala'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1267
        repo, client = self.setup_fake_client_and_repository(transport_path)
1268
        client.add_success_response_with_body(encoded_body, 'ok')
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1269
        result = self.applyDeprecated(one_four, repo.get_revision_graph, r2)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1270
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1271
            [('call_expecting_body', 'Repository.get_revision_graph',
3104.4.2 by Andrew Bennetts
All tests passing.
1272
             ('sinhala/', r2))],
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1273
            client._calls)
2625.8.1 by Robert Collins
LIBRARY API BREAKS:
1274
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1275
1276
    def test_no_such_revision(self):
1277
        revid = '123'
1278
        transport_path = 'sinhala'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1279
        repo, client = self.setup_fake_client_and_repository(transport_path)
1280
        client.add_error_response('nosuchrevision', revid)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1281
        # also check that the right revision is reported in the error
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1282
        self.assertRaises(errors.NoSuchRevision,
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1283
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1284
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1285
            [('call_expecting_body', 'Repository.get_revision_graph',
3104.4.2 by Andrew Bennetts
All tests passing.
1286
             ('sinhala/', revid))],
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1287
            client._calls)
1288
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1289
    def test_unexpected_error(self):
1290
        revid = '123'
1291
        transport_path = 'sinhala'
1292
        repo, client = self.setup_fake_client_and_repository(transport_path)
1293
        client.add_error_response('AnUnexpectedError')
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1294
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1295
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
1296
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
1297
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1298
        
1299
class TestRepositoryIsShared(TestRemoteRepository):
1300
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1301
    def test_is_shared(self):
1302
        # ('yes', ) for Repository.is_shared -> 'True'.
1303
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1304
        repo, client = self.setup_fake_client_and_repository(transport_path)
1305
        client.add_success_response('yes')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1306
        result = repo.is_shared()
1307
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1308
            [('call', 'Repository.is_shared', ('quack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1309
            client._calls)
1310
        self.assertEqual(True, result)
1311
1312
    def test_is_not_shared(self):
1313
        # ('no', ) for Repository.is_shared -> 'False'.
1314
        transport_path = 'qwack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1315
        repo, client = self.setup_fake_client_and_repository(transport_path)
1316
        client.add_success_response('no')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1317
        result = repo.is_shared()
1318
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1319
            [('call', 'Repository.is_shared', ('qwack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1320
            client._calls)
1321
        self.assertEqual(False, result)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1322
1323
1324
class TestRepositoryLockWrite(TestRemoteRepository):
1325
1326
    def test_lock_write(self):
1327
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1328
        repo, client = self.setup_fake_client_and_repository(transport_path)
1329
        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
1330
        result = repo.lock_write()
1331
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1332
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1333
            client._calls)
1334
        self.assertEqual('a token', result)
1335
1336
    def test_lock_write_already_locked(self):
1337
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1338
        repo, client = self.setup_fake_client_and_repository(transport_path)
1339
        client.add_error_response('LockContention')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1340
        self.assertRaises(errors.LockContention, repo.lock_write)
1341
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1342
            [('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.
1343
            client._calls)
1344
1345
    def test_lock_write_unlockable(self):
1346
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1347
        repo, client = self.setup_fake_client_and_repository(transport_path)
1348
        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.
1349
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
1350
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1351
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1352
            client._calls)
1353
1354
1355
class TestRepositoryUnlock(TestRemoteRepository):
1356
1357
    def test_unlock(self):
1358
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1359
        repo, client = self.setup_fake_client_and_repository(transport_path)
1360
        client.add_success_response('ok', 'a token')
1361
        client.add_success_response('ok')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1362
        repo.lock_write()
1363
        repo.unlock()
1364
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1365
            [('call', 'Repository.lock_write', ('quack/', '')),
1366
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1367
            client._calls)
1368
1369
    def test_unlock_wrong_token(self):
1370
        # If somehow the token is wrong, unlock will raise TokenMismatch.
1371
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1372
        repo, client = self.setup_fake_client_and_repository(transport_path)
1373
        client.add_success_response('ok', 'a token')
1374
        client.add_error_response('TokenMismatch')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1375
        repo.lock_write()
1376
        self.assertRaises(errors.TokenMismatch, repo.unlock)
1377
1378
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1379
class TestRepositoryHasRevision(TestRemoteRepository):
1380
1381
    def test_none(self):
1382
        # repo.has_revision(None) should not cause any traffic.
1383
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1384
        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.
1385
1386
        # The null revision is always there, so has_revision(None) == True.
3172.3.3 by Robert Collins
Missed one occurence of None -> NULL_REVISION.
1387
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1388
1389
        # The remote repo shouldn't be accessed.
1390
        self.assertEqual([], client._calls)
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1391
1392
1393
class TestRepositoryTarball(TestRemoteRepository):
1394
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1395
    # This is a canned tarball reponse we can validate against
2018.18.18 by Martin Pool
reformat
1396
    tarball_content = (
2018.18.23 by Martin Pool
review cleanups
1397
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
1398
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
1399
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
1400
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
1401
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
1402
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
1403
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
1404
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
1405
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
1406
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
1407
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
1408
        'nWQ7QH/F3JFOFCQ0aSPfA='
1409
        ).decode('base64')
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1410
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1411
    def test_repository_tarball(self):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1412
        # Test that Repository.tarball generates the right operations
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1413
        transport_path = 'repo'
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
1414
        expected_calls = [('call_expecting_body', 'Repository.tarball',
3104.4.2 by Andrew Bennetts
All tests passing.
1415
                           ('repo/', 'bz2',),),
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1416
            ]
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1417
        repo, client = self.setup_fake_client_and_repository(transport_path)
1418
        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
1419
        # Now actually ask for the tarball
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1420
        tarball_file = repo._get_tarball('bz2')
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1421
        try:
1422
            self.assertEqual(expected_calls, client._calls)
1423
            self.assertEqual(self.tarball_content, tarball_file.read())
1424
        finally:
1425
            tarball_file.close()
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1426
1427
1428
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
1429
    """RemoteRepository.copy_content_into optimizations"""
1430
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1431
    def test_copy_content_remote_to_local(self):
1432
        self.transport_server = server.SmartTCPServer_for_testing
1433
        src_repo = self.make_repository('repo1')
1434
        src_repo = repository.Repository.open(self.get_url('repo1'))
1435
        # At the moment the tarball-based copy_content_into can't write back
1436
        # into a smart server.  It would be good if it could upload the
1437
        # tarball; once that works we'd have to create repositories of
1438
        # different formats. -- mbp 20070410
1439
        dest_url = self.get_vfs_only_url('repo2')
1440
        dest_bzrdir = BzrDir.create(dest_url)
1441
        dest_repo = dest_bzrdir.create_repository()
1442
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
1443
        self.assertTrue(isinstance(src_repo, RemoteRepository))
1444
        src_repo.copy_content_into(dest_repo)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1445
1446
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1447
class _StubRealPackRepository(object):
1448
1449
    def __init__(self, calls):
1450
        self._pack_collection = _StubPackCollection(calls)
1451
1452
1453
class _StubPackCollection(object):
1454
1455
    def __init__(self, calls):
1456
        self.calls = calls
1457
1458
    def autopack(self):
1459
        self.calls.append(('pack collection autopack',))
1460
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1461
    def reload_pack_names(self):
1462
        self.calls.append(('pack collection reload_pack_names',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1463
1464
    
1465
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
1466
    """Tests for RemoteRepository.autopack implementation."""
1467
1468
    def test_ok(self):
1469
        """When the server returns 'ok' and there's no _real_repository, then
1470
        nothing else happens: the autopack method is done.
1471
        """
1472
        transport_path = 'quack'
1473
        repo, client = self.setup_fake_client_and_repository(transport_path)
1474
        client.add_expected_call(
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1475
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1476
        repo.autopack()
1477
        client.finished_test()
1478
1479
    def test_ok_with_real_repo(self):
1480
        """When the server returns 'ok' and there is a _real_repository, then
1481
        the _real_repository's reload_pack_name's method will be called.
1482
        """
1483
        transport_path = 'quack'
1484
        repo, client = self.setup_fake_client_and_repository(transport_path)
1485
        client.add_expected_call(
1486
            'PackRepository.autopack', ('quack/',),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1487
            'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1488
        repo._real_repository = _StubRealPackRepository(client._calls)
1489
        repo.autopack()
1490
        self.assertEqual(
1491
            [('call', 'PackRepository.autopack', ('quack/',)),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1492
             ('pack collection reload_pack_names',)],
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1493
            client._calls)
1494
        
1495
    def test_backwards_compatibility(self):
1496
        """If the server does not recognise the PackRepository.autopack verb,
1497
        fallback to the real_repository's implementation.
1498
        """
1499
        transport_path = 'quack'
1500
        repo, client = self.setup_fake_client_and_repository(transport_path)
1501
        client.add_unknown_method_response('PackRepository.autopack')
1502
        def stub_ensure_real():
1503
            client._calls.append(('_ensure_real',))
1504
            repo._real_repository = _StubRealPackRepository(client._calls)
1505
        repo._ensure_real = stub_ensure_real
1506
        repo.autopack()
1507
        self.assertEqual(
1508
            [('call', 'PackRepository.autopack', ('quack/',)),
1509
             ('_ensure_real',),
1510
             ('pack collection autopack',)],
1511
            client._calls)
1512
1513
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1514
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
1515
    """Base class for unit tests for bzrlib.remote._translate_error."""
1516
1517
    def translateTuple(self, error_tuple, **context):
1518
        """Call _translate_error with an ErrorFromSmartServer built from the
1519
        given error_tuple.
1520
1521
        :param error_tuple: A tuple of a smart server response, as would be
1522
            passed to an ErrorFromSmartServer.
1523
        :kwargs context: context items to call _translate_error with.
1524
1525
        :returns: The error raised by _translate_error.
1526
        """
1527
        # Raise the ErrorFromSmartServer before passing it as an argument,
1528
        # because _translate_error may need to re-raise it with a bare 'raise'
1529
        # statement.
1530
        server_error = errors.ErrorFromSmartServer(error_tuple)
1531
        translated_error = self.translateErrorFromSmartServer(
1532
            server_error, **context)
1533
        return translated_error
1534
1535
    def translateErrorFromSmartServer(self, error_object, **context):
1536
        """Like translateTuple, but takes an already constructed
1537
        ErrorFromSmartServer rather than a tuple.
1538
        """
1539
        try:
1540
            raise error_object
1541
        except errors.ErrorFromSmartServer, server_error:
1542
            translated_error = self.assertRaises(
1543
                errors.BzrError, remote._translate_error, server_error,
1544
                **context)
1545
        return translated_error
1546
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1547
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1548
class TestErrorTranslationSuccess(TestErrorTranslationBase):
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1549
    """Unit tests for bzrlib.remote._translate_error.
1550
    
1551
    Given an ErrorFromSmartServer (which has an error tuple from a smart
1552
    server) and some context, _translate_error raises more specific errors from
1553
    bzrlib.errors.
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1554
1555
    This test case covers the cases where _translate_error succeeds in
1556
    translating an ErrorFromSmartServer to something better.  See
1557
    TestErrorTranslationRobustness for other cases.
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1558
    """
1559
1560
    def test_NoSuchRevision(self):
1561
        branch = self.make_branch('')
1562
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1563
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1564
            ('NoSuchRevision', revid), branch=branch)
1565
        expected_error = errors.NoSuchRevision(branch, revid)
1566
        self.assertEqual(expected_error, translated_error)
1567
1568
    def test_nosuchrevision(self):
1569
        repository = self.make_repository('')
1570
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1571
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1572
            ('nosuchrevision', revid), repository=repository)
1573
        expected_error = errors.NoSuchRevision(repository, revid)
1574
        self.assertEqual(expected_error, translated_error)
1575
1576
    def test_nobranch(self):
1577
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1578
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1579
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
1580
        self.assertEqual(expected_error, translated_error)
1581
1582
    def test_LockContention(self):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1583
        translated_error = self.translateTuple(('LockContention',))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1584
        expected_error = errors.LockContention('(remote lock)')
1585
        self.assertEqual(expected_error, translated_error)
1586
1587
    def test_UnlockableTransport(self):
1588
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1589
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1590
            ('UnlockableTransport',), bzrdir=bzrdir)
1591
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
1592
        self.assertEqual(expected_error, translated_error)
1593
1594
    def test_LockFailed(self):
1595
        lock = 'str() of a server lock'
1596
        why = 'str() of why'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1597
        translated_error = self.translateTuple(('LockFailed', lock, why))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1598
        expected_error = errors.LockFailed(lock, why)
1599
        self.assertEqual(expected_error, translated_error)
1600
1601
    def test_TokenMismatch(self):
1602
        token = 'a lock token'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1603
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1604
        expected_error = errors.TokenMismatch(token, '(remote token)')
1605
        self.assertEqual(expected_error, translated_error)
1606
1607
    def test_Diverged(self):
1608
        branch = self.make_branch('a')
1609
        other_branch = self.make_branch('b')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1610
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1611
            ('Diverged',), branch=branch, other_branch=other_branch)
1612
        expected_error = errors.DivergedBranches(branch, other_branch)
1613
        self.assertEqual(expected_error, translated_error)
1614
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
1615
    def test_ReadError_no_args(self):
1616
        path = 'a path'
1617
        translated_error = self.translateTuple(('ReadError',), path=path)
1618
        expected_error = errors.ReadError(path)
1619
        self.assertEqual(expected_error, translated_error)
1620
1621
    def test_ReadError(self):
1622
        path = 'a path'
1623
        translated_error = self.translateTuple(('ReadError', path))
1624
        expected_error = errors.ReadError(path)
1625
        self.assertEqual(expected_error, translated_error)
1626
1627
    def test_PermissionDenied_no_args(self):
1628
        path = 'a path'
1629
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
1630
        expected_error = errors.PermissionDenied(path)
1631
        self.assertEqual(expected_error, translated_error)
1632
1633
    def test_PermissionDenied_one_arg(self):
1634
        path = 'a path'
1635
        translated_error = self.translateTuple(('PermissionDenied', path))
1636
        expected_error = errors.PermissionDenied(path)
1637
        self.assertEqual(expected_error, translated_error)
1638
1639
    def test_PermissionDenied_one_arg_and_context(self):
1640
        """Given a choice between a path from the local context and a path on
1641
        the wire, _translate_error prefers the path from the local context.
1642
        """
1643
        local_path = 'local path'
1644
        remote_path = 'remote path'
1645
        translated_error = self.translateTuple(
1646
            ('PermissionDenied', remote_path), path=local_path)
1647
        expected_error = errors.PermissionDenied(local_path)
1648
        self.assertEqual(expected_error, translated_error)
1649
1650
    def test_PermissionDenied_two_args(self):
1651
        path = 'a path'
1652
        extra = 'a string with extra info'
1653
        translated_error = self.translateTuple(
1654
            ('PermissionDenied', path, extra))
1655
        expected_error = errors.PermissionDenied(path, extra)
1656
        self.assertEqual(expected_error, translated_error)
1657
1658
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1659
class TestErrorTranslationRobustness(TestErrorTranslationBase):
1660
    """Unit tests for bzrlib.remote._translate_error's robustness.
1661
    
1662
    TestErrorTranslationSuccess is for cases where _translate_error can
1663
    translate successfully.  This class about how _translate_err behaves when
1664
    it fails to translate: it re-raises the original error.
1665
    """
1666
1667
    def test_unrecognised_server_error(self):
1668
        """If the error code from the server is not recognised, the original
1669
        ErrorFromSmartServer is propagated unmodified.
1670
        """
1671
        error_tuple = ('An unknown error tuple',)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1672
        server_error = errors.ErrorFromSmartServer(error_tuple)
1673
        translated_error = self.translateErrorFromSmartServer(server_error)
1674
        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.
1675
        self.assertEqual(expected_error, translated_error)
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1676
1677
    def test_context_missing_a_key(self):
1678
        """In case of a bug in the client, or perhaps an unexpected response
1679
        from a server, _translate_error returns the original error tuple from
1680
        the server and mutters a warning.
1681
        """
1682
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
1683
        # in the context dict.  So let's give it an empty context dict instead
1684
        # to exercise its error recovery.
1685
        empty_context = {}
1686
        error_tuple = ('NoSuchRevision', 'revid')
1687
        server_error = errors.ErrorFromSmartServer(error_tuple)
1688
        translated_error = self.translateErrorFromSmartServer(server_error)
1689
        self.assertEqual(server_error, translated_error)
1690
        # In addition to re-raising ErrorFromSmartServer, some debug info has
1691
        # been muttered to the log file for developer to look at.
1692
        self.assertContainsRe(
1693
            self._get_log(keep_log_file=True),
1694
            "Missing key 'branch' in context")
1695
        
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
1696
    def test_path_missing(self):
1697
        """Some translations (PermissionDenied, ReadError) can determine the
1698
        'path' variable from either the wire or the local context.  If neither
1699
        has it, then an error is raised.
1700
        """
1701
        error_tuple = ('ReadError',)
1702
        server_error = errors.ErrorFromSmartServer(error_tuple)
1703
        translated_error = self.translateErrorFromSmartServer(server_error)
1704
        self.assertEqual(server_error, translated_error)
1705
        # In addition to re-raising ErrorFromSmartServer, some debug info has
1706
        # been muttered to the log file for developer to look at.
1707
        self.assertContainsRe(
1708
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
1709
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
1710
1711
class TestStacking(tests.TestCaseWithTransport):
1712
    """Tests for operations on stacked remote repositories.
1713
    
1714
    The underlying format type must support stacking.
1715
    """
1716
1717
    def test_access_stacked_remote(self):
1718
        # based on <http://launchpad.net/bugs/261315>
1719
        # make a branch stacked on another repository containing an empty
1720
        # revision, then open it over hpss - we should be able to see that
1721
        # revision.
1722
        base_transport = self.get_transport()
1723
        base_builder = self.make_branch_builder('base', format='1.6')
1724
        base_builder.start_series()
1725
        base_revid = base_builder.build_snapshot('rev-id', None,
1726
            [('add', ('', None, 'directory', None))],
1727
            'message')
1728
        base_builder.finish_series()
1729
        stacked_branch = self.make_branch('stacked', format='1.6')
1730
        stacked_branch.set_stacked_on_url('../base')
1731
        # start a server looking at this
1732
        smart_server = server.SmartTCPServer_for_testing()
1733
        smart_server.setUp()
1734
        self.addCleanup(smart_server.tearDown)
1735
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
1736
        # can get its branch and repository
1737
        remote_branch = remote_bzrdir.open_branch()
1738
        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
1739
        remote_repo.lock_read()
1740
        try:
1741
            # it should have an appropriate fallback repository, which should also
1742
            # be a RemoteRepository
1743
            self.assertEquals(len(remote_repo._fallback_repositories), 1)
1744
            self.assertIsInstance(remote_repo._fallback_repositories[0],
1745
                RemoteRepository)
1746
            # and it has the revision committed to the underlying repository;
1747
            # these have varying implementations so we try several of them
1748
            self.assertTrue(remote_repo.has_revisions([base_revid]))
1749
            self.assertTrue(remote_repo.has_revision(base_revid))
1750
            self.assertEqual(remote_repo.get_revision(base_revid).message,
1751
                'message')
1752
        finally:
1753
            remote_repo.unlock()
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.
1754
1755
1756
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
1757
1758
    def setUp(self):
1759
        super(TestRemoteBranchEffort, self).setUp()
1760
        # Create a smart server that publishes whatever the backing VFS server
1761
        # does.
1762
        self.smart_server = server.SmartTCPServer_for_testing()
1763
        self.smart_server.setUp(self.get_server())
1764
        self.addCleanup(self.smart_server.tearDown)
1765
        # Log all HPSS calls into self.hpss_calls.
1766
        _SmartClient.hooks.install_named_hook(
1767
            'call', self.capture_hpss_call, None)
1768
        self.hpss_calls = []
1769
1770
    def capture_hpss_call(self, params):
1771
        self.hpss_calls.append(params.method)
1772
1773
    def test_copy_content_into_avoids_revision_history(self):
1774
        local = self.make_branch('local')
1775
        remote_backing_tree = self.make_branch_and_tree('remote')
1776
        remote_backing_tree.commit("Commit.")
1777
        remote_branch_url = self.smart_server.get_url() + 'remote'
1778
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
1779
        local.repository.fetch(remote_branch.repository)
1780
        self.hpss_calls = []
1781
        remote_branch.copy_content_into(local)
1782
        self.assert_('Branch.revision_history' not in self.hpss_calls)
1783