/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3407.2.2 by Martin Pool
Remove special case in RemoteBranchLockableFiles for branch.conf
1
# Copyright (C) 2006, 2007, 2008 Canonical Ltd
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""Tests for remote bzrdir/branch/repo/etc
18
19
These are proxy objects which act on remote objects by sending messages
20
through a smart client.  The proxies are to be created when attempting to open
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
21
the object given a transport that supports smartserver rpc operations.
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
22
23
These tests correspond to tests.test_smart, which exercises the server side.
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
24
"""
25
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
26
import bz2
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
27
from cStringIO import StringIO
28
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
29
from bzrlib import (
3834.3.2 by Andrew Bennetts
Preserve BzrBranch5's _synchronize_history code without affecting Branch or BzrBranch7; add effort test for RemoteBranch.copy_content_into.
30
    bzrdir,
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
31
    config,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
32
    errors,
3184.1.9 by Robert Collins
* ``Repository.get_data_stream`` is now deprecated in favour of
33
    graph,
2535.3.39 by Andrew Bennetts
Tidy some XXXs.
34
    pack,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
35
    remote,
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
36
    repository,
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
37
    smart,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
38
    tests,
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
39
    urlutils,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
40
    )
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
41
from bzrlib.branch import Branch
42
from bzrlib.bzrdir import BzrDir, BzrDirFormat
43
from bzrlib.remote import (
44
    RemoteBranch,
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
45
    RemoteBranchFormat,
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
46
    RemoteBzrDir,
47
    RemoteBzrDirFormat,
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
48
    RemoteRepository,
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
49
    )
50
from bzrlib.revision import NULL_REVISION
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
51
from bzrlib.smart import server, medium
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
52
from bzrlib.smart.client import _SmartClient
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
53
from bzrlib.tests import (
54
    condition_isinstance,
55
    split_suite_by_condition,
56
    multiply_tests,
57
    )
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
58
from bzrlib.transport import get_transport, http
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
59
from bzrlib.transport.memory import MemoryTransport
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
60
from bzrlib.transport.remote import (
61
    RemoteTransport,
62
    RemoteSSHTransport,
63
    RemoteTCPTransport,
64
)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
65
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
66
def load_tests(standard_tests, module, loader):
67
    to_adapt, result = split_suite_by_condition(
68
        standard_tests, condition_isinstance(BasicRemoteObjectTests))
69
    smart_server_version_scenarios = [
70
        ('HPSS-v2', 
71
            {'transport_server': server.SmartTCPServer_for_testing_v2_only}),
72
        ('HPSS-v3', 
73
            {'transport_server': server.SmartTCPServer_for_testing})]
74
    return multiply_tests(to_adapt, smart_server_version_scenarios, result)
75
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)
76
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
77
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
78
79
    def setUp(self):
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
80
        super(BasicRemoteObjectTests, self).setUp()
81
        self.transport = self.get_transport()
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
82
        # 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
83
        self.local_wt = BzrDir.create_standalone_workingtree('.')
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
84
2018.5.171 by Andrew Bennetts
Disconnect RemoteTransports in some tests to avoid tripping up test_strace with leftover threads from previous tests.
85
    def tearDown(self):
86
        self.transport.disconnect()
87
        tests.TestCaseWithTransport.tearDown(self)
88
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
89
    def test_create_remote_bzrdir(self):
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
90
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
91
        self.assertIsInstance(b, BzrDir)
92
93
    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.
94
        # open a standalone branch in the working directory
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
95
        b = remote.RemoteBzrDir(self.transport, remote.RemoteBzrDirFormat())
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
96
        branch = b.open_branch()
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
97
        self.assertIsInstance(branch, Branch)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
98
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
99
    def test_remote_repository(self):
100
        b = BzrDir.open_from_transport(self.transport)
101
        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.
102
        revid = u'\xc823123123'.encode('utf8')
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
103
        self.assertFalse(repo.has_revision(revid))
104
        self.local_wt.commit(message='test commit', rev_id=revid)
105
        self.assertTrue(repo.has_revision(revid))
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
106
107
    def test_remote_branch_revision_history(self):
108
        b = BzrDir.open_from_transport(self.transport).open_branch()
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
109
        self.assertEqual([], b.revision_history())
110
        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.
111
        r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
112
        self.assertEqual([r1, r2], b.revision_history())
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
113
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
114
    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)
115
        """Should open a RemoteBzrDir over a RemoteTransport"""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
116
        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.
117
        self.assertTrue(RemoteBzrDirFormat
118
                        in BzrDirFormat._control_server_formats)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
119
        self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
120
121
    def test_open_detected_smart_format(self):
122
        fmt = BzrDirFormat.find_format(self.transport)
123
        d = fmt.open(self.transport)
124
        self.assertIsInstance(d, BzrDir)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
125
2477.1.1 by Martin Pool
Add RemoteBranch repr
126
    def test_remote_branch_repr(self):
127
        b = BzrDir.open_from_transport(self.transport).open_branch()
128
        self.assertStartsWith(str(b), 'RemoteBranch(')
129
4103.2.2 by Andrew Bennetts
Fix RemoteBranchFormat.supports_stacking()
130
    def test_remote_branch_format_supports_stacking(self):
131
        t = self.transport
132
        self.make_branch('unstackable', format='pack-0.92')
133
        b = BzrDir.open_from_transport(t.clone('unstackable')).open_branch()
134
        self.assertFalse(b._format.supports_stacking())
135
        self.make_branch('stackable', format='1.9')
136
        b = BzrDir.open_from_transport(t.clone('stackable')).open_branch()
137
        self.assertTrue(b._format.supports_stacking())
138
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
139
    def test_remote_repo_format_supports_external_references(self):
140
        t = self.transport
141
        bd = self.make_bzrdir('unstackable', format='pack-0.92')
142
        r = bd.create_repository()
143
        self.assertFalse(r._format.supports_external_lookups)
144
        r = BzrDir.open_from_transport(t.clone('unstackable')).open_repository()
145
        self.assertFalse(r._format.supports_external_lookups)
146
        bd = self.make_bzrdir('stackable', format='1.9')
147
        r = bd.create_repository()
148
        self.assertTrue(r._format.supports_external_lookups)
149
        r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
150
        self.assertTrue(r._format.supports_external_lookups)
151
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
152
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
153
class FakeProtocol(object):
154
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
155
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
156
    def __init__(self, body, fake_client):
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
157
        self.body = body
158
        self._body_buffer = None
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
159
        self._fake_client = fake_client
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
160
161
    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.
162
        if self._body_buffer is None:
163
            self._body_buffer = StringIO(self.body)
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
164
        bytes = self._body_buffer.read(count)
165
        if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
166
            self._fake_client.expecting_body = False
167
        return bytes
168
169
    def cancel_read_body(self):
170
        self._fake_client.expecting_body = False
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
171
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
172
    def read_streamed_body(self):
173
        return self.body
174
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
175
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
176
class FakeClient(_SmartClient):
177
    """Lookalike for _SmartClient allowing testing."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
178
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
179
    def __init__(self, fake_medium_base='fake base'):
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
180
        """Create a FakeClient."""
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
181
        self.responses = []
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
182
        self._calls = []
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
183
        self.expecting_body = False
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
184
        # if non-None, this is the list of expected calls, with only the
185
        # method name and arguments included.  the body might be hard to
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
186
        # compute so is not included. If a call is None, that call can
187
        # be anything.
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
188
        self._expected_calls = None
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
189
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
190
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
191
    def add_expected_call(self, call_name, call_args, response_type,
192
        response_args, response_body=None):
193
        if self._expected_calls is None:
194
            self._expected_calls = []
195
        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
196
        self.responses.append((response_type, response_args, response_body))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
197
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
198
    def add_success_response(self, *args):
199
        self.responses.append(('success', args, None))
200
201
    def add_success_response_with_body(self, body, *args):
202
        self.responses.append(('success', args, body))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
203
        if self._expected_calls is not None:
204
            self._expected_calls.append(None)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
205
206
    def add_error_response(self, *args):
207
        self.responses.append(('error', args))
208
209
    def add_unknown_method_response(self, verb):
210
        self.responses.append(('unknown', verb))
211
3691.2.8 by Martin Pool
Update some test_remote tests for Branch.get_stacked_on_url and with clearer assertions
212
    def finished_test(self):
213
        if self._expected_calls:
214
            raise AssertionError("%r finished but was still expecting %r"
215
                % (self, self._expected_calls[0]))
216
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.
217
    def _get_next_response(self):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
218
        try:
219
            response_tuple = self.responses.pop(0)
220
        except IndexError, e:
221
            raise AssertionError("%r didn't expect any more calls"
222
                % (self,))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
223
        if response_tuple[0] == 'unknown':
224
            raise errors.UnknownSmartMethod(response_tuple[1])
225
        elif response_tuple[0] == 'error':
226
            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.
227
        return response_tuple
228
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
229
    def _check_call(self, method, args):
230
        if self._expected_calls is None:
231
            # the test should be updated to say what it expects
232
            return
233
        try:
234
            next_call = self._expected_calls.pop(0)
235
        except IndexError:
236
            raise AssertionError("%r didn't expect any more calls "
237
                "but got %r%r"
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
238
                % (self, method, args,))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
239
        if next_call is None:
240
            return
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
241
        if method != next_call[0] or args != next_call[1]:
242
            raise AssertionError("%r expected %r%r "
243
                "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
244
                % (self, next_call[0], next_call[1], method, args,))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
