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