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