/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/tests/test_remote.py

  • Committer: Andrew Bennetts
  • Date: 2008-04-08 06:38:34 UTC
  • mfrom: (2892.2.1 smart-set-last-revision)
  • mto: This revision was merged to the branch mainline in revision 3355.
  • Revision ID: andrew.bennetts@canonical.com-20080408063834-o4mid7woclibs6yj
Merge 'Add Branch.set_last_revision_info smart method'.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
 
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
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
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
 
21
the object given a transport that supports smartserver rpc operations. 
 
22
 
 
23
These tests correspond to tests.test_smart, which exercises the server side.
 
24
"""
 
25
 
 
26
import bz2
 
27
from cStringIO import StringIO
 
28
 
 
29
from bzrlib import (
 
30
    errors,
 
31
    graph,
 
32
    pack,
 
33
    remote,
 
34
    repository,
 
35
    tests,
 
36
    )
 
37
from bzrlib.branch import Branch
 
38
from bzrlib.bzrdir import BzrDir, BzrDirFormat
 
39
from bzrlib.remote import (
 
40
    RemoteBranch,
 
41
    RemoteBzrDir,
 
42
    RemoteBzrDirFormat,
 
43
    RemoteRepository,
 
44
    )
 
45
from bzrlib.revision import NULL_REVISION
 
46
from bzrlib.smart import server, medium
 
47
from bzrlib.smart.client import _SmartClient
 
48
from bzrlib.symbol_versioning import one_four
 
49
from bzrlib.transport import get_transport
 
50
from bzrlib.transport.memory import MemoryTransport
 
51
from bzrlib.transport.remote import RemoteTransport
 
52
 
 
53
 
 
54
class BasicRemoteObjectTests(tests.TestCaseWithTransport):
 
55
 
 
56
    def setUp(self):
 
57
        self.transport_server = server.SmartTCPServer_for_testing
 
58
        super(BasicRemoteObjectTests, self).setUp()
 
59
        self.transport = self.get_transport()
 
60
        # make a branch that can be opened over the smart transport
 
61
        self.local_wt = BzrDir.create_standalone_workingtree('.')
 
62
 
 
63
    def tearDown(self):
 
64
        self.transport.disconnect()
 
65
        tests.TestCaseWithTransport.tearDown(self)
 
66
 
 
67
    def test_create_remote_bzrdir(self):
 
68
        b = remote.RemoteBzrDir(self.transport)
 
69
        self.assertIsInstance(b, BzrDir)
 
70
 
 
71
    def test_open_remote_branch(self):
 
72
        # open a standalone branch in the working directory
 
73
        b = remote.RemoteBzrDir(self.transport)
 
74
        branch = b.open_branch()
 
75
        self.assertIsInstance(branch, Branch)
 
76
 
 
77
    def test_remote_repository(self):
 
78
        b = BzrDir.open_from_transport(self.transport)
 
79
        repo = b.open_repository()
 
80
        revid = u'\xc823123123'.encode('utf8')
 
81
        self.assertFalse(repo.has_revision(revid))
 
82
        self.local_wt.commit(message='test commit', rev_id=revid)
 
83
        self.assertTrue(repo.has_revision(revid))
 
84
 
 
85
    def test_remote_branch_revision_history(self):
 
86
        b = BzrDir.open_from_transport(self.transport).open_branch()
 
87
        self.assertEqual([], b.revision_history())
 
88
        r1 = self.local_wt.commit('1st commit')
 
89
        r2 = self.local_wt.commit('1st commit', rev_id=u'\xc8'.encode('utf8'))
 
90
        self.assertEqual([r1, r2], b.revision_history())
 
91
 
 
92
    def test_find_correct_format(self):
 
93
        """Should open a RemoteBzrDir over a RemoteTransport"""
 
94
        fmt = BzrDirFormat.find_format(self.transport)
 
95
        self.assertTrue(RemoteBzrDirFormat
 
96
                        in BzrDirFormat._control_server_formats)
 
97
        self.assertIsInstance(fmt, remote.RemoteBzrDirFormat)
 
98
 
 
99
    def test_open_detected_smart_format(self):
 
100
        fmt = BzrDirFormat.find_format(self.transport)
 
101
        d = fmt.open(self.transport)
 
102
        self.assertIsInstance(d, BzrDir)
 
103
 
 
104
    def test_remote_branch_repr(self):
 
105
        b = BzrDir.open_from_transport(self.transport).open_branch()
 
106
        self.assertStartsWith(str(b), 'RemoteBranch(')
 
107
 
 
108
 
 
109
class FakeProtocol(object):
 
110
    """Lookalike SmartClientRequestProtocolOne allowing body reading tests."""
 
111
 
 
112
    def __init__(self, body, fake_client):
 
113
        self.body = body
 
114
        self._body_buffer = None
 
115
        self._fake_client = fake_client
 
116
 
 
117
    def read_body_bytes(self, count=-1):
 
118
        if self._body_buffer is None:
 
119
            self._body_buffer = StringIO(self.body)
 
120
        bytes = self._body_buffer.read(count)
 
121
        if self._body_buffer.tell() == len(self._body_buffer.getvalue()):
 
122
            self._fake_client.expecting_body = False
 
123
        return bytes
 
124
 
 
125
    def cancel_read_body(self):
 
126
        self._fake_client.expecting_body = False
 
127
 
 
128
    def read_streamed_body(self):
 
129
        return self.body
 
130
 
 
131
 
 
132
class FakeClient(_SmartClient):
 
133
    """Lookalike for _SmartClient allowing testing."""
 
134
    
 
135
    def __init__(self, responses, fake_medium_base='fake base'):
 
136
        """Create a FakeClient.
 
137
 
 
138
        :param responses: A list of response-tuple, body-data pairs to be sent
 
139
            back to callers.  A special case is if the response-tuple is
 
140
            'unknown verb', then a UnknownSmartMethod will be raised for that
 
141
            call, using the second element of the tuple as the verb in the
 
142
            exception.
 
