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