~bzr-pqm/bzr/bzr.dev

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
3840.1.1 by Andrew Bennetts
Fix RemoteTransport's translation of errors involving paths; it wasn't passing orig_path to _translate_error.
1016
class TestTransportMkdir(tests.TestCase):
1017
1018
    def test_permissiondenied(self):
1019
        client = FakeClient()
1020
        client.add_error_response('PermissionDenied', 'remote path', 'extra')
1021
        transport = RemoteTransport('bzr://example.com/', medium=False,
1022
                                    _client=client)
1023
        exc = self.assertRaises(
1024
            errors.PermissionDenied, transport.mkdir, 'client path')
1025
        expected_error = errors.PermissionDenied('/client path', 'extra')
1026
        self.assertEqual(expected_error, exc)
1027
1028
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1029
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
1030
1031
    def test_defaults_to_none(self):
1032
        t = RemoteSSHTransport('bzr+ssh://example.com')
1033
        self.assertIs(None, t._get_credentials()[0])
1034
1035
    def test_uses_authentication_config(self):
1036
        conf = config.AuthenticationConfig()
1037
        conf._get_config().update(
1038
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
1039
            'example.com'}})
1040
        conf._save()
1041
        t = RemoteSSHTransport('bzr+ssh://example.com')
1042
        self.assertEqual('bar', t._get_credentials()[0])
1043
1044
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1045
class TestRemoteRepository(tests.TestCase):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1046
    """Base for testing RemoteRepository protocol usage.
1047
    
1048
    These tests contain frozen requests and responses.  We want any changes to 
1049
    what is sent or expected to be require a thoughtful update to these tests
1050
    because they might break compatibility with different-versioned servers.
1051
    """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1052
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1053
    def setup_fake_client_and_repository(self, transport_path):
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1054
        """Create the fake client and repository for testing with.
1055
        
1056
        There's no real server here; we just have canned responses sent
1057
        back one by one.
1058
        
1059
        :param transport_path: Path below the root of the MemoryTransport
1060
            where the repository will be created.
1061
        """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1062
        transport = MemoryTransport()
1063
        transport.mkdir(transport_path)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1064
        client = FakeClient(transport.base)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1065
        transport = transport.clone(transport_path)
1066
        # we do not want bzrdir to make any remote calls
1067
        bzrdir = RemoteBzrDir(transport, _client=False)
1068
        repo = RemoteRepository(bzrdir, None, _client=client)
1069
        return repo, client
1070
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1071
2018.12.2 by Andrew Bennetts
Remove some duplicate code in test_remote
1072
class TestRepositoryGatherStats(TestRemoteRepository):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1073
1074
    def test_revid_none(self):
1075
        # ('ok',), body with revisions and size
1076
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1077
        repo, client = self.setup_fake_client_and_repository(transport_path)