143
        """
 
144
        self.responses = responses
 
145
        self._calls = []
 
146
        self.expecting_body = False
 
147
        _SmartClient.__init__(self, FakeMedium(self._calls), fake_medium_base)
 
148
 
 
149
    def _get_next_response(self):
 
150
        response_tuple = self.responses.pop(0)
 
151
        if response_tuple[0][0] == 'unknown verb':
 
152
            raise errors.UnknownSmartMethod(response_tuple[0][1])
 
153
        return response_tuple
 
154
 
 
155
    def call(self, method, *args):
 
156
        self._calls.append(('call', method, args))
 
157
        return self._get_next_response()[0]
 
158
 
 
159
    def call_expecting_body(self, method, *args):
 
160
        self._calls.append(('call_expecting_body', method, args))
 
161
        result = self._get_next_response()
 
162
        self.expecting_body = True
 
163
        return result[0], FakeProtocol(result[1], self)
 
164
 
 
165
    def call_with_body_bytes_expecting_body(self, method, args, body):
 
166
        self._calls.append(('call_with_body_bytes_expecting_body', method,
 
167
            args, body))
 
168
        result = self._get_next_response()
 
169
        self.expecting_body = True
 
170
        return result[0], FakeProtocol(result[1], self)
 
171
 
 
172
 
 
173
class FakeMedium(object):
 
174
 
 
175
    def __init__(self, client_calls):
 
176
        self._remote_is_at_least_1_2 = True
 
177
        self._client_calls = client_calls
 
178
 
 
179
    def disconnect(self):
 
180
        self._client_calls.append(('disconnect medium',))
 
181
 
 
182
 
 
183
class TestVfsHas(tests.TestCase):
 
184
 
 
185
    def test_unicode_path(self):
 
186
        client = FakeClient([(('yes',), )], '/')
 
187
        transport = RemoteTransport('bzr://localhost/', _client=client)
 
188
        filename = u'/hell\u00d8'.encode('utf8')
 
189
        result = transport.has(filename)
 
190
        self.assertEqual(
 
191
            [('call', 'has', (filename,))],
 
192
            client._calls)
 
193
        self.assertTrue(result)
 
194
 
 
195
 
 
196
class Test_SmartClient_remote_path_from_transport(tests.TestCase):
 
197
    """Tests for the behaviour of _SmartClient.remote_path_from_transport."""
 
198
 
 
199
    def assertRemotePath(self, expected, client_base, transport_base):
 
200
        """Assert that the result of _SmartClient.remote_path_from_transport
 
201
        is the expected value for a given client_base and transport_base.
 
202
        """
 
203
        dummy_medium = 'dummy medium'
 
204
        client = _SmartClient(dummy_medium, client_base)
 
205
        transport = get_transport(transport_base)
 
206
        result = client.remote_path_from_transport(transport)
 
207
        self.assertEqual(expected, result)
 
208
        
 
209
    def test_remote_path_from_transport(self):
 
210
        """_SmartClient.remote_path_from_transport calculates a URL for the
 
211
        given transport relative to the root of the client base URL.
 
212
        """
 
213
        self.assertRemotePath('xyz/', 'bzr://host/path', 'bzr://host/xyz')
 
214
        self.assertRemotePath(
 
215
            'path/xyz/', 'bzr://host/path', 'bzr://host/path/xyz')
 
216
 
 
217
    def test_remote_path_from_transport_http(self):
 
218
        """Remote paths for HTTP transports are calculated differently to other
 
219
        transports.  They are just relative to the client base, not the root
 
220
        directory of the host.
 
221
        """
 
222
        for scheme in ['http:', 'https:', 'bzr+http:', 'bzr+https:']:
 
223
            self.assertRemotePath(
 
224
                '../xyz/', scheme + '//host/path', scheme + '//host/xyz')
 
225
            self.assertRemotePath(
 
226
                'xyz/', scheme + '//host/path', scheme + '//host/path/xyz')
 
227
 
 
228
 
 
229
class TestBzrDirOpenBranch(tests.TestCase):
 
230
 
 
231
    def test_branch_present(self):
 
232
        transport = MemoryTransport()
 
233
        transport.mkdir('quack')
 
234
        transport = transport.clone('quack')
 
235
        client = FakeClient([(('ok', ''), ), (('ok', '', 'no', 'no', 'no'), )],
 
236
                            transport.base)
 
237
        bzrdir = RemoteBzrDir(transport, _client=client)
 
238
        result = bzrdir.open_branch()
 
239
        self.assertEqual(
 
240
            [('call', 'BzrDir.open_branch', ('quack/',)),
 
241
             ('call', 'BzrDir.find_repositoryV2', ('quack/',))],
 
242
            client._calls)
 
243
        self.assertIsInstance(result, RemoteBranch)
 
244
        self.assertEqual(bzrdir, result.bzrdir)
 
245
 
 
246
    def test_branch_missing(self):
 
247
        transport = MemoryTransport()
 
248
        transport.mkdir('quack')
 
249
        transport = transport.clone('quack')
 
250
        client = FakeClient([(('nobranch',), )], transport.base)
 
251
        bzrdir = RemoteBzrDir(transport, _client=client)
 
252
        self.assertRaises(errors.NotBranchError, bzrdir.open_branch)
 
253
        self.assertEqual(
 
254
            [('call', 'BzrDir.open_branch', ('quack/',))],
 
255
            client._calls)
 
256
 
 
257
    def test__get_tree_branch(self):
 
258
        # _get_tree_branch is a form of open_branch, but it should only ask for
 
259
        # branch opening, not any other network requests.
 
260
        calls = []
 
261
        def open_branch():
 
262
            calls.append("Called")
 
263
            return "a-branch"
 
264
        transport = MemoryTransport()
 
265
        # no requests on the network - catches other api calls being made.
 
266
        client = FakeClient([], transport.base)
 
267
        bzrdir = RemoteBzrDir(transport, _client=client)
 
268
        # patch the open_branch call to record that it was called.
 
269
        bzrdir.open_branch = open_branch
 
270
        self.assertEqual((None, "a-branch"), bzrdir._get_tree_branch())
 
271
        self.assertEqual(["Called"], calls)
 
272
        self.assertEqual([], client._calls)
 
273
 
 
274
    def test_url_quoting_of_path(self):
 
275
        # Relpaths on the wire should not be URL-escaped.  So "~" should be
 
276
        # transmitted as "~", not "%7E".
 
277
        transport = RemoteTransport('bzr://localhost/~hello/')
 
278
        client = FakeClient([(('ok', ''), ), (('ok', '', 'no', 'no', 'no'), )],
 
279
                            transport.base)
 
280
        bzrdir = RemoteBzrDir(transport, _client=client)
 
281
        result = bzrdir.open_branch()
 
282
        self.assertEqual(
 
283
            [('call', 'BzrDir.open_branch', ('~hello/',)),
 
284
             ('call', 'BzrDir.find_repositoryV2', ('~hello/',))],
 
285
            client._calls)
 
286
 
 
287
    def check_open_repository(self, rich_root, subtrees, external_lookup='no'):
 
288
        transport = MemoryTransport()
 
289
        transport.mkdir('quack')
 
290
        transport = transport.clone('quack')
 
291
        if rich_root:
 
292
            rich_response = 'yes'
 
293
        else:
 
294
            rich_response = 'no'
 
295
        if subtrees:
 
296
            subtree_response = 'yes'
 
297
        else:
 
298
            subtree_response = 'no'
 
299
        client = FakeClient(
 
300
            [(('ok', '', rich_response, subtree_response, external_lookup), ),],
 
301
            transport.base)
 
302
        bzrdir = RemoteBzrDir(transport, _client=client)
 
303
        result = bzrdir.open_repository()
 
304
        self.assertEqual(
 
305
            [('call', 'BzrDir.find_repositoryV2', ('quack/',))],
 
306
            client._calls)
 
307
        self.assertIsInstance(result, RemoteRepository)
 
308
        self.assertEqual(bzrdir, result.bzrdir)
 
309
        self.assertEqual(rich_root, result._format.rich_root_data)
 
310
        self.assertEqual(subtrees, result._format.supports_tree_reference)
 
311
 
 
312
    def test_open_repository_sets_format_attributes(self):
 
313
        self.check_open_repository(True, True)
 
314
        self.check_open_repository(False, True)
 
315
        self.check_open_repository(True, False)
 
316
        self.check_open_repository(False, False)
 
317
        self.check_open_repository(False, False, 'yes')
 
318
 
 
319
    def test_old_server(self):
 
320
        """RemoteBzrDirFormat should fail to probe if the server version is too
 
