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