/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
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1041
class TestBranchGetParent(RemoteBranchTestCase):
1042
1043
    def test_no_parent(self):
1044
        # in an empty branch we decode the response properly
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.get_parent', ('quack/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
1052
            'success', ('',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1053
        transport.mkdir('quack')
1054
        transport = transport.clone('quack')
1055
        branch = self.make_remote_branch(transport, client)
1056
        result = branch.get_parent()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1057
        self.assertFinished(client)
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1058
        self.assertEqual(None, result)
1059
1060
    def test_parent_relative(self):
1061
        transport = MemoryTransport()
1062
        client = FakeClient(transport.base)
1063
        client.add_expected_call(
1064
            'Branch.get_stacked_on_url', ('kwaak/',),
1065
            'error', ('NotStacked',))
1066
        client.add_expected_call(
1067
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
1068
            'success', ('../foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1069
        transport.mkdir('kwaak')
1070
        transport = transport.clone('kwaak')
1071
        branch = self.make_remote_branch(transport, client)
1072
        result = branch.get_parent()
1073
        self.assertEqual(transport.clone('../foo').base, result)
1074
1075
    def test_parent_absolute(self):
1076
        transport = MemoryTransport()
1077
        client = FakeClient(transport.base)
1078
        client.add_expected_call(
1079
            'Branch.get_stacked_on_url', ('kwaak/',),
1080
            'error', ('NotStacked',))
1081
        client.add_expected_call(
1082
            'Branch.get_parent', ('kwaak/',),
4083.1.7 by Andrew Bennetts
Fix same trivial bug [(x) != (x,)] in test_remote and test_smart.
1083
            'success', ('http://foo/',))
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1084
        transport.mkdir('kwaak')
1085
        transport = transport.clone('kwaak')
1086
        branch = self.make_remote_branch(transport, client)
1087
        result = branch.get_parent()
1088
        self.assertEqual('http://foo/', result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1089
        self.assertFinished(client)
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
1090
1091
1092
class TestBranchSetParentLocation(RemoteBranchTestCase):
1093
1094
    def test_no_parent(self):
1095
        # We call the verb when setting parent to None
1096
        transport = MemoryTransport()
1097
        client = FakeClient(transport.base)
1098
        client.add_expected_call(
1099
            'Branch.get_stacked_on_url', ('quack/',),
1100
            'error', ('NotStacked',))
1101
        client.add_expected_call(
1102
            'Branch.set_parent_location', ('quack/', 'b', 'r', ''),
1103
            'success', ())
1104
        transport.mkdir('quack')
1105
        transport = transport.clone('quack')
1106
        branch = self.make_remote_branch(transport, client)
1107
        branch._lock_token = 'b'
1108
        branch._repo_lock_token = 'r'
1109
        branch._set_parent_location(None)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1110
        self.assertFinished(client)
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
1111
1112
    def test_parent(self):
1113
        transport = MemoryTransport()
1114
        client = FakeClient(transport.base)
1115
        client.add_expected_call(
1116
            'Branch.get_stacked_on_url', ('kwaak/',),
1117
            'error', ('NotStacked',))
1118
        client.add_expected_call(
1119
            'Branch.set_parent_location', ('kwaak/', 'b', 'r', 'foo'),
1120
            'success', ())
1121
        transport.mkdir('kwaak')
1122
        transport = transport.clone('kwaak')
1123
        branch = self.make_remote_branch(transport, client)
1124
        branch._lock_token = 'b'
1125
        branch._repo_lock_token = 'r'
1126
        branch._set_parent_location('foo')
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1127
        self.assertFinished(client)
4288.1.7 by Robert Collins
Add new remote server verb Branch.set_parent_location, dropping roundtrips further on push operations.
1128
1129
    def test_backwards_compat(self):
1130
        self.setup_smart_server_with_call_log()
1131
        branch = self.make_branch('.')
1132
        self.reset_smart_call_log()
1133
        verb = 'Branch.set_parent_location'
1134
        self.disable_verb(verb)
1135
        branch.set_parent('http://foo/')
1136
        self.assertLength(12, self.hpss_calls)
4078.2.1 by Robert Collins
Add a Branch.get_parent remote call for RemoteBranch.
1137
1138
4084.2.1 by Robert Collins
Make accessing a branch.tags.get_tag_dict use a smart[er] method rather than VFS calls and real objects.
1139
class TestBranchGetTagsBytes(RemoteBranchTestCase):
1140
1141
    def test_backwards_compat(self):
1142
        self.setup_smart_server_with_call_log()
1143
        branch = self.make_branch('.')
1144
        self.reset_smart_call_log()
1145
        verb = 'Branch.get_tags_bytes'
1146
        self.disable_verb(verb)
1147
        branch.tags.get_tag_dict()
1148
        call_count = len([call for call in self.hpss_calls if
1149
            call.call.method == verb])
1150
        self.assertEqual(1, call_count)
1151
1152
    def test_trivial(self):
1153
        transport = MemoryTransport()
1154
        client = FakeClient(transport.base)
1155
        client.add_expected_call(
1156
            'Branch.get_stacked_on_url', ('quack/',),
1157
            'error', ('NotStacked',))
1158
        client.add_expected_call(
1159
            'Branch.get_tags_bytes', ('quack/',),
1160
            'success', ('',))
1161
        transport.mkdir('quack')
1162
        transport = transport.clone('quack')
1163
        branch = self.make_remote_branch(transport, client)
1164
        result = branch.tags.get_tag_dict()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1165
        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.
1166
        self.assertEqual({}, result)
1167
1168
4634.36.1 by Andrew Bennetts
Fix trivial bug in RemoteBranch._set_tags_bytes, and add some unit tests for it.
1169
class TestBranchSetTagsBytes(RemoteBranchTestCase):
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.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1179
            'success', ('',))
1180
        transport.mkdir('quack')
1181
        transport = transport.clone('quack')
1182
        branch = self.make_remote_branch(transport, client)
1183
        self.lock_remote_branch(branch)
1184
        branch._set_tags_bytes('tags bytes')
1185
        self.assertFinished(client)
1186
        self.assertEqual('tags bytes', client._calls[-1][-1])
1187
1188
    def test_backwards_compatible(self):
1189
        transport = MemoryTransport()
1190
        client = FakeClient(transport.base)
1191
        client.add_expected_call(
1192
            'Branch.get_stacked_on_url', ('quack/',),
1193
            'error', ('NotStacked',))
1194
        client.add_expected_call(
1195
            'Branch.set_tags_bytes', ('quack/', 'branch token', 'repo token'),
1196
            'unknown', ('Branch.set_tags_bytes',))
1197
        transport.mkdir('quack')
1198
        transport = transport.clone('quack')
1199
        branch = self.make_remote_branch(transport, client)
1200
        self.lock_remote_branch(branch)
1201
        class StubRealBranch(object):
1202
            def __init__(self):
1203
                self.calls = []
1204
            def _set_tags_bytes(self, bytes):
1205
                self.calls.append(('set_tags_bytes', bytes))
1206
        real_branch = StubRealBranch()
1207
        branch._real_branch = real_branch
1208
        branch._set_tags_bytes('tags bytes')
1209
        # Call a second time, to exercise the 'remote version already inferred'
1210
        # code path.
1211
        branch._set_tags_bytes('tags bytes')
1212
        self.assertFinished(client)
1213
        self.assertEqual(
1214
            [('set_tags_bytes', 'tags bytes')] * 2, real_branch.calls)
1215
1216
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1217
class TestBranchHeadsToFetch(RemoteBranchTestCase):
1218
1219
    def test_uses_last_revision_info_and_tags_by_default(self):
1220
        transport = MemoryTransport()
1221
        client = FakeClient(transport.base)
1222
        client.add_expected_call(
1223
            'Branch.get_stacked_on_url', ('quack/',),
1224
            'error', ('NotStacked',))
1225
        client.add_expected_call(
1226
            'Branch.last_revision_info', ('quack/',),
1227
            'success', ('ok', '1', 'rev-tip'))
6015.15.4 by John Arbash Meinel
Catch a couple more cases that test tag fetching.
1228
        client.add_expected_call(
1229
            'Branch.get_config_file', ('quack/',),
1230
            'success', ('ok',), '')
1231
        transport.mkdir('quack')
1232
        transport = transport.clone('quack')
1233
        branch = self.make_remote_branch(transport, client)
1234
        result = branch.heads_to_fetch()
1235
        self.assertFinished(client)
1236
        self.assertEqual((set(['rev-tip']), set()), result)
1237
1238
    def test_uses_last_revision_info_and_tags_when_set(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'))
1247
        client.add_expected_call(
1248
            'Branch.get_config_file', ('quack/',),
1249
            'success', ('ok',), 'branch.fetch_tags = True')
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1250
        # XXX: this will break if the default format's serialization of tags
1251
        # changes, or if the RPC for fetching tags changes from get_tags_bytes.
1252
        client.add_expected_call(
1253
            'Branch.get_tags_bytes', ('quack/',),
1254
            'success', ('d5:tag-17:rev-foo5:tag-27:rev-bare',))
1255
        transport.mkdir('quack')
1256
        transport = transport.clone('quack')
1257
        branch = self.make_remote_branch(transport, client)
1258
        result = branch.heads_to_fetch()
1259
        self.assertFinished(client)
1260
        self.assertEqual(
1261
            (set(['rev-tip']), set(['rev-foo', 'rev-bar'])), result)
1262
1263
    def test_uses_rpc_for_formats_with_non_default_heads_to_fetch(self):
1264
        transport = MemoryTransport()
1265
        client = FakeClient(transport.base)
1266
        client.add_expected_call(
1267
            'Branch.get_stacked_on_url', ('quack/',),
1268
            'error', ('NotStacked',))
1269
        client.add_expected_call(
5741.1.11 by Jelmer Vernooij
Don't make heads_to_fetch() take a stop_revision.
1270
            'Branch.heads_to_fetch', ('quack/',),
5672.1.6 by Andrew Bennetts
Add another test.
1271
            'success', (['tip'], ['tagged-1', 'tagged-2']))
5672.1.5 by Andrew Bennetts
Add some tests for RemoteBranch.heads_to_fetch, and add release-note.
1272
        transport.mkdir('quack')
1273
        transport = transport.clone('quack')
1274
        branch = self.make_remote_branch(transport, client)
5672.1.7 by Andrew Bennetts
Use a more explicit method name.
1275
        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.
1276
        result = branch.heads_to_fetch()
1277
        self.assertFinished(client)
5672.1.6 by Andrew Bennetts
Add another test.
1278
        self.assertEqual((set(['tip']), set(['tagged-1', 'tagged-2'])), result)
1279
6015.15.1 by John Arbash Meinel
Start working on a config entry for testing whether we should fetch tags or not.
1280
    def make_branch_with_tags(self):
5672.1.6 by Andrew Bennetts
Add another test.
1281
        self.setup_smart_server_with_call_log()
1282
        # Make a branch with a single revision.
1283
        builder = self.make_branch_builder('foo')
1284
        builder.start_series()
1285
        builder.build_snapshot('tip', None, [
1286
            ('add', ('', 'root-id', 'directory', ''))])
1287
        builder.finish_series()
1288
        branch = builder.get_branch()
1289
        # Add two tags to that branch
1290
        branch.tags.set_tag('tag-1', 'rev-1')
1291
        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.
1292
        return branch
1293
1294
    def test_backwards_compatible(self):
1295
        branch = self.make_branch_with_tags()
1296
        c = branch.get_config()
1297
        c.set_user_option('branch.fetch_tags', 'True')
5672.1.6 by Andrew Bennetts
Add another test.
1298
        self.addCleanup(branch.lock_read().unlock)
1299
        # Disable the heads_to_fetch verb
1300
        verb = 'Branch.heads_to_fetch'
1301
        self.disable_verb(verb)
1302
        self.reset_smart_call_log()
1303
        result = branch.heads_to_fetch()
1304
        self.assertEqual((set(['tip']), set(['rev-1', 'rev-2'])), result)
1305
        self.assertEqual(
6015.15.1 by John Arbash Meinel
Start working on a config entry for testing whether we should fetch tags or not.
1306
            ['Branch.last_revision_info', 'Branch.get_config_file',
1307
             'Branch.get_tags_bytes'],
1308
            [call.call.method for call in self.hpss_calls])
1309
1310
    def test_backwards_compatible_no_tags(self):
1311
        branch = self.make_branch_with_tags()
1312
        c = branch.get_config()
1313
        c.set_user_option('branch.fetch_tags', 'False')
1314
        self.addCleanup(branch.lock_read().unlock)
1315
        # Disable the heads_to_fetch verb
1316
        verb = 'Branch.heads_to_fetch'
1317
        self.disable_verb(verb)
1318
        self.reset_smart_call_log()
1319
        result = branch.heads_to_fetch()
1320
        self.assertEqual((set(['tip']), set()), result)
1321
        self.assertEqual(
1322
            ['Branch.last_revision_info', 'Branch.get_config_file'],
5672.1.6 by Andrew Bennetts
Add another test.
1323
            [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.
1324
1325
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1326
class TestBranchLastRevisionInfo(RemoteBranchTestCase):
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1327
1328
    def test_empty_branch(self):
1329
        # in an empty branch we decode the response properly
1330
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1331
        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
1332
        client.add_expected_call(
1333
            'Branch.get_stacked_on_url', ('quack/',),
1334
            'error', ('NotStacked',))
1335
        client.add_expected_call(
1336
            'Branch.last_revision_info', ('quack/',),
1337
            'success', ('ok', '0', 'null:'))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1338
        transport.mkdir('quack')
1339
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1340
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1341
        result = branch.last_revision_info()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1342
        self.assertFinished(client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1343
        self.assertEqual((0, NULL_REVISION), result)
1344
1345
    def test_non_empty_branch(self):
1346
        # 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.
1347
        revid = u'\xc8'.encode('utf8')
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1348
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1349
        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
1350
        client.add_expected_call(
1351
            'Branch.get_stacked_on_url', ('kwaak/',),
1352
            'error', ('NotStacked',))
1353
        client.add_expected_call(
1354
            'Branch.last_revision_info', ('kwaak/',),
1355
            'success', ('ok', '2', revid))
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1356
        transport.mkdir('kwaak')
1357
        transport = transport.clone('kwaak')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1358
        branch = self.make_remote_branch(transport, client)
2018.5.51 by Wouter van Heyst
Test and implement RemoteBranch.last_revision_info()
1359
        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.
1360
        self.assertEqual((2, revid), result)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
1361
1362
4053.1.2 by Robert Collins
Actually make this branch work.
1363
class TestBranch_get_stacked_on_url(TestRemote):
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1364
    """Test Branch._get_stacked_on_url rpc"""
1365
3691.2.10 by Martin Pool
Update more test_remote tests
1366
    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.
1367
        # test that asking for a stacked on url the server can't access works.
1368
        # This isn't perfect, but then as we're in the same process there
1369
        # really isn't anything we can do to be 100% sure that the server
1370
        # doesn't just open in - this test probably needs to be rewritten using
1371
        # a spawn()ed server.
1372
        stacked_branch = self.make_branch('stacked', format='1.9')
1373
        memory_branch = self.make_branch('base', format='1.9')
1374
        vfs_url = self.get_vfs_only_url('base')
1375
        stacked_branch.set_stacked_on_url(vfs_url)
1376
        transport = stacked_branch.bzrdir.root_transport
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1377
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1378
        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.
1379
            'Branch.get_stacked_on_url', ('stacked/',),
1380
            'success', ('ok', vfs_url))
1381
        # XXX: Multiple calls are bad, this second call documents what is
1382
        # today.
1383
        client.add_expected_call(
1384
            'Branch.get_stacked_on_url', ('stacked/',),
1385
            'success', ('ok', vfs_url))
5712.3.17 by Jelmer Vernooij
more fixes.
1386
        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.
1387
            _client=client)
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
1388
        repo_fmt = remote.RemoteRepositoryFormat()
1389
        repo_fmt._custom_format = stacked_branch.repository._format
1390
        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.
1391
            _client=client)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1392
        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.
1393
        self.assertEqual(vfs_url, result)
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1394
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1395
    def test_backwards_compatible(self):
1396
        # like with bzr1.6 with no Branch.get_stacked_on_url rpc
1397
        base_branch = self.make_branch('base', format='1.6')
1398
        stacked_branch = self.make_branch('stacked', format='1.6')
1399
        stacked_branch.set_stacked_on_url('../base')
1400
        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.
1401
        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
1402
        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).
1403
            '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.
1404
            'success', ('branch', branch_network_name))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1405
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
1406
            'BzrDir.find_repositoryV3', ('stacked/',),
4118.1.5 by Andrew Bennetts
Fix test_remote tests.
1407
            'success', ('ok', '', 'no', 'no', 'yes',
4053.1.2 by Robert Collins
Actually make this branch work.
1408
                stacked_branch.repository._format.network_name()))
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1409
        # called twice, once from constructor and then again by us
1410
        client.add_expected_call(
1411
            'Branch.get_stacked_on_url', ('stacked/',),
1412
            'unknown', ('Branch.get_stacked_on_url',))
1413
        client.add_expected_call(
1414
            'Branch.get_stacked_on_url', ('stacked/',),
1415
            'unknown', ('Branch.get_stacked_on_url',))
1416
        # this will also do vfs access, but that goes direct to the transport
1417
        # 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.
1418
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
5712.3.17 by Jelmer Vernooij
more fixes.
1419
            RemoteBzrDirFormat(), _client=client)
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1420
        branch = bzrdir.open_branch()