321
        old.
 
322
        """
 
323
        self.assertRaises(errors.NotBranchError,
 
324
            RemoteBzrDirFormat.probe_transport, OldServerTransport())
 
325
 
 
326
 
 
327
class TestBzrDirOpenRepository(tests.TestCase):
 
328
 
 
329
    def test_backwards_compat_1_2(self):
 
330
        transport = MemoryTransport()
 
331
        transport.mkdir('quack')
 
332
        transport = transport.clone('quack')
 
333
        client = FakeClient([
 
334
            (('unknown verb', 'RemoteRepository.find_repositoryV2'), ''),
 
335
            (('ok', '', 'no', 'no'), ''),],
 
336
            transport.base)
 
337
        bzrdir = RemoteBzrDir(transport, _client=client)
 
338
        repo = bzrdir.open_repository()
 
339
        self.assertEqual(
 
340
            [('call', 'BzrDir.find_repositoryV2', ('quack/',)),
 
341
             ('call', 'BzrDir.find_repository', ('quack/',))],
 
342
            client._calls)
 
343
 
 
344
 
 
345
class OldSmartClient(object):
 
346
    """A fake smart client for test_old_version that just returns a version one
 
347
    response to the 'hello' (query version) command.
 
348
    """
 
349
 
 
350
    def get_request(self):
 
351
        input_file = StringIO('ok\x011\n')
 
352
        output_file = StringIO()
 
353
        client_medium = medium.SmartSimplePipesClientMedium(
 
354
            input_file, output_file)
 
355
        return medium.SmartClientStreamMediumRequest(client_medium)
 
356
 
 
357
    def protocol_version(self):
 
358
        return 1
 
359
 
 
360
 
 
361
class OldServerTransport(object):
 
362
    """A fake transport for test_old_server that reports it's smart server
 
363
    protocol version as version one.
 
