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