/brz/remove-bazaar

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