364
    """
 
365
 
 
366
    def __init__(self):
 
367
        self.base = 'fake:'
 
368
 
 
369
    def get_smart_client(self):
 
370
        return OldSmartClient()
 
371
 
 
372
 
 
373
class TestBranchLastRevisionInfo(tests.TestCase):
 
374
 
 
375
    def test_empty_branch(self):
 
376
        # in an empty branch we decode the response properly
 
377
        transport = MemoryTransport()
 
378
        client = FakeClient([(('ok', '0', 'null:'), )], transport.base)
 
379
        transport.mkdir('quack')
 
380
        transport = transport.clone('quack')
 
381
        # we do not want bzrdir to make any remote calls
 
382
        bzrdir = RemoteBzrDir(transport, _client=False)
 
383
        branch = RemoteBranch(bzrdir, None, _client=client)
 
384
        result = branch.last_revision_info()
 
385
 
 
386
        self.assertEqual(
 
387
            [('call', 'Branch.last_revision_info', ('quack/',))],
 
388
            client._calls)
 
389
        self.assertEqual((0, NULL_REVISION), result)
 
390
 
 
391
    def test_non_empty_branch(self):
 
392
        # in a non-empty branch we also decode the response properly
 
393
        revid = u'\xc8'.encode('utf8')
 
394
        transport = MemoryTransport()
 
395
        client = FakeClient([(('ok', '2', revid), )], transport.base)
 
396
        transport.mkdir('kwaak')
 
397
        transport = transport.clone('kwaak')
 
398
        # we do not want bzrdir to make any remote calls
 
399
        bzrdir = RemoteBzrDir(transport, _client=False)
 
400
        branch = RemoteBranch(bzrdir, None, _client=client)
 
401
        result = branch.last_revision_info()
 
402
 
 
403
        self.assertEqual(
 
404
            [('call', 'Branch.last_revision_info', ('kwaak/',))],
 
405
            client._calls)
 
406
        self.assertEqual((2, revid), result)
 
407
 
 
408
 
 
409
class TestBranchSetLastRevision(tests.TestCase):
 
410
 
 
411
    def test_set_empty(self):
 
412
        # set_revision_history([]) is translated to calling
 
413
        # Branch.set_last_revision(path, '') on the wire.
 
414
        transport = MemoryTransport()
 
415
        transport.mkdir('branch')
 
416
        transport = transport.clone('branch')
 
417
 
 
418
        client = FakeClient([
 
419
            # lock_write
 
420
            (('ok', 'branch token', 'repo token'), ),
 
421
            # set_last_revision
 
422
            (('ok',), ),
 
423
            # unlock
 
424
            (('ok',), )],
 
425
            transport.base)
 
426
        bzrdir = RemoteBzrDir(transport, _client=False)
 
427
        branch = RemoteBranch(bzrdir, None, _client=client)
 
428
        # This is a hack to work around the problem that RemoteBranch currently
 
429
        # unnecessarily invokes _ensure_real upon a call to lock_write.
 
430
        branch._ensure_real = lambda: None
 
431
        branch.lock_write()
 
432
        client._calls = []
 
433
        result = branch.set_revision_history([])
 
434
        self.assertEqual(
 
435
            [('call', 'Branch.set_last_revision',
 
436
                ('branch/', 'branch token', 'repo token', 'null:'))],
 
437
            client._calls)
 
438
        branch.unlock()
 
439
        self.assertEqual(None, result)
 
440
 
 
441
    def test_set_nonempty(self):
 
442
        # set_revision_history([rev-id1, ..., rev-idN]) is translated to calling
 
443
        # Branch.set_last_revision(path, rev-idN) on the wire.
 
444
        transport = MemoryTransport()
 
445
        transport.mkdir('branch')
 
446
        transport = transport.clone('branch')
 
447
 
 
448
        client = FakeClient([
 
449
            # lock_write
 
450
            (('ok', 'branch token', 'repo token'), ),
 
451
            # set_last_revision
 
452
            (('ok',), ),
 
453
            # unlock
 
454
            (('ok',), )],
 
455
            transport.base)
 
456
        bzrdir = RemoteBzrDir(transport, _client=False)
 
457
        branch = RemoteBranch(bzrdir, None, _client=client)
 
458
        # This is a hack to work around the problem that RemoteBranch currently
 
459
        # unnecessarily invokes _ensure_real upon a call to lock_write.
 
460
        branch._ensure_real = lambda: None
 
461
        # Lock the branch, reset the record of remote calls.
 
462
        branch.lock_write()
 
463
        client._calls = []
 
464
 
 
465
        result = branch.set_revision_history(['rev-id1', 'rev-id2'])
 
466
        self.assertEqual(
 
467
            [('call', 'Branch.set_last_revision',
 
468
                ('branch/', 'branch token', 'repo token', 'rev-id2'))],
 
469
            client._calls)
 
470
        branch.unlock()
 
471
        self.assertEqual(None, result)
 
472
 
 
473
    def test_no_such_revision(self):
 
474
        # A response of 'NoSuchRevision' is translated into an exception.
 
475
        client = FakeClient([
 
476
            # lock_write
 
477
            (('ok', 'branch token', 'repo token'), ),
 
478
            # set_last_revision
 
479
            (('NoSuchRevision', 'rev-id'), ),
 
480
            # unlock
 
481
            (('ok',), )])
 
482
        transport = MemoryTransport()
 
483
        transport.mkdir('branch')
 
484
        transport = transport.clone('branch')
 
485
 
 
486
        bzrdir = RemoteBzrDir(transport, _client=False)
 
487
        branch = RemoteBranch(bzrdir, None, _client=client)
 
488
        branch._ensure_real = lambda: None
 
489
        branch.lock_write()
 
490
        client._calls = []
 
491
 
 
492
        self.assertRaises(
 
493
            errors.NoSuchRevision, branch.set_revision_history, ['rev-id'])
 
494
        branch.unlock()
 
495
 
 
496
 
 
497
class TestBranchSetLastRevisionInfo(tests.TestCase):
 
498
 
 
499
    def test_set_empty(self):
 
500
        # set_last_revision_info(num, 'rev-id') is translated to calling
 
501
        # Branch.set_last_revision_info(num, 'rev-id') on the wire.
 
502
        transport = MemoryTransport()
 
503
        transport.mkdir('branch')
 
504
        transport = transport.clone('branch')
 
505
        client = FakeClient([
 
506
            # lock_write
 
507
            (('ok', 'branch token', 'repo token'), ),
 
508
            # set_last_revision_info
 
509
            (('ok',), ),
 
510
            # unlock
 
511
            (('ok',), )], transport.base)
 
512
 
 
513
        bzrdir = RemoteBzrDir(transport, _client=False)
 
514
        branch = RemoteBranch(bzrdir, None, _client=client)
 
515
        # This is a hack to work around the problem that RemoteBranch currently
 
516
        # unnecessarily invokes _ensure_real upon a call to lock_write.
 
517
        branch._ensure_real = lambda: None
 
518
        # Lock the branch, reset the record of remote calls.
 
519
        branch.lock_write()
 
520
        client._calls = []
 
521
        result = branch.set_last_revision_info(1234, 'a-revision-id')
 
522
        self.assertEqual(
 
523
            [('call', 'Branch.set_last_revision_info',
 
524
                ('branch/', 'branch token', 'repo token',
 
525
                 '1234', 'a-revision-id'))],
 
526
            client._calls)
 
527
        self.assertEqual(None, result)
 
528
 
 
529
    def test_no_such_revision(self):
 
530
        # A response of 'NoSuchRevision' is translated into an exception.
 
531
        client = FakeClient([
 
532
            # lock_write
 
533
            (('ok', 'branch token', 'repo token'), ),
 
534
            # set_last_revision_info
 
535
            (('NoSuchRevision', 'revid'), ),
 
536
            # unlock
 
537
            (('ok',), ),
 
538
            ])
 
539
        transport = MemoryTransport()
 
540
        transport.mkdir('branch')
 
541
        transport = transport.clone('branch')
 
542
 
 
543
        bzrdir = RemoteBzrDir(transport, _client=False)
 
544
        branch = RemoteBranch(bzrdir, None, _client=client)
 
545
        # This is a hack to work around the problem that RemoteBranch currently
 
546
        # unnecessarily invokes _ensure_real upon a call to lock_write.
 
547
        branch._ensure_real = lambda: None
 
548
        # Lock the branch, reset the record of remote calls.
 
549
        branch.lock_write()
 
550
        client._calls = []
 
551
 
 
552
        self.assertRaises(
 
553
            errors.NoSuchRevision, branch.set_last_revision_info, 123, 'revid')
 
554
        branch.unlock()
 
555
 
 
556
 
 
557
class TestBranchControlGetBranchConf(tests.TestCaseWithMemoryTransport):
 
558
    """Test branch.control_files api munging...
 
559
 
 
560
    We special case RemoteBranch.control_files.get('branch.conf') to
 
561
    call a specific API so that RemoteBranch's can intercept configuration
 
562
    file reading, allowing them to signal to the client about things like
 
563
    'email is configured for commits'.
 