1421
        result = branch.get_stacked_on_url()
1422
        self.assertEqual('../base', result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1423
        self.assertFinished(client)
3691.2.12 by Martin Pool
Add test for coping without Branch.get_stacked_on_url
1424
        # it's in the fallback list both for the RemoteRepository and its vfs
1425
        # repository
1426
        self.assertEqual(1, len(branch.repository._fallback_repositories))
1427
        self.assertEqual(1,
1428
            len(branch.repository._real_repository._fallback_repositories))
1429
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1430
    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.
1431
        base_branch = self.make_branch('base')
1432
        stacked_branch = self.make_branch('stacked')
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1433
        stacked_branch.set_stacked_on_url('../base')
4053.1.2 by Robert Collins
Actually make this branch work.
1434
        reference_format = self.get_repo_format()
1435
        network_name = reference_format.network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1436
        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.
1437
        branch_network_name = self.get_branch_format().network_name()
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1438
        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).
1439
            '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.
1440
            'success', ('branch', branch_network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1441
        client.add_expected_call(
4053.1.2 by Robert Collins
Actually make this branch work.
1442
            'BzrDir.find_repositoryV3', ('stacked/',),
5158.4.3 by Andrew Bennetts
Fix test_remote tests that accidentally assumed it was ok to stack mismatched formats.
1443
            'success', ('ok', '', 'yes', 'no', 'yes', network_name))
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1444
        # called twice, once from constructor and then again by us
1445
        client.add_expected_call(
1446
            'Branch.get_stacked_on_url', ('stacked/',),
1447
            'success', ('ok', '../base'))
1448
        client.add_expected_call(
1449
            'Branch.get_stacked_on_url', ('stacked/',),
1450
            '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.
1451
        bzrdir = RemoteBzrDir(self.get_transport('stacked'),
5712.3.17 by Jelmer Vernooij
more fixes.
1452
            RemoteBzrDirFormat(), _client=client)
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1453
        branch = bzrdir.open_branch()
1454
        result = branch.get_stacked_on_url()
1455
        self.assertEqual('../base', result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1456
        self.assertFinished(client)
4226.1.2 by Robert Collins
Fix test_remote failing because of less _real_repository objects.
1457
        # it's in the fallback list both for the RemoteRepository.
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1458
        self.assertEqual(1, len(branch.repository._fallback_repositories))
4226.1.2 by Robert Collins
Fix test_remote failing because of less _real_repository objects.
1459
        # And we haven't had to construct a real repository.
1460
        self.assertEqual(None, branch.repository._real_repository)
3691.2.11 by Martin Pool
More tests around RemoteBranch stacking.
1461
3691.2.5 by Martin Pool
Add Branch.get_stacked_on_url rpc and tests for same
1462
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1463
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.
1464
1465
    def test_set_empty(self):
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1466
        # _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.
1467
        # Branch.set_last_revision(path, '') on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
1468
        transport = MemoryTransport()
1469
        transport.mkdir('branch')
1470
        transport = transport.clone('branch')
1471
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1472
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1473
        client.add_expected_call(
1474
            'Branch.get_stacked_on_url', ('branch/',),
1475
            'error', ('NotStacked',))
1476
        client.add_expected_call(
1477
            'Branch.lock_write', ('branch/', '', ''),
1478
            'success', ('ok', 'branch token', 'repo token'))
1479
        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.
1480
            'Branch.last_revision_info',
1481
            ('branch/',),
1482
            'success', ('ok', '0', 'null:'))
1483
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1484
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'null:',),
1485
            'success', ('ok',))
1486
        client.add_expected_call(
1487
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1488
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1489
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1490
        # This is a hack to work around the problem that RemoteBranch currently
1491
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1492
        branch._ensure_real = lambda: None
1493
        branch.lock_write()
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1494
        result = branch._set_last_revision(NULL_REVISION)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1495
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1496
        self.assertEqual(None, result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1497
        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.
1498
1499
    def test_set_nonempty(self):
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
1500
        # 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.
1501
        # Branch.set_last_revision(path, rev-idN) on the wire.
3104.4.2 by Andrew Bennetts
All tests passing.
1502
        transport = MemoryTransport()
1503
        transport.mkdir('branch')
1504
        transport = transport.clone('branch')
1505
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1506
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1507
        client.add_expected_call(
1508
            'Branch.get_stacked_on_url', ('branch/',),
1509
            'error', ('NotStacked',))
1510
        client.add_expected_call(
1511
            'Branch.lock_write', ('branch/', '', ''),
1512
            'success', ('ok', 'branch token', 'repo token'))
1513
        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.
1514
            'Branch.last_revision_info',
1515
            ('branch/',),
1516
            'success', ('ok', '0', 'null:'))
1517
        lines = ['rev-id2']
1518
        encoded_body = bz2.compress('\n'.join(lines))
1519
        client.add_success_response_with_body(encoded_body, 'ok')
1520
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1521
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id2',),
1522
            'success', ('ok',))
1523
        client.add_expected_call(
1524
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1525
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1526
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1527
        # This is a hack to work around the problem that RemoteBranch currently
1528
        # unnecessarily invokes _ensure_real upon a call to lock_write.
1529
        branch._ensure_real = lambda: None
1530
        # Lock the branch, reset the record of remote calls.
1531
        branch.lock_write()
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1532
        result = branch._set_last_revision('rev-id2')
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1533
        branch.unlock()
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1534
        self.assertEqual(None, result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1535
        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.
1536
1537
    def test_no_such_revision(self):
1538
        transport = MemoryTransport()
1539
        transport.mkdir('branch')
1540
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1541
        # A response of 'NoSuchRevision' is translated into an exception.
1542
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1543
        client.add_expected_call(
1544
            'Branch.get_stacked_on_url', ('branch/',),
1545
            'error', ('NotStacked',))
1546
        client.add_expected_call(
1547
            'Branch.lock_write', ('branch/', '', ''),
1548
            'success', ('ok', 'branch token', 'repo token'))
1549
        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.
1550
            'Branch.last_revision_info',
1551
            ('branch/',),
1552
            'success', ('ok', '0', 'null:'))
1553
        # get_graph calls to construct the revision history, for the set_rh
1554
        # hook
1555
        lines = ['rev-id']
1556
        encoded_body = bz2.compress('\n'.join(lines))
1557
        client.add_success_response_with_body(encoded_body, 'ok')
1558
        client.add_expected_call(
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1559
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1560
            'error', ('NoSuchRevision', 'rev-id'))
1561
        client.add_expected_call(
1562
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1563
            'success', ('ok',))
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1564
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1565
        branch = self.make_remote_branch(transport, client)
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1566
        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.
1567
        self.assertRaises(
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1568
            errors.NoSuchRevision, branch._set_last_revision, 'rev-id')
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
1569
        branch.unlock()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1570
        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.
1571
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1572
    def test_tip_change_rejected(self):
1573
        """TipChangeRejected responses cause a TipChangeRejected exception to
1574
        be raised.
1575
        """
1576
        transport = MemoryTransport()
1577
        transport.mkdir('branch')
1578
        transport = transport.clone('branch')
1579
        client = FakeClient(transport.base)
1580
        rejection_msg_unicode = u'rejection message\N{INTERROBANG}'
1581
        rejection_msg_utf8 = rejection_msg_unicode.encode('utf8')
3691.2.10 by Martin Pool
Update more test_remote tests
1582
        client.add_expected_call(
1583
            'Branch.get_stacked_on_url', ('branch/',),
1584
            'error', ('NotStacked',))
1585
        client.add_expected_call(
1586
            'Branch.lock_write', ('branch/', '', ''),
1587
            'success', ('ok', 'branch token', 'repo token'))
1588
        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.
1589
            'Branch.last_revision_info',
1590
            ('branch/',),
1591
            'success', ('ok', '0', 'null:'))
1592
        lines = ['rev-id']
1593
        encoded_body = bz2.compress('\n'.join(lines))
1594
        client.add_success_response_with_body(encoded_body, 'ok')
1595
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1596
            'Branch.set_last_revision', ('branch/', 'branch token', 'repo token', 'rev-id',),
1597
            'error', ('TipChangeRejected', rejection_msg_utf8))
1598
        client.add_expected_call(
1599
            'Branch.unlock', ('branch/', 'branch token', 'repo token'),
1600
            'success', ('ok',))
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1601
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1602
        branch._ensure_real = lambda: None
1603
        branch.lock_write()
1604
        # The 'TipChangeRejected' error response triggered by calling
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
1605
        # 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.
1606
        err = self.assertRaises(
5718.7.4 by Jelmer Vernooij
Branch.set_revision_history.
1607
            errors.TipChangeRejected,
5718.7.12 by Jelmer Vernooij
Fix use of _set_last_revision.
1608
            branch._set_last_revision, 'rev-id')
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1609
        # The UTF-8 message from the response has been decoded into a unicode
1610
        # object.
1611
        self.assertIsInstance(err.msg, unicode)
1612
        self.assertEqual(rejection_msg_unicode, err.msg)
3691.2.10 by Martin Pool
Update more test_remote tests
1613
        branch.unlock()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1614
        self.assertFinished(client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1615
2018.12.3 by Andrew Bennetts
Add a Branch.set_last_revision smart method, and make RemoteBranch.set_revision_history use it.
1616
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1617
class TestBranchSetLastRevisionInfo(RemoteBranchTestCase):
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1618
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1619
    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.
1620
        # set_last_revision_info(num, 'rev-id') is translated to calling
1621
        # 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'.
1622
        transport = MemoryTransport()
1623
        transport.mkdir('branch')
1624
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1625
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1626
        # get_stacked_on_url
1627
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1628
        # lock_write
1629
        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.
1630
        # query the current revision
1631
        client.add_success_response('ok', '0', 'null:')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1632
        # set_last_revision
1633
        client.add_success_response('ok')
1634
        # unlock
1635
        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.
1636
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1637
        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.
1638
        # Lock the branch, reset the record of remote calls.
1639
        branch.lock_write()
1640
        client._calls = []
1641
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1642
        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.
1643
            [('call', 'Branch.last_revision_info', ('branch/',)),
1644
             ('call', 'Branch.set_last_revision_info',
3297.4.1 by Andrew Bennetts
Merge 'Add Branch.set_last_revision_info smart method'.
1645
                ('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.
1646
                 '1234', 'a-revision-id'))],
1647
            client._calls)
1648
        self.assertEqual(None, result)
1649
1650
    def test_no_such_revision(self):
1651
        # A response of 'NoSuchRevision' is translated into an exception.
1652
        transport = MemoryTransport()
1653
        transport.mkdir('branch')
1654
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1655
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1656
        # get_stacked_on_url
1657
        client.add_error_response('NotStacked')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1658
        # lock_write
1659
        client.add_success_response('ok', 'branch token', 'repo token')
1660
        # set_last_revision
1661
        client.add_error_response('NoSuchRevision', 'revid')
1662
        # unlock
1663
        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.
1664
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1665
        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.
1666
        # Lock the branch, reset the record of remote calls.
1667
        branch.lock_write()
1668
        client._calls = []
1669
1670
        self.assertRaises(
1671
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
1672
        branch.unlock()
1673
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1674
    def test_backwards_compatibility(self):
1675
        """If the server does not support the Branch.set_last_revision_info
1676
        verb (which is new in 1.4), then the client falls back to VFS methods.
1677
        """
1678
        # This test is a little messy.  Unlike most tests in this file, it
1679
        # doesn't purely test what a Remote* object sends over the wire, and
1680
        # how it reacts to responses from the wire.  It instead relies partly
1681
        # on asserting that the RemoteBranch will call
1682
        # self._real_branch.set_last_revision_info(...).
1683
1684
        # First, set up our RemoteBranch with a FakeClient that raises
1685
        # UnknownSmartMethod, and a StubRealBranch that logs how it is called.
1686
        transport = MemoryTransport()
1687
        transport.mkdir('branch')
1688
        transport = transport.clone('branch')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1689
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1690
        client.add_expected_call(
1691
            'Branch.get_stacked_on_url', ('branch/',),
1692
            'error', ('NotStacked',))
1693
        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.
1694
            'Branch.last_revision_info',
1695
            ('branch/',),
1696
            'success', ('ok', '0', 'null:'))
1697
        client.add_expected_call(
3691.2.10 by Martin Pool
Update more test_remote tests
1698
            'Branch.set_last_revision_info',
1699
            ('branch/', 'branch token', 'repo token', '1234', 'a-revision-id',),
1700
            'unknown', 'Branch.set_last_revision_info')
