/brz/remove-bazaar

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