/brz/remove-bazaar

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