1701
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1702
        branch = self.make_remote_branch(transport, client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1703
        class StubRealBranch(object):
1704
            def __init__(self):
1705
                self.calls = []
1706
            def set_last_revision_info(self, revno, revision_id):
1707
                self.calls.append(
1708
                    ('set_last_revision_info', revno, revision_id))
3441.5.5 by Andrew Bennetts
Some small tweaks and comments.
1709
            def _clear_cached_state(self):
1710
                pass
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1711
        real_branch = StubRealBranch()
1712
        branch._real_branch = real_branch
1713
        self.lock_remote_branch(branch)
1714
1715
        # Call set_last_revision_info, and verify it behaved as expected.
1716
        result = branch.set_last_revision_info(1234, 'a-revision-id')
1717
        self.assertEqual(
1718
            [('set_last_revision_info', 1234, 'a-revision-id')],
1719
            real_branch.calls)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1720
        self.assertFinished(client)
3297.4.2 by Andrew Bennetts
Add backwards compatibility for servers older than 1.4.
1721
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1722
    def test_unexpected_error(self):
3697.2.6 by Martin Pool
Merge 261315 fix into 1.7 branch
1723
        # If the server sends an error the client doesn't understand, it gets
1724
        # turned into an UnknownErrorFromSmartServer, which is presented as a
1725
        # non-internal error to the user.
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1726
        transport = MemoryTransport()
1727
        transport.mkdir('branch')
1728
        transport = transport.clone('branch')
1729
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1730
        # get_stacked_on_url
1731
        client.add_error_response('NotStacked')
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1732
        # lock_write
1733
        client.add_success_response('ok', 'branch token', 'repo token')
1734
        # set_last_revision
1735
        client.add_error_response('UnexpectedError')
1736
        # unlock
1737
        client.add_success_response('ok')
1738
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1739
        branch = self.make_remote_branch(transport, client)
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1740
        # Lock the branch, reset the record of remote calls.
1741
        branch.lock_write()
1742
        client._calls = []
1743
1744
        err = self.assertRaises(
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
1745
            errors.UnknownErrorFromSmartServer,
3245.4.53 by Andrew Bennetts
Add some missing 'raise' statements to test_remote.
1746
            branch.set_last_revision_info, 123, 'revid')
1747
        self.assertEqual(('UnexpectedError',), err.error_tuple)
1748
        branch.unlock()
1749
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1750
    def test_tip_change_rejected(self):
1751
        """TipChangeRejected responses cause a TipChangeRejected exception to
1752
        be raised.
1753
        """
1754
        transport = MemoryTransport()
1755
        transport.mkdir('branch')
1756
        transport = transport.clone('branch')
1757
        client = FakeClient(transport.base)
3691.2.10 by Martin Pool
Update more test_remote tests
1758
        # get_stacked_on_url
1759
        client.add_error_response('NotStacked')
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1760
        # lock_write
1761
        client.add_success_response('ok', 'branch token', 'repo token')
1762
        # set_last_revision
1763
        client.add_error_response('TipChangeRejected', 'rejection message')
1764
        # unlock
1765
        client.add_success_response('ok')
1766
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1767
        branch = self.make_remote_branch(transport, client)
3577.1.1 by Andrew Bennetts
Cherry-pick TipChangeRejected changes from pre-branch-tip-changed-hook loom.
1768
        # Lock the branch, reset the record of remote calls.
1769
        branch.lock_write()
1770
        self.addCleanup(branch.unlock)
1771
        client._calls = []
1772
1773
        # The 'TipChangeRejected' error response triggered by calling
1774
        # set_last_revision_info causes a TipChangeRejected exception.
1775
        err = self.assertRaises(
1776
            errors.TipChangeRejected,
1777
            branch.set_last_revision_info, 123, 'revid')
1778
        self.assertEqual('rejection message', err.msg)
1779
2892.2.1 by Andrew Bennetts
Add Branch.set_last_revision_info smart method, and make the RemoteBranch client use it.
1780
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1781
class TestBranchGetSetConfig(RemoteBranchTestCase):
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1782
1783
    def test_get_branch_conf(self):
4226.1.5 by Robert Collins
Reinstate the use of the Branch.get_config_file verb.
1784
        # in an empty branch we decode the response properly
1785
        client = FakeClient()
1786
        client.add_expected_call(
1787
            'Branch.get_stacked_on_url', ('memory:///',),
1788
            'error', ('NotStacked',),)
1789
        client.add_success_response_with_body('# config file body', 'ok')
1790
        transport = MemoryTransport()
1791
        branch = self.make_remote_branch(transport, client)
1792
        config = branch.get_config()
1793
        config.has_explicit_nickname()
1794
        self.assertEqual(
1795
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
1796
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
1797
            client._calls)
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1798
4241.5.2 by Matt Nordhoff
Add a test
1799
    def test_get_multi_line_branch_conf(self):
1800
        # Make sure that multiple-line branch.conf files are supported
1801
        #
5243.1.2 by Martin
Point launchpad links in comments at production server rather than edge
1802
        # https://bugs.launchpad.net/bzr/+bug/354075
4241.5.2 by Matt Nordhoff
Add a test
1803
        client = FakeClient()
1804
        client.add_expected_call(
1805
            'Branch.get_stacked_on_url', ('memory:///',),
1806
            'error', ('NotStacked',),)
1807
        client.add_success_response_with_body('a = 1\nb = 2\nc = 3\n', 'ok')
1808
        transport = MemoryTransport()
1809
        branch = self.make_remote_branch(transport, client)
1810
        config = branch.get_config()
1811
        self.assertEqual(u'2', config.get_user_option('b'))
1812
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1813
    def test_set_option(self):
1814
        client = FakeClient()
1815
        client.add_expected_call(
1816
            'Branch.get_stacked_on_url', ('memory:///',),
1817
            'error', ('NotStacked',),)
1818
        client.add_expected_call(
1819
            'Branch.lock_write', ('memory:///', '', ''),
1820
            'success', ('ok', 'branch token', 'repo token'))
1821
        client.add_expected_call(
1822
            'Branch.set_config_option', ('memory:///', 'branch token',
1823
            'repo token', 'foo', 'bar', ''),
1824
            'success', ())
1825
        client.add_expected_call(
1826
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1827
            'success', ('ok',))
1828
        transport = MemoryTransport()
1829
        branch = self.make_remote_branch(transport, client)
1830
        branch.lock_write()
1831
        config = branch._get_config()
1832
        config.set_option('foo', 'bar')
1833
        branch.unlock()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
1834
        self.assertFinished(client)
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1835
5227.1.2 by Andrew Bennetts
Add Branch.set_config_option_dict RPC (and VFS fallback), fixes #430382.
1836
    def test_set_option_with_dict(self):
1837
        client = FakeClient()
1838
        client.add_expected_call(
1839
            'Branch.get_stacked_on_url', ('memory:///',),
1840
            'error', ('NotStacked',),)
1841
        client.add_expected_call(
1842
            'Branch.lock_write', ('memory:///', '', ''),
1843
            'success', ('ok', 'branch token', 'repo token'))
1844
        encoded_dict_value = 'd5:ascii1:a11:unicode \xe2\x8c\x9a3:\xe2\x80\xbde'
1845
        client.add_expected_call(
1846
            'Branch.set_config_option_dict', ('memory:///', 'branch token',
1847
            'repo token', encoded_dict_value, 'foo', ''),
1848
            'success', ())
1849
        client.add_expected_call(
1850
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1851
            'success', ('ok',))
1852
        transport = MemoryTransport()
1853
        branch = self.make_remote_branch(transport, client)
1854
        branch.lock_write()
1855
        config = branch._get_config()
1856
        config.set_option(
1857
            {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'},
1858
            'foo')
1859
        branch.unlock()
1860
        self.assertFinished(client)
1861
4226.2.1 by Robert Collins
Set branch config options via a smart method.
1862
    def test_backwards_compat_set_option(self):
1863
        self.setup_smart_server_with_call_log()
1864
        branch = self.make_branch('.')
1865
        verb = 'Branch.set_config_option'
1866
        self.disable_verb(verb)
1867
        branch.lock_write()
1868
        self.addCleanup(branch.unlock)
1869
        self.reset_smart_call_log()
1870
        branch._get_config().set_option('value', 'name')
1871
        self.assertLength(10, self.hpss_calls)
1872
        self.assertEqual('value', branch._get_config().get_option('name'))
1873
5227.1.2 by Andrew Bennetts
Add Branch.set_config_option_dict RPC (and VFS fallback), fixes #430382.
1874
    def test_backwards_compat_set_option_with_dict(self):
1875
        self.setup_smart_server_with_call_log()
1876
        branch = self.make_branch('.')
1877
        verb = 'Branch.set_config_option_dict'
1878
        self.disable_verb(verb)
1879
        branch.lock_write()
1880
        self.addCleanup(branch.unlock)
1881
        self.reset_smart_call_log()
1882
        config = branch._get_config()
1883
        value_dict = {'ascii': 'a', u'unicode \N{WATCH}': u'\N{INTERROBANG}'}
1884
        config.set_option(value_dict, 'name')
1885
        self.assertLength(10, self.hpss_calls)
1886
        self.assertEqual(value_dict, branch._get_config().get_option('name'))
1887
2018.5.59 by Robert Collins
Get BranchConfig working somewhat on RemoteBranches (Robert Collins, Vincent Ladeuil).
1888
6270.1.23 by Jelmer Vernooij
Add notes about Remote{Control,Branch}Store.
1889
class TestBranchGetPutConfigStore(RemoteBranchTestCase):
6270.1.10 by Jelmer Vernooij
Fix testing Branch.set_config_file.
1890
1891
    def test_get_branch_conf(self):
1892
        # in an empty branch we decode the response properly
1893
        client = FakeClient()
1894
        client.add_expected_call(
1895
            'Branch.get_stacked_on_url', ('memory:///',),
1896
            'error', ('NotStacked',),)
1897
        client.add_success_response_with_body('# config file body', 'ok')
1898
        transport = MemoryTransport()
1899
        branch = self.make_remote_branch(transport, client)
1900
        config = branch.get_config_stack()
1901
        config.get("email")
1902
        config.get("log_format")
1903
        self.assertEqual(
1904
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
1905
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',))],
1906
            client._calls)
1907
1908
    def test_set_branch_conf(self):
1909
        client = FakeClient()
1910
        client.add_expected_call(
1911
            'Branch.get_stacked_on_url', ('memory:///',),
1912
            'error', ('NotStacked',),)
1913
        client.add_expected_call(
1914
            'Branch.lock_write', ('memory:///', '', ''),
1915
            'success', ('ok', 'branch token', 'repo token'))
1916
        client.add_expected_call(
1917
            'Branch.get_config_file', ('memory:///', ),
1918
            'success', ('ok', ), "# line 1\n")
1919
        client.add_expected_call(
6270.1.17 by Jelmer Vernooij
s/set_config_file/put_config_file.
1920
            'Branch.put_config_file', ('memory:///', 'branch token',
6270.1.10 by Jelmer Vernooij
Fix testing Branch.set_config_file.
1921
            'repo token'),
6270.1.16 by Jelmer Vernooij
Expect 'ok' response from set_config_file.
1922
            'success', ('ok',))
6270.1.10 by Jelmer Vernooij
Fix testing Branch.set_config_file.
1923
        client.add_expected_call(
1924
            'Branch.unlock', ('memory:///', 'branch token', 'repo token'),
1925
            'success', ('ok',))
1926
        transport = MemoryTransport()
1927
        branch = self.make_remote_branch(transport, client)
1928
        branch.lock_write()
1929
        config = branch.get_config_stack()
1930
        config.set('email', 'The Dude <lebowski@example.com>')
1931
        branch.unlock()
1932
        self.assertFinished(client)
1933
        self.assertEqual(
1934
            [('call', 'Branch.get_stacked_on_url', ('memory:///',)),
1935
             ('call', 'Branch.lock_write', ('memory:///', '', '')),
1936
             ('call_expecting_body', 'Branch.get_config_file', ('memory:///',)),
6270.1.18 by Jelmer Vernooij
Fix a test.
1937
             ('call_with_body_bytes_expecting_body', 'Branch.put_config_file',
6270.1.10 by Jelmer Vernooij
Fix testing Branch.set_config_file.
1938
                 ('memory:///', 'branch token', 'repo token'),
1939
                 '# line 1\nemail = The Dude <lebowski@example.com>\n'),
1940
             ('call', 'Branch.unlock', ('memory:///', 'branch token', 'repo token'))],
1941
            client._calls)
1942
1943
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1944
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.
1945
1946
    def test_lock_write_unlockable(self):
1947
        transport = MemoryTransport()
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1948
        client = FakeClient(transport.base)
3691.2.9 by Martin Pool
Convert and update more test_remote tests
1949
        client.add_expected_call(
1950
            'Branch.get_stacked_on_url', ('quack/',),
1951
            'error', ('NotStacked',),)
1952
        client.add_expected_call(
1953
            'Branch.lock_write', ('quack/', '', ''),
1954
            '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.
1955
        transport.mkdir('quack')
1956
        transport = transport.clone('quack')
3692.1.1 by Andrew Bennetts
Make RemoteBranch.lock_write lock the repository too.
1957
        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.
1958
        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.
1959
        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.
1960
1961
4288.1.1 by Robert Collins
Add support for a RemoteBzrDirConfig to support optimising push operations which need to look for default stacking locations.
1962
class TestBzrDirGetSetConfig(RemoteBzrDirTestCase):
1963
1964
    def test__get_config(self):
1965
        client = FakeClient()
1966
        client.add_success_response_with_body('default_stack_on = /\n', 'ok')
1967
        transport = MemoryTransport()
1968
        bzrdir = self.make_remote_bzrdir(transport, client)
1969
        config = bzrdir.get_config()
1970
        self.assertEqual('/', config.get_default_stack_on())
1971
        self.assertEqual(
1972
            [('call_expecting_body', 'BzrDir.get_config_file', ('memory:///',))],
1973
            client._calls)
1974
1975
    def test_set_option_uses_vfs(self):
1976
        self.setup_smart_server_with_call_log()
1977
        bzrdir = self.make_bzrdir('.')
1978
        self.reset_smart_call_log()
1979
        config = bzrdir.get_config()
1980
        config.set_default_stack_on('/')
1981
        self.assertLength(3, self.hpss_calls)
1982
1983
    def test_backwards_compat_get_option(self):
1984
        self.setup_smart_server_with_call_log()
1985
        bzrdir = self.make_bzrdir('.')
1986
        verb = 'BzrDir.get_config_file'
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
1987
        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.
1988
        self.reset_smart_call_log()
1989
        self.assertEqual(None,
1990
            bzrdir._get_config().get_option('default_stack_on'))
1991
        self.assertLength(3, self.hpss_calls)
1992
1993
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
1994
class TestTransportIsReadonly(tests.TestCase):
1995
1996
    def test_true(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
1997
        client = FakeClient()
1998
        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.
1999
        transport = RemoteTransport('bzr://example.com/', medium=False,
2000
                                    _client=client)
2001
        self.assertEqual(True, transport.is_readonly())
2002
        self.assertEqual(
2003
            [('call', 'Transport.is_readonly', ())],
2004
            client._calls)
2005
2006
    def test_false(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2007
        client = FakeClient()
2008
        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.
2009
        transport = RemoteTransport('bzr://example.com/', medium=False,
2010
                                    _client=client)
2011
        self.assertEqual(False, transport.is_readonly())
2012
        self.assertEqual(
2013
            [('call', 'Transport.is_readonly', ())],
2014
            client._calls)
2015
2016
    def test_error_from_old_server(self):
2017
        """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
2018
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
2019
        Clients should treat it as a "no" response, because is_readonly is only
2020
        advisory anyway (a transport could be read-write, but then the
2021
        underlying filesystem could be readonly anyway).
2022
        """
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2023
        client = FakeClient()
2024
        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.
2025
        transport = RemoteTransport('bzr://example.com/', medium=False,
2026
                                    _client=client)
2027
        self.assertEqual(False, transport.is_readonly())
2028
        self.assertEqual(
2029
            [('call', 'Transport.is_readonly', ())],
2030
            client._calls)
2031
2466.2.2 by Andrew Bennetts
Add tests for RemoteTransport.is_readonly in the style of the other remote object tests.
2032
3840.1.1 by Andrew Bennetts
Fix RemoteTransport's translation of errors involving paths; it wasn't passing orig_path to _translate_error.
2033
class TestTransportMkdir(tests.TestCase):
2034
2035
    def test_permissiondenied(self):
2036
        client = FakeClient()
2037
        client.add_error_response('PermissionDenied', 'remote path', 'extra')
2038
        transport = RemoteTransport('bzr://example.com/', medium=False,
2039
                                    _client=client)
2040
        exc = self.assertRaises(
2041
            errors.PermissionDenied, transport.mkdir, 'client path')
2042
        expected_error = errors.PermissionDenied('/client path', 'extra')
2043
        self.assertEqual(expected_error, exc)
2044
2045
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
2046
class TestRemoteSSHTransportAuthentication(tests.TestCaseInTempDir):
2047
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2048
    def test_defaults_to_none(self):
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
2049
        t = RemoteSSHTransport('bzr+ssh://example.com')
4304.2.1 by Vincent Ladeuil
Fix bug #367726 by reverting some default user handling introduced
2050
        self.assertIs(None, t._get_credentials()[0])
3777.1.3 by Aaron Bentley
Use SSH default username from authentication.conf
2051
2052
    def test_uses_authentication_config(self):
2053
        conf = config.AuthenticationConfig()
2054
        conf._get_config().update(
2055
            {'bzr+sshtest': {'scheme': 'ssh', 'user': 'bar', 'host':
2056
            'example.com'}})
2057
        conf._save()
2058
        t = RemoteSSHTransport('bzr+ssh://example.com')
2059
        self.assertEqual('bar', t._get_credentials()[0])
2060
2061
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2062
class TestRemoteRepository(TestRemote):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2063
    """Base for testing RemoteRepository protocol usage.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2064
2065
    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
2066
    what is sent or expected to be require a thoughtful update to these tests
2067
    because they might break compatibility with different-versioned servers.
2068
    """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2069
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2070
    def setup_fake_client_and_repository(self, transport_path):
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2071
        """Create the fake client and repository for testing with.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2072
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2073
        There's no real server here; we just have canned responses sent
2074
        back one by one.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2075
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2076
        :param transport_path: Path below the root of the MemoryTransport
2077
            where the repository will be created.
2078
        """
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2079
        transport = MemoryTransport()
2080
        transport.mkdir(transport_path)
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2081
        client = FakeClient(transport.base)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2082
        transport = transport.clone(transport_path)
2083
        # we do not want bzrdir to make any remote calls
5712.3.17 by Jelmer Vernooij
more fixes.
2084
        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.
2085
            _client=False)
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2086
        repo = RemoteRepository(bzrdir, None, _client=client)
2087
        return repo, client
2088
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
2089
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2090
def remoted_description(format):
2091
    return 'Remote: ' + format.get_format_description()
2092
2093
2094
class TestBranchFormat(tests.TestCase):
2095
2096
    def test_get_format_description(self):
2097
        remote_format = RemoteBranchFormat()
5662.2.2 by Jelmer Vernooij
Move most format registration functions to BranchFormatRegistry.
2098
        real_format = branch.format_registry.get_default()
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2099
        remote_format._network_name = real_format.network_name()
2100
        self.assertEqual(remoted_description(real_format),
2101
            remote_format.get_format_description())
2102
2103
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2104
class TestRepositoryFormat(TestRemoteRepository):
2105
2106
    def test_fast_delta(self):
5546.1.1 by Andrew Bennetts
Remove RepositoryFormatCHK1 and RepositoryFormatCHK2.
2107
        true_name = groupcompress_repo.RepositoryFormat2a().network_name()
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2108
        true_format = RemoteRepositoryFormat()
2109
        true_format._network_name = true_name
2110
        self.assertEqual(True, true_format.fast_deltas)
5757.1.7 by Jelmer Vernooij
Fix more imports.
2111
        false_name = knitpack_repo.RepositoryFormatKnitPack1().network_name()
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2112
        false_format = RemoteRepositoryFormat()
2113
        false_format._network_name = false_name
2114
        self.assertEqual(False, false_format.fast_deltas)
2115
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2116
    def test_get_format_description(self):
2117
        remote_repo_format = RemoteRepositoryFormat()
5651.3.9 by Jelmer Vernooij
Avoid using deprecated functions.
2118
        real_format = repository.format_registry.get_default()
4792.1.1 by Andrew Bennetts
Show real branch/repo format description in 'info -v' over HPSS.
2119
        remote_repo_format._network_name = real_format.network_name()
2120
        self.assertEqual(remoted_description(real_format),
2121
            remote_repo_format.get_format_description())
2122
4183.5.1 by Robert Collins
Add RepositoryFormat.fast_deltas to signal fast delta creation.
2123
6280.3.1 by Jelmer Vernooij
Add remote side of Repository.all_revision_ids.
2124
class TestRepositoryAllRevisionIds(TestRemoteRepository):
2125
2126
    def test_empty(self):
2127
        transport_path = 'quack'
2128
        repo, client = self.setup_fake_client_and_repository(transport_path)
2129
        client.add_success_response_with_body('', 'ok')
2130
        self.assertEquals([], repo.all_revision_ids())
2131
        self.assertEqual(
2132
            [('call_expecting_body', 'Repository.all_revision_ids',
2133
             ('quack/',))],
2134
            client._calls)
2135
2136
    def test_with_some_content(self):
2137
        transport_path = 'quack'
2138
        repo, client = self.setup_fake_client_and_repository(transport_path)
2139
        client.add_success_response_with_body(
2140
            'rev1\nrev2\nanotherrev\n', 'ok')
2141
        self.assertEquals(["rev1", "rev2", "anotherrev"],
2142
            repo.all_revision_ids())
2143
        self.assertEqual(
2144
            [('call_expecting_body', 'Repository.all_revision_ids',
2145
             ('quack/',))],
2146
            client._calls)
2147
2148
2018.12.2 by Andrew Bennetts
Remove some duplicate code in test_remote
2149
class TestRepositoryGatherStats(TestRemoteRepository):
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2150
2151
    def test_revid_none(self):
2152
        # ('ok',), body with revisions and size
2153
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2154
        repo, client = self.setup_fake_client_and_repository(transport_path)
2155
        client.add_success_response_with_body(
2156
            'revisions: 2\nsize: 18\n', 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2157
        result = repo.gather_stats(None)
2158
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
2159
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
2160
             ('quack/','','no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2161
            client._calls)
2162
        self.assertEqual({'revisions': 2, 'size': 18}, result)
2163
2164
    def test_revid_no_committers(self):
2165
        # ('ok',), body without committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2166
        body = ('firstrev: 123456.300 3600\n'
2167
                'latestrev: 654231.400 0\n'
2168
                'revisions: 2\n'
2169
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2170
        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.
2171
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2172
        repo, client = self.setup_fake_client_and_repository(transport_path)
2173
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2174
        result = repo.gather_stats(revid)
2175
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
2176
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
2177
              ('quick/', revid, 'no'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2178
            client._calls)
2179
        self.assertEqual({'revisions': 2, 'size': 18,
2180
                          'firstrev': (123456.300, 3600),
2181
                          'latestrev': (654231.400, 0),},
2182
                         result)
2183
2184
    def test_revid_with_committers(self):
2185
        # ('ok',), body with committers
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2186
        body = ('committers: 128\n'
2187
                'firstrev: 123456.300 3600\n'
2188
                'latestrev: 654231.400 0\n'
2189
                'revisions: 2\n'
2190
                'size: 18\n')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2191
        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.
2192
        revid = u'\xc8'.encode('utf8')
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2193
        repo, client = self.setup_fake_client_and_repository(transport_path)
2194
        client.add_success_response_with_body(body, 'ok')
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2195
        result = repo.gather_stats(revid, True)
2196
        self.assertEqual(
2018.5.153 by Andrew Bennetts
Rename call2 to call_expecting_body, and other small changes prompted by review.
2197
            [('call_expecting_body', 'Repository.gather_stats',
3104.4.2 by Andrew Bennetts
All tests passing.
2198
              ('buick/', revid, 'yes'))],
2018.10.3 by v.ladeuil+lp at free
more tests for gather_stats
2199
            client._calls)
2200
        self.assertEqual({'revisions': 2, 'size': 18,
2201
                          'committers': 128,
2202
                          'firstrev': (123456.300, 3600),
2203
                          'latestrev': (654231.400, 0),},
2204
                         result)
2205
2206
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2207
class TestRepositoryGetGraph(TestRemoteRepository):
2208
2209
    def test_get_graph(self):
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
2210
        # 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.
2211
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2212
        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.
2213
        graph = repo.get_graph()
3835.1.6 by Aaron Bentley
Reduce inefficiency when doing make_parents_provider frequently
2214
        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.
2215
2216
2217
class TestRepositoryGetParentMap(TestRemoteRepository):
2218
2219
    def test_get_parent_map_caching(self):
2220
        # get_parent_map returns from cache until unlock()
2221
        # setup a reponse with two revisions
2222
        r1 = u'\u0e33'.encode('utf8')
2223
        r2 = u'\u0dab'.encode('utf8')
2224
        lines = [' '.join([r2, r1]), r1]
3211.5.2 by Robert Collins
Change RemoteRepository.get_parent_map to use bz2 not gzip for compression.
2225
        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.
2226
2227
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2228
        repo, client = self.setup_fake_client_and_repository(transport_path)
2229
        client.add_success_response_with_body(encoded_body, 'ok')
2230
        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.
2231
        repo.lock_read()
2232
        graph = repo.get_graph()
2233
        parents = graph.get_parent_map([r2])
2234
        self.assertEqual({r2: (r1,)}, parents)
2235
        # locking and unlocking deeper should not reset
2236
        repo.lock_read()
2237
        repo.unlock()
2238
        parents = graph.get_parent_map([r1])
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
2239
        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.
2240
        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.
2241
            [('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
2242
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
2243
              '\n\n0')],
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2244
            client._calls)
2245
        repo.unlock()
2246
        # now we call again, and it should use the second response.
2247
        repo.lock_read()
2248
        graph = repo.get_graph()
3172.5.6 by Robert Collins
Create new smart server verb Repository.get_parent_map.
2249
        parents = graph.get_parent_map([r1])
2250
        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.
2251
        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.
2252
            [('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
2253
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
2254
              '\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.
2255
             ('call_with_body_bytes_expecting_body',
4190.1.6 by Robert Collins
Missed some unit tests.
2256
              'Repository.get_parent_map', ('quack/', 'include-missing:', r1),
2257
              '\n\n0'),
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2258
            ],
2259
            client._calls)
2260
        repo.unlock()
2261
3213.1.2 by Andrew Bennetts
Add test for reconnection if get_parent_map is unknown by the server.
2262
    def test_get_parent_map_reconnects_if_unknown_method(self):
2263
        transport_path = 'quack'
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2264
        rev_id = 'revision-id'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2265
        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.
2266
        client.add_unknown_method_response('Repository.get_parent_map')
2267
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.10 by Andrew Bennetts
Change _is_remote_at_least to _is_remote_before.
2268
        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.
2269
        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.
2270
        self.assertEqual(
3213.1.8 by Andrew Bennetts
Merge from bzr.dev.
2271
            [('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.
2272
              'Repository.get_parent_map',
2273
              ('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.
2274
             ('disconnect medium',),
2275
             ('call_expecting_body', 'Repository.get_revision_graph',
2276
              ('quack/', ''))],
2277
            client._calls)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2278
        # 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.
2279
        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.
2280
        self.assertEqual({rev_id: ('null:',)}, parents)
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2281
2282
    def test_get_parent_map_fallback_parentless_node(self):
2283
        """get_parent_map falls back to get_revision_graph on old servers.  The
2284
        results from get_revision_graph are tweaked to match the get_parent_map
2285
        API.
2286
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
2287
        Specifically, a {key: ()} result from get_revision_graph means "no
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2288
        parents" for that key, which in get_parent_map results should be
3389.1.3 by Andrew Bennetts
Remove XXX from test description.
2289
        represented as {key: ('null:',)}.
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2290
2291
        This is the test for https://bugs.launchpad.net/bzr/+bug/214894
2292
        """
2293
        rev_id = 'revision-id'
2294
        transport_path = 'quack'
3245.4.40 by Andrew Bennetts
Merge from bzr.dev.
2295
        repo, client = self.setup_fake_client_and_repository(transport_path)
2296
        client.add_success_response_with_body(rev_id, 'ok')
3453.4.9 by Andrew Bennetts
Rename _remote_is_not to _remember_remote_is_before.
2297
        client._medium._remember_remote_is_before((1, 2))
3948.3.7 by Martin Pool
Updated tests for RemoteRepository.get_parent_map on old servers.
2298
        parents = repo.get_parent_map([rev_id])
3389.1.2 by Andrew Bennetts
Add test for the bug John found.
2299
        self.assertEqual(
2300
            [('call_expecting_body', 'Repository.get_revision_graph',
2301
             ('quack/', ''))],
2302
            client._calls)
2303
        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.
2304
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
2305
    def test_get_parent_map_unexpected_response(self):
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2306
        repo, client = self.setup_fake_client_and_repository('path')
2307
        client.add_success_response('something unexpected!')
3297.2.3 by Andrew Bennetts
Test the code path that the typo is on.
2308
        self.assertRaises(
2309
            errors.UnexpectedSmartServerResponse,
2310
            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.
2311
4190.1.1 by Robert Collins
Negatively cache misses during read-locks in RemoteRepository.
2312
    def test_get_parent_map_negative_caches_missing_keys(self):
2313
        self.setup_smart_server_with_call_log()
2314
        repo = self.make_repository('foo')
2315
        self.assertIsInstance(repo, RemoteRepository)
2316
        repo.lock_read()
2317
        self.addCleanup(repo.unlock)
2318
        self.reset_smart_call_log()
2319
        graph = repo.get_graph()
2320
        self.assertEqual({},
2321
            graph.get_parent_map(['some-missing', 'other-missing']))
2322
        self.assertLength(1, self.hpss_calls)
2323
        # No call if we repeat this
2324
        self.reset_smart_call_log()
2325
        graph = repo.get_graph()
2326
        self.assertEqual({},
2327
            graph.get_parent_map(['some-missing', 'other-missing']))
2328
        self.assertLength(0, self.hpss_calls)
2329
        # Asking for more unknown keys makes a request.
2330
        self.reset_smart_call_log()
2331
        graph = repo.get_graph()
2332
        self.assertEqual({},
2333
            graph.get_parent_map(['some-missing', 'other-missing',
2334
                'more-missing']))
2335
        self.assertLength(1, self.hpss_calls)
2336
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2337
    def disableExtraResults(self):
4985.1.5 by Vincent Ladeuil
Deploying the new overrideAttr facility further reduces the complexity
2338
        self.overrideAttr(SmartServerRepositoryGetParentMap,
2339
                          'no_extra_results', True)
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2340
4214.2.5 by Andrew Bennetts
Fix the bug.
2341
    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.
2342
        self.setup_smart_server_with_call_log()
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2343
        # 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.
2344
        builder = self.make_branch_builder('foo')
2345
        builder.start_series()
2346
        builder.build_snapshot('first', None, [
2347
            ('add', ('', 'root-id', 'directory', ''))])
2348
        builder.finish_series()
2349
        branch = builder.get_branch()
2350
        repo = branch.repository
2351
        self.assertIsInstance(repo, RemoteRepository)
4214.2.3 by Andrew Bennetts
Further simplify test case, and add more comments.
2352
        # Stop the server from sending extra results.
2353
        self.disableExtraResults()
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2354
        repo.lock_read()
2355
        self.addCleanup(repo.unlock)
2356
        self.reset_smart_call_log()
2357
        graph = repo.get_graph()
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2358
        # Query for 'first' and 'null:'.  Because 'null:' is a parent of
4214.2.5 by Andrew Bennetts
Fix the bug.
2359
        # 'first' it will be a candidate for the stop_keys of subsequent
2360
        # requests, and because 'null:' was queried but not returned it will be
2361
        # cached as missing.
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2362
        self.assertEqual({'first': ('null:',)},
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2363
            graph.get_parent_map(['first', 'null:']))
2364
        # Now query for another key.  This request will pass along a recipe of
2365
        # start and stop keys describing the already cached results, and this
4214.2.5 by Andrew Bennetts
Fix the bug.
2366
        # 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.
2367
        # error from the server).
4214.2.5 by Andrew Bennetts
Fix the bug.
2368
        self.assertEqual({}, graph.get_parent_map(['another-key']))
4214.2.3 by Andrew Bennetts
Further simplify test case, and add more comments.
2369
        # This assertion guards against disableExtraResults silently failing to
2370
        # work, thus invalidating the test.
4214.2.4 by Andrew Bennetts
Further simplify the test to reproduce the bug.
2371
        self.assertLength(2, self.hpss_calls)
4214.2.1 by Andrew Bennetts
A long but failing test for the get_parent_map RPC bug.
2372
4190.1.4 by Robert Collins
Cache ghosts when we can get them from a RemoteRepository in get_parent_map.
2373
    def test_get_parent_map_gets_ghosts_from_result(self):
2374
        # asking for a revision should negatively cache close ghosts in its
2375
        # ancestry.
2376
        self.setup_smart_server_with_call_log()
2377
        tree = self.make_branch_and_memory_tree('foo')
2378
        tree.lock_write()
2379
        try:
2380
            builder = treebuilder.TreeBuilder()
2381
            builder.start_tree(tree)
2382
            builder.build([])
2383
            builder.finish_tree()
2384
            tree.set_parent_ids(['non-existant'], allow_leftmost_as_ghost=True)
2385
            rev_id = tree.commit('')
2386
        finally:
2387
            tree.unlock()
2388
        tree.lock_read()
2389
        self.addCleanup(tree.unlock)
2390
        repo = tree.branch.repository
2391
        self.assertIsInstance(repo, RemoteRepository)
2392
        # ask for rev_id
2393
        repo.get_parent_map([rev_id])
2394
        self.reset_smart_call_log()
2395
        # Now asking for rev_id's ghost parent should not make calls
2396
        self.assertEqual({}, repo.get_parent_map(['non-existant']))
2397
        self.assertLength(0, self.hpss_calls)
2398
6015.24.4 by John Arbash Meinel
For it to all work properly, we have to expose get_parent_map_cached on RemoteRepository.
2399
    def test_exposes_get_cached_parent_map(self):
2400
        """RemoteRepository exposes get_cached_parent_map from
2401
        _unstacked_provider
2402
        """
2403
        r1 = u'\u0e33'.encode('utf8')
2404
        r2 = u'\u0dab'.encode('utf8')
2405
        lines = [' '.join([r2, r1]), r1]
2406
        encoded_body = bz2.compress('\n'.join(lines))
2407
2408
        transport_path = 'quack'
2409
        repo, client = self.setup_fake_client_and_repository(transport_path)
2410
        client.add_success_response_with_body(encoded_body, 'ok')
2411
        repo.lock_read()
6015.24.5 by John Arbash Meinel
Bug #388269.
2412
        # get_cached_parent_map should *not* trigger an RPC
2413
        self.assertEqual({}, repo.get_cached_parent_map([r1]))
2414
        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.
2415
        self.assertEqual({r2: (r1,)}, repo.get_parent_map([r2]))
2416
        self.assertEqual({r1: (NULL_REVISION,)},
2417
            repo.get_cached_parent_map([r1]))
2418
        self.assertEqual(
2419
            [('call_with_body_bytes_expecting_body',
2420
              'Repository.get_parent_map', ('quack/', 'include-missing:', r2),
2421
              '\n\n0')],
2422
            client._calls)
2423
        repo.unlock()
2424
3172.5.4 by Robert Collins
Implement get_parent_map for RemoteRepository with caching, based on get_revision_graph.
2425
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
2426
class TestGetParentMapAllowsNew(tests.TestCaseWithTransport):
2427
2428
    def test_allows_new_revisions(self):
2429
        """get_parent_map's results can be updated by commit."""
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
2430
        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,
2431
        self.start_server(smart_server)
3835.1.15 by Aaron Bentley
Allow miss caching to be disabled.
2432
        self.make_branch('branch')
2433
        branch = Branch.open(smart_server.get_url() + '/branch')
2434
        tree = branch.create_checkout('tree', lightweight=True)
2435
        tree.lock_write()
2436
        self.addCleanup(tree.unlock)
2437
        graph = tree.branch.repository.get_graph()
2438
        # This provides an opportunity for the missing rev-id to be cached.
2439
        self.assertEqual({}, graph.get_parent_map(['rev1']))
2440
        tree.commit('message', rev_id='rev1')
2441
        graph = tree.branch.repository.get_graph()
2442
        self.assertEqual({'rev1': ('null:',)}, graph.get_parent_map(['rev1']))
2443
2444
3948.3.9 by Martin Pool
Undelete TestRepositoryGetRevisionGraph but make it use private client methods to simulate old clients
2445
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
2446
2447
    def test_null_revision(self):
2448
        # a null revision has the predictable result {}, we should have no wire
2449
        # traffic when calling it with this argument
2450
        transport_path = 'empty'
2451
        repo, client = self.setup_fake_client_and_repository(transport_path)
2452
        client.add_success_response('notused')
2453
        # actual RemoteRepository.get_revision_graph is gone, but there's an
2454
        # equivalent private method for testing
2455
        result = repo._get_revision_graph(NULL_REVISION)
2456
        self.assertEqual([], client._calls)
2457
        self.assertEqual({}, result)
2458
2459
    def test_none_revision(self):
2460
        # with none we want the entire graph
2461
        r1 = u'\u0e33'.encode('utf8')
2462
        r2 = u'\u0dab'.encode('utf8')
2463
        lines = [' '.join([r2, r1]), r1]
2464
        encoded_body = '\n'.join(lines)
2465
2466
        transport_path = 'sinhala'
2467
        repo, client = self.setup_fake_client_and_repository(transport_path)
2468
        client.add_success_response_with_body(encoded_body, 'ok')
2469
        # actual RemoteRepository.get_revision_graph is gone, but there's an
2470
        # equivalent private method for testing
2471
        result = repo._get_revision_graph(None)
2472
        self.assertEqual(
2473
            [('call_expecting_body', 'Repository.get_revision_graph',
2474
             ('sinhala/', ''))],
2475
            client._calls)
2476
        self.assertEqual({r1: (), r2: (r1, )}, result)
2477
2478
    def test_specific_revision(self):
2479
        # with a specific revision we want the graph for that
2480
        # with none we want the entire graph
2481
        r11 = u'\u0e33'.encode('utf8')
2482
        r12 = u'\xc9'.encode('utf8')
2483
        r2 = u'\u0dab'.encode('utf8')
2484
        lines = [' '.join([r2, r11, r12]), r11, r12]
2485
        encoded_body = '\n'.join(lines)
2486
2487
        transport_path = 'sinhala'
2488
        repo, client = self.setup_fake_client_and_repository(transport_path)
2489
        client.add_success_response_with_body(encoded_body, 'ok')
2490
        result = repo._get_revision_graph(r2)
2491
        self.assertEqual(
2492
            [('call_expecting_body', 'Repository.get_revision_graph',
2493
             ('sinhala/', r2))],
2494
            client._calls)
2495
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
2496
2497
    def test_no_such_revision(self):
2498
        revid = '123'
2499
        transport_path = 'sinhala'
2500
        repo, client = self.setup_fake_client_and_repository(transport_path)
2501
        client.add_error_response('nosuchrevision', revid)
2502
        # also check that the right revision is reported in the error
2503
        self.assertRaises(errors.NoSuchRevision,
2504
            repo._get_revision_graph, revid)
2505
        self.assertEqual(
2506
            [('call_expecting_body', 'Repository.get_revision_graph',
2507
             ('sinhala/', revid))],
2508
            client._calls)
2509
2510
    def test_unexpected_error(self):
2511
        revid = '123'
2512
        transport_path = 'sinhala'
2513
        repo, client = self.setup_fake_client_and_repository(transport_path)
2514
        client.add_error_response('AnUnexpectedError')
2515
        e = self.assertRaises(errors.UnknownErrorFromSmartServer,
2516
            repo._get_revision_graph, revid)
2517
        self.assertEqual(('AnUnexpectedError',), e.error_tuple)
2518
2519
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2520
class TestRepositoryGetRevIdForRevno(TestRemoteRepository):
2521
2522
    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.
2523
        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.
2524
        client.add_expected_call(
2525
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2526
            'success', ('ok', 'rev-five'))
2527
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2528
        self.assertEqual((True, 'rev-five'), result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
2529
        self.assertFinished(client)
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2530
2531
    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.
2532
        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.
2533
        client.add_expected_call(
2534
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2535
            'success', ('history-incomplete', 10, 'rev-ten'))
2536
        result = repo.get_rev_id_for_revno(5, (42, 'rev-foo'))
2537
        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.
2538
        self.assertFinished(client)
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2539
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.
2540
    def test_history_incomplete_with_fallback(self):
2541
        """A 'history-incomplete' response causes the fallback repository to be
2542
        queried too, if one is set.
2543
        """
2544
        # Make a repo with a fallback repo, both using a FakeClient.
2545
        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.
2546
            ('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.
2547
        repo, client = self.setup_fake_client_and_repository('quack')
2548
        repo._format = format
2549
        fallback_repo, ignored = self.setup_fake_client_and_repository(
2550
            'fallback')
2551
        fallback_repo._client = client
5158.4.3 by Andrew Bennetts
Fix test_remote tests that accidentally assumed it was ok to stack mismatched formats.
2552
        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.
2553
        repo.add_fallback_repository(fallback_repo)
2554
        # First the client should ask the primary repo
2555
        client.add_expected_call(
2556
            'Repository.get_rev_id_for_revno', ('quack/', 1, (42, 'rev-foo')),
2557
            'success', ('history-incomplete', 2, 'rev-two'))
2558
        # Then it should ask the fallback, using revno/revid from the
2559
        # history-incomplete response as the known revno/revid.
2560
        client.add_expected_call(
2561
            'Repository.get_rev_id_for_revno',('fallback/', 1, (2, 'rev-two')),
2562
            'success', ('ok', 'rev-one'))
2563
        result = repo.get_rev_id_for_revno(1, (42, 'rev-foo'))
2564
        self.assertEqual((True, 'rev-one'), result)
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
2565
        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.
2566
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2567
    def test_nosuchrevision(self):
2568
        # 'nosuchrevision' is returned when the known-revid is not found in the
2569
        # 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.
2570
        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.
2571
        client.add_expected_call(
2572
            'Repository.get_rev_id_for_revno', ('quack/', 5, (42, 'rev-foo')),
2573
            'error', ('nosuchrevision', 'rev-foo'))
2574
        self.assertRaises(
2575
            errors.NoSuchRevision,
2576
            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.
2577
        self.assertFinished(client)
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2578
4634.69.1 by Andrew Bennetts
Apply @needs_read_lock to RemoteBranch.get_rev_id.
2579
    def test_branch_fallback_locking(self):
2580
        """RemoteBranch.get_rev_id takes a read lock, and tries to call the
2581
        get_rev_id_for_revno verb.  If the verb is unknown the VFS fallback
2582
        will be invoked, which will fail if the repo is unlocked.
2583
        """
2584
        self.setup_smart_server_with_call_log()
2585
        tree = self.make_branch_and_memory_tree('.')
2586
        tree.lock_write()
5222.1.1 by Aaron Bentley
Refuse to commit trees with no root.
2587
        tree.add('')
4634.69.1 by Andrew Bennetts
Apply @needs_read_lock to RemoteBranch.get_rev_id.
2588
        rev1 = tree.commit('First')
2589
        rev2 = tree.commit('Second')
2590
        tree.unlock()
2591
        branch = tree.branch
2592
        self.assertFalse(branch.is_locked())
2593
        self.reset_smart_call_log()
2594
        verb = 'Repository.get_rev_id_for_revno'
2595
        self.disable_verb(verb)
2596
        self.assertEqual(rev1, branch.get_rev_id(1))
2597
        self.assertLength(1, [call for call in self.hpss_calls if
2598
                              call.call.method == verb])
2599
4419.2.7 by Andrew Bennetts
Add unit tests for RemoteRepository.get_rev_id_for_revno.
2600
6265.1.1 by Jelmer Vernooij
Add new HPSS call ``Repository.has_signature_for_revision_id``.
2601
class TestRepositoryHasSignatureForRevisionId(TestRemoteRepository):
2602
2603
    def test_has_signature_for_revision_id(self):
2604
        # ('yes', ) for Repository.has_signature_for_revision_id -> 'True'.
2605
        transport_path = 'quack'
2606
        repo, client = self.setup_fake_client_and_repository(transport_path)
2607
        client.add_success_response('yes')
2608
        result = repo.has_signature_for_revision_id('A')
2609
        self.assertEqual(
2610
            [('call', 'Repository.has_signature_for_revision_id',
2611
              ('quack/', 'A'))],
2612
            client._calls)
2613
        self.assertEqual(True, result)
2614
2615
    def test_is_not_shared(self):
2616
        # ('no', ) for Repository.has_signature_for_revision_id -> 'False'.
2617
        transport_path = 'qwack'
2618
        repo, client = self.setup_fake_client_and_repository(transport_path)
2619
        client.add_success_response('no')
2620
        result = repo.has_signature_for_revision_id('A')
2621
        self.assertEqual(
2622
            [('call', 'Repository.has_signature_for_revision_id',
2623
              ('qwack/', 'A'))],
2624
            client._calls)
2625
        self.assertEqual(False, result)
2626
2627
2018.5.67 by Wouter van Heyst
Implement RemoteRepository.get_revision_graph (Wouter van Heyst, Robert Collins)
2628
class TestRepositoryIsShared(TestRemoteRepository):
2629
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2630
    def test_is_shared(self):
2631
        # ('yes', ) for Repository.is_shared -> 'True'.
2632
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2633
        repo, client = self.setup_fake_client_and_repository(transport_path)
2634
        client.add_success_response('yes')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2635
        result = repo.is_shared()
2636
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2637
            [('call', 'Repository.is_shared', ('quack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2638
            client._calls)
2639
        self.assertEqual(True, result)
2640
2641
    def test_is_not_shared(self):
2642
        # ('no', ) for Repository.is_shared -> 'False'.
2643
        transport_path = 'qwack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2644
        repo, client = self.setup_fake_client_and_repository(transport_path)
2645
        client.add_success_response('no')
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2646
        result = repo.is_shared()
2647
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2648
            [('call', 'Repository.is_shared', ('qwack/',))],
2018.5.57 by Robert Collins
Implement RemoteRepository.is_shared (Robert Collins, Vincent Ladeuil).
2649
            client._calls)
2650
        self.assertEqual(False, result)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2651
2652
6263.2.1 by Jelmer Vernooij
Add hpss call ``Repository.make_working_trees``
2653
class TestRepositoryMakeWorkingTrees(TestRemoteRepository):
2654
2655
    def test_make_working_trees(self):
2656
        # ('yes', ) for Repository.make_working_trees -> 'True'.
2657
        transport_path = 'quack'
2658
        repo, client = self.setup_fake_client_and_repository(transport_path)
2659
        client.add_success_response('yes')
2660
        result = repo.make_working_trees()
2661
        self.assertEqual(
2662
            [('call', 'Repository.make_working_trees', ('quack/',))],
2663
            client._calls)
2664
        self.assertEqual(True, result)
2665
2666
    def test_no_working_trees(self):
2667
        # ('no', ) for Repository.make_working_trees -> 'False'.
2668
        transport_path = 'qwack'
2669
        repo, client = self.setup_fake_client_and_repository(transport_path)
2670
        client.add_success_response('no')
2671
        result = repo.make_working_trees()
2672
        self.assertEqual(
2673
            [('call', 'Repository.make_working_trees', ('qwack/',))],
2674
            client._calls)
2675
        self.assertEqual(False, result)
2676
2677
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2678
class TestRepositoryLockWrite(TestRemoteRepository):
2679
2680
    def test_lock_write(self):
2681
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2682
        repo, client = self.setup_fake_client_and_repository(transport_path)
2683
        client.add_success_response('ok', 'a token')
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2684
        token = repo.lock_write().repository_token
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2685
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2686
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2687
            client._calls)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2688
        self.assertEqual('a token', token)
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2689
2690
    def test_lock_write_already_locked(self):
2691
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2692
        repo, client = self.setup_fake_client_and_repository(transport_path)
2693
        client.add_error_response('LockContention')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2694
        self.assertRaises(errors.LockContention, repo.lock_write)
2695
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2696
            [('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.
2697
            client._calls)
2698
2699
    def test_lock_write_unlockable(self):
2700
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2701
        repo, client = self.setup_fake_client_and_repository(transport_path)
2702
        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.
2703
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
2704
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2705
            [('call', 'Repository.lock_write', ('quack/', ''))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2706
            client._calls)
2707
2708
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2709
class TestRepositorySetMakeWorkingTrees(TestRemoteRepository):
2710
2711
    def test_backwards_compat(self):
2712
        self.setup_smart_server_with_call_log()
2713
        repo = self.make_repository('.')
2714
        self.reset_smart_call_log()
2715
        verb = 'Repository.set_make_working_trees'
2716
        self.disable_verb(verb)
2717
        repo.set_make_working_trees(True)
2718
        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.
2719
            call.call.method == verb])
4017.3.4 by Robert Collins
Create a verb for Repository.set_make_working_trees.
2720
        self.assertEqual(1, call_count)
2721
2722
    def test_current(self):
2723
        transport_path = 'quack'
2724
        repo, client = self.setup_fake_client_and_repository(transport_path)
2725
        client.add_expected_call(
2726
            'Repository.set_make_working_trees', ('quack/', 'True'),
2727
            'success', ('ok',))
2728
        client.add_expected_call(
2729
            'Repository.set_make_working_trees', ('quack/', 'False'),
2730
            'success', ('ok',))
2731
        repo.set_make_working_trees(True)
2732
        repo.set_make_working_trees(False)
2733
2734
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2735
class TestRepositoryUnlock(TestRemoteRepository):
2736
2737
    def test_unlock(self):
2738
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2739
        repo, client = self.setup_fake_client_and_repository(transport_path)
2740
        client.add_success_response('ok', 'a token')
2741
        client.add_success_response('ok')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2742
        repo.lock_write()
2743
        repo.unlock()
2744
        self.assertEqual(
3104.4.2 by Andrew Bennetts
All tests passing.
2745
            [('call', 'Repository.lock_write', ('quack/', '')),
2746
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2747
            client._calls)
2748
2749
    def test_unlock_wrong_token(self):
2750
        # If somehow the token is wrong, unlock will raise TokenMismatch.
2751
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2752
        repo, client = self.setup_fake_client_and_repository(transport_path)
2753
        client.add_success_response('ok', 'a token')
2754
        client.add_error_response('TokenMismatch')
2018.5.78 by Andrew Bennetts
Implement RemoteRepository.lock_write/unlock to expect and send tokens over the
2755
        repo.lock_write()
2756
        self.assertRaises(errors.TokenMismatch, repo.unlock)
2757
2758
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2759
class TestRepositoryHasRevision(TestRemoteRepository):
2760
2761
    def test_none(self):
2762
        # repo.has_revision(None) should not cause any traffic.
2763
        transport_path = 'quack'
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
2764
        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.
2765
2766
        # The null revision is always there, so has_revision(None) == True.
3172.3.3 by Robert Collins
Missed one occurence of None -> NULL_REVISION.
2767
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
2018.14.1 by Andrew Bennetts
Update to current hpss branch? Fix lots of test failures.
2768
2769
        # The remote repo shouldn't be accessed.
2770
        self.assertEqual([], client._calls)
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2771
2772
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2773
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.
2774
    """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.
2775
    tests.
2776
    """
2777
    
2778
    def checkInsertEmptyStream(self, repo, client):
2779
        """Insert an empty stream, checking the result.
2780
2781
        This checks that there are no resume_tokens or missing_keys, and that
2782
        the client is finished.
2783
        """
2784
        sink = repo._get_sink()
5651.3.9 by Jelmer Vernooij
Avoid using deprecated functions.
2785
        fmt = repository.format_registry.get_default()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2786
        resume_tokens, missing_keys = sink.insert_stream([], fmt, [])
2787
        self.assertEqual([], resume_tokens)
2788
        self.assertEqual(set(), missing_keys)
2789
        self.assertFinished(client)
2790
2791
2792
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.
2793
    """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).
2794
    not available.
2795
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.
2796
    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).
2797
    """
2798
2799
    def setUp(self):
2800
        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.
2801
        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).
2802
2803
    def test_unlocked_repo(self):
2804
        transport_path = 'quack'
2805
        repo, client = self.setup_fake_client_and_repository(transport_path)
2806
        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.
2807
            'Repository.insert_stream_1.19', ('quack/', ''),
2808
            '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).
2809
        client.add_expected_call(
2810
            'Repository.insert_stream', ('quack/', ''),
2811
            'success', ('ok',))
2812
        client.add_expected_call(
2813
            'Repository.insert_stream', ('quack/', ''),
2814
            'success', ('ok',))
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2815
        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).
2816
2817
    def test_locked_repo_with_no_lock_token(self):
2818
        transport_path = 'quack'
2819
        repo, client = self.setup_fake_client_and_repository(transport_path)
2820
        client.add_expected_call(
2821
            'Repository.lock_write', ('quack/', ''),
2822
            'success', ('ok', ''))
2823
        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.
2824
            'Repository.insert_stream_1.19', ('quack/', ''),
2825
            '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).
2826
        client.add_expected_call(
2827
            'Repository.insert_stream', ('quack/', ''),
2828
            'success', ('ok',))
2829
        client.add_expected_call(
2830
            'Repository.insert_stream', ('quack/', ''),
2831
            'success', ('ok',))
2832
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2833
        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).
2834
2835
    def test_locked_repo_with_lock_token(self):
2836
        transport_path = 'quack'
2837
        repo, client = self.setup_fake_client_and_repository(transport_path)
2838
        client.add_expected_call(
2839
            'Repository.lock_write', ('quack/', ''),
2840
            'success', ('ok', 'a token'))
2841
        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.
2842
            'Repository.insert_stream_1.19', ('quack/', '', 'a token'),
2843
            '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).
2844
        client.add_expected_call(
2845
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2846
            'success', ('ok',))
2847
        client.add_expected_call(
2848
            'Repository.insert_stream_locked', ('quack/', '', 'a token'),
2849
            'success', ('ok',))
2850
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2851
        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).
2852
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2853
    def test_stream_with_inventory_deltas(self):
4476.3.71 by Andrew Bennetts
Clearer comments prompted by Robert's review.
2854
        """'inventory-deltas' substreams cannot be sent to the
2855
        Repository.insert_stream verb, because not all servers that implement
2856
        that verb will accept them.  So when one is encountered the RemoteSink
2857
        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.
2858
        """
2859
        transport_path = 'quack'
2860
        repo, client = self.setup_fake_client_and_repository(transport_path)
2861
        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.
2862
            'Repository.insert_stream_1.19', ('quack/', ''),
2863
            '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.
2864
        client.add_expected_call(
2865
            'Repository.insert_stream', ('quack/', ''),
2866
            'success', ('ok',))
2867
        client.add_expected_call(
2868
            'Repository.insert_stream', ('quack/', ''),
2869
            'success', ('ok',))
2870
        # Create a fake real repository for insert_stream to fall back on, so
2871
        # that we can directly see the records the RemoteSink passes to the
2872
        # real sink.
2873
        class FakeRealSink:
2874
            def __init__(self):
2875
                self.records = []
2876
            def insert_stream(self, stream, src_format, resume_tokens):
2877
                for substream_kind, substream in stream:
2878
                    self.records.append(
2879
                        (substream_kind, [record.key for record in substream]))
2880
                return ['fake tokens'], ['fake missing keys']
2881
        fake_real_sink = FakeRealSink()
2882
        class FakeRealRepository:
2883
            def _get_sink(self):
2884
                return fake_real_sink
4634.35.20 by Andrew Bennetts
Fix test_remote.
2885
            def is_in_write_group(self):
2886
                return False
2887
            def refresh_data(self):
2888
                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.
2889
        repo._real_repository = FakeRealRepository()
2890
        sink = repo._get_sink()
5651.3.9 by Jelmer Vernooij
Avoid using deprecated functions.
2891
        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.
2892
        stream = self.make_stream_with_inv_deltas(fmt)
2893
        resume_tokens, missing_keys = sink.insert_stream(stream, fmt, [])
2894
        # Every record from the first inventory delta should have been sent to
2895
        # the VFS sink.
2896
        expected_records = [
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2897
            ('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.
2898
            ('texts', [('some-rev', 'some-file')])]
2899
        self.assertEqual(expected_records, fake_real_sink.records)
2900
        # The return values from the real sink's insert_stream are propagated
2901
        # back to the original caller.
2902
        self.assertEqual(['fake tokens'], resume_tokens)
2903
        self.assertEqual(['fake missing keys'], missing_keys)
4476.3.40 by Andrew Bennetts
Merge bzr.dev.
2904
        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.
2905
2906
    def make_stream_with_inv_deltas(self, fmt):
2907
        """Make a simple stream with an inventory delta followed by more
2908
        records and more substreams to test that all records and substreams
2909
        from that point on are used.
2910
2911
        This sends, in order:
2912
           * inventories substream: rev1, rev2, rev3.  rev2 and rev3 are
2913
             inventory-deltas.
2914
           * texts substream: (some-rev, some-file)
2915
        """
2916
        # 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.
2917
        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.
2918
        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.
2919
        def stream_with_inv_delta():
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2920
            yield ('inventories', inventories_substream())
2921
            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.
2922
            yield ('texts', [
2923
                versionedfile.FulltextContentFactory(
2924
                    ('some-rev', 'some-file'), (), None, 'content')])
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2925
        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.
2926
            # An empty inventory fulltext.  This will be streamed normally.
2927
            text = fmt._serializer.write_inventory_to_string(inv)
2928
            yield versionedfile.FulltextContentFactory(
2929
                ('rev1',), (), None, text)
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2930
        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.
2931
            # An inventory delta.  This can't be streamed via this verb, so it
2932
            # will trigger a fallback to VFS insert_stream.
2933
            entry = inv.make_entry(
2934
                'directory', 'newdir', inv.root.file_id, 'newdir-id')
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2935
            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.
2936
            delta = [(None, 'newdir', 'newdir-id', entry)]
4476.3.76 by Andrew Bennetts
Split out InventoryDeltaDeserializer from InventoryDeltaSerializer.
2937
            serializer = inventory_delta.InventoryDeltaSerializer(
2938
                versioned_root=True, tree_references=False)
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2939
            lines = serializer.delta_to_lines('rev1', 'rev2', delta)
2940
            yield versionedfile.ChunkedContentFactory(
2941
                ('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.
2942
            # Another delta.
4476.3.56 by Andrew Bennetts
Update test_stream_with_inventory_deltas for inventory-deltas substream.
2943
            lines = serializer.delta_to_lines('rev1', 'rev3', delta)
2944
            yield versionedfile.ChunkedContentFactory(
2945
                ('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.
2946
        return stream_with_inv_delta()
2947
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).
2948
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
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).
2950
2951
    def test_unlocked_repo(self):
2952
        transport_path = 'quack'
2953
        repo, client = self.setup_fake_client_and_repository(transport_path)
2954
        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.
2955
            '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).
2956
            'success', ('ok',))
2957
        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.
2958
            '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).
2959
            'success', ('ok',))
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2960
        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).
2961
2962
    def test_locked_repo_with_no_lock_token(self):
2963
        transport_path = 'quack'
2964
        repo, client = self.setup_fake_client_and_repository(transport_path)
2965
        client.add_expected_call(
2966
            'Repository.lock_write', ('quack/', ''),
2967
            'success', ('ok', ''))
2968
        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.
2969
            '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).
2970
            'success', ('ok',))
2971
        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.
2972
            '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).
2973
            'success', ('ok',))
2974
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2975
        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).
2976
2977
    def test_locked_repo_with_lock_token(self):
2978
        transport_path = 'quack'
2979
        repo, client = self.setup_fake_client_and_repository(transport_path)
2980
        client.add_expected_call(
2981
            'Repository.lock_write', ('quack/', ''),
2982
            'success', ('ok', 'a token'))
2983
        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.
2984
            '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).
2985
            'success', ('ok',))
2986
        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.
2987
            '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.
2988
            'success', ('ok',))
2989
        repo.lock_write()
4476.3.79 by Andrew Bennetts
Remove a bit of duplication from Repository.insert_stream* tests.
2990
        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.
2991
2992
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
2993
class TestRepositoryTarball(TestRemoteRepository):
2994
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
2995
    # This is a canned tarball reponse we can validate against
2018.18.18 by Martin Pool
reformat
2996
    tarball_content = (
2018.18.23 by Martin Pool
review cleanups
2997
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
2998
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
2999
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
3000
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
3001
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
3002
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
3003
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
3004
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
3005
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
3006
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
3007
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
3008
        'nWQ7QH/F3JFOFCQ0aSPfA='
3009
        ).decode('base64')
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
3010
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
3011
    def test_repository_tarball(self):
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
3012
        # Test that Repository.tarball generates the right operations
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
3013
        transport_path = 'repo'
2018.18.14 by Martin Pool
merge hpss again; restore incorrectly removed RemoteRepository.break_lock
3014
        expected_calls = [('call_expecting_body', 'Repository.tarball',
3104.4.2 by Andrew Bennetts
All tests passing.
3015
                           ('repo/', 'bz2',),),
2018.18.7 by Martin Pool
(broken) Start addng client proxy test for Repository.tarball
3016
            ]
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
3017
        repo, client = self.setup_fake_client_and_repository(transport_path)
3018
        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
3019
        # Now actually ask for the tarball
3245.4.24 by Andrew Bennetts
Consistently raise errors from the server as ErrorFromSmartServer exceptions.
3020
        tarball_file = repo._get_tarball('bz2')
2018.18.25 by Martin Pool
Repository.tarball fixes for python2.4
3021
        try:
3022
            self.assertEqual(expected_calls, client._calls)
3023
            self.assertEqual(self.tarball_content, tarball_file.read())
3024
        finally:
3025
            tarball_file.close()
2018.18.9 by Martin Pool
remote Repository.tarball builds a temporary directory and tars that
3026
3027
3028
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
3029
    """RemoteRepository.copy_content_into optimizations"""
3030
2018.18.10 by Martin Pool
copy_content_into from Remote repositories by using temporary directories on both ends.
3031
    def test_copy_content_remote_to_local(self):
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
3032
        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.
3033
        src_repo = self.make_repository('repo1')
3034
        src_repo = repository.Repository.open(self.get_url('repo1'))
3035
        # At the moment the tarball-based copy_content_into can't write back
3036
        # into a smart server.  It would be good if it could upload the
3037
        # tarball; once that works we'd have to create repositories of
3038
        # different formats. -- mbp 20070410
3039
        dest_url = self.get_vfs_only_url('repo2')
3040
        dest_bzrdir = BzrDir.create(dest_url)
3041
        dest_repo = dest_bzrdir.create_repository()
3042
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
3043
        self.assertTrue(isinstance(src_repo, RemoteRepository))
3044
        src_repo.copy_content_into(dest_repo)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3045
3046
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3047
class _StubRealPackRepository(object):
3048
3049
    def __init__(self, calls):
4145.1.6 by Robert Collins
More test fallout, but all caught now.
3050
        self.calls = calls
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3051
        self._pack_collection = _StubPackCollection(calls)
3052
4145.1.6 by Robert Collins
More test fallout, but all caught now.
3053
    def is_in_write_group(self):
3054
        return False
3055
3056
    def refresh_data(self):
3057
        self.calls.append(('pack collection reload_pack_names',))
3058
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3059
3060
class _StubPackCollection(object):
3061
3062
    def __init__(self, calls):
3063
        self.calls = calls
3064
3065
    def autopack(self):
3066
        self.calls.append(('pack collection autopack',))
3067
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3068
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3069
class TestRemotePackRepositoryAutoPack(TestRemoteRepository):
3070
    """Tests for RemoteRepository.autopack implementation."""
3071
3072
    def test_ok(self):
3073
        """When the server returns 'ok' and there's no _real_repository, then
3074
        nothing else happens: the autopack method is done.
3075
        """
3076
        transport_path = 'quack'
3077
        repo, client = self.setup_fake_client_and_repository(transport_path)
3078
        client.add_expected_call(
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
3079
            'PackRepository.autopack', ('quack/',), 'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3080
        repo.autopack()
4523.3.1 by Andrew Bennetts
Change FakeClient.finished_test into a more typical assertion method on TestRemote.
3081
        self.assertFinished(client)
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3082
3083
    def test_ok_with_real_repo(self):
3084
        """When the server returns 'ok' and there is a _real_repository, then
3085
        the _real_repository's reload_pack_name's method will be called.
3086
        """
3087
        transport_path = 'quack'
3088
        repo, client = self.setup_fake_client_and_repository(transport_path)
3089
        client.add_expected_call(
3090
            'PackRepository.autopack', ('quack/',),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
3091
            'success', ('ok',))
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3092
        repo._real_repository = _StubRealPackRepository(client._calls)
3093
        repo.autopack()
3094
        self.assertEqual(
3095
            [('call', 'PackRepository.autopack', ('quack/',)),
3801.1.13 by Andrew Bennetts
Revert returning of pack-names from the RPC.
3096
             ('pack collection reload_pack_names',)],
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3097
            client._calls)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3098
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3099
    def test_backwards_compatibility(self):
3100
        """If the server does not recognise the PackRepository.autopack verb,
3101
        fallback to the real_repository's implementation.
3102
        """
3103
        transport_path = 'quack'
3104
        repo, client = self.setup_fake_client_and_repository(transport_path)
3105
        client.add_unknown_method_response('PackRepository.autopack')
3106
        def stub_ensure_real():
3107
            client._calls.append(('_ensure_real',))
3108
            repo._real_repository = _StubRealPackRepository(client._calls)
3109
        repo._ensure_real = stub_ensure_real
3110
        repo.autopack()
3111
        self.assertEqual(
3112
            [('call', 'PackRepository.autopack', ('quack/',)),
3113
             ('_ensure_real',),
3114
             ('pack collection autopack',)],
3115
            client._calls)
3116
5677.2.2 by Martin
Give clearer message when remote server reports a MemoryError
3117
    def test_oom_error_reporting(self):
3118
        """An out-of-memory condition on the server is reported clearly"""
3119
        transport_path = 'quack'
3120
        repo, client = self.setup_fake_client_and_repository(transport_path)
3121
        client.add_expected_call(
3122
            'PackRepository.autopack', ('quack/',),
3123
            'error', ('MemoryError',))
3124
        err = self.assertRaises(errors.BzrError, repo.autopack)
3125
        self.assertContainsRe(str(err), "^remote server out of mem")
3126
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3127
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3128
class TestErrorTranslationBase(tests.TestCaseWithMemoryTransport):
3129
    """Base class for unit tests for bzrlib.remote._translate_error."""
3130
3131
    def translateTuple(self, error_tuple, **context):
3132
        """Call _translate_error with an ErrorFromSmartServer built from the
3133
        given error_tuple.
3134
3135
        :param error_tuple: A tuple of a smart server response, as would be
3136
            passed to an ErrorFromSmartServer.
3137
        :kwargs context: context items to call _translate_error with.
3138
3139
        :returns: The error raised by _translate_error.
3140
        """
3141
        # Raise the ErrorFromSmartServer before passing it as an argument,
3142
        # because _translate_error may need to re-raise it with a bare 'raise'
3143
        # statement.
3144
        server_error = errors.ErrorFromSmartServer(error_tuple)
3145
        translated_error = self.translateErrorFromSmartServer(
3146
            server_error, **context)
3147
        return translated_error
3148
3149
    def translateErrorFromSmartServer(self, error_object, **context):
3150
        """Like translateTuple, but takes an already constructed
3151
        ErrorFromSmartServer rather than a tuple.
3152
        """
3153
        try:
3154
            raise error_object
3155
        except errors.ErrorFromSmartServer, server_error:
3156
            translated_error = self.assertRaises(
3157
                errors.BzrError, remote._translate_error, server_error,
3158
                **context)
3159
        return translated_error
3160
3801.1.4 by Andrew Bennetts
Add tests for autopack RPC.
3161
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3162
class TestErrorTranslationSuccess(TestErrorTranslationBase):
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3163
    """Unit tests for bzrlib.remote._translate_error.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3164
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3165
    Given an ErrorFromSmartServer (which has an error tuple from a smart
3166
    server) and some context, _translate_error raises more specific errors from
3167
    bzrlib.errors.
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3168
3169
    This test case covers the cases where _translate_error succeeds in
3170
    translating an ErrorFromSmartServer to something better.  See
3171
    TestErrorTranslationRobustness for other cases.
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3172
    """
3173
3174
    def test_NoSuchRevision(self):
3175
        branch = self.make_branch('')
3176
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3177
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3178
            ('NoSuchRevision', revid), branch=branch)
3179
        expected_error = errors.NoSuchRevision(branch, revid)
3180
        self.assertEqual(expected_error, translated_error)
3181
3182
    def test_nosuchrevision(self):
3183
        repository = self.make_repository('')
3184
        revid = 'revid'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3185
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3186
            ('nosuchrevision', revid), repository=repository)
3187
        expected_error = errors.NoSuchRevision(repository, revid)
3188
        self.assertEqual(expected_error, translated_error)
3189
3190
    def test_nobranch(self):
3191
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3192
        translated_error = self.translateTuple(('nobranch',), bzrdir=bzrdir)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3193
        expected_error = errors.NotBranchError(path=bzrdir.root_transport.base)
3194
        self.assertEqual(expected_error, translated_error)
3195
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).
3196
    def test_nobranch_one_arg(self):
