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