/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
5557.1.7 by John Arbash Meinel
Merge in the bzr.dev 5582
1
# Copyright (C) 2006-2011 Canonical Ltd
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
16
17
"""Tests for remote bzrdir/branch/repo/etc
18
19
These are proxy objects which act on remote objects by sending messages
20
through a smart client.  The proxies are to be created when attempting to open
4032.1.2 by John Arbash Meinel
Track down a few more files that have trailing whitespace.
21
the object given a transport that supports smartserver rpc operations.
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
22
23
These tests correspond to tests.test_smart, which exercises the server side.
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
24
"""
25
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
26
import bz2
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
27
from cStringIO import StringIO
28
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
29
from bzrlib import (
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
30
    branch,
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.
31
    bzrdir,
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
32
    config,
5363.2.9 by Jelmer Vernooij
Fix some tests.
33
    controldir,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
34
    errors,
5972.3.16 by Jelmer Vernooij
Rename import.
35
    graph as _mod_graph,
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
36
    inventory,
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
37
    inventory_delta,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
38
    remote,
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
39
    repository,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
40
    tests,
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
41
    transport,
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
42
    treebuilder,
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
43
    versionedfile,
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
44
    )
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
45
from bzrlib.branch import Branch
5363.2.9 by Jelmer Vernooij
Fix some tests.
46
from bzrlib.bzrdir import (
47
    BzrDir,
48
    BzrDirFormat,
49
    RemoteBzrProber,
50
    )
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
51
from bzrlib.remote import (
52
    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.
53
    RemoteBranchFormat,
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
54
    RemoteBzrDir,
5712.3.17 by Jelmer Vernooij
more fixes.
55
    RemoteBzrDirFormat,
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
56
    RemoteRepository,
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
57
    RemoteRepositoryFormat,
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
58
    )
5757.1.7 by Jelmer Vernooij
Fix more imports.
59
from bzrlib.repofmt import groupcompress_repo, knitpack_repo
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
60
from bzrlib.revision import NULL_REVISION
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
61
from bzrlib.smart import medium, request
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
62
from bzrlib.smart.client import _SmartClient
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
63
from bzrlib.smart.repository import (
64
    SmartServerRepositoryGetParentMap,
65
    SmartServerRepositoryGetStream_1_19,
66
    )
6165.4.7 by Jelmer Vernooij
More fixes.
67
from bzrlib.symbol_versioning import deprecated_in
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
68
from bzrlib.tests import (
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
69
    test_server,
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
70
    )
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
71
from bzrlib.tests.scenarios import load_tests_apply_scenarios
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
72
from bzrlib.transport.memory import MemoryTransport
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
73
from bzrlib.transport.remote import (
74
    RemoteTransport,
75
    RemoteSSHTransport,
76
    RemoteTCPTransport,
5579.3.1 by Jelmer Vernooij
Remove unused imports.
77
    )
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
78
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
79
80
load_tests = load_tests_apply_scenarios
81
82
83
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
84
85
    scenarios = [
4104.4.2 by Robert Collins
Fix test_source for 1.13 landing.
86
        ('HPSS-v2',
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
87
            {'transport_server': test_server.SmartTCPServer_for_testing_v2_only}),
4104.4.2 by Robert Collins
Fix test_source for 1.13 landing.
88
        ('HPSS-v3',
5559.2.2 by Martin Pool
Change to using standard load_tests_apply_scenarios.
89
            {'transport_server': test_server.SmartTCPServer_for_testing})]
90
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
91
92
    def setUp(self):
2018.5.42 by Robert Collins
Various hopefully improvements, but wsgi is broken, handing over to spiv :).
93
        super(BasicRemoteObjectTests, self).setUp()
94
        self.transport = self.get_transport()
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
95
        # 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
96
        self.local_wt = BzrDir.create_standalone_workingtree('.')
4986.2.1 by Martin Pool
Remove tearDown in tests in favor of addCleanup
97
        self.addCleanup(self.transport.disconnect)
2018.5.171 by Andrew Bennetts
Disconnect RemoteTransports in some tests to avoid tripping up test_strace with leftover threads from previous tests.
98
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
99
    def test_create_remote_bzrdir(self):
5712.3.17 by Jelmer Vernooij
more fixes.
100
        b = remote.RemoteBzrDir(self.transport, RemoteBzrDirFormat())
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
101
        self.assertIsInstance(b, BzrDir)
102
103
    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.
104
        # open a standalone branch in the working directory
5712.3.17 by Jelmer Vernooij
more fixes.
105
        b = remote.RemoteBzrDir(self.transport, RemoteBzrDirFormat())
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
106
        branch = b.open_branch()
2018.5.163 by Andrew Bennetts
Deal with various review comments from Robert.
107
        self.assertIsInstance(branch, Branch)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
108
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
109
    def test_remote_repository(self):
110
        b = BzrDir.open_from_transport(self.transport)
111
        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.
112
        revid = u'\xc823123123'.encode('utf8')
2018.5.40 by Robert Collins
Implement a remote Repository.has_revision method.
113
        self.assertFalse(repo.has_revision(revid))
114
        self.local_wt.commit(message='test commit', rev_id=revid)
115
        self.assertTrue(repo.has_revision(revid))
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
116
117
    def test_remote_branch_revision_history(self):
118
        b = BzrDir.open_from_transport(self.transport).open_branch()
6165.4.7 by Jelmer Vernooij
More fixes.
119
        self.assertEqual([],
120
            self.applyDeprecated(deprecated_in((2, 5, 0)), b.revision_history))
2018.5.38 by Robert Collins
Implement RemoteBranch.revision_history().
121
        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.
122
        r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
6165.4.7 by Jelmer Vernooij
More fixes.
123
        self.assertEqual([r1, r2],
124
            self.applyDeprecated(deprecated_in((2, 5, 0)), b.revision_history))
1752.2.31 by Martin Pool
[broken] some support for write operations over hpss
125
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
126
    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)
127
        """Should open a RemoteBzrDir over a RemoteTransport"""
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
128
        fmt = BzrDirFormat.find_format(self.transport)
5363.2.9 by Jelmer Vernooij
Fix some tests.
129
        self.assertTrue(bzrdir.RemoteBzrProber
130
                        in controldir.ControlDirFormat._server_probers)
5712.3.17 by Jelmer Vernooij
more fixes.
131
        self.assertIsInstance(fmt, RemoteBzrDirFormat)
1752.2.30 by Martin Pool
Start adding a RemoteBzrDir, etc
132
133
    def test_open_detected_smart_format(self):
134
        fmt = BzrDirFormat.find_format(self.transport)
135
        d = fmt.open(self.transport)
136
        self.assertIsInstance(d, BzrDir)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
137
2477.1.1 by Martin Pool
Add RemoteBranch repr
138
    def test_remote_branch_repr(self):
139
        b = BzrDir.open_from_transport(self.transport).open_branch()
140
        self.assertStartsWith(str(b), 'RemoteBranch(')
141
4964.2.1 by Martin Pool
Add RemoteBzrDir repr
142
    def test_remote_bzrdir_repr(self):
143
        b = BzrDir.open_from_transport(self.transport)
144
        self.assertStartsWith(str(b), 'RemoteBzrDir(')
145
4103.2.2 by Andrew Bennetts
Fix RemoteBranchFormat.supports_stacking()
146
    def test_remote_branch_format_supports_stacking(self):
147
        t = self.transport
148
        self.make_branch('unstackable', format='pack-0.92')
149
        b = BzrDir.open_from_transport(t.clone('unstackable')).open_branch()
150
        self.assertFalse(b._format.supports_stacking())
151
        self.make_branch('stackable', format='1.9')
152
        b = BzrDir.open_from_transport(t.clone('stackable')).open_branch()
153
        self.assertTrue(b._format.supports_stacking())
154
4118.1.1 by Andrew Bennetts
Fix performance regression (many small round-trips) when pushing to a remote pack, and tidy the tests.
155
    def test_remote_repo_format_supports_external_references(self):
156
        t = self.transport
157
        bd = self.make_bzrdir('unstackable', format='pack-0.92')
158
        r = bd.create_repository()
159
        self.assertFalse(r._format.supports_external_lookups)
160
        r = BzrDir.open_from_transport(t.clone('unstackable')).open_repository()
161
        self.assertFalse(r._format.supports_external_lookups)
162
        bd = self.make_bzrdir('stackable', format='1.9')
163
        r = bd.create_repository()
164
        self.assertTrue(r._format.supports_external_lookups)
165
        r = BzrDir.open_from_transport(t.clone('stackable')).open_repository()
166
        self.assertTrue(r._format.supports_external_lookups)
167
4301.3.1 by Andrew Bennetts
Implement RemoteBranch.set_append_revisions_only.
168
    def test_remote_branch_set_append_revisions_only(self):
169
        # Make a format 1.9 branch, which supports append_revisions_only
170
        branch = self.make_branch('branch', format='1.9')
171
        config = branch.get_config()
172
        branch.set_append_revisions_only(True)
173
        self.assertEqual(
174
            'True', config.get_user_option('append_revisions_only'))
175
        branch.set_append_revisions_only(False)
176
        self.assertEqual(
177
            'False', config.get_user_option('append_revisions_only'))
178
179
    def test_remote_branch_set_append_revisions_only_upgrade_reqd(self):
180
        branch = self.make_branch('branch', format='knit')
181
        config = branch.get_config()
182
        self.assertRaises(
4301.3.3 by Andrew Bennetts
Move check onto base Branch class, and add a supports_set_append_revisions_only method to BranchFormat, as suggested by Robert.
183
            errors.UpgradeRequired, branch.set_append_revisions_only, True)
4301.3.1 by Andrew Bennetts
Implement RemoteBranch.set_append_revisions_only.
184
3691.2.4 by Martin Pool
Add FakeRemoteTransport to clarify test_remote
185
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
186
class FakeProtocol(object):
187
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
188
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
189
    def __init__(self, body, fake_client):
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
190
        self.body = body
191
        self._body_buffer = None
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
192
        self._fake_client = fake_client
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
193
194
    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.
195
        if self._body_buffer is None:
196
            self._body_buffer = StringIO(self.body)
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
197
        bytes = self._body_buffer.read(count)
198
        if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
199
            self._fake_client.expecting_body = False
200
        return bytes
201
202
    def cancel_read_body(self):
203
        self._fake_client.expecting_body = False
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
204
2535.4.2 by Andrew Bennetts
Nasty hackery to make stream_knit_data_for_revisions response use streaming.
205
    def read_streamed_body(self):
206
        return self.body
207
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
208
2018.5.159 by Andrew Bennetts
Rename SmartClient to _SmartClient.
209
class FakeClient(_SmartClient):
210
    """Lookalike for _SmartClient allowing testing."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
211
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
212
    def __init__(self, fake_medium_base='fake base'):
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
213
        """Create a FakeClient."""
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
214
        self.responses = []
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
215
        self._calls = []
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
216
        self.expecting_body = False
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
217
        # if non-None, this is the list of expected calls, with only the
218
        # 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.
219
        # compute so is not included. If a call is None, that call can
220
        # be anything.
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
221
        self._expected_calls = None
3431.3.2 by Andrew Bennetts
Remove 'base' from _SmartClient entirely, now that the medium has it.
222
        _SmartClient.__init__(self, FakeMedium(self._calls, fake_medium_base))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
223
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
224
    def add_expected_call(self, call_name, call_args, response_type,
225
        response_args, response_body=None):
226
        if self._expected_calls is None:
227
            self._expected_calls = []
228
        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
229
        self.responses.append((response_type, response_args, response_body))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
230
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
231
    def add_success_response(self, *args):
232
        self.responses.append(('success', args, None))
233
234
    def add_success_response_with_body(self, body, *args):
235
        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.
236
        if self._expected_calls is not None:
237
            self._expected_calls.append(None)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
238
239
    def add_error_response(self, *args):
240
        self.responses.append(('error', args))
241
242
    def add_unknown_method_response(self, verb):
243
        self.responses.append(('unknown', verb))
244
4523.3.2 by Andrew Bennetts
Adjust according to Robert's review.
245
    def finished_test(self):
246
        if self._expected_calls:
247
            raise AssertionError("%r finished but was still expecting %r"
248
                % (self, self._expected_calls[0]))
249
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.
250
    def _get_next_response(self):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
251
        try:
252
            response_tuple = self.responses.pop(0)
253
        except IndexError, e:
254
            raise AssertionError("%r didn't expect any more calls"
255
                % (self,))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
256
        if response_tuple[0] == 'unknown':
257
            raise errors.UnknownSmartMethod(response_tuple[1])
258
        elif response_tuple[0] == 'error':
259
            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.
260
        return response_tuple
261
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
262
    def _check_call(self, method, args):
263
        if self._expected_calls is None:
264
            # the test should be updated to say what it expects
265
            return
266
        try:
267
            next_call = self._expected_calls.pop(0)
268
        except IndexError:
269
            raise AssertionError("%r didn't expect any more calls "
270
                "but got %r%r"
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
271
                % (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.
272
        if next_call is None:
273
            return
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
274
        if method != next_call[0] or args != next_call[1]:
275
            raise AssertionError("%r expected %r%r "
276
                "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
277
                % (self, next_call[0], next_call[1], method, args,))
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
278
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
279
    def call(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
280
        self._check_call(method, args)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
281
        self._calls.append(('call', method, args))
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
282
        return self._get_next_response()[1]
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
283
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
284
    def call_expecting_body(self, method, *args):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
285
        self._check_call(method, args)
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
286
        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.
287
        result = self._get_next_response()
2535.3.68 by Andrew Bennetts
Backwards compatibility for new smart method.
288
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
289
        return result[1], FakeProtocol(result[2], self)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
290
4634.36.1 by Andrew Bennetts
Fix trivial bug in RemoteBranch._set_tags_bytes, and add some unit tests for it.
291
    def call_with_body_bytes(self, method, args, body):
292
        self._check_call(method, args)
293
        self._calls.append(('call_with_body_bytes', method, args, body))
294
        result = self._get_next_response()
295
        return result[1], FakeProtocol(result[2], self)
296
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.
297
    def call_with_body_bytes_expecting_body(self, method, args, body):
3691.2.7 by Martin Pool
FakeClient can know what calls to expect
298
        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.
299
        self._calls.append(('call_with_body_bytes_expecting_body', method,
300
            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.
301
        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.
302
        self.expecting_body = True
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
303
        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.
304
3842.3.9 by Andrew Bennetts
Backing up the stream so that we can fallback correctly.
305
    def call_with_body_stream(self, args, stream):
306
        # Explicitly consume the stream before checking for an error, because
307
        # that's what happens a real medium.
308
        stream = list(stream)
309
        self._check_call(args[0], args[1:])
310
        self._calls.append(('call_with_body_stream', args[0], args[1:], stream))
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
311
        result = self._get_next_response()
4144.3.3 by Andrew Bennetts
Tweaks based on review from Robert.
312
        # The second value returned from call_with_body_stream is supposed to
313
        # be a response_handler object, but so far no tests depend on that.
314
        response_handler = None 
315
        return result[1], response_handler
3842.3.9 by Andrew Bennetts
Backing up the stream so that we can fallback correctly.
316
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
317
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
318
class FakeMedium(medium.SmartClientMedium):
3104.4.2 by Andrew Bennetts
All tests passing.
319
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.
320
    def __init__(self, client_calls, base):
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
321
        medium.SmartClientMedium.__init__(self, base)
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
322
        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.
323
324
    def disconnect(self):
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
325
        self._client_calls.append(('disconnect medium',))
3104.4.2 by Andrew Bennetts
All tests passing.
326
327
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.
328
class TestVfsHas(tests.TestCase):
329
330
    def test_unicode_path(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
331
        client = FakeClient('/')
332
        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.
333
        transport = RemoteTransport('bzr://localhost/', _client=client)
334
        filename = u'/hell\u00d8'.encode('utf8')
335
        result = transport.has(filename)
336
        self.assertEqual(
337
            [('call', 'has', (filename,))],
338
            client._calls)
339
        self.assertTrue(result)
340
341
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
342
class TestRemote(tests.TestCaseWithMemoryTransport):
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
343
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.
344
    def get_branch_format(self):
345
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
346
        return reference_bzrdir_format.get_branch_format()
347
4053.1.2 by Robert Collins
Actually make this branch work.
348
    def get_repo_format(self):
349
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
350
        return reference_bzrdir_format.repository_format
351
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
352
    def assertFinished(self, fake_client):
353
        """Assert that all of a FakeClient's expected calls have occurred."""
4523.3.2 by Andrew Bennetts
Adjust according to Robert's review.
354
        fake_client.finished_test()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
355
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
356
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
357
class Test_ClientMedium_remote_path_from_transport(tests.TestCase):
358
    """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.
359
360
    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.
361
        """Assert that the result of
362
        SmartClientMedium.remote_path_from_transport is the expected value for
363
        a given client_base and transport_base.
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
364
        """
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
365
        client_medium = medium.SmartClientMedium(client_base)
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
366
        t = transport.get_transport(transport_base)
367
        result = client_medium.remote_path_from_transport(t)
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
368
        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.
369
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
370
    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.
371
        """SmartClientMedium.remote_path_from_transport calculates a URL for
372
        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.
373
        """
374
        self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
375
        self.assertRemotePath(
376
            'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
377
3431.3.11 by Andrew Bennetts
Push remote_path_from_transport logic into SmartClientMedium, removing special-casing of bzr+http from _SmartClient.
378
    def assertRemotePathHTTP(self, expected, transport_base, relpath):
379
        """Assert that the result of
380
        HttpTransportBase.remote_path_from_transport is the expected value for
381
        a given transport_base and relpath of that transport.  (Note that
382
        HttpTransportBase is a subclass of SmartClientMedium)
383
        """
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
384
        base_transport = 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.
385
        client_medium = base_transport.get_smart_medium()
386
        cloned_transport = base_transport.clone(relpath)
387
        result = client_medium.remote_path_from_transport(cloned_transport)
388
        self.assertEqual(expected, result)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
389
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
390
    def test_remote_path_from_transport_http(self):
391
        """Remote paths for HTTP transports are calculated differently to other
392
        transports.  They are just relative to the client base, not the root
393
        directory of the host.
394
        """
395
        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.
396
            self.assertRemotePathHTTP(
397
                '../xyz/', scheme + '//host/path', '../xyz/')
398
            self.assertRemotePathHTTP(
399
                'xyz/', scheme + '//host/path', 'xyz/')
3313.3.3 by Andrew Bennetts
Add tests for _SmartClient.remote_path_for_transport.
400
401
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
402
class Test_ClientMedium_remote_is_at_least(tests.TestCase):
403
    """Tests for the behaviour of client_medium.remote_is_at_least."""
404
405
    def test_initially_unlimited(self):
406
        """A fresh medium assumes that the remote side supports all
407
        versions.
408
        """
409
        client_medium = medium.SmartClientMedium('dummy base')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
410
        self.assertFalse(client_medium._is_remote_before((99, 99)))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
411
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
412
    def test__remember_remote_is_before(self):
413
        """Calling _remember_remote_is_before ratchets down the known remote
414
        version.