245
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
246
    def call(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
247
        self._check_call(method, args)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
248
        self._calls.append(('call', method, args))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
249
        return self._get_next_response()[1]
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
250
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
251
    def call_expecting_body(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
252
        self._check_call(method, args)
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
253
        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.
254
        result = self._get_next_response()
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
255
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
256
        return result[1], FakeProtocol(result[2], self)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
257
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.
258
    def call_with_body_bytes_expecting_body(self, method, args, body):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
259
        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.
260
        self._calls.append(('call_with_body_bytes_expecting_body', method,
261
            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.
262
        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.
263
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
264
        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.
265
3842.3.9 by Andrew Bennetts
Backing up the stream so that we can fallback correctly.
266
    def call_with_body_stream(self, args, stream):
267
        # Explicitly consume the stream before checking for an error, because
268
        # that's what happens a real medium.
269
        stream = list(stream)
270
        self._check_call(args[0], args[1:])
271
        self._calls.append(('call_with_body_stream', args[0], args[1:], stream))
272
        return self._get_next_response()[1]
273
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
274
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
275
class FakeMedium(medium.SmartClientMedium):
3104.4.2 by Andrew Bennetts
All tests passing.
276
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.
277
    def __init__(self, client_calls, base):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
278
        medium.SmartClientMedium.__init__(self, base)
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
279
        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.
280
281
    def disconnect(self):
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
282
        self._client_calls.append(('disconnect medium',))
3104.4.2 by Andrew Bennetts
All tests passing.
283
284
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.
285
class TestVfsHas(tests.TestCase):
286
287
    def test_unicode_path(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
288
        client = FakeClient('/')
289
        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.
290
        transport = RemoteTransport('bzr://localhost/', _client=client)
291
        filename = u'/hell\u00d8'.encode('utf8')
292
        result = transport.has(filename)
293
        self.assertEqual(
294
            [('call', 'has', (filename,))],
295
            client._calls)
296
        self.assertTrue(result)
297
298
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
299
class TestRemote(tests.TestCaseWithMemoryTransport):
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
300
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
301
    def get_branch_format(self):
302
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
303
        return reference_bzrdir_format.get_branch_format()
304
4053.1.2 by Robert Collins
Actually make this branch work.
305
    def get_repo_format(self):
306
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
307
        return reference_bzrdir_format.repository_format
308
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
309
    def disable_verb(self, verb):
310
        """Disable a verb for one test."""
311
        request_handlers = smart.request.request_handlers
312
        orig_method = request_handlers.get(verb)
313
        request_handlers.remove(verb)
314
        def restoreVerb():
315
            request_handlers.register(verb, orig_method)
316
        self.addCleanup(restoreVerb)
317
318
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
319
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
320
    """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.
321
322
    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.
323
        """Assert that the result of
324
        SmartClientMedium.remote_path_from_transport is the expected value for
325
        a given client_base and transport_base.
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
326
        """
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
327
        client_medium = medium.SmartClientMedium(client_base)
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
328
        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.
329
        result = client_medium.remote_path_from_transport(transport)
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
330
        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.
331
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
332
    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.
333
        """SmartClientMedium.remote_path_from_transport calculates a URL for
334
        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.
335
        """
336
        self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
337
        self.assertRemotePath(
338
            'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
339
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
340
    def assertRemotePathHTTP(self, expected, transport_base, relpath):
341
        """Assert that the result of
342
        HttpTransportBase.remote_path_from_transport is the expected value for
343
        a given transport_base and relpath of that transport.  (Note that
344
        HttpTransportBase is a subclass of SmartClientMedium)
345
        """
346
        base_transport = get_transport(transport_base)
347
        client_medium = base_transport.get_smart_medium()
348
        cloned_transport = base_transport.clone(relpath)
349
        result = client_medium.remote_path_from_transport(cloned_transport)
350
        self.assertEqual(expected, result)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
351
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
352
    def test_remote_path_from_transport_http(self):
353
        """Remote paths for HTTP transports are calculated differently to other
354
        transports.  They are just relative to the client base, not the root
355
        directory of the host.
356
        """
357
        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.
358
            self.assertRemotePathHTTP(
359
                '../xyz/', scheme + '//host/path', '../xyz/')
360
            self.assertRemotePathHTTP(
361
                'xyz/', scheme + '//host/path', 'xyz/')
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
362
363
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
364
class Test_ClientMedium_remote_is_at_least(tests.TestCase):
365
    """Tests for the behaviour of client_medium.remote_is_at_least."""
366
367
    def test_initially_unlimited(self):
368
        """A fresh medium assumes that the remote side supports all
369
        versions.
370
        """
371
        client_medium = medium.SmartClientMedium('dummy base')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
372
        self.assertFalse(client_medium._is_remote_before((99, 99)))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
373
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
374
    def test__remember_remote_is_before(self):
375
        """Calling _remember_remote_is_before ratchets down the known remote
376
        version.
377
        """
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
378
        client_medium = medium.SmartClientMedium('dummy base')
379
        # Mark the remote side as being less than 1.6.  The remote side may
380
        # still be 1.5.
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
381
        client_medium._remember_remote_is_before((1, 6))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
382
        self.assertTrue(client_medium._is_remote_before((1, 6)))
383
        self.assertFalse(client_medium._is_remote_before((1, 5)))
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
384
        # Calling _remember_remote_is_before again with a lower value works.
385
        client_medium._remember_remote_is_before((1, 5))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
386
        self.assertTrue(client_medium._is_remote_before((1, 5)))
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
387
        # 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.
388
        self.assertRaises(
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
389
            AssertionError, client_medium._remember_remote_is_before, (1, 9))
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
390
391
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
392
class TestBzrDirCloningMetaDir(TestRemote):
393
394
    def test_backwards_compat(self):
395
        self.setup_smart_server_with_call_log()
396
        a_dir = self.make_bzrdir('.')
397
        self.reset_smart_call_log()
398
        verb = 'BzrDir.cloning_metadir'
399
        self.disable_verb(verb)
400
        format = a_dir.cloning_metadir()
401
        call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
402
            call.call.method == verb])
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
403
        self.assertEqual(1, call_count)
404
405
    def test_current_server(self):
406
        transport = self.get_transport('.')
407
        transport = transport.clone('quack')
408
        self.make_bzrdir('quack')
409
        client = FakeClient(transport.base)
410
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
411
        control_name = reference_bzrdir_format.network_name()
412
        client.add_expected_call(
413
            'BzrDir.cloning_metadir', ('quack/', 'False'),
4084.2.2 by Robert Collins
Review feedback.
414
            'success', (control_name, '', ('branch', ''))),
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
415
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
416
            _client=client)
417
        result = a_bzrdir.cloning_metadir()
418
        # We should have got a reference control dir with default branch and
419
        # repository formats.
420
        # This pokes a little, just to be sure.
421
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
4070.2.8 by Robert Collins
Really test the current BzrDir.cloning_metadir contract.
422
        self.assertEqual(None, result._repository_format)
423
        self.assertEqual(None, result._branch_format)
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
424
        client.finished_test()
425
426
4053.1.2 by Robert Collins
Actually make this branch work.
427
class TestBzrDirOpenBranch(TestRemote):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
428
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
429
    def test_backwards_compat(self):
430
        self.setup_smart_server_with_call_log()
431
        self.make_branch('.')
432
        a_dir = BzrDir.open(self.get_url('.'))
433
        self.reset_smart_call_log()
434
        verb = 'BzrDir.open_branchV2'
435
        self.disable_verb(verb)
436
        format = a_dir.open_branch()
437
        call_count = len([call for call in self.hpss_calls if
438
            call.call.method == verb])
439
        self.assertEqual(1, call_count)
440
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
441
    def test_branch_present(self):
4053.1.2 by Robert Collins
Actually make this branch work.
442
        reference_format = self.get_repo_format()
443
        network_name = reference_format.network_name()
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
444
        branch_network_name = self.get_branch_format().network_name()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
445
        transport = MemoryTransport()
446
        transport.mkdir('quack')
447
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
448
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
449
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
450
            'BzrDir.open_branchV2', ('quack/',),
451
            'success', ('branch', branch_network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
452
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
453
            'BzrDir.find_repositoryV3', ('quack/',),
454
            'success', ('ok', '', 'no', 'no', 'no', network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
455
        client.add_expected_call(
456
            'Branch.get_stacked_on_url', ('quack/',),
457
            'error', ('NotStacked',))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
458
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
459
            _client=client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
460
        result = bzrdir.open_branch()
461
        self.assertIsInstance(result, RemoteBranch)
462
        self.assertEqual(bzrdir, result.bzrdir)
3691.2.10 by Martin Pool
Update more test_remote tests
463
        client.finished_test()
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
464
465
    def test_branch_missing(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_error_response('nobranch')
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
471
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
472
            _client=client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
473
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
474
        self.assertEqual(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
475
            [('call', 'BzrDir.open_branchV2', ('quack/',))],
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
476
            client._calls)
477
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
478
    def test__get_tree_branch(self):
479
        # _get_tree_branch is a form of open_branch, but it should only ask for
480
        # branch opening, not any other network requests.
481
        calls = []
482
        def open_branch():
483
            calls.append("Called")
484
            return "a-branch"
485
        transport = MemoryTransport()
486
        # 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.
487
        client = FakeClient(transport.base)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
488
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
489
            _client=client)
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
490
        # patch the open_branch call to record that it was called.
491
        bzrdir.open_branch = open_branch
492
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
493
        self.assertEqual(["Called"], calls)
494
        self.assertEqual([], client._calls)
495
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.
496
    def test_url_quoting_of_path(self):
497
        # Relpaths on the wire should not be URL-escaped.  So "~" should be
498
        # 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.
499
        transport = RemoteTCPTransport('bzr://localhost/~hello/')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
500
        client = FakeClient(transport.base)
4053.1.2 by Robert Collins
Actually make this branch work.
501
        reference_format = self.get_repo_format()
502
        network_name = reference_format.network_name()
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
503
        branch_network_name = self.get_branch_format().network_name()
3691.2.10 by Martin Pool
Update more test_remote tests
504
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
505
            'BzrDir.open_branchV2', ('~hello/',),
506
            'success', ('branch', branch_network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
507
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
508
            'BzrDir.find_repositoryV3', ('~hello/',),
509
            'success', ('ok', '', 'no', 'no', 'no', network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
510
        client.add_expected_call(
511
            'Branch.get_stacked_on_url', ('~hello/',),
512
            'error', ('NotStacked',))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
513
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
514
            _client=client)
3192.2.1 by Andrew Bennetts
Don't transmit URL-escaped relpaths in the smart protocol, which is back to how things worked in bzr 1.1 and earlier.
515
        result = bzrdir.open_branch()
3691.2.10 by Martin Pool
Update more test_remote tests
516
        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.
517
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
518
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
4053.1.2 by Robert Collins
Actually make this branch work.
519
        reference_format = self.get_repo_format()
520
        network_name = reference_format.network_name()
3104.4.2 by Andrew Bennetts
All tests passing.
521
        transport = MemoryTransport()
522
        transport.mkdir('quack')
523
        transport = transport.clone('quack')
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
524
        if rich_root:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
525
            rich_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
526
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
527
            rich_response = 'no'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
528
        if subtrees:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
529
            subtree_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
530
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
531
            subtree_response = 'no'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
532
        client = FakeClient(transport.base)
533
        client.add_success_response(
4053.1.2 by Robert Collins
Actually make this branch work.
534
            'ok', '', rich_response, subtree_response, external_lookup,
535
            network_name)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
536
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
537
            _client=client)
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
538
        result = bzrdir.open_repository()
539
        self.assertEqual(
4053.1.2 by Robert Collins
Actually make this branch work.
540
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
541
            client._calls)
542
        self.assertIsInstance(result, RemoteRepository)
543
        self.assertEqual(bzrdir, result.bzrdir)
544
        self.assertEqual(rich_root, result._format.rich_root_data)
2018.5.138 by Robert Collins
Merge bzr.dev.
545
        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.
546
547
    def test_open_repository_sets_format_attributes(self):
548
        self.check_open_repository(True, True)
549
        self.check_open_repository(False, True)
550
        self.check_open_repository(True, False)
551
        self.check_open_repository(False, False)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
552
        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.
553
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
554
    def test_old_server(self):
555
        """RemoteBzrDirFormat should fail to probe if the server version is too
556
        old.
557
        """
558
        self.assertRaises(errors.NotBranchError,
559
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
560
561
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
562
class TestBzrDirCreateBranch(TestRemote):
563
564
    def test_backwards_compat(self):
565
        self.setup_smart_server_with_call_log()
566
        repo = self.make_repository('.')
567
        self.reset_smart_call_log()
568
        self.disable_verb('BzrDir.create_branch')
569
        branch = repo.bzrdir.create_branch()
570
        create_branch_call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
571
            call.call.method == 'BzrDir.create_branch'])
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
572
        self.assertEqual(1, create_branch_call_count)
573
574
    def test_current_server(self):
575
        transport = self.get_transport('.')
576
        transport = transport.clone('quack')
577
        self.make_repository('quack')
578
        client = FakeClient(transport.base)
579
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
580
        reference_format = reference_bzrdir_format.get_branch_format()
581
        network_name = reference_format.network_name()
582
        reference_repo_fmt = reference_bzrdir_format.repository_format
583
        reference_repo_name = reference_repo_fmt.network_name()
584
        client.add_expected_call(
585
            'BzrDir.create_branch', ('quack/', network_name),
586
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
587
            reference_repo_name))
588
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
589
            _client=client)
590
        branch = a_bzrdir.create_branch()
591
        # We should have got a remote branch
592
        self.assertIsInstance(branch, remote.RemoteBranch)
593
        # its format should have the settings from the response
594
        format = branch._format
595
        self.assertEqual(network_name, format.network_name())
596
597
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
598
class TestBzrDirCreateRepository(TestRemote):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
599
600
    def test_backwards_compat(self):
601
        self.setup_smart_server_with_call_log()
602
        bzrdir = self.make_bzrdir('.')
603
        self.reset_smart_call_log()
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
604
        self.disable_verb('BzrDir.create_repository')
605
        repo = bzrdir.create_repository()
606
        create_repo_call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
607
            call.call.method == 'BzrDir.create_repository'])
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
608
        self.assertEqual(1, create_repo_call_count)
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
609
610
    def test_current_server(self):
611
        transport = self.get_transport('.')
612
        transport = transport.clone('quack')
613
        self.make_bzrdir('quack')
614
        client = FakeClient(transport.base)
615
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
616
        reference_format = reference_bzrdir_format.repository_format
617
        network_name = reference_format.network_name()
618
        client.add_expected_call(
619
            'BzrDir.create_repository', ('quack/',
620
                'Bazaar pack repository format 1 (needs bzr 0.92)\n', 'False'),
621
            'success', ('ok', 'no', 'no', 'no', network_name))
622
        a_bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
623
            _client=client)
624
        repo = a_bzrdir.create_repository()
625
        # We should have got a remote repository
626
        self.assertIsInstance(repo, remote.RemoteRepository)
627
        # its format should have the settings from the response
628
        format = repo._format
629
        self.assertFalse(format.rich_root_data)
630
        self.assertFalse(format.supports_tree_reference)
631
        self.assertFalse(format.supports_external_lookups)
632
        self.assertEqual(network_name, format.network_name())
633
634
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
635
class TestBzrDirOpenRepository(TestRemote):
636
637
    def test_backwards_compat_1_2_3(self):
638
        # fallback all the way to the first version.
639
        reference_format = self.get_repo_format()
640
        network_name = reference_format.network_name()
641
        client = FakeClient('bzr://example.com/')
642
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
643
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
644
        client.add_success_response('ok', '', 'no', 'no')
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
645
        # A real repository instance will be created to determine the network
646
        # name.
647
        client.add_success_response_with_body(
648
            "Bazaar-NG meta directory, format 1\n", 'ok')
649
        client.add_success_response_with_body(
650
            reference_format.get_format_string(), 'ok')
651
        # PackRepository wants to do a stat
652
        client.add_success_response('stat', '0', '65535')
653
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
654
            _client=client)
655
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
656
            _client=client)
657
        repo = bzrdir.open_repository()
658
        self.assertEqual(
659
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
660
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
661
             ('call', 'BzrDir.find_repository', ('quack/',)),
662
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
663
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
664
             ('call', 'stat', ('/quack/.bzr/repository',)),
665
             ],
666
            client._calls)
667
        self.assertEqual(network_name, repo._format.network_name())
668
669
    def test_backwards_compat_2(self):
670
        # fallback to find_repositoryV2
671
        reference_format = self.get_repo_format()
672
        network_name = reference_format.network_name()
673
        client = FakeClient('bzr://example.com/')
674
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
675
        client.add_success_response('ok', '', 'no', 'no', 'no')
676
        # A real repository instance will be created to determine the network
677
        # name.
678
        client.add_success_response_with_body(
679
            "Bazaar-NG meta directory, format 1\n", 'ok')
680
        client.add_success_response_with_body(
681
            reference_format.get_format_string(), 'ok')
682
        # PackRepository wants to do a stat
683
        client.add_success_response('stat', '0', '65535')
684
        remote_transport = RemoteTransport('bzr://example.com/quack/', medium=False,
685
            _client=client)
686
        bzrdir = RemoteBzrDir(remote_transport, remote.RemoteBzrDirFormat(),
687
            _client=client)
688
        repo = bzrdir.open_repository()
689
        self.assertEqual(
690
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
691
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
692
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
693
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
694
             ('call', 'stat', ('/quack/.bzr/repository',)),
695
             ],
696
            client._calls)
697
        self.assertEqual(network_name, repo._format.network_name())
698
699
    def test_current_server(self):
700
        reference_format = self.get_repo_format()
701
        network_name = reference_format.network_name()
702
        transport = MemoryTransport()
703
        transport.mkdir('quack')
704
        transport = transport.clone('quack')
705
        client = FakeClient(transport.base)
706
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
707
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
708
            _client=client)
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
709
        repo = bzrdir.open_repository()
710
        self.assertEqual(
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
711
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
712
            client._calls)
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
713
        self.assertEqual(network_name, repo._format.network_name())
3297.3.3 by Andrew Bennetts
SmartClientRequestProtocol*.read_response_tuple can now raise UnknownSmartMethod. Callers no longer need to do their own ad hoc unknown smart method error detection.
714
715
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
716
class OldSmartClient(object):
717
    """A fake smart client for test_old_version that just returns a version one
718
    response to the 'hello' (query version) command.
719
    """
720
721
    def get_request(self):
722
        input_file = StringIO('ok\x011\n')
723
        output_file = StringIO()
724
        client_medium = medium.SmartSimplePipesClientMedium(
725
            input_file, output_file)
726
        return medium.SmartClientStreamMediumRequest(client_medium)
727
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
728
    def protocol_version(self):
729
        return 1
730
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
731
732
class OldServerTransport(object):
733
    """A fake transport for test_old_server that reports it's smart server
734
    protocol version as version one.
735
    """
736
737
    def __init__(self):
738
        self.base = 'fake:'
739
740
    def get_smart_client(self):
741
        return OldSmartClient()
742
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
743
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
744
class RemoteBranchTestCase(TestRemote):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
745
746
    def make_remote_branch(self, transport, client):
747
        """Make a RemoteBranch using 'client' as its _SmartClient.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
748
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
749
        A RemoteBzrDir and RemoteRepository will also be created to fill out
750
        the RemoteBranch, albeit with stub values for some of their attributes.
751
        """
752
        # we do not want bzrdir to make any remote calls, so use False as its
753
        # _client.  If it tries to make a remote call, this will fail
754
        # immediately.
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
755
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
756
            _client=False)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
757
        repo = RemoteRepository(bzrdir, None, _client=client)
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
758
        branch_format = self.get_branch_format()
759
        format = RemoteBranchFormat(network_name=branch_format.network_name())
760
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
761
762
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
763
class TestBranchGetParent(RemoteBranchTestCase):
764
765
    def test_no_parent(self):
766
        # in an empty branch we decode the response properly
767
        transport = MemoryTransport()
768
        client = FakeClient(transport.base)
769
        client.add_expected_call(
770
            'Branch.get_stacked_on_url', ('quack/',),
771
            'error', ('NotStacked',))
772
        client.add_expected_call(
773
            'Branch.get_parent', ('quack/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
774
            'success', ('',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
775
        transport.mkdir('quack')
776
        transport = transport.clone('quack')
777
        branch = self.make_remote_branch(transport, client)
778
        result = branch.get_parent()
779
        client.finished_test()
780
        self.assertEqual(None, result)
781
782
    def test_parent_relative(self):
783
        transport = MemoryTransport()
784
        client = FakeClient(transport.base)
785
        client.add_expected_call(
786
            'Branch.get_stacked_on_url', ('kwaak/',),
787
            'error', ('NotStacked',))
788
        client.add_expected_call(
789
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
790
            'success', ('../foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
791
        transport.mkdir('kwaak')
792
        transport = transport.clone('kwaak')
793
        branch = self.make_remote_branch(transport, client)
794
        result = branch.get_parent()
795
        self.assertEqual(transport.clone('../foo').base, result)
796
797
    def test_parent_absolute(self):
798
        transport = MemoryTransport()
799
        client = FakeClient(transport.base)
800
        client.add_expected_call(
801
            'Branch.get_stacked_on_url', ('kwaak/',),
802
            'error', ('NotStacked',))
803
        client.add_expected_call(
804
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
805
            'success', ('http://foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
806
        transport.mkdir('kwaak')
807
        transport = transport.clone('kwaak')
808
        branch = self.make_remote_branch(transport, client)
809
        result = branch.get_parent()
810
        self.assertEqual('http://foo/', result)
811
812
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
813
class TestBranchGetTagsBytes(RemoteBranchTestCase):
814
815
    def test_backwards_compat(self):
816
        self.setup_smart_server_with_call_log()
817
        branch = self.make_branch('.')
818
        self.reset_smart_call_log()
819
        verb = 'Branch.get_tags_bytes'
820
        self.disable_verb(verb)
821
        branch.tags.get_tag_dict()
822
        call_count = len([call for call in self.hpss_calls if
823
            call.call.method == verb])
824
        self.assertEqual(1, call_count)
825
826
    def test_trivial(self):
827
        transport = MemoryTransport()
828
        client = FakeClient(transport.base)
829
        client.add_expected_call(
830
            'Branch.get_stacked_on_url', ('quack/',),
831
            'error', ('NotStacked',))
832
        client.add_expected_call(
833
            'Branch.get_tags_bytes', ('quack/',),
834
            'success', ('',))
835
        transport.mkdir('quack')
836
        transport = transport.clone('quack')
837
        branch = self.make_remote_branch(transport, client)
838
        result = branch.tags.get_tag_dict()
839
        client.finished_test()
840
        self.assertEqual({}, result)
841
842
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
843
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
844
845
    def test_empty_branch(self):
846
        # in an empty branch we decode the response properly
847
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
848
        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
849
        client.add_expected_call(
850
            'Branch.get_stacked_on_url', ('quack/',),
851
            'error', ('NotStacked',))
852
        client.add_expected_call(
853
            'Branch.last_revision_info', ('quack/',),
854
            'success', ('ok', '0', 'null:'))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
855
        transport.mkdir('quack')
856
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
857
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
858
        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
859
        client.finished_test()
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
860
        self.assertEqual((0, NULL_REVISION), result)
861
862
    def test_non_empty_branch(self):
863
        # 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.
864
        revid = u'\xc8'.encode('utf8')
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
865
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
866
        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
867
        client.add_expected_call(
868
            'Branch.get_stacked_on_url', ('kwaak/',),
869
            'error', ('NotStacked',))
870
        client.add_expected_call(
871
            'Branch.last_revision_info', ('kwaak/',),
872
            'success', ('ok', '2', revid))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
873
        transport.mkdir('kwaak')
874
        transport = transport.clone('kwaak')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
875
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
876
        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.
877
        self.assertEqual((2, revid), result)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
878
879
4053.1.2 by Robert Collins
Actually make this branch work.
880
class TestBranch_get_stacked_on_url(TestRemote):
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
881
    """Test Branch._get_stacked_on_url rpc"""
882
3691.2.10 by Martin Pool
Update more test_remote tests
883
    def test_get_stacked_on_invalid_url(self):
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
884
        # test that asking for a stacked on url the server can't access works.
885
        # This isn't perfect, but then as we're in the same process there
886
        # really isn't anything we can do to be 100% sure that the server
887
        # doesn't just open in - this test probably needs to be rewritten using
888
        # a spawn()ed server.
889
        stacked_branch = self.make_branch('stacked', format='1.9')
890
        memory_branch = self.make_branch('base', format='1.9')
891
        vfs_url = self.get_vfs_only_url('base')
892
        stacked_branch.set_stacked_on_url(vfs_url)
893
        transport = stacked_branch.bzrdir.root_transport
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
894
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
895
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
896
            'Branch.get_stacked_on_url', ('stacked/',),
897
            'success', ('ok', vfs_url))
898
        # XXX: Multiple calls are bad, this second call documents what is
899
        # today.
900
        client.add_expected_call(
901
            'Branch.get_stacked_on_url', ('stacked/',),
902
            'success', ('ok', vfs_url))
903
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
904
            _client=client)
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
905
        repo_fmt = remote.RemoteRepositoryFormat()
906
        repo_fmt._custom_format = stacked_branch.repository._format
907
        branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, repo_fmt),
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
908
            _client=client)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
909
        result = branch.get_stacked_on_url()
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
910
        self.assertEqual(vfs_url, result)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
911
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
912
    def test_backwards_compatible(self):
913
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
914
        base_branch = self.make_branch('base', format='1.6')
915
        stacked_branch = self.make_branch('stacked', format='1.6')
916
        stacked_branch.set_stacked_on_url('../base')
917
        client = FakeClient(self.get_url())
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
918
        branch_network_name = self.get_branch_format().network_name()
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
919
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
920
            'BzrDir.open_branchV2', ('stacked/',),
921
            'success', ('branch', branch_network_name))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
922
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
923
            'BzrDir.find_repositoryV3', ('stacked/',),
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
924
            'success', ('ok', '', 'no', 'no', 'yes',
4053.1.2 by Robert Collins
Actually make this branch work.
925
                stacked_branch.repository._format.network_name()))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
926
        # called twice, once from constructor and then again by us
927
        client.add_expected_call(
928
            'Branch.get_stacked_on_url', ('stacked/',),
929
            'unknown', ('Branch.get_stacked_on_url',))
930
        client.add_expected_call(
931
            'Branch.get_stacked_on_url', ('stacked/',),
932
            'unknown', ('Branch.get_stacked_on_url',))
933
        # this will also do vfs access, but that goes direct to the transport
934
        # and isn't seen by the FakeClient.
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
935
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
936
            remote.RemoteBzrDirFormat(), _client=client)
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
937
        branch = bzrdir.open_branch()
938
        result = branch.get_stacked_on_url()
939
        self.assertEqual('../base', result)
940
        client.finished_test()
941
        # it's in the fallback list both for the RemoteRepository and its vfs
942
        # repository
943
        self.assertEqual(1, len(branch.repository._fallback_repositories))
944
        self.assertEqual(1,
945
            len(branch.repository._real_repository._fallback_repositories))
946
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
947
    def test_get_stacked_on_real_branch(self):
948
        base_branch = self.make_branch('base', format='1.6')
949
        stacked_branch = self.make_branch('stacked', format='1.6')
950
        stacked_branch.set_stacked_on_url('../base')
4053.1.2 by Robert Collins
Actually make this branch work.
951
        reference_format = self.get_repo_format()
952
        network_name = reference_format.network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
953
        client = FakeClient(self.get_url())
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
954
        branch_network_name = self.get_branch_format().network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
955
        client.add_expected_call(
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
956
            'BzrDir.open_branchV2', ('stacked/',),
957
            'success', ('branch', branch_network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
958
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
959
            'BzrDir.find_repositoryV3', ('stacked/',),
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
960
            'success', ('ok', '', 'no', 'no', 'yes', network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
961
        # called twice, once from constructor and then again by us
962
        client.add_expected_call(
963
            'Branch.get_stacked_on_url', ('stacked/',),
964
            'success', ('ok', '../base'))
965
        client.add_expected_call(
966
            'Branch.get_stacked_on_url', ('stacked/',),
967
            'success', ('ok', '../base'))
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
968
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
969
            remote.RemoteBzrDirFormat(), _client=client)
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
970
        branch = bzrdir.open_branch()
971
        result = branch.get_stacked_on_url()
972
        self.assertEqual('../base', result)
973
        client.finished_test()
974
        # it's in the fallback list both for the RemoteRepository and its vfs
975
        # repository
976
        self.assertEqual(1, len(branch.repository._fallback_repositories))
977
        self.assertEqual(1,
978
            len(branch.repository._real_repository._fallback_repositories))
979
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
980
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
981
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.
982
983
    def test_set_empty(self):
984
        # set_revision_history([]) is translated to calling
985
        # Branch.set_last_revision(path, '') on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
986
        transport = MemoryTransport()
987
        transport.mkdir('branch')
988
        transport = transport.clone('branch')
989
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
990
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
991
        client.add_expected_call(
992
            'Branch.get_stacked_on_url', ('branch/',),
993
            'error', ('NotStacked',))
994
        client.add_expected_call(
995
            'Branch.lock_write', ('branch/', '', ''),
996
            'success', ('ok', 'branch token', 'repo token'))
997
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
998
            'Branch.last_revision_info',
999
            ('branch/',),
1000
            'success', ('ok', '0', 'null:'))
1001
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1002
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
1003
            'success', ('ok',))
1004
        client.add_expected_call(
1005
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1006
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1007
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1008
        # This is a hack to work around the problem that RemoteBranch currently
1009
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1010
        branch._ensure_real = lambda: None
1011
        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.
1012
        result = branch.set_revision_history([])
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1013
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1014
        self.assertEqual(None, result)
3691.2.10 by Martin Pool
Update more test_remote tests
1015
        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.
1016
1017
    def test_set_nonempty(self):
1018
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
1019
        # Branch.set_last_revision(path, rev-idN) on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
1020
        transport = MemoryTransport()
1021
        transport.mkdir('branch')
1022
        transport = transport.clone('branch')
1023
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1024
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1025
        client.add_expected_call(
1026
            'Branch.get_stacked_on_url', ('branch/',),
1027
            'error', ('NotStacked',))
1028
        client.add_expected_call(
1029
            'Branch.lock_write', ('branch/', '', ''),
1030
            'success', ('ok', 'branch token', 'repo token'))
1031
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1032
            'Branch.last_revision_info',
1033
            ('branch/',),
1034
            'success', ('ok', '0', 'null:'))
1035
        lines = ['rev-id2']
1036
        encoded_body = bz2.compress('\n'.join(lines))
1037
        client.add_success_response_with_body(encoded_body, 'ok')
1038
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1039
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
1040
            'success', ('ok',))
1041
        client.add_expected_call(
1042
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1043
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1044
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1045
        # This is a hack to work around the problem that RemoteBranch currently
1046
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1047
        branch._ensure_real = lambda: None
1048
        # Lock the branch, reset the record of remote calls.
1049
        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.
1050
        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.
1051
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1052
        self.assertEqual(None, result)
3691.2.10 by Martin Pool
Update more test_remote tests
1053
        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.
1054
1055
    def test_no_such_revision(self):
1056
        transport = MemoryTransport()
1057
        transport.mkdir('branch')
1058
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1059
        # A response of 'NoSuchRevision' is translated into an exception.
1060
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1061
        client.add_expected_call(
1062
            'Branch.get_stacked_on_url', ('branch/',),
1063
            'error', ('NotStacked',))
1064
        client.add_expected_call(
1065
            'Branch.lock_write', ('branch/', '', ''),
1066
            'success', ('ok', 'branch token', 'repo token'))
1067
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1068
            'Branch.last_revision_info',
1069
            ('branch/',),
1070
            'success', ('ok', '0', 'null:'))
1071
        # get_graph calls to construct the revision history, for the set_rh
1072
        # hook
1073
        lines = ['rev-id']
1074
        encoded_body = bz2.compress('\n'.join(lines))
1075
        client.add_success_response_with_body(encoded_body, 'ok')
1076
        client.add_expected_call(
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1077
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1078
            'error', ('NoSuchRevision', 'rev-id'))
1079
        client.add_expected_call(
1080
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1081
            'success', ('ok',))
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1082
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1083
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1084
        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.
1085
        self.assertRaises(
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1086
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1087
        branch.unlock()
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1088
        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.
1089
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1090
    def test_tip_change_rejected(self):
1091
        """TipChangeRejected responses cause a TipChangeRejected exception to
1092
        be raised.
1093
        """
1094
        transport = MemoryTransport()
1095
        transport.mkdir('branch')
1096
        transport = transport.clone('branch')
1097
        client = FakeClient(transport.base)
1098
        rejection_msg_unicode = u'rejection message\N{INTERROBANG}'
1099
        rejection_msg_utf8 = rejection_msg_unicode.encode('utf8')
3691.2.10 by Martin Pool
Update more test_remote tests
1100
        client.add_expected_call(
1101
            'Branch.get_stacked_on_url', ('branch/',),
1102
            'error', ('NotStacked',))
1103
        client.add_expected_call(
1104
            'Branch.lock_write', ('branch/', '', ''),
1105
            'success', ('ok', 'branch token', 'repo token'))
1106
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1107
            'Branch.last_revision_info',
1108
            ('branch/',),
1109
            'success', ('ok', '0', 'null:'))
1110
        lines = ['rev-id']
1111
        encoded_body = bz2.compress('\n'.join(lines))
1112
        client.add_success_response_with_body(encoded_body, 'ok')
1113
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1114
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1115
            'error', ('TipChangeRejected', rejection_msg_utf8))
1116
        client.add_expected_call(
1117
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1118
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1119
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1120
        branch._ensure_real = lambda: None
1121
        branch.lock_write()
1122
        # The 'TipChangeRejected' error response triggered by calling
1123
        # set_revision_history causes a TipChangeRejected exception.
1124
        err = self.assertRaises(
1125
            errors.TipChangeRejected, branch.set_revision_history, ['rev-id'])
1126
        # The UTF-8 message from the response has been decoded into a unicode
1127
        # object.
1128
        self.assertIsInstance(err.msg, unicode)
1129
        self.assertEqual(rejection_msg_unicode, err.msg)
3691.2.10 by Martin Pool
Update more test_remote tests
1130
        branch.unlock()
1131
        client.finished_test()
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1132
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1133
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1134
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1135
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1136
    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.
1137
        # set_last_revision_info(num, 'rev-id') is translated to calling
1138
        # 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'.
1139
        transport = MemoryTransport()
1140
        transport.mkdir('branch')
1141
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1142
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1143
        # get_stacked_on_url
1144
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1145
        # lock_write
1146
        client.add_success_response('ok', 'branch token', 'repo token')
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1147
        # query the current revision
1148
        client.add_success_response('ok', '0', 'null:')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1149
        # set_last_revision
1150
        client.add_success_response('ok')
1151
        # unlock
1152
        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.
1153
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1154
        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.
1155
        # Lock the branch, reset the record of remote calls.
1156
        branch.lock_write()
1157
        client._calls = []
1158
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1159
        self.assertEqual(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1160
            [('call', 'Branch.last_revision_info', ('branch/',)),
1161
             ('call', 'Branch.set_last_revision_info',
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
1162
                ('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.
1163
                 '1234', 'a-revision-id'))],
1164
            client._calls)
1165
        self.assertEqual(None, result)
1166
1167
    def test_no_such_revision(self):
1168
        # A response of 'NoSuchRevision' is translated into an exception.
1169
        transport = MemoryTransport()
1170
        transport.mkdir('branch')
1171
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1172
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1173
        # get_stacked_on_url
1174
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1175
        # lock_write
1176
        client.add_success_response('ok', 'branch token', 'repo token')
1177
        # set_last_revision
1178
        client.add_error_response('NoSuchRevision', 'revid')
1179
        # unlock
1180
        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.
1181
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1182
        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.
1183
        # Lock the branch, reset the record of remote calls.
1184
        branch.lock_write()
1185
        client._calls = []
1186
1187
        self.assertRaises(
1188
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1189
        branch.unlock()
1190
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1191
    def lock_remote_branch(self, branch):
1192
        """Trick a RemoteBranch into thinking it is locked."""
1193
        branch._lock_mode = 'w'
1194
        branch._lock_count = 2
1195
        branch._lock_token = 'branch token'
1196
        branch._repo_lock_token = 'repo token'
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1197
        branch.repository._lock_mode = 'w'
1198
        branch.repository._lock_count = 2
1199
        branch.repository._lock_token = 'repo token'
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1200
1201
    def test_backwards_compatibility(self):
1202
        """If the server does not support the Branch.set_last_revision_info
1203
        verb (which is new in 1.4), then the client falls back to VFS methods.
1204
        """
1205
        # This test is a little messy.  Unlike most tests in this file, it
1206
        # doesn't purely test what a Remote* object sends over the wire, and
1207
        # how it reacts to responses from the wire.  It instead relies partly
1208
        # on asserting that the RemoteBranch will call
1209
        # self._real_branch.set_last_revision_info(...).
1210
1211
        # First, set up our RemoteBranch with a FakeClient that raises
1212
        # UnknownSmartMethod, and a StubRealBranch that logs how it is called.
1213
        transport = MemoryTransport()
1214
        transport.mkdir('branch')
1215
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1216
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1217
        client.add_expected_call(
1218
            'Branch.get_stacked_on_url', ('branch/',),
1219
            'error', ('NotStacked',))
1220
        client.add_expected_call(
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1221
            'Branch.last_revision_info',
1222
            ('branch/',),
1223
            'success', ('ok', '0', 'null:'))
1224
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1225
            'Branch.set_last_revision_info',
1226
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
1227
            'unknown', 'Branch.set_last_revision_info')
1228
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1229
        branch = self.make_remote_branch(transport, client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1230
        class StubRealBranch(object):
1231
            def __init__(self):
1232
                self.calls = []
1233
            def set_last_revision_info(self, revno, revision_id):
1234
                self.calls.append(
1235
                    ('set_last_revision_info', revno, revision_id))
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1236
            def _clear_cached_state(self):
1237
                pass
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1238
        real_branch = StubRealBranch()
1239
        branch._real_branch = real_branch
1240
        self.lock_remote_branch(branch)
1241
1242
        # Call set_last_revision_info, and verify it behaved as expected.
1243
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1244
        self.assertEqual(
1245
            [('set_last_revision_info', 1234, 'a-revision-id')],
1246
            real_branch.calls)
3691.2.10 by Martin Pool
Update more test_remote tests
1247
        client.finished_test()
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1248
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1249
    def test_unexpected_error(self):
3697.2.6 by Martin Pool
Merge 261315 fix into 1.7 branch
1250
        # If the server sends an error the client doesn't understand, it gets
1251
        # turned into an UnknownErrorFromSmartServer, which is presented as a
1252
        # non-internal error to the user.
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1253
        transport = MemoryTransport()
1254
        transport.mkdir('branch')
1255
        transport = transport.clone('branch')
1256
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1257
        # get_stacked_on_url
1258
        client.add_error_response('NotStacked')
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1259
        # lock_write
1260
        client.add_success_response('ok', 'branch token', 'repo token')
1261
        # set_last_revision
1262
        client.add_error_response('UnexpectedError')
1263
        # unlock
1264
        client.add_success_response('ok')
1265
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1266
        branch = self.make_remote_branch(transport, client)
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1267
        # Lock the branch, reset the record of remote calls.
1268
        branch.lock_write()
1269
        client._calls = []
1270
1271
        err = self.assertRaises(
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1272
            errors.UnknownErrorFromSmartServer,
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1273
            branch.set_last_revision_info, 123, 'revid')
1274
        self.assertEqual(('UnexpectedError',), err.error_tuple)
1275
        branch.unlock()
1276
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1277
    def test_tip_change_rejected(self):
1278
        """TipChangeRejected responses cause a TipChangeRejected exception to
1279
        be raised.
1280
        """
1281
        transport = MemoryTransport()
1282
        transport.mkdir('branch')
1283
        transport = transport.clone('branch')
1284
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1285
        # get_stacked_on_url
1286
        client.add_error_response('NotStacked')
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1287
        # lock_write
1288
        client.add_success_response('ok', 'branch token', 'repo token')
1289
        # set_last_revision
1290
        client.add_error_response('TipChangeRejected', 'rejection message')
1291
        # unlock
1292
        client.add_success_response('ok')
1293
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1294
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1295
        # Lock the branch, reset the record of remote calls.
1296
        branch.lock_write()
1297
        self.addCleanup(branch.unlock)
1298
        client._calls = []
1299
1300
        # The 'TipChangeRejected' error response triggered by calling
1301
        # set_last_revision_info causes a TipChangeRejected exception.
1302
        err = self.assertRaises(
1303
            errors.TipChangeRejected,
1304
            branch.set_last_revision_info, 123, 'revid')
1305
        self.assertEqual('rejection message', err.msg)
1306
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1307
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.
1308
class TestBranchControlGetBranchConf(tests.TestCaseWithMemoryTransport):
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
1309
    """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).
1310
    """
1311
1312
    def test_get_branch_conf(self):
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
1313
        raise tests.KnownFailure('branch.conf is not retrieved by get_config_file')
3407.2.10 by Martin Pool
Merge trunk
1314
        ## # We should see that branch.get_config() does a single rpc to get the
1315
        ## # remote configuration file, abstracting away where that is stored on
1316
        ## # the server.  However at the moment it always falls back to using the
1317
        ## # vfs, and this would need some changes in config.py.
3408.3.1 by Martin Pool
Remove erroneous handling of branch.conf for RemoteBranch
1318
3407.2.10 by Martin Pool
Merge trunk
1319
        ## # in an empty branch we decode the response properly
1320
        ## client = FakeClient([(('ok', ), '# config file body')], self.get_url())
1321
        ## # we need to make a real branch because the remote_branch.control_files
1322
        ## # will trigger _ensure_real.
1323
        ## branch = self.make_branch('quack')
1324
        ## transport = branch.bzrdir.root_transport
1325
        ## # we do not want bzrdir to make any remote calls
1326
        ## bzrdir = RemoteBzrDir(transport, _client=False)
1327
        ## branch = RemoteBranch(bzrdir, None, _client=client)
1328
        ## config = branch.get_config()
1329
        ## self.assertEqual(
1330
        ##     [('call_expecting_body', 'Branch.get_config_file', ('quack/',))],
1331
        ##     client._calls)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1332
1333
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1334
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.
1335
1336
    def test_lock_write_unlockable(self):
1337
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1338
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1339
        client.add_expected_call(
1340
            'Branch.get_stacked_on_url', ('quack/',),
1341
            'error', ('NotStacked',),)
1342
        client.add_expected_call(
1343
            'Branch.lock_write', ('quack/', '', ''),
1344
            '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.
1345
        transport.mkdir('quack')
1346
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1347
        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.
1348
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1349
        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.
1350
1351
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1352
class TestTransportIsReadonly(tests.TestCase):
1353
1354
    def test_true(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1355
        client = FakeClient()
1356
        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.
1357
        transport = RemoteTransport('bzr://example.com/', medium=False,
1358
                                    _client=client)
1359
        self.assertEqual(True, transport.is_readonly())
1360
        self.assertEqual(
1361
            [('call', 'Transport.is_readonly', ())],
1362
            client._calls)
1363
1364
    def test_false(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1365
        client = FakeClient()
1366
        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.
1367
        transport = RemoteTransport('bzr://example.com/', medium=False,
1368
                                    _client=client)
1369
        self.assertEqual(False, transport.is_readonly())
1370
        self.assertEqual(
1371
            [('call', 'Transport.is_readonly', ())],
1372
            client._calls)
1373
1374
    def test_error_from_old_server(self):
1375
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1376
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1377
        Clients should treat it as a "no" response, because is_readonly is only
1378
        advisory anyway (a transport could be read-write, but then the
1379
        underlying filesystem could be readonly anyway).
1380
        """
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1381
        client = FakeClient()
1382
        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.
1383
        transport = RemoteTransport('bzr://example.com/', medium=False,
1384
                                    _client=client)
1385
        self.assertEqual(False, transport.is_readonly())
1386
        self.assertEqual(
1387
            [('call', 'Transport.is_readonly', ())],
1388
            client._calls)
1389
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1390
3840.1.1 by Andrew Bennetts
Fix RemoteTransport's translation of errors involving paths; it wasn't passing orig_path to _translate_error.
1391
class TestTransportMkdir(tests.TestCase):
1392
1393
    def test_permissiondenied(self):
1394
        client = FakeClient()
1395
        client.add_error_response('PermissionDenied', 'remote path', 'extra')
1396
        transport = RemoteTransport('bzr://example.com/', medium=False,
1397
                                    _client=client)
1398
        exc = self.assertRaises(
1399
            errors.PermissionDenied, transport.mkdir, 'client path')
1400
        expected_error = errors.PermissionDenied('/client path', 'extra')
1401
        self.assertEqual(expected_error, exc)
1402
1403
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1404
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
1405
1406
    def test_defaults_to_none(self):
1407
        t = RemoteSSHTransport('bzr+ssh://example.com')
1408
        self.assertIs(None, t._get_credentials()[0])
1409
1410
    def test_uses_authentication_config(self):
1411
        conf = config.AuthenticationConfig()
1412
        conf._get_config().update(
1413
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
1414
            'example.com'}})
1415
        conf._save()
1416
        t = RemoteSSHTransport('bzr+ssh://example.com')
1417
        self.assertEqual('bar', t._get_credentials()[0])
1418
1419
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1420
class TestRemoteRepository(TestRemote):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1421
    """Base for testing RemoteRepository protocol usage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1422
1423
    These tests contain frozen requests and responses.  We want any changes to
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1424
    what is sent or expected to be require a thoughtful update to these tests
1425
    because they might break compatibility with different-versioned servers.
1426
    """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1427
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1428
    def setup_fake_client_and_repository(self, transport_path):
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1429
        """Create the fake client and repository for testing with.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1430
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1431
        There's no real server here; we just have canned responses sent
1432
        back one by one.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1433
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1434
        :param transport_path: Path below the root of the MemoryTransport
1435
            where the repository will be created.
1436
        """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1437
        transport = MemoryTransport()
1438
        transport.mkdir(transport_path)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1439
        client = FakeClient(transport.base)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1440
        transport = transport.clone(transport_path)
1441
        # we do not want bzrdir to make any remote calls
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1442
        bzrdir = RemoteBzrDir(transport, remote.RemoteBzrDirFormat(),
1443
            _client=False)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1444
        repo = RemoteRepository(bzrdir, None, _client=client)
1445
        return repo, client
1446
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1447
2018.12.2 by Andrew Bennetts
Remove some duplicate code in test_remote
1448
class TestRepositoryGatherStats(TestRemoteRepository):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1449
1450
    def test_revid_none(self):
1451
        # ('ok',), body with revisions and size
1452
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1453
        repo, client = self.setup_fake_client_and_repository(transport_path)
1454
        client.add_success_response_with_body(
1455
            'revisions: 2\nsize: 18\n', 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1456
        result = repo.gather_stats(None)
1457
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1458
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1459
             ('quack/','','no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1460
            client._calls)
1461
        self.assertEqual({'revisions': 2, 'size': 18}, result)
1462
1463
    def test_revid_no_committers(self):
1464
        # ('ok',), body without committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1465
        body = ('firstrev: 123456.300 3600\n'
1466
                'latestrev: 654231.400 0\n'
1467
                'revisions: 2\n'
1468
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1469
        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.
1470
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1471
        repo, client = self.setup_fake_client_and_repository(transport_path)
1472
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1473
        result = repo.gather_stats(revid)
1474
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1475
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1476
              ('quick/', revid, 'no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1477
            client._calls)
1478
        self.assertEqual({'revisions': 2, 'size': 18,
1479
                          'firstrev': (123456.300, 3600),
1480
                          'latestrev': (654231.400, 0),},
1481
                         result)
1482
1483
    def test_revid_with_committers(self):
1484
        # ('ok',), body with committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1485
        body = ('committers: 128\n'
1486
                'firstrev: 123456.300 3600\n'
1487
                'latestrev: 654231.400 0\n'
1488
                'revisions: 2\n'
1489
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1490
        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.
1491
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1492
        repo, client = self.setup_fake_client_and_repository(transport_path)
1493
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1494
        result = repo.gather_stats(revid, True)
1495
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
1496
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
1497
              ('buick/', revid, 'yes'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
1498
            client._calls)
1499
        self.assertEqual({'revisions': 2, 'size': 18,
1500
                          'committers': 128,
1501
                          'firstrev': (123456.300, 3600),
1502
                          'latestrev': (654231.400, 0),},
1503
                         result)
1504
1505
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1506
class TestRepositoryGetGraph(TestRemoteRepository):
1507
1508
    def test_get_graph(self):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1509
        # 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.
1510
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1511
        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.
1512
        graph = repo.get_graph()
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
1513
        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.
1514
1515
1516
class TestRepositoryGetParentMap(TestRemoteRepository):
1517
1518
    def test_get_parent_map_caching(self):
1519
        # get_parent_map returns from cache until unlock()
1520
        # setup a reponse with two revisions
1521
        r1 = u'\u0e33'.encode('utf8')
1522
        r2 = u'\u0dab'.encode('utf8')
1523
        lines = [' '.join([r2, r1]), r1]
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
1524
        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.
1525
1526
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1527
        repo, client = self.setup_fake_client_and_repository(transport_path)
1528
        client.add_success_response_with_body(encoded_body, 'ok')
1529
        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.
1530
        repo.lock_read()
1531
        graph = repo.get_graph()
1532
        parents = graph.get_parent_map([r2])
1533
        self.assertEqual({r2: (r1,)}, parents)
1534
        # locking and unlocking deeper should not reset
1535
        repo.lock_read()
1536
        repo.unlock()
1537
        parents = graph.get_parent_map([r1])
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1538
        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.
1539
        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.
1540
            [('call_with_body_bytes_expecting_body',
1541
              '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.
1542
            client._calls)
1543
        repo.unlock()
1544
        # now we call again, and it should use the second response.
1545
        repo.lock_read()
1546
        graph = repo.get_graph()
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
1547
        parents = graph.get_parent_map([r1])
1548
        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.
1549
        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.
1550
            [('call_with_body_bytes_expecting_body',
1551
              'Repository.get_parent_map', ('quack/', r2), '\n\n0'),
1552
             ('call_with_body_bytes_expecting_body',
1553
              '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.
1554
            ],
1555
            client._calls)
1556
        repo.unlock()
1557
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
1558
    def test_get_parent_map_reconnects_if_unknown_method(self):
1559
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1560
        repo, client = self.setup_fake_client_and_repository(transport_path)
3842.3.20 by Andrew Bennetts
Re-revert changes from another thread that accidentally got reinstated here.
1561
        client.add_unknown_method_response('Repository,get_parent_map')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1562
        client.add_success_response_with_body('', 'ok')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
1563
        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.
1564
        rev_id = 'revision-id'
3297.3.5 by Andrew Bennetts
Suppress a deprecation warning.
1565
        expected_deprecations = [
1566
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1567
            'in version 1.4.']
1568
        parents = self.callDeprecated(
1569
            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.
1570
        self.assertEqual(
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
1571
            [('call_with_body_bytes_expecting_body',
1572
              '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.
1573
             ('disconnect medium',),
1574
             ('call_expecting_body', 'Repository.get_revision_graph',
1575
              ('quack/', ''))],
1576
            client._calls)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1577
        # 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.
1578
        self.assertTrue(client._medium._is_remote_before((1, 2)))
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1579
1580
    def test_get_parent_map_fallback_parentless_node(self):
1581
        """get_parent_map falls back to get_revision_graph on old servers.  The
1582
        results from get_revision_graph are tweaked to match the get_parent_map
1583
        API.
1584
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1585
        Specifically, a {key: ()} result from get_revision_graph means "no
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1586
        parents" for that key, which in get_parent_map results should be
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
1587
        represented as {key: ('null:',)}.
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1588
1589
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
1590
        """
1591
        rev_id = 'revision-id'
1592
        transport_path = 'quack'
3245.4.40 by Andrew Bennetts
Merge from bzr.dev.
1593
        repo, client = self.setup_fake_client_and_repository(transport_path)
1594
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
1595
        client._medium._remember_remote_is_before((1, 2))
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
1596
        expected_deprecations = [
1597
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
1598
            'in version 1.4.']
1599
        parents = self.callDeprecated(
1600
            expected_deprecations, repo.get_parent_map, [rev_id])
1601
        self.assertEqual(
1602
            [('call_expecting_body', 'Repository.get_revision_graph',
1603
             ('quack/', ''))],
1604
            client._calls)
1605
        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.
1606
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1607
    def test_get_parent_map_unexpected_response(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1608
        repo, client = self.setup_fake_client_and_repository('path')
1609
        client.add_success_response('something unexpected!')
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
1610
        self.assertRaises(
1611
            errors.UnexpectedSmartServerResponse,
1612
            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.
1613
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
1614
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
1615
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
1616
1617
    def test_allows_new_revisions(self):
1618
        """get_parent_map's results can be updated by commit."""
1619
        smart_server = server.SmartTCPServer_for_testing()
1620
        smart_server.setUp()
1621
        self.addCleanup(smart_server.tearDown)
1622
        self.make_branch('branch')
1623
        branch = Branch.open(smart_server.get_url() + '/branch')
1624
        tree = branch.create_checkout('tree', lightweight=True)
1625
        tree.lock_write()
1626
        self.addCleanup(tree.unlock)
1627
        graph = tree.branch.repository.get_graph()
1628
        # This provides an opportunity for the missing rev-id to be cached.
1629
        self.assertEqual({}, graph.get_parent_map(['rev1']))
1630
        tree.commit('message', rev_id='rev1')
1631
        graph = tree.branch.repository.get_graph()
1632
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
1633
1634
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1635
class TestRepositoryIsShared(TestRemoteRepository):
1636
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1637
    def test_is_shared(self):
1638
        # ('yes', ) for Repository.is_shared -> 'True'.
1639
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1640
        repo, client = self.setup_fake_client_and_repository(transport_path)
1641
        client.add_success_response('yes')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1642
        result = repo.is_shared()
1643
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1644
            [('call', 'Repository.is_shared', ('quack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1645
            client._calls)
1646
        self.assertEqual(True, result)
1647
1648
    def test_is_not_shared(self):
1649
        # ('no', ) for Repository.is_shared -> 'False'.
1650
        transport_path = 'qwack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1651
        repo, client = self.setup_fake_client_and_repository(transport_path)
1652
        client.add_success_response('no')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1653
        result = repo.is_shared()
1654
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1655
            [('call', 'Repository.is_shared', ('qwack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1656
            client._calls)
1657
        self.assertEqual(False, result)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1658
1659
1660
class TestRepositoryLockWrite(TestRemoteRepository):
1661
1662
    def test_lock_write(self):
1663
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1664
        repo, client = self.setup_fake_client_and_repository(transport_path)
1665
        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
1666
        result = repo.lock_write()
1667
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1668
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1669
            client._calls)
1670
        self.assertEqual('a token', result)
1671
1672
    def test_lock_write_already_locked(self):
1673
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1674
        repo, client = self.setup_fake_client_and_repository(transport_path)
1675
        client.add_error_response('LockContention')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1676
        self.assertRaises(errors.LockContention, repo.lock_write)
1677
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1678
            [('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.
1679
            client._calls)
1680
1681
    def test_lock_write_unlockable(self):
1682
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1683
        repo, client = self.setup_fake_client_and_repository(transport_path)
1684
        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.
1685
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
1686
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1687
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1688
            client._calls)
1689
1690
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1691
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
1692
1693
    def test_backwards_compat(self):
1694
        self.setup_smart_server_with_call_log()
1695
        repo = self.make_repository('.')
1696
        self.reset_smart_call_log()
1697
        verb = 'Repository.set_make_working_trees'
1698
        self.disable_verb(verb)
1699
        repo.set_make_working_trees(True)
1700
        call_count = len([call for call in self.hpss_calls if
4070.3.1 by Robert Collins
Alter branch sprouting with an alternate fix for stacked branches that does not require multiple copy_content_into and set_parent calls, reducing IO and round trips.
1701
            call.call.method == verb])
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1702
        self.assertEqual(1, call_count)
1703
1704
    def test_current(self):
1705
        transport_path = 'quack'
1706
        repo, client = self.setup_fake_client_and_repository(transport_path)
1707
        client.add_expected_call(
1708
            'Repository.set_make_working_trees', ('quack/', 'True'),
1709
            'success', ('ok',))
1710
        client.add_expected_call(
1711
            'Repository.set_make_working_trees', ('quack/', 'False'),
1712
            'success', ('ok',))
1713
        repo.set_make_working_trees(True)
1714
        repo.set_make_working_trees(False)
1715
1716
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1717
class TestRepositoryUnlock(TestRemoteRepository):
1718
1719
    def test_unlock(self):
1720
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1721
        repo, client = self.setup_fake_client_and_repository(transport_path)
1722
        client.add_success_response('ok', 'a token')
1723
        client.add_success_response('ok')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1724
        repo.lock_write()
1725
        repo.unlock()
1726
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
1727
            [('call', 'Repository.lock_write', ('quack/', '')),
1728
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1729
            client._calls)
1730
1731
    def test_unlock_wrong_token(self):
1732
        # If somehow the token is wrong, unlock will raise TokenMismatch.
1733
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1734
        repo, client = self.setup_fake_client_and_repository(transport_path)
1735
        client.add_success_response('ok', 'a token')
1736
        client.add_error_response('TokenMismatch')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
1737
        repo.lock_write()
1738
        self.assertRaises(errors.TokenMismatch, repo.unlock)
1739
1740
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1741
class TestRepositoryHasRevision(TestRemoteRepository):
1742
1743
    def test_none(self):
1744
        # repo.has_revision(None) should not cause any traffic.
1745
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1746
        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.
1747
1748
        # The null revision is always there, so has_revision(None) == True.
3172.3.3 by Robert Collins
Missed one occurence of None -> NULL_REVISION.
1749
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1750
1751
        # The remote repo shouldn't be accessed.
1752
        self.assertEqual([], client._calls)
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1753
1754
1755
class TestRepositoryTarball(TestRemoteRepository):
1756
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1757
    # This is a canned tarball reponse we can validate against
2018.18.18 by Martin Pool
reformat
1758
    tarball_content = (
2018.18.23 by Martin Pool
review cleanups
1759
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
1760
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
1761
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
1762
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
1763
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
1764
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
1765
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
1766
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
1767
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
1768
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
1769
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
1770
        'nWQ7QH/F3JFOFCQ0aSPfA='
1771
        ).decode('base64')
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1772
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1773
    def test_repository_tarball(self):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1774
        # Test that Repository.tarball generates the right operations
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1775
        transport_path = 'repo'
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
1776
        expected_calls = [('call_expecting_body', 'Repository.tarball',
3104.4.2 by Andrew Bennetts
All tests passing.
1777
                           ('repo/', 'bz2',),),
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1778
            ]
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1779
        repo, client = self.setup_fake_client_and_repository(transport_path)
1780
        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
1781
        # Now actually ask for the tarball
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1782
        tarball_file = repo._get_tarball('bz2')
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
1783
        try:
1784
            self.assertEqual(expected_calls, client._calls)
1785
            self.assertEqual(self.tarball_content, tarball_file.read())
1786
        finally:
1787
            tarball_file.close()
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1788
1789
1790
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
1791
    """RemoteRepository.copy_content_into optimizations"""
1792
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
1793
    def test_copy_content_remote_to_local(self):
1794
        self.transport_server = server.SmartTCPServer_for_testing
1795
        src_repo = self.make_repository('repo1')
1796
        src_repo = repository.Repository.open(self.get_url('repo1'))
1797
        # At the moment the tarball-based copy_content_into can't write back
1798
        # into a smart server.  It would be good if it could upload the
1799
        # tarball; once that works we'd have to create repositories of
1800
        # different formats. -- mbp 20070410
1801
        dest_url = self.get_vfs_only_url('repo2')
1802
        dest_bzrdir = BzrDir.create(dest_url)
1803
        dest_repo = dest_bzrdir.create_repository()
1804
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
1805
        self.assertTrue(isinstance(src_repo, RemoteRepository))
1806
        src_repo.copy_content_into(dest_repo)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1807
1808
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1809
class _StubRealPackRepository(object):
1810
1811
    def __init__(self, calls):
1812
        self._pack_collection = _StubPackCollection(calls)
1813
1814
1815
class _StubPackCollection(object):
1816
1817
    def __init__(self, calls):
1818
        self.calls = calls
1819
1820
    def autopack(self):
1821
        self.calls.append(('pack collection autopack',))
1822
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1823
    def reload_pack_names(self):
1824
        self.calls.append(('pack collection reload_pack_names',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1825
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1826
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1827
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
1828
    """Tests for RemoteRepository.autopack implementation."""
1829
1830
    def test_ok(self):
1831
        """When the server returns 'ok' and there's no _real_repository, then
1832
        nothing else happens: the autopack method is done.
1833
        """
1834
        transport_path = 'quack'
1835
        repo, client = self.setup_fake_client_and_repository(transport_path)
1836
        client.add_expected_call(
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1837
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1838
        repo.autopack()
1839
        client.finished_test()
1840
1841
    def test_ok_with_real_repo(self):
1842
        """When the server returns 'ok' and there is a _real_repository, then
1843
        the _real_repository's reload_pack_name's method will be called.
1844
        """
1845
        transport_path = 'quack'
1846
        repo, client = self.setup_fake_client_and_repository(transport_path)
1847
        client.add_expected_call(
1848
            'PackRepository.autopack', ('quack/',),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1849
            'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1850
        repo._real_repository = _StubRealPackRepository(client._calls)
1851
        repo.autopack()
1852
        self.assertEqual(
1853
            [('call', 'PackRepository.autopack', ('quack/',)),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
1854
             ('pack collection reload_pack_names',)],
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1855
            client._calls)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1856
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1857
    def test_backwards_compatibility(self):
1858
        """If the server does not recognise the PackRepository.autopack verb,
1859
        fallback to the real_repository's implementation.
1860
        """
1861
        transport_path = 'quack'
1862
        repo, client = self.setup_fake_client_and_repository(transport_path)
1863
        client.add_unknown_method_response('PackRepository.autopack')
1864
        def stub_ensure_real():
1865
            client._calls.append(('_ensure_real',))
1866
            repo._real_repository = _StubRealPackRepository(client._calls)
1867
        repo._ensure_real = stub_ensure_real
1868
        repo.autopack()
1869
        self.assertEqual(
1870
            [('call', 'PackRepository.autopack', ('quack/',)),
1871
             ('_ensure_real',),
1872
             ('pack collection autopack',)],
1873
            client._calls)
1874
1875
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1876
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
1877
    """Base class for unit tests for bzrlib.remote._translate_error."""
1878
1879
    def translateTuple(self, error_tuple, **context):
1880
        """Call _translate_error with an ErrorFromSmartServer built from the
1881
        given error_tuple.
1882
1883
        :param error_tuple: A tuple of a smart server response, as would be
1884
            passed to an ErrorFromSmartServer.
1885
        :kwargs context: context items to call _translate_error with.
1886
1887
        :returns: The error raised by _translate_error.
1888
        """
1889
        # Raise the ErrorFromSmartServer before passing it as an argument,
1890
        # because _translate_error may need to re-raise it with a bare 'raise'
1891
        # statement.
1892
        server_error = errors.ErrorFromSmartServer(error_tuple)
1893
        translated_error = self.translateErrorFromSmartServer(
1894
            server_error, **context)
1895
        return translated_error
1896
1897
    def translateErrorFromSmartServer(self, error_object, **context):
1898
        """Like translateTuple, but takes an already constructed
1899
        ErrorFromSmartServer rather than a tuple.
1900
        """
1901
        try:
1902
            raise error_object
1903
        except errors.ErrorFromSmartServer, server_error:
1904
            translated_error = self.assertRaises(
1905
                errors.BzrError, remote._translate_error, server_error,
1906
                **context)
1907
        return translated_error
1908
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
1909
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1910
class TestErrorTranslationSuccess(TestErrorTranslationBase):
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1911
    """Unit tests for bzrlib.remote._translate_error.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1912
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1913
    Given an ErrorFromSmartServer (which has an error tuple from a smart
1914
    server) and some context, _translate_error raises more specific errors from
1915
    bzrlib.errors.
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1916
1917
    This test case covers the cases where _translate_error succeeds in
1918
    translating an ErrorFromSmartServer to something better.  See
1919
    TestErrorTranslationRobustness for other cases.
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1920
    """
1921
1922
    def test_NoSuchRevision(self):
1923
        branch = self.make_branch('')
1924
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1925
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1926
            ('NoSuchRevision', revid), branch=branch)
1927
        expected_error = errors.NoSuchRevision(branch, revid)
1928
        self.assertEqual(expected_error, translated_error)
1929
1930
    def test_nosuchrevision(self):
1931
        repository = self.make_repository('')
1932
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1933
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1934
            ('nosuchrevision', revid), repository=repository)
1935
        expected_error = errors.NoSuchRevision(repository, revid)
1936
        self.assertEqual(expected_error, translated_error)
1937
1938
    def test_nobranch(self):
1939
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1940
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1941
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
1942
        self.assertEqual(expected_error, translated_error)
1943
1944
    def test_LockContention(self):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1945
        translated_error = self.translateTuple(('LockContention',))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1946
        expected_error = errors.LockContention('(remote lock)')
1947
        self.assertEqual(expected_error, translated_error)
1948
1949
    def test_UnlockableTransport(self):
1950
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1951
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1952
            ('UnlockableTransport',), bzrdir=bzrdir)
1953
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
1954
        self.assertEqual(expected_error, translated_error)
1955
1956
    def test_LockFailed(self):
1957
        lock = 'str() of a server lock'
1958
        why = 'str() of why'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1959
        translated_error = self.translateTuple(('LockFailed', lock, why))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1960
        expected_error = errors.LockFailed(lock, why)
1961
        self.assertEqual(expected_error, translated_error)
1962
1963
    def test_TokenMismatch(self):
1964
        token = 'a lock token'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1965
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1966
        expected_error = errors.TokenMismatch(token, '(remote token)')
1967
        self.assertEqual(expected_error, translated_error)
1968
1969
    def test_Diverged(self):
1970
        branch = self.make_branch('a')
1971
        other_branch = self.make_branch('b')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
1972
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
1973
            ('Diverged',), branch=branch, other_branch=other_branch)
1974
        expected_error = errors.DivergedBranches(branch, other_branch)
1975
        self.assertEqual(expected_error, translated_error)
1976
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
1977
    def test_ReadError_no_args(self):
1978
        path = 'a path'
1979
        translated_error = self.translateTuple(('ReadError',), path=path)
1980
        expected_error = errors.ReadError(path)
1981
        self.assertEqual(expected_error, translated_error)
1982
1983
    def test_ReadError(self):
1984
        path = 'a path'
1985
        translated_error = self.translateTuple(('ReadError', path))
1986
        expected_error = errors.ReadError(path)
1987
        self.assertEqual(expected_error, translated_error)
1988
1989
    def test_PermissionDenied_no_args(self):
1990
        path = 'a path'
1991
        translated_error = self.translateTuple(('PermissionDenied',), path=path)
1992
        expected_error = errors.PermissionDenied(path)
1993
        self.assertEqual(expected_error, translated_error)
1994
1995
    def test_PermissionDenied_one_arg(self):
1996
        path = 'a path'
1997
        translated_error = self.translateTuple(('PermissionDenied', path))
1998
        expected_error = errors.PermissionDenied(path)
1999
        self.assertEqual(expected_error, translated_error)
2000
2001
    def test_PermissionDenied_one_arg_and_context(self):
2002
        """Given a choice between a path from the local context and a path on
2003
        the wire, _translate_error prefers the path from the local context.
2004
        """
2005
        local_path = 'local path'
2006
        remote_path = 'remote path'
2007
        translated_error = self.translateTuple(
2008
            ('PermissionDenied', remote_path), path=local_path)
2009
        expected_error = errors.PermissionDenied(local_path)
2010
        self.assertEqual(expected_error, translated_error)
2011
2012
    def test_PermissionDenied_two_args(self):
2013
        path = 'a path'
2014
        extra = 'a string with extra info'
2015
        translated_error = self.translateTuple(
2016
            ('PermissionDenied', path, extra))
2017
        expected_error = errors.PermissionDenied(path, extra)
2018
        self.assertEqual(expected_error, translated_error)
2019
2020
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2021
class TestErrorTranslationRobustness(TestErrorTranslationBase):
2022
    """Unit tests for bzrlib.remote._translate_error's robustness.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2023
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2024
    TestErrorTranslationSuccess is for cases where _translate_error can
2025
    translate successfully.  This class about how _translate_err behaves when
2026
    it fails to translate: it re-raises the original error.
2027
    """
2028
2029
    def test_unrecognised_server_error(self):
2030
        """If the error code from the server is not recognised, the original
2031
        ErrorFromSmartServer is propagated unmodified.
2032
        """
2033
        error_tuple = ('An unknown error tuple',)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
2034
        server_error = errors.ErrorFromSmartServer(error_tuple)
2035
        translated_error = self.translateErrorFromSmartServer(server_error)
2036
        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.
2037
        self.assertEqual(expected_error, translated_error)
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2038
2039
    def test_context_missing_a_key(self):
2040
        """In case of a bug in the client, or perhaps an unexpected response
2041
        from a server, _translate_error returns the original error tuple from
2042
        the server and mutters a warning.
2043
        """
2044
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
2045
        # in the context dict.  So let's give it an empty context dict instead
2046
        # to exercise its error recovery.
2047
        empty_context = {}
2048
        error_tuple = ('NoSuchRevision', 'revid')
2049
        server_error = errors.ErrorFromSmartServer(error_tuple)
2050
        translated_error = self.translateErrorFromSmartServer(server_error)
2051
        self.assertEqual(server_error, translated_error)
2052
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2053
        # been muttered to the log file for developer to look at.
2054
        self.assertContainsRe(
2055
            self._get_log(keep_log_file=True),
2056
            "Missing key 'branch' in context")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2057
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
2058
    def test_path_missing(self):
2059
        """Some translations (PermissionDenied, ReadError) can determine the
2060
        'path' variable from either the wire or the local context.  If neither
2061
        has it, then an error is raised.
2062
        """
2063
        error_tuple = ('ReadError',)
2064
        server_error = errors.ErrorFromSmartServer(error_tuple)
2065
        translated_error = self.translateErrorFromSmartServer(server_error)
2066
        self.assertEqual(server_error, translated_error)
2067
        # In addition to re-raising ErrorFromSmartServer, some debug info has
2068
        # been muttered to the log file for developer to look at.
2069
        self.assertContainsRe(
2070
            self._get_log(keep_log_file=True), "Missing key 'path' in context")
2071
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
2072
2073
class TestStacking(tests.TestCaseWithTransport):
2074
    """Tests for operations on stacked remote repositories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2075
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
2076
    The underlying format type must support stacking.
2077
    """
2078
2079
    def test_access_stacked_remote(self):
2080
        # based on <http://launchpad.net/bugs/261315>
2081
        # make a branch stacked on another repository containing an empty
2082
        # revision, then open it over hpss - we should be able to see that
2083
        # revision.
2084
        base_transport = self.get_transport()
2085
        base_builder = self.make_branch_builder('base', format='1.6')
2086
        base_builder.start_series()
2087
        base_revid = base_builder.build_snapshot('rev-id', None,
2088
            [('add', ('', None, 'directory', None))],
2089
            'message')
2090
        base_builder.finish_series()
2091
        stacked_branch = self.make_branch('stacked', format='1.6')
2092
        stacked_branch.set_stacked_on_url('../base')
2093
        # start a server looking at this
2094
        smart_server = server.SmartTCPServer_for_testing()
2095
        smart_server.setUp()
2096
        self.addCleanup(smart_server.tearDown)
2097
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
2098
        # can get its branch and repository
2099
        remote_branch = remote_bzrdir.open_branch()
2100
        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
2101
        remote_repo.lock_read()
2102
        try:
2103
            # it should have an appropriate fallback repository, which should also
2104
            # be a RemoteRepository
2105
            self.assertEquals(len(remote_repo._fallback_repositories), 1)
2106
            self.assertIsInstance(remote_repo._fallback_repositories[0],
2107
                RemoteRepository)
2108
            # and it has the revision committed to the underlying repository;
2109
            # these have varying implementations so we try several of them
2110
            self.assertTrue(remote_repo.has_revisions([base_revid]))
2111
            self.assertTrue(remote_repo.has_revision(base_revid))
2112
            self.assertEqual(remote_repo.get_revision(base_revid).message,
2113
                'message')
2114
        finally:
2115
            remote_repo.unlock()
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
2116
3835.1.7 by Aaron Bentley
Updates from review
2117
    def prepare_stacked_remote_branch(self):
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
2118
        smart_server = server.SmartTCPServer_for_testing()
2119
        smart_server.setUp()
2120
        self.addCleanup(smart_server.tearDown)
2121
        tree1 = self.make_branch_and_tree('tree1')
2122
        tree1.commit('rev1', rev_id='rev1')
2123
        tree2 = self.make_branch_and_tree('tree2', format='1.6')
2124
        tree2.branch.set_stacked_on_url(tree1.branch.base)
2125
        branch2 = Branch.open(smart_server.get_url() + '/tree2')
2126
        branch2.lock_read()
2127
        self.addCleanup(branch2.unlock)
3835.1.7 by Aaron Bentley
Updates from review
2128
        return branch2
2129
2130
    def test_stacked_get_parent_map(self):
2131
        # the public implementation of get_parent_map obeys stacking
2132
        branch = self.prepare_stacked_remote_branch()
2133
        repo = branch.repository
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
2134
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
3835.1.7 by Aaron Bentley
Updates from review
2135
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
2136
    def test_unstacked_get_parent_map(self):
2137
        # _unstacked_provider.get_parent_map ignores stacking
3835.1.7 by Aaron Bentley
Updates from review
2138
        branch = self.prepare_stacked_remote_branch()
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
2139
        provider = branch.repository._unstacked_provider
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
2140
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
2141
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.
2142
2143
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
2144
2145
    def setUp(self):
2146
        super(TestRemoteBranchEffort, self).setUp()
2147
        # Create a smart server that publishes whatever the backing VFS server
2148
        # does.
2149
        self.smart_server = server.SmartTCPServer_for_testing()
2150
        self.smart_server.setUp(self.get_server())
2151
        self.addCleanup(self.smart_server.tearDown)
2152
        # Log all HPSS calls into self.hpss_calls.
2153
        _SmartClient.hooks.install_named_hook(
2154
            'call', self.capture_hpss_call, None)
2155
        self.hpss_calls = []
2156
2157
    def capture_hpss_call(self, params):
2158
        self.hpss_calls.append(params.method)
2159
2160
    def test_copy_content_into_avoids_revision_history(self):
2161
        local = self.make_branch('local')
2162
        remote_backing_tree = self.make_branch_and_tree('remote')
2163
        remote_backing_tree.commit("Commit.")
2164
        remote_branch_url = self.smart_server.get_url() + 'remote'
2165
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
2166
        local.repository.fetch(remote_branch.repository)
2167
        self.hpss_calls = []
2168
        remote_branch.copy_content_into(local)
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
2169
        self.assertFalse('Branch.revision_history' in self.hpss_calls)