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