564
    """
 
565
 
 
566
    def test_get_branch_conf(self):
 
567
        # in an empty branch we decode the response properly
 
568
        client = FakeClient([(('ok', ), 'config file body')], self.get_url())
 
569
        # we need to make a real branch because the remote_branch.control_files
 
570
        # will trigger _ensure_real.
 
571
        branch = self.make_branch('quack')
 
572
        transport = branch.bzrdir.root_transport
 
573
        # we do not want bzrdir to make any remote calls
 
574
        bzrdir = RemoteBzrDir(transport, _client=False)
 
575
        branch = RemoteBranch(bzrdir, None, _client=client)
 
576
        result = branch.control_files.get('branch.conf')
 
577
        self.assertEqual(
 
578
            [('call_expecting_body', 'Branch.get_config_file', ('quack/',))],
 
579
            client._calls)
 
580
        self.assertEqual('config file body', result.read())
 
581
 
 
582
 
 
583
class TestBranchLockWrite(tests.TestCase):
 
584
 
 
585
    def test_lock_write_unlockable(self):
 
586
        transport = MemoryTransport()
 
587
        client = FakeClient([(('UnlockableTransport', ), '')], transport.base)
 
588
        transport.mkdir('quack')
 
589
        transport = transport.clone('quack')
 
590
        # we do not want bzrdir to make any remote calls
 
591
        bzrdir = RemoteBzrDir(transport, _client=False)
 
592
        branch = RemoteBranch(bzrdir, None, _client=client)
 
593
        self.assertRaises(errors.UnlockableTransport, branch.lock_write)
 
594
        self.assertEqual(
 
595
            [('call', 'Branch.lock_write', ('quack/', '', ''))],
 
596
            client._calls)
 
597
 
 
598
 
 
599
class TestTransportIsReadonly(tests.TestCase):
 
600
 
 
601
    def test_true(self):
 
602
        client = FakeClient([(('yes',), '')])
 
603
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
604
                                    _client=client)
 
605
        self.assertEqual(True, transport.is_readonly())
 
606
        self.assertEqual(
 
607
            [('call', 'Transport.is_readonly', ())],
 
608
            client._calls)
 
609
 
 
610
    def test_false(self):
 
611
        client = FakeClient([(('no',), '')])
 
612
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
613
                                    _client=client)
 
614
        self.assertEqual(False, transport.is_readonly())
 
615
        self.assertEqual(
 
616
            [('call', 'Transport.is_readonly', ())],
 
617
            client._calls)
 
618
 
 
619
    def test_error_from_old_server(self):
 
620
        """bzr 0.15 and earlier servers don't recognise the is_readonly verb.
 
621
        
 
622
        Clients should treat it as a "no" response, because is_readonly is only
 
623
        advisory anyway (a transport could be read-write, but then the
 
624
        underlying filesystem could be readonly anyway).
 
625
        """
 
626
        client = FakeClient([(('unknown verb', 'Transport.is_readonly'), '')])
 
627
        transport = RemoteTransport('bzr://example.com/', medium=False,
 
628
                                    _client=client)
 
629
        self.assertEqual(False, transport.is_readonly())
 
630
        self.assertEqual(
 
631
            [('call', 'Transport.is_readonly', ())],
 
632
            client._calls)
 
633
 
 
634
 
 
635
class TestRemoteRepository(tests.TestCase):
 
636
    """Base for testing RemoteRepository protocol usage.
 
637
    
 
638
    These tests contain frozen requests and responses.  We want any changes to 
 
639
    what is sent or expected to be require a thoughtful update to these tests
 
640
    because they might break compatibility with different-versioned servers.
 
641
    """
 
642
 
 
643
    def setup_fake_client_and_repository(self, responses, transport_path):
 
644
        """Create the fake client and repository for testing with.
 
645
        
 
646
        There's no real server here; we just have canned responses sent
 
647
        back one by one.
 
648
        
 
649
        :param transport_path: Path below the root of the MemoryTransport
 
650
            where the repository will be created.
 