3197
        bzrdir = self.make_bzrdir('')
3198
        translated_error = self.translateTuple(
3199
            ('nobranch', 'extra detail'), bzrdir=bzrdir)
3200
        expected_error = errors.NotBranchError(
3201
            path=bzrdir.root_transport.base,
3202
            detail='extra detail')
3203
        self.assertEqual(expected_error, translated_error)
3204
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3205
    def test_norepository(self):
3206
        bzrdir = self.make_bzrdir('')
3207
        translated_error = self.translateTuple(('norepository',),
3208
            bzrdir=bzrdir)
3209
        expected_error = errors.NoRepositoryPresent(bzrdir)
3210
        self.assertEqual(expected_error, translated_error)
3211
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3212
    def test_LockContention(self):
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3213
        translated_error = self.translateTuple(('LockContention',))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3214
        expected_error = errors.LockContention('(remote lock)')
3215
        self.assertEqual(expected_error, translated_error)
3216
3217
    def test_UnlockableTransport(self):
3218
        bzrdir = self.make_bzrdir('')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3219
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3220
            ('UnlockableTransport',), bzrdir=bzrdir)
3221
        expected_error = errors.UnlockableTransport(bzrdir.root_transport)
3222
        self.assertEqual(expected_error, translated_error)
3223
3224
    def test_LockFailed(self):