415
        """
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
416
        client_medium = medium.SmartClientMedium('dummy base')
417
        # Mark the remote side as being less than 1.6.  The remote side may
418
        # still be 1.5.
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
419
        client_medium._remember_remote_is_before((1, 6))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
420
        self.assertTrue(client_medium._is_remote_before((1, 6)))
421
        self.assertFalse(client_medium._is_remote_before((1, 5)))
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
422
        # Calling _remember_remote_is_before again with a lower value works.
423
        client_medium._remember_remote_is_before((1, 5))
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
424
        self.assertTrue(client_medium._is_remote_before((1, 5)))
4797.49.4 by Andrew Bennetts
Expand test a little further, and use consistent terminology in its comments.
425
        # If you call _remember_remote_is_before with a higher value it logs a
426
        # warning, and continues to remember the lower value.
4797.49.1 by Andrew Bennetts
First, fix _remember_remote_is_before to never raise AssertionError for what is a very minor bug.
427
        self.assertNotContainsRe(self.get_log(), '_remember_remote_is_before')
428
        client_medium._remember_remote_is_before((1, 9))
429
        self.assertContainsRe(self.get_log(), '_remember_remote_is_before')
4797.49.4 by Andrew Bennetts
Expand test a little further, and use consistent terminology in its comments.
430
        self.assertTrue(client_medium._is_remote_before((1, 5)))
3453.4.1 by Andrew Bennetts
Better infrastructure on SmartClientMedium for tracking the remote version.
431
432
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
433
class TestBzrDirCloningMetaDir(TestRemote):
434
435
    def test_backwards_compat(self):
436
        self.setup_smart_server_with_call_log()
437
        a_dir = self.make_bzrdir('.')
438
        self.reset_smart_call_log()
439
        verb = 'BzrDir.cloning_metadir'
440
        self.disable_verb(verb)
441
        format = a_dir.cloning_metadir()
442
        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.
443
            call.call.method == verb])
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
444
        self.assertEqual(1, call_count)
445
4160.2.9 by Andrew Bennetts
Fix BzrDir.cloning_metadir RPC to fail on branch references, and make
446
    def test_branch_reference(self):
447
        transport = self.get_transport('quack')
448
        referenced = self.make_branch('referenced')
449
        expected = referenced.bzrdir.cloning_metadir()
450
        client = FakeClient(transport.base)
451
        client.add_expected_call(
452
            'BzrDir.cloning_metadir', ('quack/', 'False'),
453
            'error', ('BranchReference',)),
454
        client.add_expected_call(
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
455
            'BzrDir.open_branchV3', ('quack/',),
4160.2.9 by Andrew Bennetts
Fix BzrDir.cloning_metadir RPC to fail on branch references, and make
456
            'success', ('ref', self.get_url('referenced'))),
5712.3.17 by Jelmer Vernooij
more fixes.
457
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4160.2.9 by Andrew Bennetts
Fix BzrDir.cloning_metadir RPC to fail on branch references, and make
458
            _client=client)
459
        result = a_bzrdir.cloning_metadir()
460
        # We should have got a control dir matching the referenced branch.
461
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
462
        self.assertEqual(expected._repository_format, result._repository_format)
463
        self.assertEqual(expected._branch_format, result._branch_format)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
464
        self.assertFinished(client)
4160.2.9 by Andrew Bennetts
Fix BzrDir.cloning_metadir RPC to fail on branch references, and make
465
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
466
    def test_current_server(self):
467
        transport = self.get_transport('.')
468
        transport = transport.clone('quack')
469
        self.make_bzrdir('quack')
470
        client = FakeClient(transport.base)
471
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
472
        control_name = reference_bzrdir_format.network_name()
473
        client.add_expected_call(
474
            'BzrDir.cloning_metadir', ('quack/', 'False'),
4084.2.2 by Robert Collins
Review feedback.
475
            'success', (control_name, '', ('branch', ''))),
5712.3.17 by Jelmer Vernooij
more fixes.
476
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
477
            _client=client)
478
        result = a_bzrdir.cloning_metadir()
479
        # We should have got a reference control dir with default branch and
480
        # repository formats.
481
        # This pokes a little, just to be sure.
482
        self.assertEqual(bzrdir.BzrDirMetaFormat1, type(result))
4070.2.8 by Robert Collins
Really test the current BzrDir.cloning_metadir contract.
483
        self.assertEqual(None, result._repository_format)
484
        self.assertEqual(None, result._branch_format)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
485
        self.assertFinished(client)
4070.2.3 by Robert Collins
Get BzrDir.cloning_metadir working.
486
487
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
488
class TestBzrDirOpen(TestRemote):
489
490
    def make_fake_client_and_transport(self, path='quack'):
491
        transport = MemoryTransport()
492
        transport.mkdir(path)
493
        transport = transport.clone(path)
494
        client = FakeClient(transport.base)
495
        return client, transport
496
497
    def test_absent(self):
498
        client, transport = self.make_fake_client_and_transport()
499
        client.add_expected_call(
500
            'BzrDir.open_2.1', ('quack/',), 'success', ('no',))
501
        self.assertRaises(errors.NotBranchError, RemoteBzrDir, transport,
5712.3.17 by Jelmer Vernooij
more fixes.
502
                RemoteBzrDirFormat(), _client=client, _force_probe=True)
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
503
        self.assertFinished(client)
504
505
    def test_present_without_workingtree(self):
506
        client, transport = self.make_fake_client_and_transport()
507
        client.add_expected_call(
508
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'no'))
5712.3.17 by Jelmer Vernooij
more fixes.
509
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
510
            _client=client, _force_probe=True)
511
        self.assertIsInstance(bd, RemoteBzrDir)
512
        self.assertFalse(bd.has_workingtree())
513
        self.assertRaises(errors.NoWorkingTree, bd.open_workingtree)
514
        self.assertFinished(client)
515
516
    def test_present_with_workingtree(self):
517
        client, transport = self.make_fake_client_and_transport()
518
        client.add_expected_call(
519
            'BzrDir.open_2.1', ('quack/',), 'success', ('yes', 'yes'))
5712.3.17 by Jelmer Vernooij
more fixes.
520
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
521
            _client=client, _force_probe=True)
522
        self.assertIsInstance(bd, RemoteBzrDir)
523
        self.assertTrue(bd.has_workingtree())
524
        self.assertRaises(errors.NotLocalUrl, bd.open_workingtree)
525
        self.assertFinished(client)
526
527
    def test_backwards_compat(self):
528
        client, transport = self.make_fake_client_and_transport()
529
        client.add_expected_call(
530
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
531
        client.add_expected_call(
532
            'BzrDir.open', ('quack/',), 'success', ('yes',))
5712.3.17 by Jelmer Vernooij
more fixes.
533
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
534
            _client=client, _force_probe=True)
535
        self.assertIsInstance(bd, RemoteBzrDir)
536
        self.assertFinished(client)
537
4797.49.2 by Andrew Bennetts
Add test that demonstrates bug #528041.
538
    def test_backwards_compat_hpss_v2(self):
539
        client, transport = self.make_fake_client_and_transport()
540
        # Monkey-patch fake client to simulate real-world behaviour with v2
541
        # server: upon first RPC call detect the protocol version, and because
542
        # the version is 2 also do _remember_remote_is_before((1, 6)) before
543
        # continuing with the RPC.
544
        orig_check_call = client._check_call
545
        def check_call(method, args):
546
            client._medium._protocol_version = 2
547
            client._medium._remember_remote_is_before((1, 6))
548
            client._check_call = orig_check_call
549
            client._check_call(method, args)
550
        client._check_call = check_call
551
        client.add_expected_call(
552
            'BzrDir.open_2.1', ('quack/',), 'unknown', ('BzrDir.open_2.1',))
553
        client.add_expected_call(
554
            'BzrDir.open', ('quack/',), 'success', ('yes',))
5712.3.17 by Jelmer Vernooij
more fixes.
555
        bd = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4797.49.2 by Andrew Bennetts
Add test that demonstrates bug #528041.
556
            _client=client, _force_probe=True)
557
        self.assertIsInstance(bd, RemoteBzrDir)
558
        self.assertFinished(client)
559
4634.47.5 by Andrew Bennetts
Add tests, and fix BzrDirMeta1.has_workingtree which was failing if the local transport is decorated with a ChrootTransport or similar.
560
4053.1.2 by Robert Collins
Actually make this branch work.
561
class TestBzrDirOpenBranch(TestRemote):
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
562
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.
563
    def test_backwards_compat(self):
564
        self.setup_smart_server_with_call_log()
565
        self.make_branch('.')
566
        a_dir = BzrDir.open(self.get_url('.'))
567
        self.reset_smart_call_log()
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
568
        verb = 'BzrDir.open_branchV3'
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.
569
        self.disable_verb(verb)
570
        format = a_dir.open_branch()
571
        call_count = len([call for call in self.hpss_calls if
572
            call.call.method == verb])
573
        self.assertEqual(1, call_count)
574
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
575
    def test_branch_present(self):
4053.1.2 by Robert Collins
Actually make this branch work.
576
        reference_format = self.get_repo_format()
577
        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.
578
        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.
579
        transport = MemoryTransport()
580
        transport.mkdir('quack')
581
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
582
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
583
        client.add_expected_call(
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
584
            'BzrDir.open_branchV3', ('quack/',),
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.
585
            'success', ('branch', branch_network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
586
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
587
            'BzrDir.find_repositoryV3', ('quack/',),
588
            'success', ('ok', '', 'no', 'no', 'no', network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
589
        client.add_expected_call(
590
            'Branch.get_stacked_on_url', ('quack/',),
591
            'error', ('NotStacked',))
5712.3.17 by Jelmer Vernooij
more fixes.
592
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
593
            _client=client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
594
        result = bzrdir.open_branch()
595
        self.assertIsInstance(result, RemoteBranch)
596
        self.assertEqual(bzrdir, result.bzrdir)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
597
        self.assertFinished(client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
598
599
    def test_branch_missing(self):
600
        transport = MemoryTransport()
601
        transport.mkdir('quack')
602
        transport = transport.clone('quack')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
603
        client = FakeClient(transport.base)
604
        client.add_error_response('nobranch')
5712.3.17 by Jelmer Vernooij
more fixes.
605
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
606
            _client=client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
607
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
608
        self.assertEqual(
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
609
            [('call', 'BzrDir.open_branchV3', ('quack/',))],
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
610
            client._calls)
611
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
612
    def test__get_tree_branch(self):
613
        # _get_tree_branch is a form of open_branch, but it should only ask for
614
        # branch opening, not any other network requests.
615
        calls = []
5147.4.1 by Jelmer Vernooij
Pass branch names in more places.
616
        def open_branch(name=None):
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
617
            calls.append("Called")
618
            return "a-branch"
619
        transport = MemoryTransport()
620
        # 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.
621
        client = FakeClient(transport.base)
5712.3.17 by Jelmer Vernooij
more fixes.
622
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
623
            _client=client)
3211.4.1 by Robert Collins
* ``RemoteBzrDir._get_tree_branch`` no longer triggers ``_ensure_real``,
624
        # patch the open_branch call to record that it was called.
625
        bzrdir.open_branch = open_branch
626
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
627
        self.assertEqual(["Called"], calls)
628
        self.assertEqual([], client._calls)
629
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.
630
    def test_url_quoting_of_path(self):
631
        # Relpaths on the wire should not be URL-escaped.  So "~" should be
632
        # 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.
633
        transport = RemoteTCPTransport('bzr://localhost/~hello/')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
634
        client = FakeClient(transport.base)
4053.1.2 by Robert Collins
Actually make this branch work.
635
        reference_format = self.get_repo_format()
636
        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.
637
        branch_network_name = self.get_branch_format().network_name()
3691.2.10 by Martin Pool
Update more test_remote tests
638
        client.add_expected_call(
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
639
            'BzrDir.open_branchV3', ('~hello/',),
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.
640
            'success', ('branch', branch_network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
641
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
642
            'BzrDir.find_repositoryV3', ('~hello/',),
643
            'success', ('ok', '', 'no', 'no', 'no', network_name))
3691.2.10 by Martin Pool
Update more test_remote tests
644
        client.add_expected_call(
645
            'Branch.get_stacked_on_url', ('~hello/',),
646
            'error', ('NotStacked',))
5712.3.17 by Jelmer Vernooij
more fixes.
647
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
648
            _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.
649
        result = bzrdir.open_branch()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
650
        self.assertFinished(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.
651
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
652
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
4053.1.2 by Robert Collins
Actually make this branch work.
653
        reference_format = self.get_repo_format()
654
        network_name = reference_format.network_name()
3104.4.2 by Andrew Bennetts
All tests passing.
655
        transport = MemoryTransport()
656
        transport.mkdir('quack')
657
        transport = transport.clone('quack')
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
658
        if rich_root:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
659
            rich_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
660
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
661
            rich_response = 'no'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
662
        if subtrees:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
663
            subtree_response = 'yes'
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
664
        else:
2018.5.166 by Andrew Bennetts
Small changes in response to Aaron's review.
665
            subtree_response = 'no'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
666
        client = FakeClient(transport.base)
667
        client.add_success_response(
4053.1.2 by Robert Collins
Actually make this branch work.
668
            'ok', '', rich_response, subtree_response, external_lookup,
669
            network_name)
5712.3.17 by Jelmer Vernooij
more fixes.
670
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
671
            _client=client)
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
672
        result = bzrdir.open_repository()
673
        self.assertEqual(
4053.1.2 by Robert Collins
Actually make this branch work.
674
            [('call', 'BzrDir.find_repositoryV3', ('quack/',))],
2018.5.118 by Robert Collins
Fix RemoteRepositoryFormat to have appropriate rich_root_data and support_tree_reference.
675
            client._calls)
676
        self.assertIsInstance(result, RemoteRepository)
677
        self.assertEqual(bzrdir, result.bzrdir)
678
        self.assertEqual(rich_root, result._format.rich_root_data)
2018.5.138 by Robert Collins
Merge bzr.dev.
679
        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.
680
681
    def test_open_repository_sets_format_attributes(self):
682
        self.check_open_repository(True, True)
683
        self.check_open_repository(False, True)
684
        self.check_open_repository(True, False)
685
        self.check_open_repository(False, False)
3221.3.3 by Robert Collins
* Hook up the new remote method ``RemoteBzrDir.find_repositoryV2`` so
686
        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.
687
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
688
    def test_old_server(self):
689
        """RemoteBzrDirFormat should fail to probe if the server version is too
690
        old.
691
        """
692
        self.assertRaises(errors.NotBranchError,
5363.2.9 by Jelmer Vernooij
Fix some tests.
693
            RemoteBzrProber.probe_transport, OldServerTransport())
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
694
695
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
696
class TestBzrDirCreateBranch(TestRemote):
697
698
    def test_backwards_compat(self):
699
        self.setup_smart_server_with_call_log()
700
        repo = self.make_repository('.')
701
        self.reset_smart_call_log()
702
        self.disable_verb('BzrDir.create_branch')
703
        branch = repo.bzrdir.create_branch()
704
        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.
705
            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.
706
        self.assertEqual(1, create_branch_call_count)
707
708
    def test_current_server(self):
709
        transport = self.get_transport('.')
710
        transport = transport.clone('quack')
711
        self.make_repository('quack')
712
        client = FakeClient(transport.base)
713
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
714
        reference_format = reference_bzrdir_format.get_branch_format()
715
        network_name = reference_format.network_name()
716
        reference_repo_fmt = reference_bzrdir_format.repository_format
717
        reference_repo_name = reference_repo_fmt.network_name()
718
        client.add_expected_call(
719
            'BzrDir.create_branch', ('quack/', network_name),
720
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
721
            reference_repo_name))
5712.3.17 by Jelmer Vernooij
more fixes.
722
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
723
            _client=client)
724
        branch = a_bzrdir.create_branch()
725
        # We should have got a remote branch
726
        self.assertIsInstance(branch, remote.RemoteBranch)
727
        # its format should have the settings from the response
728
        format = branch._format
729
        self.assertEqual(network_name, format.network_name())
730
5609.21.2 by Andrew Bennetts
Add test.
731
    def test_already_open_repo_and_reused_medium(self):
732
        """Bug 726584: create_branch(..., repository=repo) should work
733
        regardless of what the smart medium's base URL is.
734
        """
735
        self.transport_server = test_server.SmartTCPServer_for_testing
736
        transport = self.get_transport('.')
737
        repo = self.make_repository('quack')
738
        # Client's medium rooted a transport root (not at the bzrdir)
739
        client = FakeClient(transport.base)
740
        transport = transport.clone('quack')
741
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
742
        reference_format = reference_bzrdir_format.get_branch_format()
743
        network_name = reference_format.network_name()
744
        reference_repo_fmt = reference_bzrdir_format.repository_format
745
        reference_repo_name = reference_repo_fmt.network_name()
746
        client.add_expected_call(
747
            'BzrDir.create_branch', ('extra/quack/', network_name),
748
            'success', ('ok', network_name, '', 'no', 'no', 'yes',
749
            reference_repo_name))
5712.3.17 by Jelmer Vernooij
more fixes.
750
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
5609.21.2 by Andrew Bennetts
Add test.
751
            _client=client)
752
        branch = a_bzrdir.create_branch(repository=repo)
753
        # We should have got a remote branch
754
        self.assertIsInstance(branch, remote.RemoteBranch)
755
        # its format should have the settings from the response
756
        format = branch._format
757
        self.assertEqual(network_name, format.network_name())
758
4032.3.2 by Robert Collins
Create and use a RPC call to create branches on bzr servers rather than using VFS calls.
759
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
760
class TestBzrDirCreateRepository(TestRemote):
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
761
762
    def test_backwards_compat(self):
763
        self.setup_smart_server_with_call_log()
764
        bzrdir = self.make_bzrdir('.')
765
        self.reset_smart_call_log()
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
766
        self.disable_verb('BzrDir.create_repository')
767
        repo = bzrdir.create_repository()
768
        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.
769
            call.call.method == 'BzrDir.create_repository'])
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
770
        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.
771
772
    def test_current_server(self):
773
        transport = self.get_transport('.')
774
        transport = transport.clone('quack')
775
        self.make_bzrdir('quack')
776
        client = FakeClient(transport.base)
777
        reference_bzrdir_format = bzrdir.format_registry.get('default')()
778
        reference_format = reference_bzrdir_format.repository_format
779
        network_name = reference_format.network_name()
780
        client.add_expected_call(
781
            'BzrDir.create_repository', ('quack/',
4599.4.20 by Robert Collins
Prep test_remote for 2a as default.
782
                'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
783
                'False'),
784
            'success', ('ok', 'yes', 'yes', 'yes', network_name))
5712.3.17 by Jelmer Vernooij
more fixes.
785
        a_bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
786
            _client=client)
787
        repo = a_bzrdir.create_repository()
788
        # We should have got a remote repository
789
        self.assertIsInstance(repo, remote.RemoteRepository)
790
        # its format should have the settings from the response
791
        format = repo._format
4599.4.20 by Robert Collins
Prep test_remote for 2a as default.
792
        self.assertTrue(format.rich_root_data)
793
        self.assertTrue(format.supports_tree_reference)
794
        self.assertTrue(format.supports_external_lookups)
4017.3.2 by Robert Collins
Reduce the number of round trips required to create a repository over the network.
795
        self.assertEqual(network_name, format.network_name())
796
797
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
798
class TestBzrDirOpenRepository(TestRemote):
799
800
    def test_backwards_compat_1_2_3(self):
801
        # fallback all the way to the first version.
802
        reference_format = self.get_repo_format()
803
        network_name = reference_format.network_name()
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
804
        server_url = 'bzr://example.com/'
805
        self.permit_url(server_url)
806
        client = FakeClient(server_url)
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
807
        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.
808
        client.add_unknown_method_response('BzrDir.find_repositoryV2')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
809
        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.
810
        # A real repository instance will be created to determine the network
811
        # name.
812
        client.add_success_response_with_body(
813
            "Bazaar-NG meta directory, format 1\n", 'ok')
814
        client.add_success_response_with_body(
815
            reference_format.get_format_string(), 'ok')
816
        # PackRepository wants to do a stat
817
        client.add_success_response('stat', '0', '65535')
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
818
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
819
            _client=client)
5712.3.17 by Jelmer Vernooij
more fixes.
820
        bzrdir = RemoteBzrDir(remote_transport, RemoteBzrDirFormat(),
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
821
            _client=client)
822
        repo = bzrdir.open_repository()
823
        self.assertEqual(
824
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
825
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
826
             ('call', 'BzrDir.find_repository', ('quack/',)),
827
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
828
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
829
             ('call', 'stat', ('/quack/.bzr/repository',)),
830
             ],
831
            client._calls)
832
        self.assertEqual(network_name, repo._format.network_name())
833
834
    def test_backwards_compat_2(self):
835
        # fallback to find_repositoryV2
836
        reference_format = self.get_repo_format()
837
        network_name = reference_format.network_name()
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
838
        server_url = 'bzr://example.com/'
839
        self.permit_url(server_url)
840
        client = FakeClient(server_url)
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
841
        client.add_unknown_method_response('BzrDir.find_repositoryV3')
842
        client.add_success_response('ok', '', 'no', 'no', 'no')
843
        # A real repository instance will be created to determine the network
844
        # name.
845
        client.add_success_response_with_body(
846
            "Bazaar-NG meta directory, format 1\n", 'ok')
847
        client.add_success_response_with_body(
848
            reference_format.get_format_string(), 'ok')
849
        # PackRepository wants to do a stat
850
        client.add_success_response('stat', '0', '65535')
4691.2.1 by Robert Collins
Add stronger test isolation by interception BzrDir.open and checking the thing being opened is known to the test suite.
851
        remote_transport = RemoteTransport(server_url + 'quack/', medium=False,
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
852
            _client=client)
5712.3.17 by Jelmer Vernooij
more fixes.
853
        bzrdir = RemoteBzrDir(remote_transport, RemoteBzrDirFormat(),
4053.1.1 by Robert Collins
New version of the BzrDir.find_repository verb supporting _network_name to support removing more _ensure_real calls.
854
            _client=client)
855
        repo = bzrdir.open_repository()
856
        self.assertEqual(
857
            [('call', 'BzrDir.find_repositoryV3', ('quack/',)),
858
             ('call', 'BzrDir.find_repositoryV2', ('quack/',)),
859
             ('call_expecting_body', 'get', ('/quack/.bzr/branch-format',)),
860
             ('call_expecting_body', 'get', ('/quack/.bzr/repository/format',)),
861
             ('call', 'stat', ('/quack/.bzr/repository',)),
862
             ],
863
            client._calls)
864
        self.assertEqual(network_name, repo._format.network_name())
865
866
    def test_current_server(self):
867
        reference_format = self.get_repo_format()
868
        network_name = reference_format.network_name()
869
        transport = MemoryTransport()
870
        transport.mkdir('quack')
871
        transport = transport.clone('quack')
872
        client = FakeClient(transport.base)
873
        client.add_success_response('ok', '', 'no', 'no', 'no', network_name)
5712.3.17 by Jelmer Vernooij
more fixes.
874
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
875
            _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.
876
        repo = bzrdir.open_repository()
877
        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.
878
            [('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.
879
            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.
880
        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.
881
882
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
883
class TestBzrDirFormatInitializeEx(TestRemote):
884
885
    def test_success(self):
886
        """Simple test for typical successful call."""
5712.3.17 by Jelmer Vernooij
more fixes.
887
        fmt = RemoteBzrDirFormat()
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
888
        default_format_name = BzrDirFormat.get_default_format().network_name()
889
        transport = self.get_transport()
890
        client = FakeClient(transport.base)
891
        client.add_expected_call(
4436.1.1 by Andrew Bennetts
Rename BzrDirFormat.initialize_ex verb to BzrDirFormat.initialize_ex_1.16.
892
            'BzrDirFormat.initialize_ex_1.16',
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
893
                (default_format_name, 'path', 'False', 'False', 'False', '',
894
                 '', '', '', 'False'),
895
            'success',
896
                ('.', 'no', 'no', 'yes', 'repo fmt', 'repo bzrdir fmt',
897
                 'bzrdir fmt', 'False', '', '', 'repo lock token'))
898
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
899
        # it's currently hard to test that without supplying a real remote
900
        # transport connected to a real server.
901
        result = fmt._initialize_on_transport_ex_rpc(client, 'path',
902
            transport, False, False, False, None, None, None, None, False)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
903
        self.assertFinished(client)
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
904
905
    def test_error(self):
906
        """Error responses are translated, e.g. 'PermissionDenied' raises the
