~bzr-pqm/bzr/bzr.dev

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