3225
        lock = 'str() of a server lock'
3226
        why = 'str() of why'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3227
        translated_error = self.translateTuple(('LockFailed', lock, why))
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3228
        expected_error = errors.LockFailed(lock, why)
3229
        self.assertEqual(expected_error, translated_error)
3230
3231
    def test_TokenMismatch(self):
3232
        token = 'a lock token'
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3233
        translated_error = self.translateTuple(('TokenMismatch',), token=token)
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3234
        expected_error = errors.TokenMismatch(token, '(remote token)')
3235
        self.assertEqual(expected_error, translated_error)
3236
3237
    def test_Diverged(self):
3238
        branch = self.make_branch('a')
3239
        other_branch = self.make_branch('b')
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3240
        translated_error = self.translateTuple(
3533.3.3 by Andrew Bennetts
Add unit tests for bzrlib.remote._translate_error.
3241
            ('Diverged',), branch=branch, other_branch=other_branch)
3242
        expected_error = errors.DivergedBranches(branch, other_branch)
3243
        self.assertEqual(expected_error, translated_error)
3244
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3245
    def test_NotStacked(self):
3246
        branch = self.make_branch('')
3247
        translated_error = self.translateTuple(('NotStacked',), branch=branch)
3248
        expected_error = errors.NotStacked(branch)