907
        corresponding error from the client.
908
        """
5712.3.17 by Jelmer Vernooij
more fixes.
909
        fmt = RemoteBzrDirFormat()
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
910
        default_format_name = BzrDirFormat.get_default_format().network_name()
911
        transport = self.get_transport()
912
        client = FakeClient(transport.base)
913
        client.add_expected_call(
4436.1.1 by Andrew Bennetts
Rename BzrDirFormat.initialize_ex verb to BzrDirFormat.initialize_ex_1.16.
914
            'BzrDirFormat.initialize_ex_1.16',
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
915
                (default_format_name, 'path', 'False', 'False', 'False', '',
916
                 '', '', '', 'False'),
917
            'error',
918
                ('PermissionDenied', 'path', 'extra info'))
919
        # XXX: It would be better to call fmt.initialize_on_transport_ex, but
920
        # it's currently hard to test that without supplying a real remote
921
        # transport connected to a real server.
922
        err = self.assertRaises(errors.PermissionDenied,
923
            fmt._initialize_on_transport_ex_rpc, client, 'path', transport,
924
            False, False, False, None, None, None, None, False)
925
        self.assertEqual('path', err.path)
926
        self.assertEqual(': extra info', err.extra)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
927
        self.assertFinished(client)
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
928
4384.1.3 by Andrew Bennetts
Add test suggested by John.
929
    def test_error_from_real_server(self):
930
        """Integration test for error translation."""
931
        transport = self.make_smart_server('foo')
932
        transport = transport.clone('no-such-path')
5712.3.17 by Jelmer Vernooij
more fixes.
933
        fmt = RemoteBzrDirFormat()
4384.1.3 by Andrew Bennetts
Add test suggested by John.
934
        err = self.assertRaises(errors.NoSuchFile,
935
            fmt.initialize_on_transport_ex, transport, create_prefix=False)
936
4384.1.1 by Andrew Bennetts
Translate ErrorFromSmartServer in RemoteBzrDirFormat.
937
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
938
class OldSmartClient(object):
939
    """A fake smart client for test_old_version that just returns a version one
940
    response to the 'hello' (query version) command.
941
    """
942
943
    def get_request(self):
944
        input_file = StringIO('ok\x011\n')
945
        output_file = StringIO()
946
        client_medium = medium.SmartSimplePipesClientMedium(
947
            input_file, output_file)
948
        return medium.SmartClientStreamMediumRequest(client_medium)
949
3241.1.1 by Andrew Bennetts
Shift protocol version querying from RemoteBzrDirFormat into SmartClientMedium.
950
    def protocol_version(self):
951
        return 1
952
2432.3.2 by Andrew Bennetts
Add test, and tidy implementation.
953
954
class OldServerTransport(object):
955
    """A fake transport for test_old_server that reports it's smart server
956
    protocol version as version one.
957
    """
958
959
    def __init__(self):
960
        self.base = 'fake:'
961
962
    def get_smart_client(self):
963
        return OldSmartClient()
964
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
965
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
966
class RemoteBzrDirTestCase(TestRemote):
967
968
    def make_remote_bzrdir(self, transport, client):
969
        """Make a RemotebzrDir using 'client' as the _client."""
5712.3.17 by Jelmer Vernooij
more fixes.
970
        return RemoteBzrDir(transport, RemoteBzrDirFormat(),
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
971
            _client=client)
972
973
974
class RemoteBranchTestCase(RemoteBzrDirTestCase):
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
975
4634.36.1 by Andrew Bennetts
Fix trivial bug in RemoteBranch._set_tags_bytes, and add some unit tests for it.
976
    def lock_remote_branch(self, branch):
977
        """Trick a RemoteBranch into thinking it is locked."""
978
        branch._lock_mode = 'w'
979
        branch._lock_count = 2
980
        branch._lock_token = 'branch token'
981
        branch._repo_lock_token = 'repo token'
982
        branch.repository._lock_mode = 'w'
983
        branch.repository._lock_count = 2
984
        branch.repository._lock_token = 'repo token'
985
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
986
    def make_remote_branch(self, transport, client):
987
        """Make a RemoteBranch using 'client' as its _SmartClient.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
988
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
989
        A RemoteBzrDir and RemoteRepository will also be created to fill out
990
        the RemoteBranch, albeit with stub values for some of their attributes.
991
        """
992
        # we do not want bzrdir to make any remote calls, so use False as its
993
        # _client.  If it tries to make a remote call, this will fail
994
        # immediately.
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
995
        bzrdir = self.make_remote_bzrdir(transport, False)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
996
        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.
997
        branch_format = self.get_branch_format()
998
        format = RemoteBranchFormat(network_name=branch_format.network_name())
999
        return RemoteBranch(bzrdir, repo, _client=client, format=format)
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1000
1001
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1002
class TestBranchGetParent(RemoteBranchTestCase):
1003
1004
    def test_no_parent(self):
1005
        # in an empty branch we decode the response properly
1006
        transport = MemoryTransport()
1007
        client = FakeClient(transport.base)
1008
        client.add_expected_call(
1009
            'Branch.get_stacked_on_url', ('quack/',),
1010
            'error', ('NotStacked',))
1011
        client.add_expected_call(
1012
            'Branch.get_parent', ('quack/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
1013
            'success', ('',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1014
        transport.mkdir('quack')
1015
        transport = transport.clone('quack')
1016
        branch = self.make_remote_branch(transport, client)
1017
        result = branch.get_parent()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1018
        self.assertFinished(client)
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1019
        self.assertEqual(None, result)
1020
1021
    def test_parent_relative(self):
1022
        transport = MemoryTransport()
1023
        client = FakeClient(transport.base)
1024
        client.add_expected_call(
1025
            'Branch.get_stacked_on_url', ('kwaak/',),
1026
            'error', ('NotStacked',))
1027
        client.add_expected_call(
1028
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
1029
            'success', ('../foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1030
        transport.mkdir('kwaak')
1031
        transport = transport.clone('kwaak')
1032
        branch = self.make_remote_branch(transport, client)
1033
        result = branch.get_parent()
1034
        self.assertEqual(transport.clone('../foo').base, result)
1035
1036
    def test_parent_absolute(self):
1037
        transport = MemoryTransport()
1038
        client = FakeClient(transport.base)
1039
        client.add_expected_call(
1040
            'Branch.get_stacked_on_url', ('kwaak/',),
1041
            'error', ('NotStacked',))
1042
        client.add_expected_call(
1043
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
1044
            'success', ('http://foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1045
        transport.mkdir('kwaak')
1046
        transport = transport.clone('kwaak')
1047
        branch = self.make_remote_branch(transport, client)
1048
        result = branch.get_parent()
1049
        self.assertEqual('http://foo/', result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1050
        self.assertFinished(client)
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
1051
1052
1053
class TestBranchSetParentLocation(RemoteBranchTestCase):
1054
1055
    def test_no_parent(self):
1056
        # We call the verb when setting parent to None
1057
        transport = MemoryTransport()
1058
        client = FakeClient(transport.base)
1059
        client.add_expected_call(
1060
            'Branch.get_stacked_on_url', ('quack/',),
1061
            'error', ('NotStacked',))
1062
        client.add_expected_call(
1063
            'Branch.set_parent_location', ('quack/', 'b', 'r', ''),
1064
            'success', ())
1065
        transport.mkdir('quack')
1066
        transport = transport.clone('quack')
1067
        branch = self.make_remote_branch(transport, client)
1068
        branch._lock_token = 'b'
1069
        branch._repo_lock_token = 'r'
1070
        branch._set_parent_location(None)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1071
        self.assertFinished(client)
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
1072
1073
    def test_parent(self):
1074
        transport = MemoryTransport()
1075
        client = FakeClient(transport.base)
1076
        client.add_expected_call(
1077
            'Branch.get_stacked_on_url', ('kwaak/',),
1078
            'error', ('NotStacked',))
1079
        client.add_expected_call(
1080
            'Branch.set_parent_location', ('kwaak/', 'b', 'r', 'foo'),
1081
            'success', ())
1082
        transport.mkdir('kwaak')
1083
        transport = transport.clone('kwaak')
1084
        branch = self.make_remote_branch(transport, client)
1085
        branch._lock_token = 'b'
1086
        branch._repo_lock_token = 'r'
1087
        branch._set_parent_location('foo')
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1088
        self.assertFinished(client)
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
1089
1090
    def test_backwards_compat(self):
1091
        self.setup_smart_server_with_call_log()
1092
        branch = self.make_branch('.')
1093
        self.reset_smart_call_log()
1094
        verb = 'Branch.set_parent_location'
1095
        self.disable_verb(verb)
1096
        branch.set_parent('http://foo/')
1097
        self.assertLength(12, self.hpss_calls)
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1098
1099
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.
1100
class TestBranchGetTagsBytes(RemoteBranchTestCase):
1101
1102
    def test_backwards_compat(self):
1103
        self.setup_smart_server_with_call_log()
1104
        branch = self.make_branch('.')
1105
        self.reset_smart_call_log()
1106
        verb = 'Branch.get_tags_bytes'
1107
        self.disable_verb(verb)
1108
        branch.tags.get_tag_dict()
1109
        call_count = len([call for call in self.hpss_calls if
1110
            call.call.method == verb])
1111
        self.assertEqual(1, call_count)
1112
1113
    def test_trivial(self):
1114
        transport = MemoryTransport()
1115
        client = FakeClient(transport.base)
1116
        client.add_expected_call(
1117
            'Branch.get_stacked_on_url', ('quack/',),
1118
            'error', ('NotStacked',))
1119
        client.add_expected_call(
1120
            'Branch.get_tags_bytes', ('quack/',),
1121
            'success', ('',))
1122
        transport.mkdir('quack')
1123
        transport = transport.clone('quack')
1124
        branch = self.make_remote_branch(transport, client)
1125
        result = branch.tags.get_tag_dict()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1126
        self.assertFinished(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.
1127
        self.assertEqual({}, result)
1128
1129
4634.36.1 by Andrew Bennetts
Fix trivial bug in RemoteBranch._set_tags_bytes, and add some unit tests for it.
1130
class TestBranchSetTagsBytes(RemoteBranchTestCase):
1131
1132
    def test_trivial(self):
1133
        transport = MemoryTransport()
1134
        client = FakeClient(transport.base)
1135
        client.add_expected_call(
1136
            'Branch.get_stacked_on_url', ('quack/',),
1137
            'error', ('NotStacked',))
1138
        client.add_expected_call(
1139
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1140
            'success', ('',))
1141
        transport.mkdir('quack')
1142
        transport = transport.clone('quack')
1143
        branch = self.make_remote_branch(transport, client)
1144
        self.lock_remote_branch(branch)
1145
        branch._set_tags_bytes('tags bytes')
1146
        self.assertFinished(client)
1147
        self.assertEqual('tags bytes', client._calls[-1][-1])
1148
1149
    def test_backwards_compatible(self):
1150
        transport = MemoryTransport()
1151
        client = FakeClient(transport.base)
1152
        client.add_expected_call(
1153
            'Branch.get_stacked_on_url', ('quack/',),
1154
            'error', ('NotStacked',))
1155
        client.add_expected_call(
1156
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1157
            'unknown', ('Branch.set_tags_bytes',))
1158
        transport.mkdir('quack')
1159
        transport = transport.clone('quack')
1160
        branch = self.make_remote_branch(transport, client)
1161
        self.lock_remote_branch(branch)
1162
        class StubRealBranch(object):
1163
            def __init__(self):
1164
                self.calls = []
1165
            def _set_tags_bytes(self, bytes):
1166
                self.calls.append(('set_tags_bytes', bytes))
1167
        real_branch = StubRealBranch()
1168
        branch._real_branch = real_branch
1169
        branch._set_tags_bytes('tags bytes')
1170
        # Call a second time, to exercise the 'remote version already inferred'
1171
        # code path.
1172
        branch._set_tags_bytes('tags bytes')
1173
        self.assertFinished(client)
1174
        self.assertEqual(
1175
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
1176
1177
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1178
class TestBranchHeadsToFetch(RemoteBranchTestCase):
1179
1180
    def test_uses_last_revision_info_and_tags_by_default(self):
1181
        transport = MemoryTransport()
1182
        client = FakeClient(transport.base)
1183
        client.add_expected_call(
1184
            'Branch.get_stacked_on_url', ('quack/',),
1185
            'error', ('NotStacked',))
1186
        client.add_expected_call(
1187
            'Branch.last_revision_info', ('quack/',),
1188
            'success', ('ok', '1', 'rev-tip'))
6015.15.4 by John Arbash Meinel
Catch a couple more cases that test tag fetching.
1189
        client.add_expected_call(
1190
            'Branch.get_config_file', ('quack/',),
1191
            'success', ('ok',), '')
1192
        transport.mkdir('quack')
1193
        transport = transport.clone('quack')
1194
        branch = self.make_remote_branch(transport, client)
1195
        result = branch.heads_to_fetch()
1196
        self.assertFinished(client)
1197
        self.assertEqual((set(['rev-tip']), set()), result)
1198
1199
    def test_uses_last_revision_info_and_tags_when_set(self):
1200
        transport = MemoryTransport()
1201
        client = FakeClient(transport.base)
1202
        client.add_expected_call(
1203
            'Branch.get_stacked_on_url', ('quack/',),
1204
            'error', ('NotStacked',))
1205
        client.add_expected_call(
1206
            'Branch.last_revision_info', ('quack/',),
1207
            'success', ('ok', '1', 'rev-tip'))
1208
        client.add_expected_call(
1209
            'Branch.get_config_file', ('quack/',),
1210
            'success', ('ok',), 'branch.fetch_tags = True')
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1211
        # XXX: this will break if the default format's serialization of tags
1212
        # changes, or if the RPC for fetching tags changes from get_tags_bytes.
1213
        client.add_expected_call(
1214
            'Branch.get_tags_bytes', ('quack/',),
1215
            'success', ('d5:tag-17:rev-foo5:tag-27:rev-bare',))
1216
        transport.mkdir('quack')
1217
        transport = transport.clone('quack')
1218
        branch = self.make_remote_branch(transport, client)
1219
        result = branch.heads_to_fetch()
1220
        self.assertFinished(client)
1221
        self.assertEqual(
1222
            (set(['rev-tip']), set(['rev-foo', 'rev-bar'])), result)
1223
1224
    def test_uses_rpc_for_formats_with_non_default_heads_to_fetch(self):
1225
        transport = MemoryTransport()
1226
        client = FakeClient(transport.base)
1227
        client.add_expected_call(
1228
            'Branch.get_stacked_on_url', ('quack/',),
1229
            'error', ('NotStacked',))
1230
        client.add_expected_call(
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
1231
            'Branch.heads_to_fetch', ('quack/',),
5672.1.6 by Andrew Bennetts
Add another test.
1232
            'success', (['tip'], ['tagged-1', 'tagged-2']))
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1233
        transport.mkdir('quack')
1234
        transport = transport.clone('quack')
1235
        branch = self.make_remote_branch(transport, client)
5672.1.7 by Andrew Bennetts
Use a more explicit method name.
1236
        branch._format._use_default_local_heads_to_fetch = lambda: False
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1237
        result = branch.heads_to_fetch()
1238
        self.assertFinished(client)
5672.1.6 by Andrew Bennetts
Add another test.
1239
        self.assertEqual((set(['tip']), set(['tagged-1', 'tagged-2'])), result)
1240
6015.15.1 by John Arbash Meinel
Start working on a config entry for testing whether we should fetch tags or not.
1241
    def make_branch_with_tags(self):
5672.1.6 by Andrew Bennetts
Add another test.
1242
        self.setup_smart_server_with_call_log()
1243
        # Make a branch with a single revision.
1244
        builder = self.make_branch_builder('foo')
1245
        builder.start_series()
1246
        builder.build_snapshot('tip', None, [
1247
            ('add', ('', 'root-id', 'directory', ''))])
1248
        builder.finish_series()
1249
        branch = builder.get_branch()
1250
        # Add two tags to that branch
1251
        branch.tags.set_tag('tag-1', 'rev-1')
1252
        branch.tags.set_tag('tag-2', 'rev-2')
6015.15.1 by John Arbash Meinel
Start working on a config entry for testing whether we should fetch tags or not.
1253
        return branch
1254
1255
    def test_backwards_compatible(self):
1256
        branch = self.make_branch_with_tags()
1257
        c = branch.get_config()
1258
        c.set_user_option('branch.fetch_tags', 'True')
5672.1.6 by Andrew Bennetts
Add another test.
1259
        self.addCleanup(branch.lock_read().unlock)
1260
        # Disable the heads_to_fetch verb
1261
        verb = 'Branch.heads_to_fetch'
1262
        self.disable_verb(verb)
1263
        self.reset_smart_call_log()
1264
        result = branch.heads_to_fetch()
1265
        self.assertEqual((set(['tip']), set(['rev-1', 'rev-2'])), result)
1266
        self.assertEqual(
6015.15.1 by John Arbash Meinel
Start working on a config entry for testing whether we should fetch tags or not.
1267
            ['Branch.last_revision_info', 'Branch.get_config_file',
1268
             'Branch.get_tags_bytes'],
1269
            [call.call.method for call in self.hpss_calls])
1270
1271
    def test_backwards_compatible_no_tags(self):
1272
        branch = self.make_branch_with_tags()
1273
        c = branch.get_config()
1274
        c.set_user_option('branch.fetch_tags', 'False')
1275
        self.addCleanup(branch.lock_read().unlock)
1276
        # Disable the heads_to_fetch verb
1277
        verb = 'Branch.heads_to_fetch'
1278
        self.disable_verb(verb)
1279
        self.reset_smart_call_log()
1280
        result = branch.heads_to_fetch()
1281
        self.assertEqual((set(['tip']), set()), result)
1282
        self.assertEqual(
1283
            ['Branch.last_revision_info', 'Branch.get_config_file'],
5672.1.6 by Andrew Bennetts
Add another test.
1284
            [call.call.method for call in self.hpss_calls])
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1285
1286
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1287
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1288
1289
    def test_empty_branch(self):
1290
        # in an empty branch we decode the response properly
1291
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1292
        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
1293
        client.add_expected_call(
1294
            'Branch.get_stacked_on_url', ('quack/',),
1295
            'error', ('NotStacked',))
1296
        client.add_expected_call(
1297
            'Branch.last_revision_info', ('quack/',),
1298
            'success', ('ok', '0', 'null:'))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1299
        transport.mkdir('quack')
1300
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1301
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1302
        result = branch.last_revision_info()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1303
        self.assertFinished(client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1304
        self.assertEqual((0, NULL_REVISION), result)
1305
1306
    def test_non_empty_branch(self):
1307
        # 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.
1308
        revid = u'\xc8'.encode('utf8')
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1309
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1310
        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
1311
        client.add_expected_call(
1312
            'Branch.get_stacked_on_url', ('kwaak/',),
1313
            'error', ('NotStacked',))
1314
        client.add_expected_call(
1315
            'Branch.last_revision_info', ('kwaak/',),
1316
            'success', ('ok', '2', revid))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1317
        transport.mkdir('kwaak')
1318
        transport = transport.clone('kwaak')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1319
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1320
        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.
1321
        self.assertEqual((2, revid), result)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1322
1323
4053.1.2 by Robert Collins
Actually make this branch work.
1324
class TestBranch_get_stacked_on_url(TestRemote):
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1325
    """Test Branch._get_stacked_on_url rpc"""
1326
3691.2.10 by Martin Pool
Update more test_remote tests
1327
    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.
1328
        # test that asking for a stacked on url the server can't access works.
1329
        # This isn't perfect, but then as we're in the same process there
1330
        # really isn't anything we can do to be 100% sure that the server
1331
        # doesn't just open in - this test probably needs to be rewritten using
1332
        # a spawn()ed server.
1333
        stacked_branch = self.make_branch('stacked', format='1.9')
1334
        memory_branch = self.make_branch('base', format='1.9')
1335
        vfs_url = self.get_vfs_only_url('base')
1336
        stacked_branch.set_stacked_on_url(vfs_url)
1337
        transport = stacked_branch.bzrdir.root_transport
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1338
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1339
        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.
1340
            'Branch.get_stacked_on_url', ('stacked/',),
1341
            'success', ('ok', vfs_url))
1342
        # XXX: Multiple calls are bad, this second call documents what is
1343
        # today.
1344
        client.add_expected_call(
1345
            'Branch.get_stacked_on_url', ('stacked/',),
1346
            'success', ('ok', vfs_url))
5712.3.17 by Jelmer Vernooij
more fixes.
1347
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
1348
            _client=client)
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
1349
        repo_fmt = remote.RemoteRepositoryFormat()
1350
        repo_fmt._custom_format = stacked_branch.repository._format
1351
        branch = RemoteBranch(bzrdir, RemoteRepository(bzrdir, repo_fmt),
4005.2.1 by Robert Collins
Fix RemoteBranch to be used correctly in tests using bzr+ssh, to fire off Branch hooks correctly, and improve the branch_implementations tests to check that making a branch gets the right format under test.
1352
            _client=client)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1353
        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.
1354
        self.assertEqual(vfs_url, result)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1355
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1356
    def test_backwards_compatible(self):
1357
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
1358
        base_branch = self.make_branch('base', format='1.6')
1359
        stacked_branch = self.make_branch('stacked', format='1.6')
1360
        stacked_branch.set_stacked_on_url('../base')
1361
        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.
1362
        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
1363
        client.add_expected_call(
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
1364
            'BzrDir.open_branchV3', ('stacked/',),
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.
1365
            'success', ('branch', branch_network_name))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1366
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
1367
            'BzrDir.find_repositoryV3', ('stacked/',),
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
1368
            'success', ('ok', '', 'no', 'no', 'yes',
4053.1.2 by Robert Collins
Actually make this branch work.
1369
                stacked_branch.repository._format.network_name()))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1370
        # called twice, once from constructor and then again by us
1371
        client.add_expected_call(
1372
            'Branch.get_stacked_on_url', ('stacked/',),
1373
            'unknown', ('Branch.get_stacked_on_url',))
1374
        client.add_expected_call(
1375
            'Branch.get_stacked_on_url', ('stacked/',),
1376
            'unknown', ('Branch.get_stacked_on_url',))
1377
        # this will also do vfs access, but that goes direct to the transport
1378
        # 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.
1379
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
5712.3.17 by Jelmer Vernooij
more fixes.
1380
            RemoteBzrDirFormat(), _client=client)
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1381
        branch = bzrdir.open_branch()
1382
        result = branch.get_stacked_on_url()
1383
        self.assertEqual('../base', result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1384
        self.assertFinished(client)
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1385
        # it's in the fallback list both for the RemoteRepository and its vfs
1386
        # repository
1387
        self.assertEqual(1, len(branch.repository._fallback_repositories))
1388
        self.assertEqual(1,
1389
            len(branch.repository._real_repository._fallback_repositories))
1390
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1391
    def test_get_stacked_on_real_branch(self):
5158.4.3 by Andrew Bennetts
Fix test_remote tests that accidentally assumed it was ok to stack mismatched formats.
1392
        base_branch = self.make_branch('base')
1393
        stacked_branch = self.make_branch('stacked')
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1394
        stacked_branch.set_stacked_on_url('../base')
4053.1.2 by Robert Collins
Actually make this branch work.
1395
        reference_format = self.get_repo_format()
1396
        network_name = reference_format.network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1397
        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.
1398
        branch_network_name = self.get_branch_format().network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1399
        client.add_expected_call(
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
1400
            'BzrDir.open_branchV3', ('stacked/',),
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.
1401
            'success', ('branch', branch_network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1402
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
1403
            'BzrDir.find_repositoryV3', ('stacked/',),
5158.4.3 by Andrew Bennetts
Fix test_remote tests that accidentally assumed it was ok to stack mismatched formats.
1404
            'success', ('ok', '', 'yes', 'no', 'yes', network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1405
        # called twice, once from constructor and then again by us
1406
        client.add_expected_call(
1407
            'Branch.get_stacked_on_url', ('stacked/',),
1408
            'success', ('ok', '../base'))
1409
        client.add_expected_call(
1410
            'Branch.get_stacked_on_url', ('stacked/',),
1411
            '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.
1412
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
5712.3.17 by Jelmer Vernooij
more fixes.
1413
            RemoteBzrDirFormat(), _client=client)
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1414
        branch = bzrdir.open_branch()
1415
        result = branch.get_stacked_on_url()
1416
        self.assertEqual('../base', result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1417
        self.assertFinished(client)
4226.1.2 by Robert Collins
Fix test_remote failing because of less _real_repository objects.
1418
        # it's in the fallback list both for the RemoteRepository.
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1419
        self.assertEqual(1, len(branch.repository._fallback_repositories))
4226.1.2 by Robert Collins
Fix test_remote failing because of less _real_repository objects.
1420
        # And we haven't had to construct a real repository.
1421
        self.assertEqual(None, branch.repository._real_repository)
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1422
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1423
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1424
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.
1425
1426
    def test_set_empty(self):
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1427
        # _set_last_revision_info('null:') is translated to calling
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1428
        # Branch.set_last_revision(path, '') on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
1429
        transport = MemoryTransport()
1430
        transport.mkdir('branch')
1431
        transport = transport.clone('branch')
1432
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1433
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1434
        client.add_expected_call(
1435
            'Branch.get_stacked_on_url', ('branch/',),
1436
            'error', ('NotStacked',))
1437
        client.add_expected_call(
1438
            'Branch.lock_write', ('branch/', '', ''),
1439
            'success', ('ok', 'branch token', 'repo token'))
1440
        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.
1441
            'Branch.last_revision_info',
1442
            ('branch/',),
1443
            'success', ('ok', '0', 'null:'))
1444
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1445
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
1446
            'success', ('ok',))
1447
        client.add_expected_call(
1448
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1449
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1450
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1451
        # This is a hack to work around the problem that RemoteBranch currently
1452
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1453
        branch._ensure_real = lambda: None
1454
        branch.lock_write()
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1455
        result = branch._set_last_revision(NULL_REVISION)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1456
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1457
        self.assertEqual(None, result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1458
        self.assertFinished(client)
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1459
1460
    def test_set_nonempty(self):
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
1461
        # set_last_revision_info(N, rev-idN) is translated to calling
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1462
        # Branch.set_last_revision(path, rev-idN) on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
1463
        transport = MemoryTransport()
1464
        transport.mkdir('branch')
1465
        transport = transport.clone('branch')
1466
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1467
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1468
        client.add_expected_call(
1469
            'Branch.get_stacked_on_url', ('branch/',),
1470
            'error', ('NotStacked',))
1471
        client.add_expected_call(
1472
            'Branch.lock_write', ('branch/', '', ''),
1473
            'success', ('ok', 'branch token', 'repo token'))
1474
        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.
1475
            'Branch.last_revision_info',
1476
            ('branch/',),
1477
            'success', ('ok', '0', 'null:'))
1478
        lines = ['rev-id2']
1479
        encoded_body = bz2.compress('\n'.join(lines))
1480
        client.add_success_response_with_body(encoded_body, 'ok')
1481
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1482
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
1483
            'success', ('ok',))
1484
        client.add_expected_call(
1485
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1486
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1487
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1488
        # This is a hack to work around the problem that RemoteBranch currently
1489
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1490
        branch._ensure_real = lambda: None
1491
        # Lock the branch, reset the record of remote calls.
1492
        branch.lock_write()
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1493
        result = branch._set_last_revision('rev-id2')
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1494
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1495
        self.assertEqual(None, result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1496
        self.assertFinished(client)
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1497
1498
    def test_no_such_revision(self):
1499
        transport = MemoryTransport()
1500
        transport.mkdir('branch')
1501
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1502
        # A response of 'NoSuchRevision' is translated into an exception.
1503
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1504
        client.add_expected_call(
1505
            'Branch.get_stacked_on_url', ('branch/',),
1506
            'error', ('NotStacked',))
1507
        client.add_expected_call(
1508
            'Branch.lock_write', ('branch/', '', ''),
1509
            'success', ('ok', 'branch token', 'repo token'))
1510
        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.
1511
            'Branch.last_revision_info',
1512
            ('branch/',),
1513
            'success', ('ok', '0', 'null:'))
1514
        # get_graph calls to construct the revision history, for the set_rh
1515
        # hook
1516
        lines = ['rev-id']
1517
        encoded_body = bz2.compress('\n'.join(lines))
1518
        client.add_success_response_with_body(encoded_body, 'ok')
1519
        client.add_expected_call(
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1520
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1521
            'error', ('NoSuchRevision', 'rev-id'))
1522
        client.add_expected_call(
1523
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1524
            'success', ('ok',))
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1525
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1526
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1527
        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.
1528
        self.assertRaises(
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1529
            errors.NoSuchRevision, branch._set_last_revision, 'rev-id')
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1530
        branch.unlock()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1531
        self.assertFinished(client)
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1532
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1533
    def test_tip_change_rejected(self):
1534
        """TipChangeRejected responses cause a TipChangeRejected exception to
