/brz/remove-bazaar

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