651
        """
 
652
        transport = MemoryTransport()
 
653
        transport.mkdir(transport_path)
 
654
        client = FakeClient(responses, transport.base)
 
655
        transport = transport.clone(transport_path)
 
656
        # we do not want bzrdir to make any remote calls
 
657
        bzrdir = RemoteBzrDir(transport, _client=False)
 
658
        repo = RemoteRepository(bzrdir, None, _client=client)
 
659
        return repo, client
 
660
 
 
661
 
 
662
class TestRepositoryGatherStats(TestRemoteRepository):
 
663
 
 
664
    def test_revid_none(self):
 
665
        # ('ok',), body with revisions and size
 
666
        responses = [(('ok', ), 'revisions: 2\nsize: 18\n')]
 
667
        transport_path = 'quack'
 
668
        repo, client = self.setup_fake_client_and_repository(
 
669
            responses, transport_path)
 
670
        result = repo.gather_stats(None)
 
671
        self.assertEqual(
 
672
            [('call_expecting_body', 'Repository.gather_stats',
 
673
             ('quack/','','no'))],
 
674
            client._calls)
 
675
        self.assertEqual({'revisions': 2, 'size': 18}, result)
 
676
 
 
677
    def test_revid_no_committers(self):
 
678
        # ('ok',), body without committers
 
679
        responses = [(('ok', ),
 
680
                      'firstrev: 123456.300 3600\n'
 
681
                      'latestrev: 654231.400 0\n'
 
682
                      'revisions: 2\n'
 
683
                      'size: 18\n')]
 
684
        transport_path = 'quick'
 
685
        revid = u'\xc8'.encode('utf8')
 
686
        repo, client = self.setup_fake_client_and_repository(
 
687
            responses, transport_path)
 
688
        result = repo.gather_stats(revid)
 
689
        self.assertEqual(
 
690
            [('call_expecting_body', 'Repository.gather_stats',
 
691
              ('quick/', revid, 'no'))],
 
692
            client._calls)
 
693
        self.assertEqual({'revisions': 2, 'size': 18,
 
694
                          'firstrev': (123456.300, 3600),
 
695
                          'latestrev': (654231.400, 0),},
 
696
                         result)
 
697
 
 
698
    def test_revid_with_committers(self):
 
699
        # ('ok',), body with committers
 
700
        responses = [(('ok', ),
 
701
                      'committers: 128\n'
 
702
                      'firstrev: 123456.300 3600\n'
 
703
                      'latestrev: 654231.400 0\n'
 
704
                      'revisions: 2\n'
 
705
                      'size: 18\n')]
 
706
        transport_path = 'buick'
 
707
        revid = u'\xc8'.encode('utf8')
 
708
        repo, client = self.setup_fake_client_and_repository(
 
709
            responses, transport_path)
 
710
        result = repo.gather_stats(revid, True)
 
711
        self.assertEqual(
 
712
            [('call_expecting_body', 'Repository.gather_stats',
 
713
              ('buick/', revid, 'yes'))],
 
714
            client._calls)
 
715
        self.assertEqual({'revisions': 2, 'size': 18,
 
716
                          'committers': 128,
 
717
                          'firstrev': (123456.300, 3600),
 
718
                          'latestrev': (654231.400, 0),},
 
719
                         result)
 
720
 
 
721
 
 
722
class TestRepositoryGetGraph(TestRemoteRepository):
 
723
 
 
724
    def test_get_graph(self):
 
725
        # get_graph returns a graph with the repository as the
 
726
        # parents_provider.
 
727
        responses = []
 
728
        transport_path = 'quack'
 
729
        repo, client = self.setup_fake_client_and_repository(
 
730
            responses, transport_path)
 
731
        graph = repo.get_graph()
 
732
        self.assertEqual(graph._parents_provider, repo)
 
733
 
 
734
 
 
735
class TestRepositoryGetParentMap(TestRemoteRepository):
 
736
 
 
737
    def test_get_parent_map_caching(self):
 
738
        # get_parent_map returns from cache until unlock()
 
739
        # setup a reponse with two revisions
 
740
        r1 = u'\u0e33'.encode('utf8')
 
741
        r2 = u'\u0dab'.encode('utf8')
 
742
        lines = [' '.join([r2, r1]), r1]
 
743
        encoded_body = bz2.compress('\n'.join(lines))
 
744
        responses = [(('ok', ), encoded_body), (('ok', ), encoded_body)]
 
745
 
 
746
        transport_path = 'quack'
 
747
        repo, client = self.setup_fake_client_and_repository(
 
748
            responses, transport_path)
 
749
        repo.lock_read()
 
750
        graph = repo.get_graph()
 
751
        parents = graph.get_parent_map([r2])
 
752
        self.assertEqual({r2: (r1,)}, parents)
 
753
        # locking and unlocking deeper should not reset
 
754
        repo.lock_read()
 
755
        repo.unlock()
 
756
        parents = graph.get_parent_map([r1])
 
757
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
 
758
        self.assertEqual(
 
759
            [('call_with_body_bytes_expecting_body',
 
760
              'Repository.get_parent_map', ('quack/', r2), '\n\n0')],
 
761
            client._calls)
 
762
        repo.unlock()
 
763
        # now we call again, and it should use the second response.
 
764
        repo.lock_read()
 
765
        graph = repo.get_graph()
 
766
        parents = graph.get_parent_map([r1])
 
767
        self.assertEqual({r1: (NULL_REVISION,)}, parents)
 
768
        self.assertEqual(
 
769
            [('call_with_body_bytes_expecting_body',
 
770
              'Repository.get_parent_map', ('quack/', r2), '\n\n0'),
 
771
             ('call_with_body_bytes_expecting_body',
 
772
              'Repository.get_parent_map', ('quack/', r1), '\n\n0'),
 
773
            ],
 
774
            client._calls)
 
775
        repo.unlock()
 
776
 
 
777
    def test_get_parent_map_reconnects_if_unknown_method(self):
 
778
        responses = [
 
779
            (('unknown verb', 'Repository.get_parent_map'), ''),
 
780
            (('ok',), '')]
 
781
        transport_path = 'quack'
 
782
        repo, client = self.setup_fake_client_and_repository(
 
783
            responses, transport_path)
 
784
        rev_id = 'revision-id'
 
785
        expected_deprecations = [
 
786
            'bzrlib.remote.RemoteRepository.get_revision_graph was deprecated '
 
787
            'in version 1.4.']
 
788
        parents = self.callDeprecated(
 
789
            expected_deprecations, repo.get_parent_map, [rev_id])
 
790
        self.assertEqual(
 
791
            [('call_with_body_bytes_expecting_body',
 
792
              'Repository.get_parent_map', ('quack/', rev_id), '\n\n0'),
 
793
             ('disconnect medium',),
 
794
             ('call_expecting_body', 'Repository.get_revision_graph',
 
795
              ('quack/', ''))],
 
796
            client._calls)
 
797
 
 
798
    def test_get_parent_map_unexpected_response(self):
 
799
        responses = [
 
800
            (('something unexpected!',), '')]
 
801
        repo, client = self.setup_fake_client_and_repository(responses, 'path')
 
802
        self.assertRaises(
 
803
            errors.UnexpectedSmartServerResponse,
 
804
            repo.get_parent_map, ['a-revision-id'])
 
805
 
 
806
 
 
807
class TestRepositoryGetRevisionGraph(TestRemoteRepository):
 
808
    
 
809
    def test_null_revision(self):
 
810
        # a null revision has the predictable result {}, we should have no wire
 
811
        # traffic when calling it with this argument
 
812
        responses = [(('notused', ), '')]
 
813
        transport_path = 'empty'
 
814
        repo, client = self.setup_fake_client_and_repository(
 
815
            responses, transport_path)
 
816
        result = self.applyDeprecated(one_four, repo.get_revision_graph,
 
817
            NULL_REVISION)
 
818
        self.assertEqual([], client._calls)
 
819
        self.assertEqual({}, result)
 
820
 
 
821
    def test_none_revision(self):
 
822
        # with none we want the entire graph
 
823
        r1 = u'\u0e33'.encode('utf8')
 
824
        r2 = u'\u0dab'.encode('utf8')
 
825
        lines = [' '.join([r2, r1]), r1]
 
826
        encoded_body = '\n'.join(lines)
 
827
 
 
828
        responses = [(('ok', ), encoded_body)]
 
829
        transport_path = 'sinhala'
 
830
        repo, client = self.setup_fake_client_and_repository(
 
831
            responses, transport_path)
 
832
        result = self.applyDeprecated(one_four, repo.get_revision_graph)
 
833
        self.assertEqual(
 
834
            [('call_expecting_body', 'Repository.get_revision_graph',
 
835
             ('sinhala/', ''))],
 
836
            client._calls)
 
837
        self.assertEqual({r1: (), r2: (r1, )}, result)
 
838
 
 
839
    def test_specific_revision(self):
 
840
        # with a specific revision we want the graph for that
 
841
        # with none we want the entire graph
 
842
        r11 = u'\u0e33'.encode('utf8')
 
843
        r12 = u'\xc9'.encode('utf8')
 
844
        r2 = u'\u0dab'.encode('utf8')
 
845
        lines = [' '.join([r2, r11, r12]), r11, r12]
 
846
        encoded_body = '\n'.join(lines)
 
847
 
 
848
        responses = [(('ok', ), encoded_body)]
 
849
        transport_path = 'sinhala'
 
850
        repo, client = self.setup_fake_client_and_repository(
 
851
            responses, transport_path)
 
852
        result = self.applyDeprecated(one_four, repo.get_revision_graph, r2)
 
853
        self.assertEqual(
 
854
            [('call_expecting_body', 'Repository.get_revision_graph',
 
855
             ('sinhala/', r2))],
 
856
            client._calls)
 
857
        self.assertEqual({r11: (), r12: (), r2: (r11, r12), }, result)
 
858
 
 
859
    def test_no_such_revision(self):
 
860
        revid = '123'
 
861
        responses = [(('nosuchrevision', revid), '')]
 
862
        transport_path = 'sinhala'
 
863
        repo, client = self.setup_fake_client_and_repository(
 
864
            responses, transport_path)
 
865
        # also check that the right revision is reported in the error
 
866
        self.assertRaises(errors.NoSuchRevision,
 
867
            self.applyDeprecated, one_four, repo.get_revision_graph, revid)
 
868
        self.assertEqual(
 
869
            [('call_expecting_body', 'Repository.get_revision_graph',
 
870
             ('sinhala/', revid))],
 
871
            client._calls)
 
872
 
 
873
        
 
874
class TestRepositoryIsShared(TestRemoteRepository):
 
875
 
 
876
    def test_is_shared(self):
 
877
        # ('yes', ) for Repository.is_shared -> 'True'.
 
878
        responses = [(('yes', ), )]
 
879
        transport_path = 'quack'
 
880
        repo, client = self.setup_fake_client_and_repository(
 
881
            responses, transport_path)
 
882
        result = repo.is_shared()
 
883
        self.assertEqual(
 
884
            [('call', 'Repository.is_shared', ('quack/',))],
 
885
            client._calls)
 
886
        self.assertEqual(True, result)
 
887
 
 
888
    def test_is_not_shared(self):
 
889
        # ('no', ) for Repository.is_shared -> 'False'.
 
890
        responses = [(('no', ), )]
 
891
        transport_path = 'qwack'
 
892
        repo, client = self.setup_fake_client_and_repository(
 
893
            responses, transport_path)
 
894
        result = repo.is_shared()
 
895
        self.assertEqual(
 
896
            [('call', 'Repository.is_shared', ('qwack/',))],
 
897
            client._calls)
 
898
        self.assertEqual(False, result)
 
899
 
 
900
 
 
901
class TestRepositoryLockWrite(TestRemoteRepository):
 
902
 
 
903
    def test_lock_write(self):
 
904
        responses = [(('ok', 'a token'), '')]
 
905
        transport_path = 'quack'
 
906
        repo, client = self.setup_fake_client_and_repository(
 
907
            responses, transport_path)
 
908
        result = repo.lock_write()
 
909
        self.assertEqual(
 
910
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
911
            client._calls)
 
912
        self.assertEqual('a token', result)
 
913
 
 
914
    def test_lock_write_already_locked(self):
 
915
        responses = [(('LockContention', ), '')]
 
916
        transport_path = 'quack'
 
917
        repo, client = self.setup_fake_client_and_repository(
 
918
            responses, transport_path)
 
919
        self.assertRaises(errors.LockContention, repo.lock_write)
 
920
        self.assertEqual(
 
921
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
922
            client._calls)
 
923
 
 
924
    def test_lock_write_unlockable(self):
 
925
        responses = [(('UnlockableTransport', ), '')]
 
926
        transport_path = 'quack'
 
927
        repo, client = self.setup_fake_client_and_repository(
 
928
            responses, transport_path)
 
929
        self.assertRaises(errors.UnlockableTransport, repo.lock_write)
 
930
        self.assertEqual(
 
931
            [('call', 'Repository.lock_write', ('quack/', ''))],
 
932
            client._calls)
 
933
 
 
934
 
 
935
class TestRepositoryUnlock(TestRemoteRepository):
 
936
 
 
937
    def test_unlock(self):
 
938
        responses = [(('ok', 'a token'), ''),
 
939
                     (('ok',), '')]
 
940
        transport_path = 'quack'
 
941
        repo, client = self.setup_fake_client_and_repository(
 
942
            responses, transport_path)
 
943
        repo.lock_write()
 
944
        repo.unlock()
 
945
        self.assertEqual(
 
946
            [('call', 'Repository.lock_write', ('quack/', '')),
 
947
             ('call', 'Repository.unlock', ('quack/', 'a token'))],
 
948
            client._calls)
 
949
 
 
950
    def test_unlock_wrong_token(self):
 
951
        # If somehow the token is wrong, unlock will raise TokenMismatch.
 
952
        responses = [(('ok', 'a token'), ''),
 
953
                     (('TokenMismatch',), '')]
 
954
        transport_path = 'quack'
 
955
        repo, client = self.setup_fake_client_and_repository(
 
956
            responses, transport_path)
 
957
        repo.lock_write()
 
958
        self.assertRaises(errors.TokenMismatch, repo.unlock)
 
959
 
 
960
 
 
961
class TestRepositoryHasRevision(TestRemoteRepository):
 
962
 
 
963
    def test_none(self):
 
964
        # repo.has_revision(None) should not cause any traffic.
 
965
        transport_path = 'quack'
 
966
        responses = None
 
967
        repo, client = self.setup_fake_client_and_repository(
 
968
            responses, transport_path)
 
969
 
 
970
        # The null revision is always there, so has_revision(None) == True.
 
971
        self.assertEqual(True, repo.has_revision(NULL_REVISION))
 
972
 
 
973
        # The remote repo shouldn't be accessed.
 
974
        self.assertEqual([], client._calls)
 
975
 
 
976
 
 
977
class TestRepositoryTarball(TestRemoteRepository):
 
978
 
 
979
    # This is a canned tarball reponse we can validate against
 
980
    tarball_content = (
 
981
        'QlpoOTFBWSZTWdGkj3wAAWF/k8aQACBIB//A9+8cIX/v33AACEAYABAECEACNz'
 
982
        'JqsgJJFPTSnk1A3qh6mTQAAAANPUHkagkSTEkaA09QaNAAAGgAAAcwCYCZGAEY'
 
983
        'mJhMJghpiaYBUkKammSHqNMZQ0NABkNAeo0AGneAevnlwQoGzEzNVzaYxp/1Uk'
 
984
        'xXzA1CQX0BJMZZLcPBrluJir5SQyijWHYZ6ZUtVqqlYDdB2QoCwa9GyWwGYDMA'
 
985
        'OQYhkpLt/OKFnnlT8E0PmO8+ZNSo2WWqeCzGB5fBXZ3IvV7uNJVE7DYnWj6qwB'
 
986
        'k5DJDIrQ5OQHHIjkS9KqwG3mc3t+F1+iujb89ufyBNIKCgeZBWrl5cXxbMGoMs'
 
987
        'c9JuUkg5YsiVcaZJurc6KLi6yKOkgCUOlIlOpOoXyrTJjK8ZgbklReDdwGmFgt'
 
988
        'dkVsAIslSVCd4AtACSLbyhLHryfb14PKegrVDba+U8OL6KQtzdM5HLjAc8/p6n'
 
989
        '0lgaWU8skgO7xupPTkyuwheSckejFLK5T4ZOo0Gda9viaIhpD1Qn7JqqlKAJqC'
 
990
        'QplPKp2nqBWAfwBGaOwVrz3y1T+UZZNismXHsb2Jq18T+VaD9k4P8DqE3g70qV'
 
991
        'JLurpnDI6VS5oqDDPVbtVjMxMxMg4rzQVipn2Bv1fVNK0iq3Gl0hhnnHKm/egy'
 
992
        'nWQ7QH/F3JFOFCQ0aSPfA='
 
993
        ).decode('base64')
 
994
 
 
995
    def test_repository_tarball(self):
 
996
        # Test that Repository.tarball generates the right operations
 
997
        transport_path = 'repo'
 
998
        expected_responses = [(('ok',), self.tarball_content),
 
999
            ]
 
1000
        expected_calls = [('call_expecting_body', 'Repository.tarball',
 
1001
                           ('repo/', 'bz2',),),
 
1002
            ]
 
1003
        remote_repo, client = self.setup_fake_client_and_repository(
 
1004
            expected_responses, transport_path)
 
1005
        # Now actually ask for the tarball
 
1006
        tarball_file = remote_repo._get_tarball('bz2')
 
1007
        try:
 
1008
            self.assertEqual(expected_calls, client._calls)
 
1009
            self.assertEqual(self.tarball_content, tarball_file.read())
 
1010
        finally:
 
1011
            tarball_file.close()
 
1012
 
 
1013
 
 
1014
class TestRemoteRepositoryCopyContent(tests.TestCaseWithTransport):
 
1015
    """RemoteRepository.copy_content_into optimizations"""
 
1016
 
 
1017
    def test_copy_content_remote_to_local(self):
 
1018
        self.transport_server = server.SmartTCPServer_for_testing
 
1019
        src_repo = self.make_repository('repo1')
 
1020
        src_repo = repository.Repository.open(self.get_url('repo1'))
 
1021
        # At the moment the tarball-based copy_content_into can't write back
 
1022
        # into a smart server.  It would be good if it could upload the
 
1023
        # tarball; once that works we'd have to create repositories of
 
1024
        # different formats. -- mbp 20070410
 
1025
        dest_url = self.get_vfs_only_url('repo2')
 
1026
        dest_bzrdir = BzrDir.create(dest_url)
 
1027
        dest_repo = dest_bzrdir.create_repository()
 
1028
        self.assertFalse(isinstance(dest_repo, RemoteRepository))
 
1029
        self.assertTrue(isinstance(src_repo, RemoteRepository))
 
1030
        src_repo.copy_content_into(dest_repo)
 
1031
 
 
1032
 
 
1033
class TestRepositoryStreamKnitData(TestRemoteRepository):
 
1034
 
 
1035
    def make_pack_file(self, records):
 
1036
        pack_file = StringIO()
 
1037
        pack_writer = pack.ContainerWriter(pack_file.write)
 
1038
        pack_writer.begin()
 
1039
        for bytes, names in records:
 
1040
            pack_writer.add_bytes_record(bytes, names)
 
1041
        pack_writer.end()
 
1042
        pack_file.seek(0)
 
1043
        return pack_file
 
1044
 
 
1045
    def make_pack_stream(self, records):
 
1046
        pack_serialiser = pack.ContainerSerialiser()
 
1047
        yield pack_serialiser.begin()
 
1048
        for bytes, names in records:
 
1049
            yield pack_serialiser.bytes_record(bytes, names)
 
1050
        yield pack_serialiser.end()
 
1051
 
 
1052
    def test_bad_pack_from_server(self):
 
1053
        """A response with invalid data (e.g. it has a record with multiple
 
1054
        names) triggers an exception.
 
