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