1535
        be raised.
1536
        """
1537
        transport = MemoryTransport()
1538
        transport.mkdir('branch')
1539
        transport = transport.clone('branch')
1540
        client = FakeClient(transport.base)
1541
        rejection_msg_unicode = u'rejection message\N{INTERROBANG}'
1542
        rejection_msg_utf8 = rejection_msg_unicode.encode('utf8')
3691.2.10 by Martin Pool
Update more test_remote tests
1543
        client.add_expected_call(
1544
            'Branch.get_stacked_on_url', ('branch/',),
1545
            'error', ('NotStacked',))
1546
        client.add_expected_call(
1547
            'Branch.lock_write', ('branch/', '', ''),
1548
            'success', ('ok', 'branch token', 'repo token'))
1549
        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.
1550
            'Branch.last_revision_info',
1551
            ('branch/',),
1552
            'success', ('ok', '0', 'null:'))
1553
        lines = ['rev-id']
1554
        encoded_body = bz2.compress('\n'.join(lines))
1555
        client.add_success_response_with_body(encoded_body, 'ok')
1556
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1557
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1558
            'error', ('TipChangeRejected', rejection_msg_utf8))
1559
        client.add_expected_call(
1560
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1561
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1562
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1563
        branch._ensure_real = lambda: None
1564
        branch.lock_write()
1565
        # The 'TipChangeRejected' error response triggered by calling
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
1566
        # set_last_revision_info causes a TipChangeRejected exception.
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1567
        err = self.assertRaises(
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
1568
            errors.TipChangeRejected,
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1569
            branch._set_last_revision, 'rev-id')
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1570
        # The UTF-8 message from the response has been decoded into a unicode
1571
        # object.
1572
        self.assertIsInstance(err.msg, unicode)
1573
        self.assertEqual(rejection_msg_unicode, err.msg)
3691.2.10 by Martin Pool
Update more test_remote tests
1574
        branch.unlock()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1575
        self.assertFinished(client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1576
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1577
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1578
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1579
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1580
    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.
1581
        # set_last_revision_info(num, 'rev-id') is translated to calling
1582
        # 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'.
1583
        transport = MemoryTransport()
1584
        transport.mkdir('branch')
1585
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1586
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1587
        # get_stacked_on_url
1588
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1589
        # lock_write
1590
        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.
1591
        # query the current revision
1592
        client.add_success_response('ok', '0', 'null:')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1593
        # set_last_revision
1594
        client.add_success_response('ok')
1595
        # unlock
1596
        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.
1597
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1598
        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.
1599
        # Lock the branch, reset the record of remote calls.
1600
        branch.lock_write()
1601
        client._calls = []
1602
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1603
        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.
1604
            [('call', 'Branch.last_revision_info', ('branch/',)),
1605
             ('call', 'Branch.set_last_revision_info',
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
1606
                ('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.
1607
                 '1234', 'a-revision-id'))],
1608
            client._calls)
1609
        self.assertEqual(None, result)
1610
1611
    def test_no_such_revision(self):
1612
        # A response of 'NoSuchRevision' is translated into an exception.
1613
        transport = MemoryTransport()
1614
        transport.mkdir('branch')
1615
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1616
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1617
        # get_stacked_on_url
1618
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1619
        # lock_write
1620
        client.add_success_response('ok', 'branch token', 'repo token')
1621
        # set_last_revision
1622
        client.add_error_response('NoSuchRevision', 'revid')
1623
        # unlock
1624
        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.
1625
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1626
        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.
1627
        # Lock the branch, reset the record of remote calls.
1628
        branch.lock_write()
1629
        client._calls = []
1630
1631
        self.assertRaises(
1632
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1633
        branch.unlock()
1634
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1635
    def test_backwards_compatibility(self):
1636
        """If the server does not support the Branch.set_last_revision_info
1637
        verb (which is new in 1.4), then the client falls back to VFS methods.
1638
        """
1639
        # This test is a little messy.  Unlike most tests in this file, it
1640
        # doesn't purely test what a Remote* object sends over the wire, and
1641
        # how it reacts to responses from the wire.  It instead relies partly
1642
        # on asserting that the RemoteBranch will call
1643
        # self._real_branch.set_last_revision_info(...).
1644
1645
        # First, set up our RemoteBranch with a FakeClient that raises
1646
        # UnknownSmartMethod, and a StubRealBranch that logs how it is called.
1647
        transport = MemoryTransport()
1648
        transport.mkdir('branch')
1649
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1650
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1651
        client.add_expected_call(
1652
            'Branch.get_stacked_on_url', ('branch/',),
1653
            'error', ('NotStacked',))
1654
        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.
1655
            'Branch.last_revision_info',
1656
            ('branch/',),
1657
            'success', ('ok', '0', 'null:'))
1658
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1659
            'Branch.set_last_revision_info',
1660
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
1661
            'unknown', 'Branch.set_last_revision_info')
1662
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1663
        branch = self.make_remote_branch(transport, client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1664
        class StubRealBranch(object):
1665
            def __init__(self):
1666
                self.calls = []
1667
            def set_last_revision_info(self, revno, revision_id):
1668
                self.calls.append(
1669
                    ('set_last_revision_info', revno, revision_id))
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1670
            def _clear_cached_state(self):
1671
                pass
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1672
        real_branch = StubRealBranch()
1673
        branch._real_branch = real_branch
1674
        self.lock_remote_branch(branch)
1675
1676
        # Call set_last_revision_info, and verify it behaved as expected.
1677
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1678
        self.assertEqual(
1679
            [('set_last_revision_info', 1234, 'a-revision-id')],
1680
            real_branch.calls)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1681
        self.assertFinished(client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1682
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1683
    def test_unexpected_error(self):
3697.2.6 by Martin Pool
Merge 261315 fix into 1.7 branch
1684
        # If the server sends an error the client doesn't understand, it gets
1685
        # turned into an UnknownErrorFromSmartServer, which is presented as a
1686
        # non-internal error to the user.
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1687
        transport = MemoryTransport()
1688
        transport.mkdir('branch')
1689
        transport = transport.clone('branch')
1690
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1691
        # get_stacked_on_url
1692
        client.add_error_response('NotStacked')
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1693
        # lock_write
1694
        client.add_success_response('ok', 'branch token', 'repo token')
1695
        # set_last_revision
1696
        client.add_error_response('UnexpectedError')
1697
        # unlock
1698
        client.add_success_response('ok')
1699
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1700
        branch = self.make_remote_branch(transport, client)
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1701
        # Lock the branch, reset the record of remote calls.
1702
        branch.lock_write()
1703
        client._calls = []
1704
1705
        err = self.assertRaises(
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1706
            errors.UnknownErrorFromSmartServer,
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1707
            branch.set_last_revision_info, 123, 'revid')
1708
        self.assertEqual(('UnexpectedError',), err.error_tuple)
1709
        branch.unlock()
1710
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1711
    def test_tip_change_rejected(self):
1712
        """TipChangeRejected responses cause a TipChangeRejected exception to
1713
        be raised.
