~bzr-pqm/bzr/bzr.dev

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