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