1714
        """
1715
        transport = MemoryTransport()
1716
        transport.mkdir('branch')
1717
        transport = transport.clone('branch')
1718
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1719
        # get_stacked_on_url
1720
        client.add_error_response('NotStacked')
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1721
        # lock_write
1722
        client.add_success_response('ok', 'branch token', 'repo token')
1723
        # set_last_revision
1724
        client.add_error_response('TipChangeRejected', 'rejection message')
1725
        # unlock
1726
        client.add_success_response('ok')
1727
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1728
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1729
        # Lock the branch, reset the record of remote calls.
1730
        branch.lock_write()
1731
        self.addCleanup(branch.unlock)
1732
        client._calls = []
1733
1734
        # The 'TipChangeRejected' error response triggered by calling
1735
        # set_last_revision_info causes a TipChangeRejected exception.
1736
        err = self.assertRaises(
1737
            errors.TipChangeRejected,
1738
            branch.set_last_revision_info, 123, 'revid')
1739
        self.assertEqual('rejection message', err.msg)
1740
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1741
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1742
class TestBranchGetSetConfig(RemoteBranchTestCase):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1743
1744
    def test_get_branch_conf(self):
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
1745
        # in an empty branch we decode the response properly
1746
        client = FakeClient()
1747
        client.add_expected_call(
1748
            'Branch.get_stacked_on_url', ('memory:///',),
1749
            'error', ('NotStacked',),)
1750
        client.add_success_response_with_body('# config file body', 'ok')
1751
        transport = MemoryTransport()
1752
        branch = self.make_remote_branch(transport, client)
1753
        config = branch.get_config()
1754
        config.has_explicit_nickname()
1755
        self.assertEqual(
1756
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
1757
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
1758
            client._calls)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1759
4241.5.2 by Matt Nordhoff
Add a test
1760
    def test_get_multi_line_branch_conf(self):
1761
        # Make sure that multiple-line branch.conf files are supported
1762
        #
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
1763
        # https://bugs.launchpad.net/bzr/+bug/354075
4241.5.2 by Matt Nordhoff
Add a test
1764
        client = FakeClient()
1765
        client.add_expected_call(
1766
            'Branch.get_stacked_on_url', ('memory:///',),
1767
            'error', ('NotStacked',),)
1768
        client.add_success_response_with_body('a = 1\nb = 2\nc = 3\n', 'ok')
1769
        transport = MemoryTransport()
1770
        branch = self.make_remote_branch(transport, client)
1771
        config = branch.get_config()
1772
        self.assertEqual(u'2', config.get_user_option('b'))
1773
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1774
    def test_set_option(self):
1775
        client = FakeClient()
1776
        client.add_expected_call(
1777
            'Branch.get_stacked_on_url', ('memory:///',),
1778
            'error', ('NotStacked',),)
1779
        client.add_expected_call(
1780
            'Branch.lock_write', ('memory:///', '', ''),
1781
            'success', ('ok', 'branch token', 'repo token'))
1782
        client.add_expected_call(
1783
            'Branch.set_config_option', ('memory:///', 'branch token',
1784
            'repo token', 'foo', 'bar', ''),
1785
            'success', ())
1786
        client.add_expected_call(
1787
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1788
            'success', ('ok',))
1789
        transport = MemoryTransport()
1790
        branch = self.make_remote_branch(transport, client)
1791
        branch.lock_write()
1792
        config = branch._get_config()
1793
        config.set_option('foo', 'bar')
1794
        branch.unlock()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1795
        self.assertFinished(client)
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1796
5227.1.2 by Andrew Bennetts
Add Branch.set_config_option_dict RPC (and VFS fallback), fixes #430382.
1797
    def test_set_option_with_dict(self):
1798
        client = FakeClient()
1799
        client.add_expected_call(
1800
            'Branch.get_stacked_on_url', ('memory:///',),
1801
            'error', ('NotStacked',),)
1802
        client.add_expected_call(
1803
            'Branch.lock_write', ('memory:///', '', ''),
1804
            'success', ('ok', 'branch token', 'repo token'))
1805
        encoded_dict_value = 'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde'
1806
        client.add_expected_call(
1807
            'Branch.set_config_option_dict', ('memory:///', 'branch token',
1808
            'repo token', encoded_dict_value, 'foo', ''),
1809
            'success', ())
1810
        client.add_expected_call(
1811
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1812
            'success', ('ok',))
1813
        transport = MemoryTransport()
1814
        branch = self.make_remote_branch(transport, client)
1815
        branch.lock_write()
1816
        config = branch._get_config()
1817
        config.set_option(
1818
            {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'},
1819
            'foo')
1820
        branch.unlock()
1821
        self.assertFinished(client)
1822
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1823
    def test_backwards_compat_set_option(self):
1824
        self.setup_smart_server_with_call_log()
1825
        branch = self.make_branch('.')
1826
        verb = 'Branch.set_config_option'
1827
        self.disable_verb(verb)
1828
        branch.lock_write()
1829
        self.addCleanup(branch.unlock)
1830
        self.reset_smart_call_log()
1831
        branch._get_config().set_option('value', 'name')
1832
        self.assertLength(10, self.hpss_calls)
1833
        self.assertEqual('value', branch._get_config().get_option('name'))
1834
5227.1.2 by Andrew Bennetts
Add Branch.set_config_option_dict RPC (and VFS fallback), fixes #430382.
1835
    def test_backwards_compat_set_option_with_dict(self):
1836
        self.setup_smart_server_with_call_log()
1837
        branch = self.make_branch('.')
1838
        verb = 'Branch.set_config_option_dict'
1839
        self.disable_verb(verb)
1840
        branch.lock_write()
1841
        self.addCleanup(branch.unlock)
1842
        self.reset_smart_call_log()
1843
        config = branch._get_config()
1844
        value_dict = {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
1845
        config.set_option(value_dict, 'name')
1846
        self.assertLength(10, self.hpss_calls)
1847
        self.assertEqual(value_dict, branch._get_config().get_option('name'))
1848
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1849
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1850
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.
1851
1852
    def test_lock_write_unlockable(self):
1853
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1854
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1855
        client.add_expected_call(
1856
            'Branch.get_stacked_on_url', ('quack/',),
1857
            'error', ('NotStacked',),)
1858
        client.add_expected_call(
1859
            'Branch.lock_write', ('quack/', '', ''),
1860
            '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.
1861
        transport.mkdir('quack')
1862
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1863
        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.
1864
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1865
        self.assertFinished(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.
1866
1867
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1868
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
1869
1870
    def test__get_config(self):
1871
        client = FakeClient()
1872
        client.add_success_response_with_body('default_stack_on = /\n', 'ok')
1873
        transport = MemoryTransport()
1874
        bzrdir = self.make_remote_bzrdir(transport, client)
1875
        config = bzrdir.get_config()
1876
        self.assertEqual('/', config.get_default_stack_on())
1877
        self.assertEqual(
1878
            [('call_expecting_body', 'BzrDir.get_config_file', ('memory:///',))],
1879
            client._calls)
1880
1881
    def test_set_option_uses_vfs(self):
1882
        self.setup_smart_server_with_call_log()
1883
        bzrdir = self.make_bzrdir('.')
1884
        self.reset_smart_call_log()
1885
        config = bzrdir.get_config()
1886
        config.set_default_stack_on('/')
1887
        self.assertLength(3, self.hpss_calls)
1888
1889
    def test_backwards_compat_get_option(self):
1890
        self.setup_smart_server_with_call_log()
1891
        bzrdir = self.make_bzrdir('.')
1892
        verb = 'BzrDir.get_config_file'
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
1893
        self.disable_verb(verb)
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1894
        self.reset_smart_call_log()
1895
        self.assertEqual(None,
1896
            bzrdir._get_config().get_option('default_stack_on'))
1897
        self.assertLength(3, self.hpss_calls)
1898
1899
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1900
class TestTransportIsReadonly(tests.TestCase):
1901
1902
    def test_true(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1903
        client = FakeClient()
1904
        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.
1905
        transport = RemoteTransport('bzr://example.com/', medium=False,
1906
                                    _client=client)
1907
        self.assertEqual(True, transport.is_readonly())
1908
        self.assertEqual(
1909
            [('call', 'Transport.is_readonly', ())],
1910
            client._calls)
1911
1912
    def test_false(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1913
        client = FakeClient()
1914
        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.
1915
        transport = RemoteTransport('bzr://example.com/', medium=False,
1916
                                    _client=client)
1917
        self.assertEqual(False, transport.is_readonly())
1918
        self.assertEqual(
1919
            [('call', 'Transport.is_readonly', ())],
1920
            client._calls)
1921
1922
    def test_error_from_old_server(self):
1923
        """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
1924
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1925
        Clients should treat it as a "no" response, because is_readonly is only
1926
        advisory anyway (a transport could be read-write, but then the
1927
        underlying filesystem could be readonly anyway).
1928
        """
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1929
        client = FakeClient()
1930
        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.
1931
        transport = RemoteTransport('bzr://example.com/', medium=False,
1932
                                    _client=client)
1933
        self.assertEqual(False, transport.is_readonly())
1934
        self.assertEqual(
1935
            [('call', 'Transport.is_readonly', ())],
1936
            client._calls)
1937
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1938
3840.1.1 by Andrew Bennetts
Fix RemoteTransport's translation of errors involving paths; it wasn't passing orig_path to _translate_error.
1939
class TestTransportMkdir(tests.TestCase):
1940
1941
    def test_permissiondenied(self):
1942
        client = FakeClient()
1943
        client.add_error_response('PermissionDenied', 'remote path', 'extra')
1944
        transport = RemoteTransport('bzr://example.com/', medium=False,
1945
                                    _client=client)
1946
        exc = self.assertRaises(
1947
            errors.PermissionDenied, transport.mkdir, 'client path')
1948
        expected_error = errors.PermissionDenied('/client path', 'extra')
1949
        self.assertEqual(expected_error, exc)
1950
1951
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1952
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
1953
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1954
    def test_defaults_to_none(self):
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1955
        t = RemoteSSHTransport('bzr+ssh://example.com')
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
1956
        self.assertIs(None, t._get_credentials()[0])
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
1957
1958
    def test_uses_authentication_config(self):
1959
        conf = config.AuthenticationConfig()
1960
        conf._get_config().update(
1961
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
1962
            'example.com'}})
1963
        conf._save()
1964
        t = RemoteSSHTransport('bzr+ssh://example.com')
1965
        self.assertEqual('bar', t._get_credentials()[0])
1966
1967
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
1968
class TestRemoteRepository(TestRemote):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
1969
    """Base for testing RemoteRepository protocol usage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1970
1971
    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
1972
    what is sent or expected to be require a thoughtful update to these tests
1973
    because they might break compatibility with different-versioned servers.
1974
    """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1975
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1976
    def setup_fake_client_and_repository(self, transport_path):
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1977
        """Create the fake client and repository for testing with.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1978
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1979
        There's no real server here; we just have canned responses sent
1980
        back one by one.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1981
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
1982
        :param transport_path: Path below the root of the MemoryTransport
1983
            where the repository will be created.
1984
        """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1985
        transport = MemoryTransport()
1986
        transport.mkdir(transport_path)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1987
        client = FakeClient(transport.base)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1988
        transport = transport.clone(transport_path)
1989
        # we do not want bzrdir to make any remote calls
5712.3.17 by Jelmer Vernooij
more fixes.
1990
        bzrdir = RemoteBzrDir(transport, RemoteBzrDirFormat(),
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.
1991
            _client=False)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1992
        repo = RemoteRepository(bzrdir, None, _client=client)
1993
        return repo, client
1994
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
1995
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
1996
def remoted_description(format):
1997
    return 'Remote: ' + format.get_format_description()
1998
1999
2000
class TestBranchFormat(tests.TestCase):
2001
2002
    def test_get_format_description(self):
2003
        remote_format = RemoteBranchFormat()
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
2004
        real_format = branch.format_registry.get_default()
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2005
        remote_format._network_name = real_format.network_name()
2006
        self.assertEqual(remoted_description(real_format),
2007
            remote_format.get_format_description())
2008
2009
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2010
class TestRepositoryFormat(TestRemoteRepository):
2011
2012
    def test_fast_delta(self):
5546.1.1 by Andrew Bennetts
Remove RepositoryFormatCHK1 and RepositoryFormatCHK2.
2013
        true_name = groupcompress_repo.RepositoryFormat2a().network_name()
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2014
        true_format = RemoteRepositoryFormat()
2015
        true_format._network_name = true_name
2016
        self.assertEqual(True, true_format.fast_deltas)
5757.1.7 by Jelmer Vernooij
Fix more imports.
2017
        false_name = knitpack_repo.RepositoryFormatKnitPack1().network_name()
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2018
        false_format = RemoteRepositoryFormat()
2019
        false_format._network_name = false_name
2020
        self.assertEqual(False, false_format.fast_deltas)
2021
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2022
    def test_get_format_description(self):
2023
        remote_repo_format = RemoteRepositoryFormat()
5651.3.9 by Jelmer Vernooij
Avoid using deprecated functions.
2024
        real_format = repository.format_registry.get_default()
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2025
        remote_repo_format._network_name = real_format.network_name()
2026
        self.assertEqual(remoted_description(real_format),
2027
            remote_repo_format.get_format_description())
2028
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2029
2018.12.2 by Andrew Bennetts
Remove some duplicate code in test_remote
2030
class TestRepositoryGatherStats(TestRemoteRepository):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2031
2032
    def test_revid_none(self):
2033
        # ('ok',), body with revisions and size
2034
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2035
        repo, client = self.setup_fake_client_and_repository(transport_path)
2036
        client.add_success_response_with_body(
2037
            'revisions: 2\nsize: 18\n', 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2038
        result = repo.gather_stats(None)
2039
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
2040
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
2041
             ('quack/','','no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2042
            client._calls)
2043
        self.assertEqual({'revisions': 2, 'size': 18}, result)
2044
2045
    def test_revid_no_committers(self):
2046
        # ('ok',), body without committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2047
        body = ('firstrev: 123456.300 3600\n'
2048
                'latestrev: 654231.400 0\n'
2049
                'revisions: 2\n'
2050
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2051
        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.
2052
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2053
        repo, client = self.setup_fake_client_and_repository(transport_path)
2054
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2055
        result = repo.gather_stats(revid)
2056
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
2057
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
2058
              ('quick/', revid, 'no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2059
            client._calls)
2060
        self.assertEqual({'revisions': 2, 'size': 18,
2061
                          'firstrev': (123456.300, 3600),
2062
                          'latestrev': (654231.400, 0),},
2063
                         result)
2064
2065
    def test_revid_with_committers(self):
2066
        # ('ok',), body with committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2067
        body = ('committers: 128\n'
2068
                'firstrev: 123456.300 3600\n'
2069
                'latestrev: 654231.400 0\n'
2070
                'revisions: 2\n'
2071
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2072
        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.
2073
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2074
        repo, client = self.setup_fake_client_and_repository(transport_path)
2075
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2076
        result = repo.gather_stats(revid, True)
2077
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
2078
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
2079
              ('buick/', revid, 'yes'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2080
            client._calls)
2081
        self.assertEqual({'revisions': 2, 'size': 18,
2082
                          'committers': 128,
2083
                          'firstrev': (123456.300, 3600),
2084
                          'latestrev': (654231.400, 0),},
2085
                         result)
2086
2087
6263.3.2 by Jelmer Vernooij
Add new HPSS call 'Repository.get_revision_signature_text'.
2088
class TestRepositoryGetRevisionSignatureText(TestRemoteRepository):
2089
2090
    def test_text(self):
2091
        # ('ok',), body with signature text
2092
        transport_path = 'quack'
2093
        repo, client = self.setup_fake_client_and_repository(transport_path)
2094
        client.add_success_response_with_body(
2095
            'THETEXT', 'ok')
2096
        self.assertEquals("THETEXT", repo.get_signature_text("revid"))
2097
        self.assertEqual(
2098
            [('call_expecting_body', 'Repository.get_revision_signature_text',
2099
             ('quack/', 'revid'))],
2100
            client._calls)
2101
2102
    def test_no_signature(self):
2103
        transport_path = 'quick'
2104
        repo, client = self.setup_fake_client_and_repository(transport_path)
2105
        client.add_error_response('nosuchrevision', 'unknown')
2106
        self.assertRaises(errors.NoSuchRevision, repo.get_signature_text,
2107
                "unknown")
2108
        self.assertEqual(
2109
            [('call_expecting_body', 'Repository.get_revision_signature_text',
2110
              ('quick/', 'unknown'))],
2111
            client._calls)
2112
2113
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2114
class TestRepositoryGetGraph(TestRemoteRepository):
2115
2116
    def test_get_graph(self):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
2117
        # 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.
2118
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2119
        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.
2120
        graph = repo.get_graph()
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
2121
        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.
2122
2123
2124
class TestRepositoryGetParentMap(TestRemoteRepository):
2125
2126
    def test_get_parent_map_caching(self):
2127
        # get_parent_map returns from cache until unlock()
2128
        # setup a reponse with two revisions
2129
        r1 = u'\u0e33'.encode('utf8')
2130
        r2 = u'\u0dab'.encode('utf8')
2131
        lines = [' '.join([r2, r1]), r1]
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
2132
        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.
2133
2134
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2135
        repo, client = self.setup_fake_client_and_repository(transport_path)
2136
        client.add_success_response_with_body(encoded_body, 'ok')
2137
        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.
2138
        repo.lock_read()
2139
        graph = repo.get_graph()
2140
        parents = graph.get_parent_map([r2])
2141
        self.assertEqual({r2: (r1,)}, parents)
2142
        # locking and unlocking deeper should not reset
2143
        repo.lock_read()
2144
        repo.unlock()
2145
        parents = graph.get_parent_map([r1])
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
2146
        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.
2147
        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.
2148
            [('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
2149
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
2150
              '\n\n0')],
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2151
            client._calls)
2152
        repo.unlock()
2153
        # now we call again, and it should use the second response.
2154
        repo.lock_read()
2155
        graph = repo.get_graph()
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
2156
        parents = graph.get_parent_map([r1])
2157
        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.
2158
        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.
2159
            [('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
2160
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
2161
              '\n\n0'),
3211.5.1 by Robert Collins
Change the smart server get_parents method to take a graph search to exclude already recieved parents from. This prevents history shortcuts causing huge numbers of duplicates.
2162
             ('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
2163
              'Repository.get_parent_map', ('quack/', 'include-missing:', r1),
2164
              '\n\n0'),
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2165
            ],
2166
            client._calls)
2167
        repo.unlock()
2168
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
2169
    def test_get_parent_map_reconnects_if_unknown_method(self):
2170
        transport_path = 'quack'
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2171
        rev_id = 'revision-id'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2172
        repo, client = self.setup_fake_client_and_repository(transport_path)
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2173
        client.add_unknown_method_response('Repository.get_parent_map')
2174
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
2175
        self.assertFalse(client._medium._is_remote_before((1, 2)))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2176
        parents = repo.get_parent_map([rev_id])
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
2177
        self.assertEqual(
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
2178
            [('call_with_body_bytes_expecting_body',
6015.23.17 by John Arbash Meinel
Code was relying on an empty parent map to yield an empty search.
2179
              'Repository.get_parent_map',
2180
              ('quack/', 'include-missing:', rev_id), '\n\n0'),
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
2181
             ('disconnect medium',),
2182
             ('call_expecting_body', 'Repository.get_revision_graph',
2183
              ('quack/', ''))],
2184
            client._calls)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2185
        # 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.
2186
        self.assertTrue(client._medium._is_remote_before((1, 2)))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2187
        self.assertEqual({rev_id: ('null:',)}, parents)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2188
2189
    def test_get_parent_map_fallback_parentless_node(self):
2190
        """get_parent_map falls back to get_revision_graph on old servers.  The
2191
        results from get_revision_graph are tweaked to match the get_parent_map
2192
        API.
2193
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
2194
        Specifically, a {key: ()} result from get_revision_graph means "no
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2195
        parents" for that key, which in get_parent_map results should be
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
2196
        represented as {key: ('null:',)}.
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2197
2198
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
2199
        """
2200
        rev_id = 'revision-id'
2201
        transport_path = 'quack'
3245.4.40 by Andrew Bennetts
Merge from bzr.dev.
2202
        repo, client = self.setup_fake_client_and_repository(transport_path)
2203
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
2204
        client._medium._remember_remote_is_before((1, 2))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2205
        parents = repo.get_parent_map([rev_id])
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2206
        self.assertEqual(
2207
            [('call_expecting_body', 'Repository.get_revision_graph',
2208
             ('quack/', ''))],
2209
            client._calls)
2210
        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.
2211
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
2212
    def test_get_parent_map_unexpected_response(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2213
        repo, client = self.setup_fake_client_and_repository('path')
2214
        client.add_success_response('something unexpected!')
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
2215
        self.assertRaises(
2216
            errors.UnexpectedSmartServerResponse,
2217
            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.
2218
4190.1.1 by Robert Collins
Negatively cache misses during read-locks in RemoteRepository.
2219
    def test_get_parent_map_negative_caches_missing_keys(self):
2220
        self.setup_smart_server_with_call_log()
2221
        repo = self.make_repository('foo')
2222
        self.assertIsInstance(repo, RemoteRepository)
2223
        repo.lock_read()
2224
        self.addCleanup(repo.unlock)
2225
        self.reset_smart_call_log()
2226
        graph = repo.get_graph()
2227
        self.assertEqual({},
2228
            graph.get_parent_map(['some-missing', 'other-missing']))
2229
        self.assertLength(1, self.hpss_calls)
2230
        # No call if we repeat this
2231
        self.reset_smart_call_log()
2232
        graph = repo.get_graph()
2233
        self.assertEqual({},
2234
            graph.get_parent_map(['some-missing', 'other-missing']))
2235
        self.assertLength(0, self.hpss_calls)
2236
        # Asking for more unknown keys makes a request.
2237
        self.reset_smart_call_log()
2238
        graph = repo.get_graph()
2239
        self.assertEqual({},
2240
            graph.get_parent_map(['some-missing', 'other-missing',
2241
                'more-missing']))
2242
        self.assertLength(1, self.hpss_calls)
2243
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2244
    def disableExtraResults(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
2245
        self.overrideAttr(SmartServerRepositoryGetParentMap,
2246
                          'no_extra_results', True)
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2247
4214.2.5 by Andrew Bennetts
Fix the bug.
2248
    def test_null_cached_missing_and_stop_key(self):
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2249
        self.setup_smart_server_with_call_log()
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2250
        # Make a branch with a single revision.
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2251
        builder = self.make_branch_builder('foo')
2252
        builder.start_series()
2253
        builder.build_snapshot('first', None, [
2254
            ('add', ('', 'root-id', 'directory', ''))])
2255
        builder.finish_series()
2256
        branch = builder.get_branch()
2257
        repo = branch.repository
2258
        self.assertIsInstance(repo, RemoteRepository)
4214.2.3 by Andrew Bennetts
Further simplify test case, and add more comments.
2259
        # Stop the server from sending extra results.
2260
        self.disableExtraResults()
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2261
        repo.lock_read()
2262
        self.addCleanup(repo.unlock)
2263
        self.reset_smart_call_log()
2264
        graph = repo.get_graph()
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2265
        # Query for 'first' and 'null:'.  Because 'null:' is a parent of
4214.2.5 by Andrew Bennetts
Fix the bug.
2266
        # 'first' it will be a candidate for the stop_keys of subsequent
2267
        # requests, and because 'null:' was queried but not returned it will be
2268
        # cached as missing.
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2269
        self.assertEqual({'first': ('null:',)},
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2270
            graph.get_parent_map(['first', 'null:']))
2271
        # Now query for another key.  This request will pass along a recipe of
2272
        # start and stop keys describing the already cached results, and this
4214.2.5 by Andrew Bennetts
Fix the bug.
2273
        # recipe's revision count must be correct (or else it will trigger an
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2274
        # error from the server).
4214.2.5 by Andrew Bennetts
Fix the bug.
2275
        self.assertEqual({}, graph.get_parent_map(['another-key']))
4214.2.3 by Andrew Bennetts
Further simplify test case, and add more comments.
2276
        # This assertion guards against disableExtraResults silently failing to
2277
        # work, thus invalidating the test.
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2278
        self.assertLength(2, self.hpss_calls)
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2279
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
2280
    def test_get_parent_map_gets_ghosts_from_result(self):
2281
        # asking for a revision should negatively cache close ghosts in its
2282
        # ancestry.
2283
        self.setup_smart_server_with_call_log()
2284
        tree = self.make_branch_and_memory_tree('foo')
2285
        tree.lock_write()
2286
        try:
2287
            builder = treebuilder.TreeBuilder()
2288
            builder.start_tree(tree)
2289
            builder.build([])
2290
            builder.finish_tree()
2291
            tree.set_parent_ids(['non-existant'], allow_leftmost_as_ghost=True)
2292
            rev_id = tree.commit('')
2293
        finally:
2294
            tree.unlock()
2295
        tree.lock_read()
2296
        self.addCleanup(tree.unlock)
2297
        repo = tree.branch.repository
2298
        self.assertIsInstance(repo, RemoteRepository)
2299
        # ask for rev_id
2300
        repo.get_parent_map([rev_id])
2301
        self.reset_smart_call_log()
2302
        # Now asking for rev_id's ghost parent should not make calls
2303
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
2304
        self.assertLength(0, self.hpss_calls)
2305
6015.24.4 by John Arbash Meinel
For it to all work properly, we have to expose get_parent_map_cached on RemoteRepository.
2306
    def test_exposes_get_cached_parent_map(self):
2307
        """RemoteRepository exposes get_cached_parent_map from
