/brz/remove-bazaar

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