/brz/remove-bazaar

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