2308
        _unstacked_provider
2309
        """
2310
        r1 = u'\u0e33'.encode('utf8')
2311
        r2 = u'\u0dab'.encode('utf8')
2312
        lines = [' '.join([r2, r1]), r1]
2313
        encoded_body = bz2.compress('\n'.join(lines))
2314
2315
        transport_path = 'quack'
2316
        repo, client = self.setup_fake_client_and_repository(transport_path)
2317
        client.add_success_response_with_body(encoded_body, 'ok')
2318
        repo.lock_read()
6015.24.5 by John Arbash Meinel
Bug #388269.
2319
        # get_cached_parent_map should *not* trigger an RPC
2320
        self.assertEqual({}, repo.get_cached_parent_map([r1]))
2321
        self.assertEqual([], client._calls)
6015.24.4 by John Arbash Meinel
For it to all work properly, we have to expose get_parent_map_cached on RemoteRepository.
2322
        self.assertEqual({r2: (r1,)}, repo.get_parent_map([r2]))
2323
        self.assertEqual({r1: (NULL_REVISION,)},
2324
            repo.get_cached_parent_map([r1]))
2325
        self.assertEqual(
2326
            [('call_with_body_bytes_expecting_body',
2327
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
2328
              '\n\n0')],
2329
            client._calls)
2330
        repo.unlock()
2331
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2332
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
2333
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
2334
2335
    def test_allows_new_revisions(self):
2336
        """get_parent_map's results can be updated by commit."""
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
2337
        smart_server = test_server.SmartTCPServer_for_testing()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
2338
        self.start_server(smart_server)
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
2339
        self.make_branch('branch')
2340
        branch = Branch.open(smart_server.get_url() + '/branch')
2341
        tree = branch.create_checkout('tree', lightweight=True)
2342
        tree.lock_write()
2343
        self.addCleanup(tree.unlock)
2344
        graph = tree.branch.repository.get_graph()
2345
        # This provides an opportunity for the missing rev-id to be cached.
2346
        self.assertEqual({}, graph.get_parent_map(['rev1']))
2347
        tree.commit('message', rev_id='rev1')
2348
        graph = tree.branch.repository.get_graph()
2349
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
2350
2351
3948.3.9 by Martin Pool
Undelete TestRepositoryGetRevisionGraph but make it use private client methods to simulate old clients
2352
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
2353
2354
    def test_null_revision(self):
2355
        # a null revision has the predictable result {}, we should have no wire
2356
        # traffic when calling it with this argument
2357
        transport_path = 'empty'
2358
        repo, client = self.setup_fake_client_and_repository(transport_path)
2359
        client.add_success_response('notused')
2360
        # actual RemoteRepository.get_revision_graph is gone, but there's an
2361
        # equivalent private method for testing
2362
        result = repo._get_revision_graph(NULL_REVISION)
2363
        self.assertEqual([], client._calls)
2364
        self.assertEqual({}, result)
2365
2366
    def test_none_revision(self):
2367
        # with none we want the entire graph
2368
        r1 = u'\u0e33'.encode('utf8')
2369
        r2 = u'\u0dab'.encode('utf8')
2370
        lines = [' '.join([r2, r1]), r1]
2371
        encoded_body = '\n'.join(lines)
2372
2373
        transport_path = 'sinhala'
2374
        repo, client = self.setup_fake_client_and_repository(transport_path)
2375
        client.add_success_response_with_body(encoded_body, 'ok')
2376
        # actual RemoteRepository.get_revision_graph is gone, but there's an
2377
        # equivalent private method for testing
2378
        result = repo._get_revision_graph(None)
2379
        self.assertEqual(
2380
            [('call_expecting_body', 'Repository.get_revision_graph',
2381
             ('sinhala/', ''))],
2382
            client._calls)
2383
        self.assertEqual({r1: (), r2: (r1, )}, result)
2384
2385
    def test_specific_revision(self):
2386
        # with a specific revision we want the graph for that
2387
        # with none we want the entire graph
2388
        r11 = u'\u0e33'.encode('utf8')
2389
        r12 = u'\xc9'.encode('utf8')
2390
        r2 = u'\u0dab'.encode('utf8')
2391
        lines = [' '.join([r2, r11, r12]), r11, r12]
2392
        encoded_body = '\n'.join(lines)
2393
2394
        transport_path = 'sinhala'
2395
        repo, client = self.setup_fake_client_and_repository(transport_path)
2396
        client.add_success_response_with_body(encoded_body, 'ok')
2397
        result = repo._get_revision_graph(r2)
2398
        self.assertEqual(
2399
            [('call_expecting_body', 'Repository.get_revision_graph',
2400
             ('sinhala/', r2))],
2401
            client._calls)
2402
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
2403
2404
    def test_no_such_revision(self):
2405
        revid = '123'
2406
        transport_path = 'sinhala'
2407
        repo, client = self.setup_fake_client_and_repository(transport_path)
2408
        client.add_error_response('nosuchrevision', revid)
2409
        # also check that the right revision is reported in the error
2410
        self.assertRaises(errors.NoSuchRevision,
2411
            repo._get_revision_graph, revid)
2412
        self.assertEqual(
2413
            [('call_expecting_body', 'Repository.get_revision_graph',
2414
             ('sinhala/', revid))],
2415
            client._calls)
2416
2417
    def test_unexpected_error(self):
2418
        revid = '123'
2419
        transport_path = 'sinhala'
2420
        repo, client = self.setup_fake_client_and_repository(transport_path)
2421
        client.add_error_response('AnUnexpectedError')
2422
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
2423
            repo._get_revision_graph, revid)
2424
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
2425
2426
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2427
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
2428
2429
    def test_ok(self):
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2430
        repo, client = self.setup_fake_client_and_repository('quack')
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2431
        client.add_expected_call(
2432
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2433
            'success', ('ok', 'rev-five'))
2434
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2435
        self.assertEqual((True, 'rev-five'), result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
2436
        self.assertFinished(client)
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2437
2438
    def test_history_incomplete(self):
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2439
        repo, client = self.setup_fake_client_and_repository('quack')
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2440
        client.add_expected_call(
2441
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2442
            'success', ('history-incomplete', 10, 'rev-ten'))
2443
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2444
        self.assertEqual((False, (10, 'rev-ten')), result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
2445
        self.assertFinished(client)
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2446
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2447
    def test_history_incomplete_with_fallback(self):
2448
        """A 'history-incomplete' response causes the fallback repository to be
2449
        queried too, if one is set.
2450
        """
2451
        # Make a repo with a fallback repo, both using a FakeClient.
2452
        format = remote.response_tuple_to_repo_format(
5158.4.3 by Andrew Bennetts
Fix test_remote tests that accidentally assumed it was ok to stack mismatched formats.
2453
            ('yes', 'no', 'yes', self.get_repo_format().network_name()))
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2454
        repo, client = self.setup_fake_client_and_repository('quack')
2455
        repo._format = format
2456
        fallback_repo, ignored = self.setup_fake_client_and_repository(
2457
            'fallback')
2458
        fallback_repo._client = client
5158.4.3 by Andrew Bennetts
Fix test_remote tests that accidentally assumed it was ok to stack mismatched formats.
2459
        fallback_repo._format = format
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2460
        repo.add_fallback_repository(fallback_repo)
2461
        # First the client should ask the primary repo
2462
        client.add_expected_call(
2463
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
2464
            'success', ('history-incomplete', 2, 'rev-two'))
2465
        # Then it should ask the fallback, using revno/revid from the
2466
        # history-incomplete response as the known revno/revid.
2467
        client.add_expected_call(
2468
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
2469
            'success', ('ok', 'rev-one'))
2470
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
2471
        self.assertEqual((True, 'rev-one'), result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
2472
        self.assertFinished(client)
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2473
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2474
    def test_nosuchrevision(self):
2475
        # 'nosuchrevision' is returned when the known-revid is not found in the
2476
        # remote repo.  The client translates that response to NoSuchRevision.
4419.2.8 by Andrew Bennetts
Add unit test for RemoteRepository.get_rev_id_for_revno using fallbacks if it gets a history-incomplete response.
2477
        repo, client = self.setup_fake_client_and_repository('quack')
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2478
        client.add_expected_call(
2479
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2480
            'error', ('nosuchrevision', 'rev-foo'))
2481
        self.assertRaises(
2482
            errors.NoSuchRevision,
2483
            repo.get_rev_id_for_revno, 5, (42, 'rev-foo'))
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
2484
        self.assertFinished(client)
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2485
4634.69.1 by Andrew Bennetts
Apply @needs_read_lock to RemoteBranch.get_rev_id.
2486
    def test_branch_fallback_locking(self):
2487
        """RemoteBranch.get_rev_id takes a read lock, and tries to call the
2488
        get_rev_id_for_revno verb.  If the verb is unknown the VFS fallback
2489
        will be invoked, which will fail if the repo is unlocked.
2490
        """
2491
        self.setup_smart_server_with_call_log()
2492
        tree = self.make_branch_and_memory_tree('.')
2493
        tree.lock_write()
5222.1.1 by Aaron Bentley
Refuse to commit trees with no root.
2494
        tree.add('')
4634.69.1 by Andrew Bennetts
Apply @needs_read_lock to RemoteBranch.get_rev_id.
2495
        rev1 = tree.commit('First')
2496
        rev2 = tree.commit('Second')
2497
        tree.unlock()
2498
        branch = tree.branch
2499
        self.assertFalse(branch.is_locked())
2500
        self.reset_smart_call_log()
2501
        verb = 'Repository.get_rev_id_for_revno'
2502
        self.disable_verb(verb)
2503
        self.assertEqual(rev1, branch.get_rev_id(1))
2504
        self.assertLength(1, [call for call in self.hpss_calls if
2505
                              call.call.method == verb])
2506
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2507
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
2508
class TestRepositoryIsShared(TestRemoteRepository):
2509
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2510
    def test_is_shared(self):
2511
        # ('yes', ) for Repository.is_shared -> 'True'.
2512
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2513
        repo, client = self.setup_fake_client_and_repository(transport_path)
2514
        client.add_success_response('yes')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2515
        result = repo.is_shared()
2516
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2517
            [('call', 'Repository.is_shared', ('quack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2518
            client._calls)
2519
        self.assertEqual(True, result)
2520
2521
    def test_is_not_shared(self):
2522
        # ('no', ) for Repository.is_shared -> 'False'.
2523
        transport_path = 'qwack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2524
        repo, client = self.setup_fake_client_and_repository(transport_path)
2525
        client.add_success_response('no')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2526
        result = repo.is_shared()
2527
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2528
            [('call', 'Repository.is_shared', ('qwack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2529
            client._calls)
2530
        self.assertEqual(False, result)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2531
2532
2533
class TestRepositoryLockWrite(TestRemoteRepository):
2534
2535
    def test_lock_write(self):
2536
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2537
        repo, client = self.setup_fake_client_and_repository(transport_path)
2538
        client.add_success_response('ok', 'a token')
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2539
        token = repo.lock_write().repository_token
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2540
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2541
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2542
            client._calls)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2543
        self.assertEqual('a token', token)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2544
2545
    def test_lock_write_already_locked(self):
2546
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2547
        repo, client = self.setup_fake_client_and_repository(transport_path)
2548
        client.add_error_response('LockContention')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2549
        self.assertRaises(errors.LockContention, repo.lock_write)
2550
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2551
            [('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.
2552
            client._calls)
2553
2554
    def test_lock_write_unlockable(self):
2555
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2556
        repo, client = self.setup_fake_client_and_repository(transport_path)
2557
        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.
2558
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
2559
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2560
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2561
            client._calls)
2562
2563
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2564
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
2565
2566
    def test_backwards_compat(self):
2567
        self.setup_smart_server_with_call_log()
2568
        repo = self.make_repository('.')
2569
        self.reset_smart_call_log()
2570
        verb = 'Repository.set_make_working_trees'
2571
        self.disable_verb(verb)
2572
        repo.set_make_working_trees(True)
2573
        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.
2574
            call.call.method == verb])
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2575
        self.assertEqual(1, call_count)
2576
2577
    def test_current(self):
2578
        transport_path = 'quack'
2579
        repo, client = self.setup_fake_client_and_repository(transport_path)
2580
        client.add_expected_call(
2581
            'Repository.set_make_working_trees', ('quack/', 'True'),
2582
            'success', ('ok',))
2583
        client.add_expected_call(
2584
            'Repository.set_make_working_trees', ('quack/', 'False'),
2585
            'success', ('ok',))
2586
        repo.set_make_working_trees(True)
2587
        repo.set_make_working_trees(False)
2588
2589
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2590
class TestRepositoryUnlock(TestRemoteRepository):
2591
2592
    def test_unlock(self):
2593
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2594
        repo, client = self.setup_fake_client_and_repository(transport_path)
2595
        client.add_success_response('ok', 'a token')
2596
        client.add_success_response('ok')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2597
        repo.lock_write()
2598
        repo.unlock()
2599
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2600
            [('call', 'Repository.lock_write', ('quack/', '')),
2601
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2602
            client._calls)
2603
2604
    def test_unlock_wrong_token(self):
2605
        # If somehow the token is wrong, unlock will raise TokenMismatch.
2606
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2607
        repo, client = self.setup_fake_client_and_repository(transport_path)
2608
        client.add_success_response('ok', 'a token')
2609
        client.add_error_response('TokenMismatch')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2610
        repo.lock_write()
2611
        self.assertRaises(errors.TokenMismatch, repo.unlock)
2612
2613
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2614
class TestRepositoryHasRevision(TestRemoteRepository):
2615
2616
    def test_none(self):
2617
        # repo.has_revision(None) should not cause any traffic.
2618
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2619
        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.
2620
2621
        # The null revision is always there, so has_revision(None) == True.
3172.3.3 by Robert Collins
Missed one occurence of None -> NULL_REVISION.
2622
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2623
2624
        # The remote repo shouldn't be accessed.
2625
        self.assertEqual([], client._calls)
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2626
2627
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2628
class TestRepositoryInsertStreamBase(TestRemoteRepository):
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2629
    """Base class for Repository.insert_stream and .insert_stream_1.19
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2630
    tests.
2631
    """
2632
    
2633
    def checkInsertEmptyStream(self, repo, client):
2634
        """Insert an empty stream, checking the result.
2635
2636
        This checks that there are no resume_tokens or missing_keys, and that
2637
        the client is finished.
2638
        """
2639
        sink = repo._get_sink()
5651.3.9 by Jelmer Vernooij
Avoid using deprecated functions.
2640
        fmt = repository.format_registry.get_default()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2641
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2642
        self.assertEqual([], resume_tokens)
2643
        self.assertEqual(set(), missing_keys)
2644
        self.assertFinished(client)
2645
2646
2647
class TestRepositoryInsertStream(TestRepositoryInsertStreamBase):
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2648
    """Tests for using Repository.insert_stream verb when the _1.19 variant is
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2649
    not available.
2650
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2651
    This test case is very similar to TestRepositoryInsertStream_1_19.
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2652
    """
2653
2654
    def setUp(self):
2655
        TestRemoteRepository.setUp(self)
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2656
        self.disable_verb('Repository.insert_stream_1.19')
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2657
2658
    def test_unlocked_repo(self):
2659
        transport_path = 'quack'
2660
        repo, client = self.setup_fake_client_and_repository(transport_path)
2661
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2662
            'Repository.insert_stream_1.19', ('quack/', ''),
2663
            'unknown', ('Repository.insert_stream_1.19',))
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2664
        client.add_expected_call(
2665
            'Repository.insert_stream', ('quack/', ''),
2666
            'success', ('ok',))
2667
        client.add_expected_call(
2668
            'Repository.insert_stream', ('quack/', ''),
2669
            'success', ('ok',))
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2670
        self.checkInsertEmptyStream(repo, client)
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2671
2672
    def test_locked_repo_with_no_lock_token(self):
2673
        transport_path = 'quack'
2674
        repo, client = self.setup_fake_client_and_repository(transport_path)
2675
        client.add_expected_call(
2676
            'Repository.lock_write', ('quack/', ''),
2677
            'success', ('ok', ''))
2678
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2679
            'Repository.insert_stream_1.19', ('quack/', ''),
2680
            'unknown', ('Repository.insert_stream_1.19',))
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2681
        client.add_expected_call(
2682
            'Repository.insert_stream', ('quack/', ''),
2683
            'success', ('ok',))
2684
        client.add_expected_call(
2685
            'Repository.insert_stream', ('quack/', ''),
2686
            'success', ('ok',))
2687
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2688
        self.checkInsertEmptyStream(repo, client)
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2689
2690
    def test_locked_repo_with_lock_token(self):
2691
        transport_path = 'quack'
2692
        repo, client = self.setup_fake_client_and_repository(transport_path)
2693
        client.add_expected_call(
2694
            'Repository.lock_write', ('quack/', ''),
2695
            'success', ('ok', 'a token'))
2696
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2697
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2698
            'unknown', ('Repository.insert_stream_1.19',))
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2699
        client.add_expected_call(
2700
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2701
            'success', ('ok',))
2702
        client.add_expected_call(
2703
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2704
            'success', ('ok',))
2705
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2706
        self.checkInsertEmptyStream(repo, client)
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2707
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2708
    def test_stream_with_inventory_deltas(self):
4476.3.71 by Andrew Bennetts
Clearer comments prompted by Robert's review.
2709
        """'inventory-deltas' substreams cannot be sent to the
2710
        Repository.insert_stream verb, because not all servers that implement
2711
        that verb will accept them.  So when one is encountered the RemoteSink
2712
        immediately stops using that verb and falls back to VFS insert_stream.
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2713
        """
2714
        transport_path = 'quack'
2715
        repo, client = self.setup_fake_client_and_repository(transport_path)
2716
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2717
            'Repository.insert_stream_1.19', ('quack/', ''),
2718
            'unknown', ('Repository.insert_stream_1.19',))
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2719
        client.add_expected_call(
2720
            'Repository.insert_stream', ('quack/', ''),
2721
            'success', ('ok',))
2722
        client.add_expected_call(
2723
            'Repository.insert_stream', ('quack/', ''),
2724
            'success', ('ok',))