3249
        self.assertEqual(expected_error, translated_error)
3250
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3251
    def test_ReadError_no_args(self):
3252
        path = 'a path'
3253
        translated_error = self.translateTuple(('ReadError',), path=path)
3254
        expected_error = errors.ReadError(path)
3255
        self.assertEqual(expected_error, translated_error)
3256
3257
    def test_ReadError(self):
3258
        path = 'a path'
3259
        translated_error = self.translateTuple(('ReadError', path))
3260
        expected_error = errors.ReadError(path)
3261
        self.assertEqual(expected_error, translated_error)
3262
4650.2.1 by Robert Collins
Deserialise IncompatibleRepositories errors in the client, generating
3263
    def test_IncompatibleRepositories(self):
3264
        translated_error = self.translateTuple(('IncompatibleRepositories',
3265
            "repo1", "repo2", "details here"))
3266
        expected_error = errors.IncompatibleRepositories("repo1", "repo2",
3267
            "details here")
3268
        self.assertEqual(expected_error, translated_error)
3269
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3270
    def test_PermissionDenied_no_args(self):
3271
        path = 'a path'
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3272
        translated_error = self.translateTuple(('PermissionDenied',),
3273
            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.
3274
        expected_error = errors.PermissionDenied(path)
3275
        self.assertEqual(expected_error, translated_error)
3276
3277
    def test_PermissionDenied_one_arg(self):
3278
        path = 'a path'
3279
        translated_error = self.translateTuple(('PermissionDenied', path))
3280
        expected_error = errors.PermissionDenied(path)
3281
        self.assertEqual(expected_error, translated_error)
3282
3283
    def test_PermissionDenied_one_arg_and_context(self):
3284
        """Given a choice between a path from the local context and a path on
3285
        the wire, _translate_error prefers the path from the local context.
3286
        """
3287
        local_path = 'local path'
3288
        remote_path = 'remote path'
3289
        translated_error = self.translateTuple(
3290
            ('PermissionDenied', remote_path), path=local_path)
3291
        expected_error = errors.PermissionDenied(local_path)
3292
        self.assertEqual(expected_error, translated_error)
3293
3294
    def test_PermissionDenied_two_args(self):
3295
        path = 'a path'
3296
        extra = 'a string with extra info'
3297
        translated_error = self.translateTuple(
3298
            ('PermissionDenied', path, extra))
3299
        expected_error = errors.PermissionDenied(path, extra)
3300
        self.assertEqual(expected_error, translated_error)
3301
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3302
    # GZ 2011-03-02: TODO test for PermissionDenied with non-ascii 'extra'
3303
3304
    def test_NoSuchFile_context_path(self):
3305
        local_path = "local path"
3306
        translated_error = self.translateTuple(('ReadError', "remote path"),
3307
            path=local_path)
3308
        expected_error = errors.ReadError(local_path)
3309
        self.assertEqual(expected_error, translated_error)
3310
3311
    def test_NoSuchFile_without_context(self):
3312
        remote_path = "remote path"
3313
        translated_error = self.translateTuple(('ReadError', remote_path))
3314
        expected_error = errors.ReadError(remote_path)
3315
        self.assertEqual(expected_error, translated_error)
3316
3317
    def test_ReadOnlyError(self):
3318
        translated_error = self.translateTuple(('ReadOnlyError',))
3319
        expected_error = errors.TransportNotPossible("readonly transport")
3320
        self.assertEqual(expected_error, translated_error)
3321
3322
    def test_MemoryError(self):
3323
        translated_error = self.translateTuple(('MemoryError',))
5677.2.9 by Martin
Add hint to possible ways forward for user in remote MemoryError message
3324
        self.assertStartsWith(str(translated_error),
3325
            "remote server out of memory")
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3326
5677.2.8 by Martin
More tests for handling of unexpected remote errors
3327
    def test_generic_IndexError_no_classname(self):
5677.2.5 by Martin
Add more tests for remote._translate_error including for MemoryError handling
3328
        err = errors.ErrorFromSmartServer(('error', "list index out of range"))
3329
        translated_error = self.translateErrorFromSmartServer(err)
3330
        expected_error = errors.UnknownErrorFromSmartServer(err)
3331
        self.assertEqual(expected_error, translated_error)
3332
3333
    # GZ 2011-03-02: TODO test generic non-ascii error string
3334
5677.2.8 by Martin
More tests for handling of unexpected remote errors
3335
    def test_generic_KeyError(self):
3336
        err = errors.ErrorFromSmartServer(('error', 'KeyError', "1"))
3337
        translated_error = self.translateErrorFromSmartServer(err)
3338
        expected_error = errors.UnknownErrorFromSmartServer(err)
3339
        self.assertEqual(expected_error, translated_error)
3340
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3341
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3342
class TestErrorTranslationRobustness(TestErrorTranslationBase):
3343
    """Unit tests for bzrlib.remote._translate_error's robustness.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3344
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3345
    TestErrorTranslationSuccess is for cases where _translate_error can
3346
    translate successfully.  This class about how _translate_err behaves when
3347
    it fails to translate: it re-raises the original error.
3348
    """
3349
3350
    def test_unrecognised_server_error(self):
3351
        """If the error code from the server is not recognised, the original
3352
        ErrorFromSmartServer is propagated unmodified.
3353
        """
3354
        error_tuple = ('An unknown error tuple',)
3690.1.2 by Andrew Bennetts
Rename UntranslateableErrorFromSmartServer -> UnknownErrorFromSmartServer.
3355
        server_error = errors.ErrorFromSmartServer(error_tuple)
3356
        translated_error = self.translateErrorFromSmartServer(server_error)
3357
        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.
3358
        self.assertEqual(expected_error, translated_error)
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3359
3360
    def test_context_missing_a_key(self):
3361
        """In case of a bug in the client, or perhaps an unexpected response
3362
        from a server, _translate_error returns the original error tuple from
3363
        the server and mutters a warning.
3364
        """
3365
        # To translate a NoSuchRevision error _translate_error needs a 'branch'
3366
        # in the context dict.  So let's give it an empty context dict instead
3367
        # to exercise its error recovery.
3368
        empty_context = {}
3369
        error_tuple = ('NoSuchRevision', 'revid')
3370
        server_error = errors.ErrorFromSmartServer(error_tuple)
3371
        translated_error = self.translateErrorFromSmartServer(server_error)
3372
        self.assertEqual(server_error, translated_error)
3373
        # In addition to re-raising ErrorFromSmartServer, some debug info has
3374
        # been muttered to the log file for developer to look at.
3375
        self.assertContainsRe(
4794.1.15 by Robert Collins
Review feedback.
3376
            self.get_log(),
3533.3.4 by Andrew Bennetts
Add tests for _translate_error's robustness.
3377
            "Missing key 'branch' in context")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3378
3786.4.2 by Andrew Bennetts
Add tests and fix code to make sure ReadError and PermissionDenied are robustly handled by _translate_error.
3379
    def test_path_missing(self):
3380
        """Some translations (PermissionDenied, ReadError) can determine the
3381
        'path' variable from either the wire or the local context.  If neither
3382
        has it, then an error is raised.
3383
        """
3384
        error_tuple = ('ReadError',)
3385
        server_error = errors.ErrorFromSmartServer(error_tuple)
3386
        translated_error = self.translateErrorFromSmartServer(server_error)
3387
        self.assertEqual(server_error, translated_error)
3388
        # In addition to re-raising ErrorFromSmartServer, some debug info has
3389
        # been muttered to the log file for developer to look at.
4794.1.15 by Robert Collins
Review feedback.
3390
        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.
3391
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3392
3393
class TestStacking(tests.TestCaseWithTransport):
3394
    """Tests for operations on stacked remote repositories.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3395
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3396
    The underlying format type must support stacking.
3397
    """
3398
3399
    def test_access_stacked_remote(self):
3400
        # based on <http://launchpad.net/bugs/261315>
3401
        # make a branch stacked on another repository containing an empty
3402
        # revision, then open it over hpss - we should be able to see that
3403
        # revision.
3404
        base_transport = self.get_transport()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3405
        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)