1078
        client.add_success_response_with_body(
1079
            'revisions: 2\nsize: 18\n', 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1080
        result = repo.gather_stats(None)
1081
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1082
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1083
             ('quack/','','no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1084
            client._calls)
1085
        self.assertEqual({'revisions': 2, 'size': 18}, result)
1086
1087
    def test_revid_no_committers(self):
1088
        # ('ok',), body without committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1089
        body = ('firstrev: 123456.300 3600\n'
1090
                'latestrev: 654231.400 0\n'
1091
                'revisions: 2\n'
1092
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1093
        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.
1094
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1095
        repo, client = self.setup_fake_client_and_repository(transport_path)
1096
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1097
        result = repo.gather_stats(revid)
1098
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1099
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1100
              ('quick/', revid, 'no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1101
            client._calls)
1102
        self.assertEqual({'revisions': 2, 'size': 18,
1103
                          'firstrev': (123456.300, 3600),
1104
                          'latestrev': (654231.400, 0),},
1105
                         result)
1106
1107
    def test_revid_with_committers(self):
1108
        # ('ok',), body with committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1109
        body = ('committers: 128\n'
1110
                'firstrev: 123456.300 3600\n'
1111
                'latestrev: 654231.400 0\n'
1112
                'revisions: 2\n'
1113
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1114
        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.
1115
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1116
        repo, client = self.setup_fake_client_and_repository(transport_path)
1117
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1118
        result = repo.gather_stats(revid, True)
1119
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1120
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1121
              ('buick/', revid, 'yes'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1122
            client._calls)
1123
        self.assertEqual({'revisions': 2, 'size': 18,
1124
                          'committers': 128,
1125
                          'firstrev': (123456.300, 3600),
1126
                          'latestrev': (654231.400, 0),},
1127
                         result)
1128
1129
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1130
class TestRepositoryGetGraph(TestRemoteRepository):
1131
1132
    def test_get_graph(self):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1133
        # get_graph returns a graph with a custom parents provider.
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1134
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1135
        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.
1136
        graph = repo.get_graph()
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1137
        self.assertNotEqual(graph._parents_provider, repo)
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1138
1139
1140
class TestRepositoryGetParentMap(TestRemoteRepository):
1141
1142
    def test_get_parent_map_caching(self):
1143
        # get_parent_map returns from cache until unlock()
1144
        # setup a reponse with two revisions
1145
        r1 = u'\u0e33'.encode('utf8')
1146
        r2 = u'\u0dab'.encode('utf8')
1147
        lines = [' '.join([r2, r1]), r1]
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
1148
        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.
1149
1150
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1151
        repo, client = self.setup_fake_client_and_repository(transport_path)
1152
        client.add_success_response_with_body(encoded_body, 'ok')
1153
        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.
1154
        repo.lock_read()
1155
        graph = repo.get_graph()
1156
        parents = graph.get_parent_map([r2])
1157
        self.assertEqual({r2: (r1,)}, parents)
1158
        # locking and unlocking deeper should not reset
1159
        repo.lock_read()
1160
        repo.unlock()
1161
        parents = graph.get_parent_map([r1])
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1162
        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.
1163
        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.
1164
            [('call_with_body_bytes_expecting_body',
1165
              '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.
1166
            client._calls)
1167
        repo.unlock()
1168
        # now we call again, and it should use the second response.
1169
        repo.lock_read()
1170
        graph = repo.get_graph()
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1171
        parents = graph.get_parent_map([r1])
1172
        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.
1173
        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.
1174
            [('call_with_body_bytes_expecting_body',
1175
              'Repository.get_parent_map', ('quack/', r2), '\n\n0'),
1176
             ('call_with_body_bytes_expecting_body',
1177
              '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.
1178
            ],
1179
            client._calls)
1180
        repo.unlock()
1181
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1182
    def test_get_parent_map_reconnects_if_unknown_method(self):
1183
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1184
        repo, client = self.setup_fake_client_and_repository(transport_path)
1185
        client.add_unknown_method_response('Repository,get_parent_map')
1186
        client.add_success_response_with_body('', 'ok')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1187
        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.
1188
        rev_id = 'revision-id'
3297.3.5 by Andrew Bennetts
Suppress a deprecation warning.
1189
        expected_deprecations = [
1190
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1191
            'in version 1.4.']
1192
        parents = self.callDeprecated(
1193
            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.
1194
        self.assertEqual(
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1195
            [('call_with_body_bytes_expecting_body',
1196
              '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.
1197
             ('disconnect medium',),
1198
             ('call_expecting_body', 'Repository.get_revision_graph',
1199
              ('quack/', ''))],
1200
            client._calls)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1201
        # 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.
1202
        self.assertTrue(client._medium._is_remote_before((1, 2)))
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1203
1204
    def test_get_parent_map_fallback_parentless_node(self):
1205
        """get_parent_map falls back to get_revision_graph on old servers.  The
1206
        results from get_revision_graph are tweaked to match the get_parent_map
1207
        API.
1208
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1209
        Specifically, a {key: ()} result from get_revision_graph means "no
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1210
        parents" for that key, which in get_parent_map results should be
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1211
        represented as {key: ('null:',)}.
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1212
1213
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
1214
        """
1215
        rev_id = 'revision-id'
1216
        transport_path = 'quack'
3245.4.40 by Andrew Bennetts
Merge from bzr.dev.
1217
        repo, client = self.setup_fake_client_and_repository(transport_path)
1218
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
1219
        client._medium._remember_remote_is_before((1, 2))
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1220
        expected_deprecations = [
1221
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1222
            'in version 1.4.']
1223
        parents = self.callDeprecated(
1224
            expected_deprecations, repo.get_parent_map, [rev_id])
1225
        self.assertEqual(
1226
            [('call_expecting_body', 'Repository.get_revision_graph',
1227
             ('quack/', ''))],
1228
            client._calls)
1229
        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.
1230
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1231
    def test_get_parent_map_unexpected_response(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1232
        repo, client = self.setup_fake_client_and_repository('path')
1233
        client.add_success_response('something unexpected!')
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1234
        self.assertRaises(
1235
            errors.UnexpectedSmartServerResponse,
1236
            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.
1237
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1238
2018.5.68 by Wouter van Heyst
Merge RemoteRepository.gather_stats.
1239
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
1240
    
1241
    def test_null_revision(self):
1242
        # a null revision has the predictable result {}, we should have no wire
1243
        # traffic when calling it with this argument
1244
        transport_path = 'empty'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1245
        repo, client = self.setup_fake_client_and_repository(transport_path)
1246
        client.add_success_response('notused')
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1247
        result = self.applyDeprecated(one_four, repo.get_revision_graph,
1248
            NULL_REVISION)
2018.5.68 by Wouter van Heyst
Merge RemoteRepository.gather_stats.
1249
        self.assertEqual([], client._calls)
1250
        self.assertEqual({}, result)
1251
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1252
    def test_none_revision(self):
1253
        # 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.
1254
        r1 = u'\u0e33'.encode('utf8')
1255
        r2 = u'\u0dab'.encode('utf8')
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1256
        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.
1257
        encoded_body = '\n'.join(lines)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1258
1259
        transport_path = 'sinhala'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1260
        repo, client = self.setup_fake_client_and_repository(transport_path)
1261
        client.add_success_response_with_body(encoded_body, 'ok')
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1262
        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)
1263
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1264
            [('call_expecting_body', 'Repository.get_revision_graph',
3104.4.2 by Andrew Bennetts
All tests passing.
1265
             ('sinhala/', ''))],
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1266
            client._calls)
2625.8.1 by Robert Collins
LIBRARY API BREAKS:
1267
        self.assertEqual({r1: (), r2: (r1, )}, result)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1268
1269
    def test_specific_revision(self):
1270
        # with a specific revision we want the graph for that
1271
        # 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.
1272
        r11 = u'\u0e33'.encode('utf8')
1273
        r12 = u'\xc9'.encode('utf8')
1274
        r2 = u'\u0dab'.encode('utf8')
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1275
        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.
1276
        encoded_body = '\n'.join(lines)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1277
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_success_response_with_body(encoded_body, 'ok')
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1281
        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)
1282
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1283
            [('call_expecting_body', 'Repository.get_revision_graph',
3104.4.2 by Andrew Bennetts
All tests passing.
1284
             ('sinhala/', r2))],
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1285
            client._calls)
2625.8.1 by Robert Collins
LIBRARY API BREAKS:
1286
        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)
1287
1288
    def test_no_such_revision(self):
1289
        revid = '123'
1290
        transport_path = 'sinhala'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1291
        repo, client = self.setup_fake_client_and_repository(transport_path)
1292
        client.add_error_response('nosuchrevision', revid)
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1293
        # 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
1294
        self.assertRaises(errors.NoSuchRevision,
3287.6.4 by Robert Collins
Fix up deprecation warnings for get_revision_graph.
1295
            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)
1296
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1297
            [('call_expecting_body', 'Repository.get_revision_graph',
3104.4.2 by Andrew Bennetts
All tests passing.
1298
             ('sinhala/', revid))],
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1299
            client._calls)
1300
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1301
    def test_unexpected_error(self):
1302
        revid = '123'
1303
        transport_path = 'sinhala'
1304
        repo, client = self.setup_fake_client_and_repository(transport_path)
1305
        client.add_error_response('AnUnexpectedError')
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1306
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1307
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
1308
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
1309
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1310
        
1311
class TestRepositoryIsShared(TestRemoteRepository):
1312
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1313
    def test_is_shared(self):
1314
        # ('yes', ) for Repository.is_shared -> 'True'.
1315
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1316
        repo, client = self.setup_fake_client_and_repository(transport_path)
1317
        client.add_success_response('yes')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1318
        result = repo.is_shared()
1319
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1320
            [('call', 'Repository.is_shared', ('quack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1321
            client._calls)
1322
        self.assertEqual(True, result)
1323
1324
    def test_is_not_shared(self):
1325
        # ('no', ) for Repository.is_shared -> 'False'.
1326
        transport_path = 'qwack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1327
        repo, client = self.setup_fake_client_and_repository(transport_path)
1328
        client.add_success_response('no')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1329
        result = repo.is_shared()
1330
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1331
            [('call', 'Repository.is_shared', ('qwack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1332
            client._calls)
1333
        self.assertEqual(False, result)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1334
1335
1336
class TestRepositoryLockWrite(TestRemoteRepository):
1337
1338
    def test_lock_write(self):
1339
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1340
        repo, client = self.setup_fake_client_and_repository(transport_path)
1341
        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
1342
        result = repo.lock_write()
1343
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1344
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1345
            client._calls)
1346
        self.assertEqual('a token', result)
1347
1348
    def test_lock_write_already_locked(self):
1349
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1350
        repo, client = self.setup_fake_client_and_repository(transport_path)
1351
        client.add_error_response('LockContention')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1352
        self.assertRaises(errors.LockContention, repo.lock_write)
1353
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1354
            [('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.
1355
            client._calls)
1356
1357
    def test_lock_write_unlockable(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_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.
1361
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
1362
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1363
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1364
            client._calls)
1365
1366
1367
class TestRepositoryUnlock(TestRemoteRepository):
1368
1369
    def test_unlock(self):
1370
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1371
        repo, client = self.setup_fake_client_and_repository(transport_path)
1372
        client.add_success_response('ok', 'a token')
1373
        client.add_success_response('ok')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1374
        repo.lock_write()
1375
        repo.unlock()
1376
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1377
            [('call', 'Repository.lock_write', ('quack/', '')),
1378
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1379
            client._calls)
1380
1381
    def test_unlock_wrong_token(self):
1382
        # If somehow the token is wrong, unlock will raise TokenMismatch.
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)
1385
        client.add_success_response('ok', 'a token')
1386
        client.add_error_response('TokenMismatch')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1387
        repo.lock_write()
1388
        self.assertRaises(errors.TokenMismatch, repo.unlock)
1389
1390
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1391
class TestRepositoryHasRevision(TestRemoteRepository):
1392
1393
    def test_none(self):
1394
        # repo.has_revision(None) should not cause any traffic.
1395
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1396
        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.
1397
1398
        # The null revision is always there, so has_revision(None) == True.
3172.3.3 by Robert Collins
Missed one occurence of None -> NULL_REVISION.
1399
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1400
1401
        # The remote repo shouldn't be accessed.
1402
        self.assertEqual([], client._calls)
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1403
1404
1405
class TestRepositoryTarball(TestRemoteRepository):
1406
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1407
    # This is a canned tarball reponse we can validate against
2018.18.18 by Martin Pool
reformat
1408
    tarball_content = (
2018.18.23 by Martin Pool
review cleanups
1409
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
1410
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
1411
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
1412
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
1413
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
1414
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
1415
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
1416
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
1417
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
1418
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
1419
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
1420
        'nWQ7QH/F3JFOFCQ0aSPfA='
1421
        ).decode('base64')
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1422
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1423
    def test_repository_tarball(self):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1424
        # Test that Repository.tarball generates the right operations
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1425
        transport_path = 'repo'
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
1426
        expected_calls = [('call_expecting_body', 'Repository.tarball',
3104.4.2 by Andrew Bennetts
All tests passing.
1427
                           ('repo/', 'bz2',),),
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1428
            ]
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1429
        repo, client = self.setup_fake_client_and_repository(transport_path)
1430
        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
1431
        # Now actually ask for the tarball
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1432
        tarball_file = repo._get_tarball('bz2')
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1433
        try:
1434
            self.assertEqual(expected_calls, client._calls)
1435
            self.assertEqual(self.tarball_content, tarball_file.read())
1436
        finally:
1437
            tarball_file.close()
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1438
1439
1440
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
1441
    """RemoteRepository.copy_content_into optimizations"""
1442
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1443
    def test_copy_content_remote_to_local(self):
1444
        self.transport_server = server.SmartTCPServer_for_testing
1445
        src_repo = self.make_repository('repo1')
1446
        src_repo = repository.Repository.open(self.get_url('repo1'))
1447
        # At the moment the tarball-based copy_content_into can't write back
1448
        # into a smart server.  It would be good if it could upload the
1449
        # tarball; once that works we'd have to create repositories of
1450
        # different formats. -- mbp 20070410
1451
        dest_url = self.get_vfs_only_url('repo2')
1452
        dest_bzrdir = BzrDir.create(dest_url)
1453
        dest_repo = dest_bzrdir.create_repository()
1454
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
1455
        self.assertTrue(isinstance(src_repo, RemoteRepository))
1456
        src_repo.copy_content_into(dest_repo)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1457
1458
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1459
class _StubRealPackRepository(object):
1460
1461
    def __init__(self, calls):
1462
        self._pack_collection = _StubPackCollection(calls)
1463
1464
1465
class _StubPackCollection(object):
1466
1467
    def __init__(self, calls):
1468
        self.calls = calls
1469
1470
    def autopack(self):
1471
        self.calls.append(('pack collection autopack',))
1472
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1473
    def reload_pack_names(self):
1474
        self.calls.append(('pack collection reload_pack_names',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1475
1476
    
1477
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
1478
    """Tests for RemoteRepository.autopack implementation."""
1479
1480
    def test_ok(self):
1481
        """When the server returns 'ok' and there's no _real_repository, then
1482
        nothing else happens: the autopack method is done.
1483
        """
1484
        transport_path = 'quack'
1485
        repo, client = self.setup_fake_client_and_repository(transport_path)
1486
        client.add_expected_call(
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1487
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1488
        repo.autopack()
1489
        client.finished_test()
1490
1491
    def test_ok_with_real_repo(self):
1492
        """When the server returns 'ok' and there is a _real_repository, then
1493
        the _real_repository's reload_pack_name's method will be called.
1494
        """
1495
        transport_path = 'quack'
1496
        repo, client = self.setup_fake_client_and_repository(transport_path)
1497
        client.add_expected_call(
1498
            'PackRepository.autopack', ('quack/',),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1499
            'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1500
        repo._real_repository = _StubRealPackRepository(client._calls)
1501
        repo.autopack()
1502
        self.assertEqual(
1503
            [('call', 'PackRepository.autopack', ('quack/',)),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1504
             ('pack collection reload_pack_names',)],
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1505
            client._calls)
1506
        
1507
    def test_backwards_compatibility(self):
1508
        """If the server does not recognise the PackRepository.autopack verb,
1509
        fallback to the real_repository's implementation.
1510
        """
1511
        transport_path = 'quack'
1512
        repo, client = self.setup_fake_client_and_repository(transport_path)
1513
        client.add_unknown_method_response('PackRepository.autopack')
1514
        def stub_ensure_real():
1515
            client._calls.append(('_ensure_real',))
1516
            repo._real_repository = _StubRealPackRepository(client._calls)
1517
        repo._ensure_real = stub_ensure_real
1518
        repo.autopack()
1519
        self.assertEqual(
1520
            [('call', 'PackRepository.autopack', ('quack/',)),
1521
             ('_ensure_real',),
1522
             ('pack collection autopack',)],
1523
            client._calls)
1524
1525
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1526
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
1527
    """Base class for unit tests for bzrlib.remote._translate_error."""
1528
1529
    def translateTuple(self, error_tuple, **context):
1530
        """Call _translate_error with an ErrorFromSmartServer built from the
1531
        given error_tuple.
1532
1533
        :param error_tuple: A tuple of a smart server response, as would be
1534
            passed to an ErrorFromSmartServer.
1535
        :kwargs context: context items to call _translate_error with.
1536
1537
        :returns: The error raised by _translate_error.
1538
        """
1539
        # Raise the ErrorFromSmartServer before passing it as an argument,
1540
        # because _translate_error may need to re-raise it with a bare 'raise'
1541
        # statement.
1542
        server_error = errors.ErrorFromSmartServer(error_tuple)
1543
        translated_error = self.translateErrorFromSmartServer(
1544
            server_error, **context)
1545
        return translated_error
1546
1547
    def translateErrorFromSmartServer(self, error_object, **context):
1548
        """Like translateTuple, but takes an already constructed
1549
        ErrorFromSmartServer rather than a tuple.
1550
        """
1551
        try:
1552
            raise error_object
1553
        except errors.ErrorFromSmartServer, server_error:
1554
            translated_error = self.assertRaises(
1555
                errors.BzrError, remote._translate_error, server_error,
1556
                **context)
1557
        return translated_error
1558
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1559
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1560
class TestErrorTranslationSuccess(TestErrorTranslationBase):
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1561
    """Unit tests for bzrlib.remote._translate_error.
1562
    
1563
    Given an ErrorFromSmartServer (which has an error tuple from a smart
1564
    server) and some context, _translate_error raises more specific errors from
1565
    bzrlib.errors.
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1566
1567
    This test case covers the cases where _translate_error succeeds in
1568
    translating an ErrorFromSmartServer to something better.  See
1569
    TestErrorTranslationRobustness for other cases.
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1570
    """
1571
1572
    def test_NoSuchRevision(self):
1573
        branch = self.make_branch('')
1574
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1575
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1576
            ('NoSuchRevision', revid), branch=branch)
1577
        expected_error = errors.NoSuchRevision(branch, revid)
1578
        self.assertEqual(expected_error, translated_error)
1579
1580
    def test_nosuchrevision(self):
1581
        repository = self.make_repository('')
1582
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1583
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1584
            ('nosuchrevision', revid), repository=repository)
1585
        expected_error = errors.NoSuchRevision(repository, revid)
1586
        self.assertEqual(expected_error, translated_error)
1587
1588
    def test_nobranch(self):
1589
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1590
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1591
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
1592
        self.assertEqual(expected_error, translated_error)
1593
1594
    def test_LockContention(self):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1595
        translated_error = self.translateTuple(('LockContention',))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1596
        expected_error = errors.LockContention('(remote lock)')
1597
        self.assertEqual(expected_error, translated_error)
1598
1599
    def test_UnlockableTransport(self):
1600
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1601
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1602
            ('UnlockableTransport',), bzrdir=bzrdir)
1603
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
1604
        self.assertEqual(expected_error, translated_error)
1605
1606
    def test_LockFailed(self):
1607
        lock = 'str() of a server lock'
1608
        why = 'str() of why'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1609
        translated_error = self.translateTuple(('LockFailed', lock, why))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1610
        expected_error = errors.LockFailed(lock, why)
1611
        self.assertEqual(expected_error, translated_error)
1612
1613
    def test_TokenMismatch(self):
1614
        token = 'a lock token'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1615
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1616
        expected_error = errors.TokenMismatch(token, '(remote token)')
1617
        self.assertEqual(expected_error, translated_error)
1618
1619
    def test_Diverged(self):
1620
        branch = self.make_branch('a')
1621
        other_branch = self.make_branch('b')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1622
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1623
            ('Diverged',), branch=branch, other_branch=other_branch)
1624
        expected_error = errors.DivergedBranches(branch, other_branch)
1625
        self.assertEqual(expected_error, translated_error)
1626
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
1627
    def test_ReadError_no_args(self):
1628
        path = 'a path'
1629
        translated_error = self.translateTuple(('ReadError',), path=path)
1630
        expected_error = errors.ReadError(path)
1631
        self.assertEqual(expected_error, translated_error)
1632
1633
    def test_ReadError(self):
1634
        path = 'a path'
1635
        translated_error = self.translateTuple(('ReadError', path))
1636
        expected_error = errors.ReadError(path)
1637
        self.assertEqual(expected_error, translated_error)
1638
1639
    def test_PermissionDenied_no_args(self):
1640
        path = 'a path'
1641
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
1642
        expected_error = errors.PermissionDenied(path)
1643
        self.assertEqual(expected_error, translated_error)
1644
1645
    def test_PermissionDenied_one_arg(self):
1646
        path = 'a path'
1647
        translated_error = self.translateTuple(('PermissionDenied', path))
1648
        expected_error = errors.PermissionDenied(path)
1649
        self.assertEqual(expected_error, translated_error)
1650
1651
    def test_PermissionDenied_one_arg_and_context(self):
1652
        """Given a choice between a path from the local context and a path on
1653
        the wire, _translate_error prefers the path from the local context.
1654
        """
1655
        local_path = 'local path'
1656
        remote_path = 'remote path'
1657
        translated_error = self.translateTuple(
1658
            ('PermissionDenied', remote_path), path=local_path)
1659
        expected_error = errors.PermissionDenied(local_path)
1660
        self.assertEqual(expected_error, translated_error)
1661
1662
    def test_PermissionDenied_two_args(self):
1663
        path = 'a path'
1664
        extra = 'a string with extra info'
1665
        translated_error = self.translateTuple(
1666
            ('PermissionDenied', path, extra))
1667
        expected_error = errors.PermissionDenied(path, extra)
1668
        self.assertEqual(expected_error, translated_error)
1669
1670
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1671
class TestErrorTranslationRobustness(TestErrorTranslationBase):
1672
    """Unit tests for bzrlib.remote._translate_error's robustness.
1673
    
1674
    TestErrorTranslationSuccess is for cases where _translate_error can
1675
    translate successfully.  This class about how _translate_err behaves when
1676
    it fails to translate: it re-raises the original error.
1677
    """
1678
1679
    def test_unrecognised_server_error(self):
1680
        """If the error code from the server is not recognised, the original
1681
        ErrorFromSmartServer is propagated unmodified.
1682
        """
1683
        error_tuple = ('An unknown error tuple',)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1684
        server_error = errors.ErrorFromSmartServer(error_tuple)
1685
        translated_error = self.translateErrorFromSmartServer(server_error)
1686
        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.
1687
        self.assertEqual(expected_error, translated_error)
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1688
1689
    def test_context_missing_a_key(self):
1690
        """In case of a bug in the client, or perhaps an unexpected response
1691
        from a server, _translate_error returns the original error tuple from
1692
        the server and mutters a warning.
1693
        """
1694
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
1695
        # in the context dict.  So let's give it an empty context dict instead
1696
        # to exercise its error recovery.
1697
        empty_context = {}
1698
        error_tuple = ('NoSuchRevision', 'revid')
1699
        server_error = errors.ErrorFromSmartServer(error_tuple)
1700
        translated_error = self.translateErrorFromSmartServer(server_error)
1701
        self.assertEqual(server_error, translated_error)
1702
        # In addition to re-raising ErrorFromSmartServer, some debug info has
1703
        # been muttered to the log file for developer to look at.
1704
        self.assertContainsRe(
1705
            self._get_log(keep_log_file=True),
1706
            "Missing key 'branch' in context")
1707
        
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
1708
    def test_path_missing(self):
1709
        """Some translations (PermissionDenied, ReadError) can determine the
1710
        'path' variable from either the wire or the local context.  If neither
1711
        has it, then an error is raised.
1712
        """
1713
        error_tuple = ('ReadError',)
1714
        server_error = errors.ErrorFromSmartServer(error_tuple)
1715
        translated_error = self.translateErrorFromSmartServer(server_error)
1716
        self.assertEqual(server_error, translated_error)
1717
        # In addition to re-raising ErrorFromSmartServer, some debug info has
1718
        # been muttered to the log file for developer to look at.
1719
        self.assertContainsRe(
1720
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
1721
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
1722
1723
class TestStacking(tests.TestCaseWithTransport):
1724
    """Tests for operations on stacked remote repositories.
1725
    
1726
    The underlying format type must support stacking.
1727
    """
1728
1729
    def test_access_stacked_remote(self):
1730
        # based on <http://launchpad.net/bugs/261315>
1731
        # make a branch stacked on another repository containing an empty
1732
        # revision, then open it over hpss - we should be able to see that
1733
        # revision.
1734
        base_transport = self.get_transport()
1735
        base_builder = self.make_branch_builder('base', format='1.6')
1736
        base_builder.start_series()
1737
        base_revid = base_builder.build_snapshot('rev-id', None,
1738
            [('add', ('', None, 'directory', None))],
1739
            'message')
1740
        base_builder.finish_series()
1741
        stacked_branch = self.make_branch('stacked', format='1.6')
1742
        stacked_branch.set_stacked_on_url('../base')
1743
        # start a server looking at this
1744
        smart_server = server.SmartTCPServer_for_testing()
1745
        smart_server.setUp()
1746
        self.addCleanup(smart_server.tearDown)
1747
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
1748
        # can get its branch and repository
1749
        remote_branch = remote_bzrdir.open_branch()
1750
        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
1751
        remote_repo.lock_read()
1752
        try:
1753
            # it should have an appropriate fallback repository, which should also
1754
            # be a RemoteRepository
1755
            self.assertEquals(len(remote_repo._fallback_repositories), 1)
1756
            self.assertIsInstance(remote_repo._fallback_repositories[0],
1757
                RemoteRepository)
1758
            # and it has the revision committed to the underlying repository;
1759
            # these have varying implementations so we try several of them
1760
            self.assertTrue(remote_repo.has_revisions([base_revid]))
1761
            self.assertTrue(remote_repo.has_revision(base_revid))
1762
            self.assertEqual(remote_repo.get_revision(base_revid).message,
1763
                'message')
1764
        finally:
1765
            remote_repo.unlock()
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
1766
3835.1.7 by Aaron Bentley
Updates from review
1767
    def prepare_stacked_remote_branch(self):
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
1768
        smart_server = server.SmartTCPServer_for_testing()
1769
        smart_server.setUp()
1770
        self.addCleanup(smart_server.tearDown)
1771
        tree1 = self.make_branch_and_tree('tree1')
1772
        tree1.commit('rev1', rev_id='rev1')
1773
        tree2 = self.make_branch_and_tree('tree2', format='1.6')
1774
        tree2.branch.set_stacked_on_url(tree1.branch.base)
1775
        branch2 = Branch.open(smart_server.get_url() + '/tree2')
1776
        branch2.lock_read()
1777
        self.addCleanup(branch2.unlock)
3835.1.7 by Aaron Bentley
Updates from review
1778
        return branch2
1779
1780
    def test_stacked_get_parent_map(self):
1781
        # the public implementation of get_parent_map obeys stacking
1782
        branch = self.prepare_stacked_remote_branch()
1783
        repo = branch.repository
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
1784
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
3835.1.7 by Aaron Bentley
Updates from review
1785
1786
    def test_stacked__get_parent_map(self):
1787
        # the private variant of _get_parent_map ignores stacking
1788
        branch = self.prepare_stacked_remote_branch()
1789
        repo = branch.repository
1790
        self.assertEqual([], repo._get_parent_map(['rev1']).keys())
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
1791
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.
1792
1793
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
1794
1795
    def setUp(self):
1796
        super(TestRemoteBranchEffort, self).setUp()
1797
        # Create a smart server that publishes whatever the backing VFS server
1798
        # does.
1799
        self.smart_server = server.SmartTCPServer_for_testing()
1800
        self.smart_server.setUp(self.get_server())
1801
        self.addCleanup(self.smart_server.tearDown)
1802
        # Log all HPSS calls into self.hpss_calls.
1803
        _SmartClient.hooks.install_named_hook(
1804
            'call', self.capture_hpss_call, None)
1805
        self.hpss_calls = []
1806
1807
    def capture_hpss_call(self, params):
1808
        self.hpss_calls.append(params.method)
1809
1810
    def test_copy_content_into_avoids_revision_history(self):
1811
        local = self.make_branch('local')
1812
        remote_backing_tree = self.make_branch_and_tree('remote')
1813
        remote_backing_tree.commit("Commit.")
1814
        remote_branch_url = self.smart_server.get_url() + 'remote'
1815
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
1816
        local.repository.fetch(remote_branch.repository)
1817
        self.hpss_calls = []
1818
        remote_branch.copy_content_into(local)
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
1819
        self.assertFalse('Branch.revision_history' in self.hpss_calls)