2725
        # Create a fake real repository for insert_stream to fall back on, so
2726
        # that we can directly see the records the RemoteSink passes to the
2727
        # real sink.
2728
        class FakeRealSink:
2729
            def __init__(self):
2730
                self.records = []
2731
            def insert_stream(self, stream, src_format, resume_tokens):
2732
                for substream_kind, substream in stream:
2733
                    self.records.append(
2734
                        (substream_kind, [record.key for record in substream]))
2735
                return ['fake tokens'], ['fake missing keys']
2736
        fake_real_sink = FakeRealSink()
2737
        class FakeRealRepository:
2738
            def _get_sink(self):
2739
                return fake_real_sink
4634.35.20 by Andrew Bennetts
Fix test_remote.
2740
            def is_in_write_group(self):
2741
                return False
2742
            def refresh_data(self):
2743
                return True
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2744
        repo._real_repository = FakeRealRepository()
2745
        sink = repo._get_sink()
5651.3.9 by Jelmer Vernooij
Avoid using deprecated functions.
2746
        fmt = repository.format_registry.get_default()
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2747
        stream = self.make_stream_with_inv_deltas(fmt)
2748
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
2749
        # Every record from the first inventory delta should have been sent to
2750
        # the VFS sink.
2751
        expected_records = [
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2752
            ('inventory-deltas', [('rev2',), ('rev3',)]),
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2753
            ('texts', [('some-rev', 'some-file')])]
2754
        self.assertEqual(expected_records, fake_real_sink.records)
2755
        # The return values from the real sink's insert_stream are propagated
2756
        # back to the original caller.
2757
        self.assertEqual(['fake tokens'], resume_tokens)
2758
        self.assertEqual(['fake missing keys'], missing_keys)
4476.3.40 by Andrew Bennetts
Merge bzr.dev.
2759
        self.assertFinished(client)
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2760
2761
    def make_stream_with_inv_deltas(self, fmt):
2762
        """Make a simple stream with an inventory delta followed by more
2763
        records and more substreams to test that all records and substreams
2764
        from that point on are used.
2765
2766
        This sends, in order:
2767
           * inventories substream: rev1, rev2, rev3.  rev2 and rev3 are
2768
             inventory-deltas.
2769
           * texts substream: (some-rev, some-file)
2770
        """
2771
        # Define a stream using generators so that it isn't rewindable.
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2772
        inv = inventory.Inventory(revision_id='rev1')
4599.4.39 by Robert Collins
Use a valid for storage inventory in test_remote's new inventory streaming test.
2773
        inv.root.revision = 'rev1'
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2774
        def stream_with_inv_delta():
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2775
            yield ('inventories', inventories_substream())
2776
            yield ('inventory-deltas', inventory_delta_substream())
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2777
            yield ('texts', [
2778
                versionedfile.FulltextContentFactory(
2779
                    ('some-rev', 'some-file'), (), None, 'content')])
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2780
        def inventories_substream():
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2781
            # An empty inventory fulltext.  This will be streamed normally.
2782
            text = fmt._serializer.write_inventory_to_string(inv)
2783
            yield versionedfile.FulltextContentFactory(
2784
                ('rev1',), (), None, text)
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2785
        def inventory_delta_substream():
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2786
            # An inventory delta.  This can't be streamed via this verb, so it
2787
            # will trigger a fallback to VFS insert_stream.
2788
            entry = inv.make_entry(
2789
                'directory', 'newdir', inv.root.file_id, 'newdir-id')
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2790
            entry.revision = 'ghost'
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2791
            delta = [(None, 'newdir', 'newdir-id', entry)]
4476.3.76 by Andrew Bennetts
Split out InventoryDeltaDeserializer from InventoryDeltaSerializer.
2792
            serializer = inventory_delta.InventoryDeltaSerializer(
2793
                versioned_root=True, tree_references=False)
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2794
            lines = serializer.delta_to_lines('rev1', 'rev2', delta)
2795
            yield versionedfile.ChunkedContentFactory(
2796
                ('rev2',), (('rev1',)), None, lines)
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2797
            # Another delta.
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2798
            lines = serializer.delta_to_lines('rev1', 'rev3', delta)
2799
            yield versionedfile.ChunkedContentFactory(
2800
                ('rev3',), (('rev1',)), None, lines)
4476.3.36 by Andrew Bennetts
Add a somewhat complex test to exercise the fallback-to-vfs logic in RemoteSink when an inventory-delta is encountered and the 1.18 verb isn't accepted.
2801
        return stream_with_inv_delta()
2802
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2803
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2804
class TestRepositoryInsertStream_1_19(TestRepositoryInsertStreamBase):
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2805
2806
    def test_unlocked_repo(self):
2807
        transport_path = 'quack'
2808
        repo, client = self.setup_fake_client_and_repository(transport_path)
2809
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2810
            'Repository.insert_stream_1.19', ('quack/', ''),
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2811
            'success', ('ok',))
2812
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2813
            'Repository.insert_stream_1.19', ('quack/', ''),
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2814
            'success', ('ok',))
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2815
        self.checkInsertEmptyStream(repo, client)
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2816
2817
    def test_locked_repo_with_no_lock_token(self):
2818
        transport_path = 'quack'
2819
        repo, client = self.setup_fake_client_and_repository(transport_path)
2820
        client.add_expected_call(
2821
            'Repository.lock_write', ('quack/', ''),
2822
            'success', ('ok', ''))
2823
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2824
            'Repository.insert_stream_1.19', ('quack/', ''),
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2825
            'success', ('ok',))
2826
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2827
            'Repository.insert_stream_1.19', ('quack/', ''),
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2828
            'success', ('ok',))
2829
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2830
        self.checkInsertEmptyStream(repo, client)
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2831
2832
    def test_locked_repo_with_lock_token(self):
2833
        transport_path = 'quack'
2834
        repo, client = self.setup_fake_client_and_repository(transport_path)
2835
        client.add_expected_call(
2836
            'Repository.lock_write', ('quack/', ''),
2837
            'success', ('ok', 'a token'))
2838
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2839
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
4476.3.32 by Andrew Bennetts
Move disable_verb into base TestCase to remove duplication, fix trivial test failures due to new insert_stream verb in test_remote (and also add some trivial tests for the new verb).
2840
            'success', ('ok',))
2841
        client.add_expected_call(
4476.3.82 by Andrew Bennetts
Mention another bug fix in NEWS, and update verb name, comments, and NEWS additions for landing on 1.19 rather than 1.18.
2842
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2843
            'success', ('ok',))
2844
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2845
        self.checkInsertEmptyStream(repo, client)
4144.3.2 by Andrew Bennetts
Use Repository.insert_stream_locked if there is a lock_token for the remote repo.
2846
2847
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2848
class TestRepositoryTarball(TestRemoteRepository):
2849
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2850
    # This is a canned tarball reponse we can validate against
2018.18.18 by Martin Pool
reformat
2851
    tarball_content = (
2018.18.23 by Martin Pool
review cleanups
2852
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
2853
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
2854
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
2855
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
2856
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
2857
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
2858
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
2859
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
2860
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
2861
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
2862
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
2863
        'nWQ7QH/F3JFOFCQ0aSPfA='
2864
        ).decode('base64')
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2865
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2866
    def test_repository_tarball(self):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2867
        # Test that Repository.tarball generates the right operations
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2868
        transport_path = 'repo'
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
2869
        expected_calls = [('call_expecting_body', 'Repository.tarball',
3104.4.2 by Andrew Bennetts
All tests passing.
2870
                           ('repo/', 'bz2',),),
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2871
            ]
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2872
        repo, client = self.setup_fake_client_and_repository(transport_path)
2873
        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
2874
        # Now actually ask for the tarball
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2875
        tarball_file = repo._get_tarball('bz2')
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
2876
        try:
2877
            self.assertEqual(expected_calls, client._calls)
2878
            self.assertEqual(self.tarball_content, tarball_file.read())
2879
        finally:
2880
            tarball_file.close()
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2881
2882
2883
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
2884
    """RemoteRepository.copy_content_into optimizations"""
2885
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
2886
    def test_copy_content_remote_to_local(self):
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
2887
        self.transport_server = test_server.SmartTCPServer_for_testing
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
2888
        src_repo = self.make_repository('repo1')
2889
        src_repo = repository.Repository.open(self.get_url('repo1'))
2890
        # At the moment the tarball-based copy_content_into can't write back
2891
        # into a smart server.  It would be good if it could upload the
2892
        # tarball; once that works we'd have to create repositories of
2893
        # different formats. -- mbp 20070410
2894
        dest_url = self.get_vfs_only_url('repo2')
2895
        dest_bzrdir = BzrDir.create(dest_url)
2896
        dest_repo = dest_bzrdir.create_repository()
2897
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
2898
        self.assertTrue(isinstance(src_repo, RemoteRepository))
2899
        src_repo.copy_content_into(dest_repo)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
2900
2901
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2902
class _StubRealPackRepository(object):
2903
2904
    def __init__(self, calls):
4145.1.6 by Robert Collins
More test fallout, but all caught now.
2905
        self.calls = calls
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2906
        self._pack_collection = _StubPackCollection(calls)
2907
4145.1.6 by Robert Collins
More test fallout, but all caught now.
2908
    def is_in_write_group(self):
2909
        return False
2910
2911
    def refresh_data(self):
2912
        self.calls.append(('pack collection reload_pack_names',))
2913
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2914
2915
class _StubPackCollection(object):
2916
2917
    def __init__(self, calls):
2918
        self.calls = calls
2919
2920
    def autopack(self):
2921
        self.calls.append(('pack collection autopack',))
2922
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2923
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2924
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
2925
    """Tests for RemoteRepository.autopack implementation."""
2926
2927
    def test_ok(self):
2928
        """When the server returns 'ok' and there's no _real_repository, then
2929
        nothing else happens: the autopack method is done.
2930
        """
2931
        transport_path = 'quack'
2932
        repo, client = self.setup_fake_client_and_repository(transport_path)
2933
        client.add_expected_call(
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
2934
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2935
        repo.autopack()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
2936
        self.assertFinished(client)
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2937
2938
    def test_ok_with_real_repo(self):
2939
        """When the server returns 'ok' and there is a _real_repository, then
2940
        the _real_repository's reload_pack_name's method will be called.
2941
        """
2942
        transport_path = 'quack'
2943
        repo, client = self.setup_fake_client_and_repository(transport_path)
2944
        client.add_expected_call(
2945
            'PackRepository.autopack', ('quack/',),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
2946
            'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2947
        repo._real_repository = _StubRealPackRepository(client._calls)
2948
        repo.autopack()
2949
        self.assertEqual(
2950
            [('call', 'PackRepository.autopack', ('quack/',)),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
2951
             ('pack collection reload_pack_names',)],
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2952
            client._calls)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2953
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2954
    def test_backwards_compatibility(self):
2955
        """If the server does not recognise the PackRepository.autopack verb,
2956
        fallback to the real_repository's implementation.
2957
        """
2958
        transport_path = 'quack'
2959
        repo, client = self.setup_fake_client_and_repository(transport_path)
2960
        client.add_unknown_method_response('PackRepository.autopack')
2961
        def stub_ensure_real():
2962
            client._calls.append(('_ensure_real',))
2963
            repo._real_repository = _StubRealPackRepository(client._calls)
2964
        repo._ensure_real = stub_ensure_real
2965
        repo.autopack()
2966
        self.assertEqual(
2967
            [('call', 'PackRepository.autopack', ('quack/',)),
2968
             ('_ensure_real',),
2969
             ('pack collection autopack',)],
2970
            client._calls)
2971
5677.2.2 by Martin
Give clearer message when remote server reports a MemoryError
2972
    def test_oom_error_reporting(self):
2973
        """An out-of-memory condition on the server is reported clearly"""
2974
        transport_path = 'quack'
2975
        repo, client = self.setup_fake_client_and_repository(transport_path)
2976
        client.add_expected_call(
2977
            'PackRepository.autopack', ('quack/',),
2978
            'error', ('MemoryError',))
2979
        err = self.assertRaises(errors.BzrError, repo.autopack)
2980
        self.assertContainsRe(str(err), "^remote server out of mem")
2981
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
2982
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
2983
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
2984
    """Base class for unit tests for bzrlib.remote._translate_error."""
2985
2986
    def translateTuple(self, error_tuple, **context):
2987
        """Call _translate_error with an ErrorFromSmartServer built from the
2988
        given error_tuple.
2989
2990
        :param error_tuple: A tuple of a smart server response, as would be
2991
            passed to an ErrorFromSmartServer.
2992
        :kwargs context: context items to call _translate_error with.
2993
2994
        :returns: The error raised by _translate_error.
2995
        """
2996
        # Raise the ErrorFromSmartServer before passing it as an argument,
2997
        # because _translate_error may need to re-raise it with a bare 'raise'
2998
        # statement.
2999
        server_error = errors.ErrorFromSmartServer(error_tuple)
3000
        translated_error = self.translateErrorFromSmartServer(
3001
            server_error, **context)
3002
        return translated_error
3003
3004
    def translateErrorFromSmartServer(self, error_object, **context):
3005
        """Like translateTuple, but takes an already constructed
3006
        ErrorFromSmartServer rather than a tuple.
3007
        """
3008
        try:
3009
            raise error_object
3010
        except errors.ErrorFromSmartServer, server_error:
3011
            translated_error = self.assertRaises(
3012
                errors.BzrError, remote._translate_error, server_error,
3013
                **context)
3014
        return translated_error
3015
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3016
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3017
class TestErrorTranslationSuccess(TestErrorTranslationBase):
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3018
    """Unit tests for bzrlib.remote._translate_error.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3019
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3020
    Given an ErrorFromSmartServer (which has an error tuple from a smart
3021
    server) and some context, _translate_error raises more specific errors from
3022
    bzrlib.errors.
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3023
3024
    This test case covers the cases where _translate_error succeeds in
3025
    translating an ErrorFromSmartServer to something better.  See
3026
    TestErrorTranslationRobustness for other cases.
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3027
    """
3028
3029
    def test_NoSuchRevision(self):
3030
        branch = self.make_branch('')
3031
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3032
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3033
            ('NoSuchRevision', revid), branch=branch)
3034
        expected_error = errors.NoSuchRevision(branch, revid)
3035
        self.assertEqual(expected_error, translated_error)
3036
3037
    def test_nosuchrevision(self):
3038
        repository = self.make_repository('')
3039
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3040
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3041
            ('nosuchrevision', revid), repository=repository)
3042
        expected_error = errors.NoSuchRevision(repository, revid)
3043
        self.assertEqual(expected_error, translated_error)
3044
3045
    def test_nobranch(self):
3046
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3047
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3048
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
3049
        self.assertEqual(expected_error, translated_error)
3050
4734.4.8 by Andrew Bennetts
Fix HPSS tests; pass 'location is a repository' message via smart server when possible (adds BzrDir.open_branchV3 verb).
3051
    def test_nobranch_one_arg(self):
3052
        bzrdir = self.make_bzrdir('')
3053
        translated_error = self.translateTuple(
3054
            ('nobranch', 'extra detail'), bzrdir=bzrdir)
3055
        expected_error = errors.NotBranchError(
3056
            path=bzrdir.root_transport.base,
3057
            detail='extra detail')
3058
        self.assertEqual(expected_error, translated_error)
3059
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3060
    def test_norepository(self):
3061
        bzrdir = self.make_bzrdir('')
3062
        translated_error = self.translateTuple(('norepository',),
3063
            bzrdir=bzrdir)
3064
        expected_error = errors.NoRepositoryPresent(bzrdir)
3065
        self.assertEqual(expected_error, translated_error)
3066
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3067
    def test_LockContention(self):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3068
        translated_error = self.translateTuple(('LockContention',))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3069
        expected_error = errors.LockContention('(remote lock)')
3070
        self.assertEqual(expected_error, translated_error)
3071
3072
    def test_UnlockableTransport(self):
3073
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3074
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3075
            ('UnlockableTransport',), bzrdir=bzrdir)
3076
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
3077
        self.assertEqual(expected_error, translated_error)
3078
3079
    def test_LockFailed(self):
3080
        lock = 'str() of a server lock'
3081
        why = 'str() of why'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3082
        translated_error = self.translateTuple(('LockFailed', lock, why))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3083
        expected_error = errors.LockFailed(lock, why)
3084
        self.assertEqual(expected_error, translated_error)
3085
3086
    def test_TokenMismatch(self):
3087
        token = 'a lock token'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3088
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3089
        expected_error = errors.TokenMismatch(token, '(remote token)')
3090
        self.assertEqual(expected_error, translated_error)
3091
3092
    def test_Diverged(self):
3093
        branch = self.make_branch('a')
3094
        other_branch = self.make_branch('b')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3095
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3096
            ('Diverged',), branch=branch, other_branch=other_branch)
3097
        expected_error = errors.DivergedBranches(branch, other_branch)
3098
        self.assertEqual(expected_error, translated_error)
3099
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3100
    def test_NotStacked(self):
3101
        branch = self.make_branch('')
3102
        translated_error = self.translateTuple(('NotStacked',), branch=branch)
3103
        expected_error = errors.NotStacked(branch)
3104
        self.assertEqual(expected_error, translated_error)
3105
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3106
    def test_ReadError_no_args(self):
3107
        path = 'a path'
3108
        translated_error = self.translateTuple(('ReadError',), path=path)
3109
        expected_error = errors.ReadError(path)
3110
        self.assertEqual(expected_error, translated_error)
3111
3112
    def test_ReadError(self):
3113
        path = 'a path'
3114
        translated_error = self.translateTuple(('ReadError', path))
3115
        expected_error = errors.ReadError(path)
3116
        self.assertEqual(expected_error, translated_error)
3117
4650.2.1 by Robert Collins
Deserialise IncompatibleRepositories errors in the client, generating
3118
    def test_IncompatibleRepositories(self):
3119
        translated_error = self.translateTuple(('IncompatibleRepositories',
3120
            "repo1", "repo2", "details here"))
3121
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
3122
            "details here")
3123
        self.assertEqual(expected_error, translated_error)
3124
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3125
    def test_PermissionDenied_no_args(self):
3126
        path = 'a path'
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3127
        translated_error = self.translateTuple(('PermissionDenied',),
3128
            path=path)
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3129
        expected_error = errors.PermissionDenied(path)
3130
        self.assertEqual(expected_error, translated_error)
3131
3132
    def test_PermissionDenied_one_arg(self):
3133
        path = 'a path'
3134
        translated_error = self.translateTuple(('PermissionDenied', path))
3135
        expected_error = errors.PermissionDenied(path)
3136
        self.assertEqual(expected_error, translated_error)
3137
3138
    def test_PermissionDenied_one_arg_and_context(self):
3139
        """Given a choice between a path from the local context and a path on
3140
        the wire, _translate_error prefers the path from the local context.
3141
        """
3142
        local_path = 'local path'
3143
        remote_path = 'remote path'
3144
        translated_error = self.translateTuple(
3145
            ('PermissionDenied', remote_path), path=local_path)
3146
        expected_error = errors.PermissionDenied(local_path)
3147
        self.assertEqual(expected_error, translated_error)
3148
3149
    def test_PermissionDenied_two_args(self):
3150
        path = 'a path'
3151
        extra = 'a string with extra info'
3152
        translated_error = self.translateTuple(
3153
            ('PermissionDenied', path, extra))
3154
        expected_error = errors.PermissionDenied(path, extra)
3155
        self.assertEqual(expected_error, translated_error)
3156
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3157
    # GZ 2011-03-02: TODO test for PermissionDenied with non-ascii 'extra'
3158
3159
    def test_NoSuchFile_context_path(self):
3160
        local_path = "local path"
3161
        translated_error = self.translateTuple(('ReadError', "remote path"),
3162
            path=local_path)
3163
        expected_error = errors.ReadError(local_path)
3164
        self.assertEqual(expected_error, translated_error)
3165
3166
    def test_NoSuchFile_without_context(self):
3167
        remote_path = "remote path"
3168
        translated_error = self.translateTuple(('ReadError', remote_path))
3169
        expected_error = errors.ReadError(remote_path)
3170
        self.assertEqual(expected_error, translated_error)
3171
3172
    def test_ReadOnlyError(self):
3173
        translated_error = self.translateTuple(('ReadOnlyError',))
3174
        expected_error = errors.TransportNotPossible("readonly transport")
3175
        self.assertEqual(expected_error, translated_error)
3176
3177
    def test_MemoryError(self):
3178
        translated_error = self.translateTuple(('MemoryError',))