3406
        base_builder.start_series()
3407
        base_revid = base_builder.build_snapshot('rev-id', None,
3408
            [('add', ('', None, 'directory', None))],
3409
            'message')
3410
        base_builder.finish_series()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3411
        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)
3412
        stacked_branch.set_stacked_on_url('../base')
3413
        # start a server looking at this
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
3414
        smart_server = test_server.SmartTCPServer_for_testing()
4659.1.3 by Robert Collins
Review feedback.
3415
        self.start_server(smart_server)
3691.2.2 by Martin Pool
Fix some problems in access to stacked repositories over hpss (#261315)
3416
        remote_bzrdir = BzrDir.open(smart_server.get_url() + '/stacked')
3417
        # can get its branch and repository
3418
        remote_branch = remote_bzrdir.open_branch()
3419
        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
3420
        remote_repo.lock_read()
3421
        try:
3422
            # it should have an appropriate fallback repository, which should also
3423
            # be a RemoteRepository
4288.1.2 by Robert Collins
Create a server verb for doing BzrDir.get_config()
3424
            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
3425
            self.assertIsInstance(remote_repo._fallback_repositories[0],
3426
                RemoteRepository)
3427
            # and it has the revision committed to the underlying repository;
3428
            # these have varying implementations so we try several of them
3429
            self.assertTrue(remote_repo.has_revisions([base_revid]))
3430
            self.assertTrue(remote_repo.has_revision(base_revid))
3431
            self.assertEqual(remote_repo.get_revision(base_revid).message,
3432
                'message')
3433
        finally:
3434
            remote_repo.unlock()
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3435
3835.1.7 by Aaron Bentley
Updates from review
3436
    def prepare_stacked_remote_branch(self):
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3437
        """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.
3438
        self.setup_smart_server_with_call_log()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3439
        tree1 = self.make_branch_and_tree('tree1', format='1.9')
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3440
        tree1.commit('rev1', rev_id='rev1')
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3441
        tree2 = tree1.branch.bzrdir.sprout('tree2', stacked=True
3442
            ).open_workingtree()
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
3443
        local_tree = tree2.branch.create_checkout('local')
3444
        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.
3445
        branch2 = Branch.open(self.get_url('tree2'))
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3446
        branch2.lock_read()
3447
        self.addCleanup(branch2.unlock)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3448
        return tree1.branch, branch2
3835.1.7 by Aaron Bentley
Updates from review
3449
3450
    def test_stacked_get_parent_map(self):
3451
        # 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.
3452
        _, branch = self.prepare_stacked_remote_branch()
3835.1.7 by Aaron Bentley
Updates from review
3453
        repo = branch.repository
3835.1.2 by Aaron Bentley
Add tests for get_parent_map
3454
        self.assertEqual(['rev1'], repo.get_parent_map(['rev1']).keys())
3835.1.7 by Aaron Bentley
Updates from review
3455
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
3456
    def test_unstacked_get_parent_map(self):
3457
        # _unstacked_provider.get_parent_map ignores stacking
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3458
        _, branch = self.prepare_stacked_remote_branch()
3835.1.10 by Aaron Bentley
Move CachingExtraParentsProvider to Graph
3459
        provider = branch.repository._unstacked_provider
3835.1.8 by Aaron Bentley
Make UnstackedParentsProvider manage the cache
3460
        self.assertEqual([], provider.get_parent_map(['rev1']).keys())
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
3461
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3462
    def fetch_stream_to_rev_order(self, stream):
3463
        result = []
3464
        for kind, substream in stream:
3465
            if not kind == 'revisions':
3466
                list(substream)
3467
            else:
3468
                for content in substream:
3469
                    result.append(content.key[-1])
3470
        return result
3471
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)
3472
    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.
3473
        """Get a list of the revisions in a stream to format format.
3474
3475
        :param format: The format of the target.
3476
        :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)
