/brz/remove-bazaar

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