5677.2.9 by Martin
Add hint to possible ways forward for user in remote MemoryError message
3179
        self.assertStartsWith(str(translated_error),
3180
            "remote server out of memory")
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3181
5677.2.8 by Martin
More tests for handling of unexpected remote errors
3182
    def test_generic_IndexError_no_classname(self):
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3183
        err = errors.ErrorFromSmartServer(('error', "list index out of range"))
3184
        translated_error = self.translateErrorFromSmartServer(err)
3185
        expected_error = errors.UnknownErrorFromSmartServer(err)
3186
        self.assertEqual(expected_error, translated_error)
3187
3188
    # GZ 2011-03-02: TODO test generic non-ascii error string
3189
5677.2.8 by Martin
More tests for handling of unexpected remote errors
3190
    def test_generic_KeyError(self):
3191
        err = errors.ErrorFromSmartServer(('error', 'KeyError', "1"))
3192
        translated_error = self.translateErrorFromSmartServer(err)
3193
        expected_error = errors.UnknownErrorFromSmartServer(err)
3194
        self.assertEqual(expected_error, translated_error)
3195
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3196
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3197
class TestErrorTranslationRobustness(TestErrorTranslationBase):
3198
    """Unit tests for bzrlib.remote._translate_error's robustness.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3199
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3200
    TestErrorTranslationSuccess is for cases where _translate_error can
3201
    translate successfully.  This class about how _translate_err behaves when
3202
    it fails to translate: it re-raises the original error.
3203
    """
3204
3205
    def test_unrecognised_server_error(self):
3206
        """If the error code from the server is not recognised, the original
3207
        ErrorFromSmartServer is propagated unmodified.
3208
        """
3209
        error_tuple = ('An unknown error tuple',)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
3210
        server_error = errors.ErrorFromSmartServer(error_tuple)
3211
        translated_error = self.translateErrorFromSmartServer(server_error)
3212
        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.
3213
        self.assertEqual(expected_error, translated_error)
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3214
3215
    def test_context_missing_a_key(self):
3216
        """In case of a bug in the client, or perhaps an unexpected response
3217
        from a server, _translate_error returns the original error tuple from
3218
        the server and mutters a warning.
3219
        """
3220
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
3221
        # in the context dict.  So let's give it an empty context dict instead
3222
        # to exercise its error recovery.
3223
        empty_context = {}
3224
        error_tuple = ('NoSuchRevision', 'revid')
3225
        server_error = errors.ErrorFromSmartServer(error_tuple)
3226
        translated_error = self.translateErrorFromSmartServer(server_error)
3227
        self.assertEqual(server_error, translated_error)
3228
        # In addition to re-raising ErrorFromSmartServer, some debug info has
3229
        # been muttered to the log file for developer to look at.
3230
        self.assertContainsRe(
4794.1.15 by Robert Collins
Review feedback.
3231
            self.get_log(),
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3232
            "Missing key 'branch' in context")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3233
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3234
    def test_path_missing(self):
3235
        """Some translations (PermissionDenied, ReadError) can determine the
3236
        'path' variable from either the wire or the local context.  If neither
3237
        has it, then an error is raised.
3238
        """
3239
        error_tuple = ('ReadError',)
3240
        server_error = errors.ErrorFromSmartServer(error_tuple)
3241
        translated_error = self.translateErrorFromSmartServer(server_error)
3242
        self.assertEqual(server_error, translated_error)
3243
        # In addition to re-raising ErrorFromSmartServer, some debug info has
3244
        # been muttered to the log file for developer to look at.
4794.1.15 by Robert Collins
Review feedback.
3245
        self.assertContainsRe(self.get_log(), "Missing key 'path' in context")
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3246
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3247
3248
class TestStacking(tests.TestCaseWithTransport):
3249
    """Tests for operations on stacked remote repositories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3250
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3251
    The underlying format type must support stacking.
3252
    """
3253
3254
    def test_access_stacked_remote(self):
3255
        # based on <http://launchpad.net/bugs/261315>
3256
        # make a branch stacked on another repository containing an empty
3257
        # revision, then open it over hpss - we should be able to see that
3258
        # revision.
3259
        base_transport = self.get_transport()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3260
        base_builder = self.make_branch_builder('base', format='1.9')
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3261
        base_builder.start_series()
3262
        base_revid = base_builder.build_snapshot('rev-id', None,
3263
            [('add', ('', None, 'directory', None))],
3264
            'message')
3265
        base_builder.finish_series()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3266
        stacked_branch = self.make_branch('stacked', format='1.9')
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3267
        stacked_branch.set_stacked_on_url('../base')
3268
        # start a server looking at this
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
3269
        smart_server = test_server.SmartTCPServer_for_testing()
4659.1.3 by Robert Collins
Review feedback.
3270
        self.start_server(smart_server)
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3271
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
3272
        # can get its branch and repository
3273
        remote_branch = remote_bzrdir.open_branch()
3274
        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
3275
        remote_repo.lock_read()
3276
        try:
3277
            # it should have an appropriate fallback repository, which should also
3278
            # be a RemoteRepository
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
3279
            self.assertLength(1, remote_repo._fallback_repositories)
3691.2.6 by Martin Pool
Disable RemoteBranch stacking, but get get_stacked_on_url working, and passing back exceptions
3280
            self.assertIsInstance(remote_repo._fallback_repositories[0],
3281
                RemoteRepository)
3282
            # and it has the revision committed to the underlying repository;
3283
            # these have varying implementations so we try several of them
3284
            self.assertTrue(remote_repo.has_revisions([base_revid]))
3285
            self.assertTrue(remote_repo.has_revision(base_revid))
3286
            self.assertEqual(remote_repo.get_revision(base_revid).message,
3287
                'message')
3288
        finally:
3289
            remote_repo.unlock()
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3290
3835.1.7 by Aaron Bentley
Updates from review
3291
    def prepare_stacked_remote_branch(self):
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3292
        """Get stacked_upon and stacked branches with content in each."""
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
3293
        self.setup_smart_server_with_call_log()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3294
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3295
        tree1.commit('rev1', rev_id='rev1')
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3296
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
3297
            ).open_workingtree()
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
3298
        local_tree = tree2.branch.create_checkout('local')
3299
        local_tree.commit('local changes make me feel good.')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
3300
        branch2 = Branch.open(self.get_url('tree2'))
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3301
        branch2.lock_read()
3302
        self.addCleanup(branch2.unlock)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3303
        return tree1.branch, branch2
3835.1.7 by Aaron Bentley
Updates from review
3304
3305
    def test_stacked_get_parent_map(self):
3306
        # the public implementation of get_parent_map obeys stacking
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3307
        _, branch = self.prepare_stacked_remote_branch()
3835.1.7 by Aaron Bentley
Updates from review
3308
        repo = branch.repository
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3309
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
3835.1.7 by Aaron Bentley
Updates from review
3310
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
3311
    def test_unstacked_get_parent_map(self):
3312
        # _unstacked_provider.get_parent_map ignores stacking
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3313
        _, branch = self.prepare_stacked_remote_branch()
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
3314
        provider = branch.repository._unstacked_provider
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
3315
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
3316
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3317
    def fetch_stream_to_rev_order(self, stream):
3318
        result = []
3319
        for kind, substream in stream:
3320
            if not kind == 'revisions':
3321
                list(substream)
3322
            else:
3323
                for content in substream:
3324
                    result.append(content.key[-1])
3325
        return result
3326
4577.1.1 by Robert Collins
Fix fetching from smart servers where there is a chain of stacked repositories rather than a single stacking point. (Robert Collins, bug #406597)
3327
    def get_ordered_revs(self, format, order, branch_factory=None):
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3328
        """Get a list of the revisions in a stream to format format.
3329
3330
        :param format: The format of the target.
3331
        :param order: the order that target should have requested.
4577.1.1 by Robert Collins
Fix fetching from smart servers where there is a chain of stacked repositories rather than a single stacking point. (Robert Collins, bug #406597)
3332
        :param branch_factory: A callable to create a trunk and stacked branch
3333
            to fetch from. If none, self.prepare_stacked_remote_branch is used.
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3334
        :result: The revision ids in the stream, in the order seen,
3335
            the topological order of revisions in the source.
3336
        """
3337
        unordered_format = bzrdir.format_registry.get(format)()
3338
        target_repository_format = unordered_format.repository_format
3339
        # Cross check
3340
        self.assertEqual(order, target_repository_format._fetch_order)
4577.1.1 by Robert Collins
Fix fetching from smart servers where there is a chain of stacked repositories rather than a single stacking point. (Robert Collins, bug #406597)
3341
        if branch_factory is None:
3342
            branch_factory = self.prepare_stacked_remote_branch
3343
        _, stacked = branch_factory()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3344
        source = stacked.repository._get_source(target_repository_format)
3345
        tip = stacked.last_revision()
5972.3.25 by Jelmer Vernooij
Fix another use of get_ancestry.
3346
        stacked.repository._ensure_real()
3347
        graph = stacked.repository.get_graph()
3348
        revs = [r for (r,ps) in graph.iter_ancestry([tip])
3349
                if r != NULL_REVISION]
3350
        revs.reverse()
5972.3.16 by Jelmer Vernooij
Rename import.
3351
        search = _mod_graph.PendingAncestryResult([tip], stacked.repository)
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
3352
        self.reset_smart_call_log()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3353
        stream = source.get_stream(search)
3354
        # We trust that if a revision is in the stream the rest of the new
3355
        # content for it is too, as per our main fetch tests; here we are
3356
        # checking that the revisions are actually included at all, and their
3357
        # order.
3358
        return self.fetch_stream_to_rev_order(stream), revs
3359
3360
    def test_stacked_get_stream_unordered(self):
3361
        # Repository._get_source.get_stream() from a stacked repository with
3362
        # unordered yields the full data from both stacked and stacked upon
3363
        # sources.
3364
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
3365
        self.assertEqual(set(expected_revs), set(rev_ord))
3366
        # Getting unordered results should have made a streaming data request
3367
        # from the server, then one from the backing branch.
3368
        self.assertLength(2, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3369
4577.1.1 by Robert Collins
Fix fetching from smart servers where there is a chain of stacked repositories rather than a single stacking point. (Robert Collins, bug #406597)
3370
    def test_stacked_on_stacked_get_stream_unordered(self):
3371
        # Repository._get_source.get_stream() from a stacked repository which
3372
        # is itself stacked yields the full data from all three sources.
3373
        def make_stacked_stacked():
3374
            _, stacked = self.prepare_stacked_remote_branch()
3375
            tree = stacked.bzrdir.sprout('tree3', stacked=True
3376
                ).open_workingtree()
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
3377
            local_tree = tree.branch.create_checkout('local-tree3')
3378
            local_tree.commit('more local changes are better')
4577.1.1 by Robert Collins
Fix fetching from smart servers where there is a chain of stacked repositories rather than a single stacking point. (Robert Collins, bug #406597)
3379
            branch = Branch.open(self.get_url('tree3'))
3380
            branch.lock_read()
4857.2.3 by John Arbash Meinel
Found the failed-to-unlocked branches in test_remote.
3381
            self.addCleanup(branch.unlock)
4577.1.1 by Robert Collins
Fix fetching from smart servers where there is a chain of stacked repositories rather than a single stacking point. (Robert Collins, bug #406597)
3382
            return None, branch
3383
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
3384
            branch_factory=make_stacked_stacked)
3385
        self.assertEqual(set(expected_revs), set(rev_ord))
3386
        # Getting unordered results should have made a streaming data request
3387
        # from the server, and one from each backing repo
3388
        self.assertLength(3, self.hpss_calls)
3389
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3390
    def test_stacked_get_stream_topological(self):
3391
        # Repository._get_source.get_stream() from a stacked repository with
3392
        # topological sorting yields the full data from both stacked and
3393
        # stacked upon sources in topological order.
3394
        rev_ord, expected_revs = self.get_ordered_revs('knit', 'topological')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
3395
        self.assertEqual(expected_revs, rev_ord)
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
3396
        # Getting topological sort requires VFS calls still - one of which is
3397
        # pushing up from the bound branch.
5972.3.25 by Jelmer Vernooij
Fix another use of get_ancestry.
3398
        self.assertLength(14, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3399
3400
    def test_stacked_get_stream_groupcompress(self):
3401
        # Repository._get_source.get_stream() from a stacked repository with
3402
        # groupcompress sorting yields the full data from both stacked and
3403
        # stacked upon sources in groupcompress order.
3404
        raise tests.TestSkipped('No groupcompress ordered format available')
3405
        rev_ord, expected_revs = self.get_ordered_revs('dev5', 'groupcompress')
4152.1.2 by Robert Collins
Add streaming from a stacked branch when the sort order is compatible with doing so.
3406
        self.assertEqual(expected_revs, reversed(rev_ord))
3407
        # Getting unordered results should have made a streaming data request
3408
        # from the backing branch, and one from the stacked on branch.
3409
        self.assertLength(2, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3410
4332.2.1 by Robert Collins
Fix bug 360791 by not raising an error when a smart server is asked for more content than it has locally; the client is assumed to be monitoring what it gets.
3411
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
3412
        # When pulling some fixed amount of content that is more than the
3413
        # source has (because some is coming from a fallback branch, no error
3414
        # should be received. This was reported as bug 360791.
3415
        # Need three branches: a trunk, a stacked branch, and a preexisting
3416
        # branch pulling content from stacked and trunk.
3417
        self.setup_smart_server_with_call_log()
3418
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
3419
        r1 = trunk.commit('start')
3420
        stacked_branch = trunk.branch.create_clone_on_transport(
3421
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
3422
        local = self.make_branch('local', format='1.9-rich-root')
3423
        local.repository.fetch(stacked_branch.repository,
3424
            stacked_branch.last_revision())
3425
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.
3426
3427
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
3428
3429
    def setUp(self):
3430
        super(TestRemoteBranchEffort, self).setUp()
3431
        # Create a smart server that publishes whatever the backing VFS server
3432
        # does.
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
3433
        self.smart_server = test_server.SmartTCPServer_for_testing()
4659.1.2 by Robert Collins
Refactor creation and shutdown of test servers to use a common helper,
3434
        self.start_server(self.smart_server, self.get_server())
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.
3435
        # Log all HPSS calls into self.hpss_calls.
3436
        _SmartClient.hooks.install_named_hook(
3437
            'call', self.capture_hpss_call, None)
3438
        self.hpss_calls = []
3439
3440
    def capture_hpss_call(self, params):
3441
        self.hpss_calls.append(params.method)
3442
3443
    def test_copy_content_into_avoids_revision_history(self):
3444
        local = self.make_branch('local')
5539.2.5 by Andrew Bennetts
Add test to test_remote, fix another shallow bug.
3445
        builder = self.make_branch_builder('remote')
3446
        builder.build_commit(message="Commit.")
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.
3447
        remote_branch_url = self.smart_server.get_url() + 'remote'
3448
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3449
        local.repository.fetch(remote_branch.repository)
3450
        self.hpss_calls = []
3451
        remote_branch.copy_content_into(local)
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
3452
        self.assertFalse('Branch.revision_history' in self.hpss_calls)
5539.2.5 by Andrew Bennetts
Add test to test_remote, fix another shallow bug.
3453
5539.2.6 by Andrew Bennetts
Better test name.
3454
    def test_fetch_everything_needs_just_one_call(self):
5539.2.5 by Andrew Bennetts
Add test to test_remote, fix another shallow bug.
3455
        local = self.make_branch('local')
3456
        builder = self.make_branch_builder('remote')
3457
        builder.build_commit(message="Commit.")
3458
        remote_branch_url = self.smart_server.get_url() + 'remote'
3459
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3460
        self.hpss_calls = []
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3461
        local.repository.fetch(
3462
            remote_branch.repository,
3463
            fetch_spec=_mod_graph.EverythingResult(remote_branch.repository))
5539.2.14 by Andrew Bennetts
Don't add a new verb; instead just teach the client to fallback if it gets a BadSearch error.
3464
        self.assertEqual(['Repository.get_stream_1.19'], self.hpss_calls)
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3465
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3466
    def override_verb(self, verb_name, verb):
3467
        request_handlers = request.request_handlers
3468
        orig_verb = request_handlers.get(verb_name)
3469
        request_handlers.register(verb_name, verb, override_existing=True)
3470
        self.addCleanup(request_handlers.register, verb_name, orig_verb,
3471
                override_existing=True)
3472
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3473
    def test_fetch_everything_backwards_compat(self):
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
3474
        """Can fetch with EverythingResult even with pre 2.4 servers.
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3475
        
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
3476
        Pre-2.4 do not support 'everything' searches with the
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3477
        Repository.get_stream_1.19 verb.
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3478
        """
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3479
        verb_log = []
3480
        class OldGetStreamVerb(SmartServerRepositoryGetStream_1_19):
3481
            """A version of the Repository.get_stream_1.19 verb patched to
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
3482
            reject 'everything' searches the way 2.3 and earlier do.
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3483
            """
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3484
            def recreate_search(self, repository, search_bytes,
3485
                                discard_excess=False):
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3486
                verb_log.append(search_bytes.split('\n', 1)[0])
3487
                if search_bytes == 'everything':
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3488
                    return (None,
3489
                            request.FailedSmartServerResponse(('BadSearch',)))
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3490
                return super(OldGetStreamVerb,
3491
                        self).recreate_search(repository, search_bytes,
3492
                            discard_excess=discard_excess)
3493
        self.override_verb('Repository.get_stream_1.19', OldGetStreamVerb)
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3494
        local = self.make_branch('local')
3495
        builder = self.make_branch_builder('remote')
3496
        builder.build_commit(message="Commit.")
3497
        remote_branch_url = self.smart_server.get_url() + 'remote'
3498
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3499
        self.hpss_calls = []
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3500
        local.repository.fetch(
3501
            remote_branch.repository,
3502
            fetch_spec=_mod_graph.EverythingResult(remote_branch.repository))
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3503
        # make sure the overridden verb was used
3504
        self.assertLength(1, verb_log)
3505
        # more than one HPSS call is needed, but because it's a VFS callback
3506
        # its hard to predict exactly how many.
3507
        self.assertTrue(len(self.hpss_calls) > 1)
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3508
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3509
5609.50.4 by Vincent Ladeuil
Add more tests for accepted bound_location variations.
3510
class TestUpdateBoundBranchWithModifiedBoundLocation(
3511
    tests.TestCaseWithTransport):
3512
    """Ensure correct handling of bound_location modifications.
3513
3514
    This is tested against a smart server as http://pad.lv/786980 was about a
3515
    ReadOnlyError (write attempt during a read-only transaction) which can only
3516
    happen in this context.
3517
    """
3518
3519
    def setUp(self):
3520
        super(TestUpdateBoundBranchWithModifiedBoundLocation, self).setUp()
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3521
        self.transport_server = test_server.SmartTCPServer_for_testing
5609.50.4 by Vincent Ladeuil
Add more tests for accepted bound_location variations.
3522
3523
    def make_master_and_checkout(self, master_name, checkout_name):
3524
        # Create the master branch and its associated checkout
3525
        self.master = self.make_branch_and_tree(master_name)
3526
        self.checkout = self.master.branch.create_checkout(checkout_name)
3527
        # Modify the master branch so there is something to update
3528
        self.master.commit('add stuff')
3529
        self.last_revid = self.master.commit('even more stuff')
3530
        self.bound_location = self.checkout.branch.get_bound_location()
3531
3532
    def assertUpdateSucceeds(self, new_location):
3533
        self.checkout.branch.set_bound_location(new_location)
3534
        self.checkout.update()
3535
        self.assertEquals(self.last_revid, self.checkout.last_revision())
3536
3537
    def test_without_final_slash(self):
3538
        self.make_master_and_checkout('master', 'checkout')
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3539
        # For unclear reasons some users have a bound_location without a final
3540
        # '/', simulate that by forcing such a value
5609.50.4 by Vincent Ladeuil
Add more tests for accepted bound_location variations.
3541
        self.assertEndsWith(self.bound_location, '/')
3542
        self.assertUpdateSucceeds(self.bound_location.rstrip('/'))
3543
3544
    def test_plus_sign(self):
3545
        self.make_master_and_checkout('+master', 'checkout')
3546
        self.assertUpdateSucceeds(self.bound_location.replace('%2B', '+', 1))
3547
3548
    def test_tilda(self):
3549
        # Embed ~ in the middle of the path just to avoid any $HOME
3550
        # interpretation
3551
        self.make_master_and_checkout('mas~ter', 'checkout')
3552
        self.assertUpdateSucceeds(self.bound_location.replace('%2E', '~', 1))