3477
        :param branch_factory: A callable to create a trunk and stacked branch
3478
            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.
3479
        :result: The revision ids in the stream, in the order seen,
3480
            the topological order of revisions in the source.
3481
        """
3482
        unordered_format = bzrdir.format_registry.get(format)()
3483
        target_repository_format = unordered_format.repository_format
3484
        # Cross check
3485
        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)
3486
        if branch_factory is None:
3487
            branch_factory = self.prepare_stacked_remote_branch
3488
        _, stacked = branch_factory()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3489
        source = stacked.repository._get_source(target_repository_format)
3490
        tip = stacked.last_revision()
5972.3.25 by Jelmer Vernooij
Fix another use of get_ancestry.
3491
        stacked.repository._ensure_real()
3492
        graph = stacked.repository.get_graph()
3493
        revs = [r for (r,ps) in graph.iter_ancestry([tip])
3494
                if r != NULL_REVISION]
3495
        revs.reverse()
5972.3.16 by Jelmer Vernooij
Rename import.
3496
        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.
3497
        self.reset_smart_call_log()
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3498
        stream = source.get_stream(search)
3499
        # We trust that if a revision is in the stream the rest of the new
3500
        # content for it is too, as per our main fetch tests; here we are
3501
        # checking that the revisions are actually included at all, and their
3502
        # order.
3503
        return self.fetch_stream_to_rev_order(stream), revs
3504
3505
    def test_stacked_get_stream_unordered(self):
3506
        # Repository._get_source.get_stream() from a stacked repository with
3507
        # unordered yields the full data from both stacked and stacked upon
3508
        # sources.
3509
        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.
3510
        self.assertEqual(set(expected_revs), set(rev_ord))
3511
        # Getting unordered results should have made a streaming data request
3512
        # from the server, then one from the backing branch.
3513
        self.assertLength(2, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3514
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)
3515
    def test_stacked_on_stacked_get_stream_unordered(self):
3516
        # Repository._get_source.get_stream() from a stacked repository which
3517
        # is itself stacked yields the full data from all three sources.
3518
        def make_stacked_stacked():
3519
            _, stacked = self.prepare_stacked_remote_branch()
3520
            tree = stacked.bzrdir.sprout('tree3', stacked=True
3521
                ).open_workingtree()
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
3522
            local_tree = tree.branch.create_checkout('local-tree3')
3523
            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)
3524
            branch = Branch.open(self.get_url('tree3'))
3525
            branch.lock_read()
4857.2.3 by John Arbash Meinel
Found the failed-to-unlocked branches in test_remote.
3526
            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)
3527
            return None, branch
3528
        rev_ord, expected_revs = self.get_ordered_revs('1.9', 'unordered',
3529
            branch_factory=make_stacked_stacked)
3530
        self.assertEqual(set(expected_revs), set(rev_ord))
3531
        # Getting unordered results should have made a streaming data request
3532
        # from the server, and one from each backing repo
3533
        self.assertLength(3, self.hpss_calls)
3534
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3535
    def test_stacked_get_stream_topological(self):
3536
        # Repository._get_source.get_stream() from a stacked repository with
3537
        # topological sorting yields the full data from both stacked and
3538
        # stacked upon sources in topological order.
3539
        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.
3540
        self.assertEqual(expected_revs, rev_ord)
4595.4.4 by Robert Collins
Disable committing directly to stacked branches from lightweight checkouts.
3541
        # Getting topological sort requires VFS calls still - one of which is
3542
        # pushing up from the bound branch.
5972.3.25 by Jelmer Vernooij
Fix another use of get_ancestry.
3543
        self.assertLength(14, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3544
3545
    def test_stacked_get_stream_groupcompress(self):
3546
        # Repository._get_source.get_stream() from a stacked repository with
3547
        # groupcompress sorting yields the full data from both stacked and
3548
        # stacked upon sources in groupcompress order.
3549
        raise tests.TestSkipped('No groupcompress ordered format available')
3550
        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.
3551
        self.assertEqual(expected_revs, reversed(rev_ord))
3552
        # Getting unordered results should have made a streaming data request
3553
        # from the backing branch, and one from the stacked on branch.
3554
        self.assertLength(2, self.hpss_calls)
4152.1.1 by Robert Collins
Add specific tests for fetch streaming in the bzr protocol client.
3555
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.
3556
    def test_stacked_pull_more_than_stacking_has_bug_360791(self):
3557
        # When pulling some fixed amount of content that is more than the
3558
        # source has (because some is coming from a fallback branch, no error
3559
        # should be received. This was reported as bug 360791.
3560
        # Need three branches: a trunk, a stacked branch, and a preexisting
3561
        # branch pulling content from stacked and trunk.
3562
        self.setup_smart_server_with_call_log()
3563
        trunk = self.make_branch_and_tree('trunk', format="1.9-rich-root")
3564
        r1 = trunk.commit('start')
3565
        stacked_branch = trunk.branch.create_clone_on_transport(
3566
            self.get_transport('stacked'), stacked_on=trunk.branch.base)
3567
        local = self.make_branch('local', format='1.9-rich-root')
3568
        local.repository.fetch(stacked_branch.repository,
3569
            stacked_branch.last_revision())
3570
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.
3571
3572
class TestRemoteBranchEffort(tests.TestCaseWithTransport):
3573
3574
    def setUp(self):
3575
        super(TestRemoteBranchEffort, self).setUp()
3576
        # Create a smart server that publishes whatever the backing VFS server
3577
        # does.
5017.3.28 by Vincent Ladeuil
selftest -s bt.test_remote passing
3578
        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,
3579
        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.
3580
        # Log all HPSS calls into self.hpss_calls.
3581
        _SmartClient.hooks.install_named_hook(
3582
            'call', self.capture_hpss_call, None)
3583
        self.hpss_calls = []
3584
3585
    def capture_hpss_call(self, params):
3586
        self.hpss_calls.append(params.method)
3587
3588
    def test_copy_content_into_avoids_revision_history(self):
3589
        local = self.make_branch('local')
5539.2.5 by Andrew Bennetts
Add test to test_remote, fix another shallow bug.
3590
        builder = self.make_branch_builder('remote')
3591
        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.
3592
        remote_branch_url = self.smart_server.get_url() + 'remote'
3593
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3594
        local.repository.fetch(remote_branch.repository)
3595
        self.hpss_calls = []
3596
        remote_branch.copy_content_into(local)
3834.3.3 by John Arbash Meinel
Merge bzr.dev, resolve conflict in tests.
3597
        self.assertFalse('Branch.revision_history' in self.hpss_calls)
5539.2.5 by Andrew Bennetts
Add test to test_remote, fix another shallow bug.
3598
5539.2.6 by Andrew Bennetts
Better test name.
3599
    def test_fetch_everything_needs_just_one_call(self):
5539.2.5 by Andrew Bennetts
Add test to test_remote, fix another shallow bug.
3600
        local = self.make_branch('local')
3601
        builder = self.make_branch_builder('remote')
3602
        builder.build_commit(message="Commit.")
3603
        remote_branch_url = self.smart_server.get_url() + 'remote'
3604
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3605
        self.hpss_calls = []
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3606
        local.repository.fetch(
3607
            remote_branch.repository,
3608
            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.
3609
        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.
3610
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3611
    def override_verb(self, verb_name, verb):
3612
        request_handlers = request.request_handlers
3613
        orig_verb = request_handlers.get(verb_name)
3614
        request_handlers.register(verb_name, verb, override_existing=True)
3615
        self.addCleanup(request_handlers.register, verb_name, orig_verb,
3616
                override_existing=True)
3617
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3618
    def test_fetch_everything_backwards_compat(self):
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
3619
        """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.
3620
        
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
3621
        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.
3622
        Repository.get_stream_1.19 verb.
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3623
        """
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3624
        verb_log = []
3625
        class OldGetStreamVerb(SmartServerRepositoryGetStream_1_19):
3626
            """A version of the Repository.get_stream_1.19 verb patched to
5536.3.3 by Andrew Bennetts
Merge lp:bzr.
3627
            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.
3628
            """
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3629
            def recreate_search(self, repository, search_bytes,
3630
                                discard_excess=False):
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3631
                verb_log.append(search_bytes.split('\n', 1)[0])
3632
                if search_bytes == 'everything':
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3633
                    return (None,
3634
                            request.FailedSmartServerResponse(('BadSearch',)))
5536.2.7 by Andrew Bennetts
Fix test_fetch_everything_backwards_compat to actually test what it is intended to test.
3635
                return super(OldGetStreamVerb,
3636
                        self).recreate_search(repository, search_bytes,
3637
                            discard_excess=discard_excess)
3638
        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.
3639
        local = self.make_branch('local')
3640
        builder = self.make_branch_builder('remote')
3641
        builder.build_commit(message="Commit.")
3642
        remote_branch_url = self.smart_server.get_url() + 'remote'
3643
        remote_branch = bzrdir.BzrDir.open(remote_branch_url).open_branch()
3644
        self.hpss_calls = []
6015.5.1 by Vincent Ladeuil
Merge 2.3 into 2.4
3645
        local.repository.fetch(
3646
            remote_branch.repository,
3647
            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.
3648
        # make sure the overridden verb was used
3649
        self.assertLength(1, verb_log)
3650
        # more than one HPSS call is needed, but because it's a VFS callback
3651
        # its hard to predict exactly how many.
3652
        self.assertTrue(len(self.hpss_calls) > 1)
5539.2.13 by Andrew Bennetts
Add a test for compatibility with pre-2.3 servers.
3653
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3654
5609.50.4 by Vincent Ladeuil
Add more tests for accepted bound_location variations.
3655
class TestUpdateBoundBranchWithModifiedBoundLocation(
3656
    tests.TestCaseWithTransport):
3657
    """Ensure correct handling of bound_location modifications.
3658
3659
    This is tested against a smart server as http://pad.lv/786980 was about a
3660
    ReadOnlyError (write attempt during a read-only transaction) which can only
3661
    happen in this context.
3662
    """
3663
3664
    def setUp(self):
3665
        super(TestUpdateBoundBranchWithModifiedBoundLocation, self).setUp()
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3666
        self.transport_server = test_server.SmartTCPServer_for_testing
5609.50.4 by Vincent Ladeuil
Add more tests for accepted bound_location variations.
3667
3668
    def make_master_and_checkout(self, master_name, checkout_name):
3669
        # Create the master branch and its associated checkout
3670
        self.master = self.make_branch_and_tree(master_name)
3671
        self.checkout = self.master.branch.create_checkout(checkout_name)
3672
        # Modify the master branch so there is something to update
3673
        self.master.commit('add stuff')
3674
        self.last_revid = self.master.commit('even more stuff')
3675
        self.bound_location = self.checkout.branch.get_bound_location()
3676
3677
    def assertUpdateSucceeds(self, new_location):
3678
        self.checkout.branch.set_bound_location(new_location)
3679
        self.checkout.update()
3680
        self.assertEquals(self.last_revid, self.checkout.last_revision())
3681
3682
    def test_without_final_slash(self):
3683
        self.make_master_and_checkout('master', 'checkout')
5609.50.1 by Vincent Ladeuil
Be more tolerant about ``bound_location`` from config files
3684
        # For unclear reasons some users have a bound_location without a final
3685
        # '/', simulate that by forcing such a value
5609.50.4 by Vincent Ladeuil
Add more tests for accepted bound_location variations.
3686
        self.assertEndsWith(self.bound_location, '/')
3687
        self.assertUpdateSucceeds(self.bound_location.rstrip('/'))
3688
3689
    def test_plus_sign(self):
3690
        self.make_master_and_checkout('+master', 'checkout')
3691
        self.assertUpdateSucceeds(self.bound_location.replace('%2B', '+', 1))
3692
3693
    def test_tilda(self):
3694
        # Embed ~ in the middle of the path just to avoid any $HOME
3695
        # interpretation
3696
        self.make_master_and_checkout('mas~ter', 'checkout')
3697
        self.assertUpdateSucceeds(self.bound_location.replace('%2E', '~', 1))
6284.1.1 by Jelmer Vernooij
Allow registering custom error handlers in the HPSS client.
3698
3699
3700
class TestWithCustomErrorHandler(RemoteBranchTestCase):
3701
3702
    def test_no_context(self):
3703
        class OutOfCoffee(errors.BzrError):
3704
            """A dummy exception for testing."""
3705
3706
            def __init__(self, urgency):
3707
                self.urgency = urgency
3708
        remote.no_context_error_translators.register("OutOfCoffee",
3709
            lambda err: OutOfCoffee(err.error_args[0]))
3710
        transport = MemoryTransport()
3711
        client = FakeClient(transport.base)
3712
        client.add_expected_call(
3713
            'Branch.get_stacked_on_url', ('quack/',),
3714
            'error', ('NotStacked',))
3715
        client.add_expected_call(
3716
            'Branch.last_revision_info',
3717
            ('quack/',),
3718
            'error', ('OutOfCoffee', 'low'))
3719
        transport.mkdir('quack')
3720
        transport = transport.clone('quack')
3721
        branch = self.make_remote_branch(transport, client)
3722
        self.assertRaises(OutOfCoffee, branch.last_revision_info)
3723
        self.assertFinished(client)
3724
3725
    def test_with_context(self):
3726
        class OutOfTea(errors.BzrError):
3727
            def __init__(self, branch, urgency):
3728
                self.branch = branch
3729
                self.urgency = urgency
3730
        remote.error_translators.register("OutOfTea",
3731
            lambda err, find, path: OutOfTea(err.error_args[0],
3732
                find("branch")))
3733
        transport = MemoryTransport()
3734
        client = FakeClient(transport.base)
3735
        client.add_expected_call(
3736
            'Branch.get_stacked_on_url', ('quack/',),
3737
            'error', ('NotStacked',))
3738
        client.add_expected_call(
3739
            'Branch.last_revision_info',
3740
            ('quack/',),
3741
            'error', ('OutOfTea', 'low'))
3742
        transport.mkdir('quack')
3743
        transport = transport.clone('quack')
3744
        branch = self.make_remote_branch(transport, client)
3745
        self.assertRaises(OutOfTea, branch.last_revision_info)
3746
        self.assertFinished(client)