1055
        
 
1056
        Not all possible errors will be caught at this stage, but obviously
 
1057
        malformed data should be.
 
1058
        """
 
1059
        record = ('bytes', [('name1',), ('name2',)])
 
1060
        pack_stream = self.make_pack_stream([record])
 
1061
        responses = [(('ok',), pack_stream), ]
 
1062
        transport_path = 'quack'
 
1063
        repo, client = self.setup_fake_client_and_repository(
 
1064
            responses, transport_path)
 
1065
        search = graph.SearchResult(set(['revid']), set(), 1, set(['revid']))
 
1066
        stream = repo.get_data_stream_for_search(search)
 
1067
        self.assertRaises(errors.SmartProtocolError, list, stream)
 
1068
    
 
1069
    def test_backwards_compatibility(self):
 
1070
        """If the server doesn't recognise this request, fallback to VFS."""
 
1071
        responses = [
 
1072
            (('unknown verb', 'Repository.stream_revisions_chunked'), '')]
 
1073
        repo, client = self.setup_fake_client_and_repository(
 
1074
            responses, 'path')
 
1075
        self.mock_called = False
 
1076
        repo._real_repository = MockRealRepository(self)
 
1077
        search = graph.SearchResult(set(['revid']), set(), 1, set(['revid']))
 
1078
        repo.get_data_stream_for_search(search)
 
1079
        self.assertTrue(self.mock_called)
 
1080
        self.failIf(client.expecting_body,
 
1081
            "The protocol has been left in an unclean state that will cause "
 
1082
            "TooManyConcurrentRequests errors.")
 
1083
 
 
1084
 
 
1085
class MockRealRepository(object):
 
1086
    """Helper class for TestRepositoryStreamKnitData.test_unknown_method."""
 
1087
 
 
1088
    def __init__(self, test):
 
1089
        self.test = test
 
1090
 
 
1091
    def get_data_stream_for_search(self, search):
 
1092
        self.test.assertEqual(set(['revid']), search.get_keys())
 
1093
        self.test.mock_called = True
 
1094
 
 
1095